From e76ded538443667d981686346424a7c4cb31880d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 4 Oct 2024 18:41:57 +0200 Subject: [PATCH 001/177] Implement CPU backface culling --- .../java/net/vulkanmod/config/Config.java | 2 + .../net/vulkanmod/config/option/Options.java | 6 + .../vulkanmod/render/chunk/RenderSection.java | 22 +- .../vulkanmod/render/chunk/WorldRenderer.java | 4 +- .../render/chunk/buffer/DrawBuffers.java | 130 ++++++--- .../render/chunk/build/BlockRenderer.java | 25 +- .../render/chunk/build/LiquidRenderer.java | 9 +- .../render/chunk/build/TaskDispatcher.java | 2 +- .../render/chunk/build/UploadBuffer.java | 45 ++- .../render/chunk/build/task/BuildTask.java | 39 +-- .../chunk/build/task/CompiledSection.java | 1 - .../build/task/SortTransparencyTask.java | 12 +- .../chunk/build/thread/ThreadBuilderPack.java | 16 +- .../render/chunk/cull/QuadFacing.java | 27 ++ .../render/profiling/ProfilerOverlay.java | 3 + .../vulkanmod/render/vertex/QuadSorter.java | 63 ++++- .../render/vertex/TerrainBufferBuilder.java | 263 ++---------------- .../render/vertex/TerrainBuilder.java | 219 +++++++++++++++ 18 files changed, 554 insertions(+), 334 deletions(-) create mode 100644 src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java create mode 100644 src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index b265f6d58f..0063415dce 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -27,6 +27,8 @@ public class Config { public int ambientOcclusion = 1; + public boolean backFaceCulling = true; + public void write() { if(!Files.exists(CONFIG_PATH.getParent())) { diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index b84b7d3a26..5e34dc547e 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -256,6 +256,12 @@ public static OptionBlock[] getOptimizationOpts() { }, () -> config.uniqueOpaqueLayer) .setTooltip(Component.translatable("vulkanmod.options.uniqueOpaqueLayer.tooltip")), + new SwitchOption(Component.translatable("Back face culling"), + value -> { + config.backFaceCulling = value; + Minecraft.getInstance().levelRenderer.allChanged(); + }, + () -> config.backFaceCulling), new SwitchOption(Component.translatable("vulkanmod.options.indirectDraw"), value -> config.indirectDraw = value, () -> config.indirectDraw) diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index a1c54fca86..5618f6c94a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -14,6 +14,7 @@ import net.vulkanmod.render.chunk.build.task.ChunkTask; import net.vulkanmod.render.chunk.build.task.CompiledSection; import net.vulkanmod.render.chunk.build.task.SortTransparencyTask; +import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.graph.GraphDirections; import net.vulkanmod.render.chunk.util.Util; import net.vulkanmod.render.vertex.TerrainRenderType; @@ -61,8 +62,9 @@ public RenderSection(int index, int x, int y, int z) { this.yOffset = y; this.zOffset = z; - this.drawParametersArray = new DrawBuffers.DrawParameters[TerrainRenderType.VALUES.length]; - for (int i = 0; i < this.drawParametersArray.length; ++i) { + final int size = TerrainRenderType.VALUES.length * QuadFacing.VALUES.length; + this.drawParametersArray = new DrawBuffers.DrawParameters[size]; + for (int i = 0; i < size; ++i) { this.drawParametersArray[i] = new DrawBuffers.DrawParameters(); } } @@ -297,8 +299,14 @@ public int zOffset() { return zOffset; } - public DrawBuffers.DrawParameters getDrawParameters(TerrainRenderType renderType) { - return drawParametersArray[renderType.ordinal()]; + public void resetDrawParameters(TerrainRenderType renderType) { + for (int i = 0; i < QuadFacing.COUNT; ++i) { + drawParametersArray[renderType.ordinal() * QuadFacing.COUNT + i].reset(this.chunkArea, renderType); + } + } + + public DrawBuffers.DrawParameters getDrawParameters(TerrainRenderType renderType, int facing) { + return drawParametersArray[renderType.ordinal() * QuadFacing.COUNT + facing]; } public void setChunkArea(ChunkArea chunkArea) { @@ -385,8 +393,10 @@ private void resetDrawParameters() { if (this.chunkArea == null) return; - for (TerrainRenderType r : TerrainRenderType.VALUES) { - this.getDrawParameters(r).reset(this.chunkArea, r); + for (TerrainRenderType renderType : TerrainRenderType.VALUES) { + for (QuadFacing facing : QuadFacing.VALUES) { + this.getDrawParameters(renderType, facing.ordinal()).reset(this.chunkArea, renderType); + } } } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index c7fe74ef1a..dca14f636d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -338,9 +338,9 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, renderer.uploadAndBindUBOs(pipeline); if (indirectDraw) - drawBuffers.buildDrawBatchesIndirect(indirectBuffers[currentFrame], queue, terrainRenderType); + drawBuffers.buildDrawBatchesIndirect(cameraPos, indirectBuffers[currentFrame], queue, terrainRenderType); else - drawBuffers.buildDrawBatchesDirect(queue, terrainRenderType); + drawBuffers.buildDrawBatchesDirect(cameraPos, queue, terrainRenderType); } } } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 8556e0426d..3d562d1435 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -1,9 +1,12 @@ package net.vulkanmod.render.chunk.buffer; +import net.minecraft.world.phys.Vec3; +import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.ChunkArea; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.build.UploadBuffer; +import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.util.StaticQueue; import net.vulkanmod.render.vertex.CustomVertexFormat; import net.vulkanmod.render.vertex.TerrainRenderType; @@ -39,28 +42,49 @@ public DrawBuffers(int index, Vector3i origin, int minHeight) { } public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType renderType) { - DrawParameters drawParameters = section.getDrawParameters(renderType); - int vertexOffset = drawParameters.vertexOffset; - int firstIndex = -1; + var vertexBuffers = buffer.getVertexBuffers(); + + if (buffer.indexOnly) { + DrawParameters drawParameters = section.getDrawParameters(renderType, QuadFacing.NONE.ordinal()); - if (!buffer.indexOnly) { - AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(buffer.getVertexBuffer(), vertexOffset, drawParameters); - vertexOffset = segment.offset / VERTEX_SIZE; + AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); + drawParameters.firstIndex = segment.offset / INDEX_SIZE; - drawParameters.baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); + buffer.release(); + return; } - if (!buffer.autoIndices) { - if (this.indexBuffer == null) + for (int i = 0; i < QuadFacing.COUNT; i++) { + DrawParameters drawParameters = section.getDrawParameters(renderType, i); + int vertexOffset = drawParameters.vertexOffset; + int firstIndex = -1; + int indexCount = 0; + + var vertexBuffer = vertexBuffers[i]; + + if (vertexBuffer != null) { + AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(vertexBuffer, vertexOffset, drawParameters); + vertexOffset = segment.offset / VERTEX_SIZE; + + drawParameters.baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); + indexCount = vertexBuffer.limit() / VERTEX_SIZE * 6 / 4; + } + + if (i == QuadFacing.NONE.ordinal() && !buffer.autoIndices) { + if (this.indexBuffer == null) { this.indexBuffer = new AreaBuffer(AreaBuffer.Usage.INDEX, 60000, INDEX_SIZE); + } - AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); - firstIndex = segment.offset / INDEX_SIZE; - } + AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); + firstIndex = segment.offset / INDEX_SIZE; + } - drawParameters.indexCount = buffer.indexCount; - drawParameters.firstIndex = firstIndex; - drawParameters.vertexOffset = vertexOffset; +// drawParameters.indexCount = buffer.indexCount; + drawParameters.firstIndex = firstIndex; + drawParameters.vertexOffset = vertexOffset; + + drawParameters.indexCount = indexCount; + } buffer.release(); } @@ -110,11 +134,11 @@ private void updateChunkAreaOrigin(VkCommandBuffer commandBuffer, Pipeline pipel vkCmdPushConstants(commandBuffer, pipeline.getLayout(), VK_SHADER_STAGE_VERTEX_BIT, 0, byteBuffer); } - public void buildDrawBatchesIndirect(IndirectBuffer indirectBuffer, StaticQueue queue, TerrainRenderType terrainRenderType) { + public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuffer, StaticQueue queue, TerrainRenderType terrainRenderType) { try (MemoryStack stack = MemoryStack.stackPush()) { - ByteBuffer byteBuffer = stack.malloc(20 * queue.size()); + ByteBuffer byteBuffer = stack.malloc(20 * queue.size() * 7); long bufferPtr = MemoryUtil.memAddress0(byteBuffer); boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; @@ -123,19 +147,28 @@ public void buildDrawBatchesIndirect(IndirectBuffer indirectBuffer, StaticQueue< for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { final RenderSection section = iterator.next(); - final DrawParameters drawParameters = section.getDrawParameters(terrainRenderType); - if (drawParameters.indexCount <= 0) - continue; + int mask = getMask(cameraPos, section); + + for (int i = 0; i < QuadFacing.COUNT; i++) { - long ptr = bufferPtr + (drawCount * 20L); - MemoryUtil.memPutInt(ptr, drawParameters.indexCount); - MemoryUtil.memPutInt(ptr + 4, 1); - MemoryUtil.memPutInt(ptr + 8, drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex); - MemoryUtil.memPutInt(ptr + 12, drawParameters.vertexOffset); - MemoryUtil.memPutInt(ptr + 16, drawParameters.baseInstance); + if((mask & 1 << i) == 0) + continue; - drawCount++; + final DrawParameters drawParameters = section.getDrawParameters(terrainRenderType, i); + + if (drawParameters.indexCount <= 0) + continue; + + long ptr = bufferPtr + (drawCount * 20L); + MemoryUtil.memPutInt(ptr, drawParameters.indexCount); + MemoryUtil.memPutInt(ptr + 4, 1); + MemoryUtil.memPutInt(ptr + 8, drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex); + MemoryUtil.memPutInt(ptr + 12, drawParameters.vertexOffset); + MemoryUtil.memPutInt(ptr + 16, drawParameters.baseInstance); + + drawCount++; + } } if (drawCount == 0) return; @@ -149,22 +182,50 @@ public void buildDrawBatchesIndirect(IndirectBuffer indirectBuffer, StaticQueue< } - public void buildDrawBatchesDirect(StaticQueue queue, TerrainRenderType renderType) { + public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue queue, TerrainRenderType renderType) { boolean isTranslucent = renderType == TerrainRenderType.TRANSLUCENT; VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { final RenderSection section = iterator.next(); - final DrawParameters drawParameters = section.getDrawParameters(renderType); - if (drawParameters.indexCount <= 0) - continue; + int mask = getMask(cameraPos, section); + + for (int i = 0; i < QuadFacing.COUNT; i++) { + + if((mask & 1 << i) == 0) + continue; + + final DrawParameters drawParameters = section.getDrawParameters(renderType, i); + + if (drawParameters.indexCount <= 0) + continue; + + final int firstIndex = drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex; + vkCmdDrawIndexed(commandBuffer, drawParameters.indexCount, 1, firstIndex, drawParameters.vertexOffset, drawParameters.baseInstance); + } - final int firstIndex = drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex; - vkCmdDrawIndexed(commandBuffer, drawParameters.indexCount, 1, firstIndex, drawParameters.vertexOffset, drawParameters.baseInstance); } } + private int getMask(Vec3 camera, RenderSection section) { + final int secX = section.xOffset; + final int secY = section.yOffset; + final int secZ = section.zOffset; + + int mask = 1 << QuadFacing.NONE.ordinal(); + + mask |= camera.x - secX >= 0 ? 1 << QuadFacing.X_POS.ordinal() : 0; + mask |= camera.y - secY >= 0 ? 1 << QuadFacing.Y_POS.ordinal() : 0; + mask |= camera.z - secZ >= 0 ? 1 << QuadFacing.Z_POS.ordinal() : 0; + mask |= camera.x - (secX + 16) < 0 ? 1 << QuadFacing.X_NEG.ordinal() : 0; + mask |= camera.y - (secY + 16) < 0 ? 1 << QuadFacing.Y_NEG.ordinal() : 0; + mask |= camera.z - (secZ + 16) < 0 ? 1 << QuadFacing.Z_NEG.ordinal() : 0; + + return mask; +// return 0xFF; + } + public void bindBuffers(VkCommandBuffer commandBuffer, Pipeline pipeline, TerrainRenderType terrainRenderType, double camX, double camY, double camZ) { try (MemoryStack stack = MemoryStack.stackPush()) { @@ -173,7 +234,8 @@ public void bindBuffers(VkCommandBuffer commandBuffer, Pipeline pipeline, Terrai updateChunkAreaOrigin(commandBuffer, pipeline, camX, camY, camZ, stack); } - if (terrainRenderType == TerrainRenderType.TRANSLUCENT) { + // TODO index buffer + if (terrainRenderType == TerrainRenderType.TRANSLUCENT && this.indexBuffer != null) { vkCmdBindIndexBuffer(commandBuffer, this.indexBuffer.getId(), 0, VK_INDEX_TYPE_UINT16); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java index 7c3e954054..592a7055c9 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java @@ -3,6 +3,7 @@ import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColors; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; @@ -16,12 +17,16 @@ import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; +import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.model.quad.QuadUtils; import net.vulkanmod.render.model.quad.QuadView; import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; +import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.render.vertex.VertexUtil; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Vector3f; @@ -43,6 +48,10 @@ public class BlockRenderer { BlockState blockState; + final boolean backFaceCulling = Initializer.CONFIG.backFaceCulling; + + private TerrainRenderType renderType; + public void setResources(BuilderResources resources) { this.resources = resources; } @@ -60,10 +69,11 @@ public static void setBlockColors(BlockColors blockColors) { BlockRenderer.blockColors = blockColors; } - public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos, TerrainBufferBuilder bufferBuilder) { + public void renderBlock(BlockState blockState, BlockPos blockPos, TerrainRenderType renderType, Vector3f pos, TerrainBuilder bufferBuilder) { this.pos = pos; this.blockPos = blockPos; this.blockState = blockState; + this.renderType = renderType; long seed = blockState.getSeed(blockPos); @@ -71,7 +81,7 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos, tessellateBlock(model, bufferBuilder, seed); } - public void tessellateBlock(BakedModel bakedModel, TerrainBufferBuilder bufferBuilder, long seed) { + public void tessellateBlock(BakedModel bakedModel, TerrainBuilder bufferBuilder, long seed) { Vec3 offset = blockState.getOffset(resources.region, blockPos); pos.add((float) offset.x, (float) offset.y, (float) offset.z); @@ -101,9 +111,18 @@ public void tessellateBlock(BakedModel bakedModel, TerrainBufferBuilder bufferBu } } - private void renderModelFace(TerrainBufferBuilder bufferBuilder, List quads, LightPipeline lightPipeline, Direction cullFace) { + private void renderModelFace(TerrainBuilder terrainBuilder, List quads, LightPipeline lightPipeline, Direction cullFace) { QuadLightData quadLightData = resources.quadLightData; + TerrainBufferBuilder bufferBuilder; + + if (cullFace != null && renderType != TerrainRenderType.TRANSLUCENT && this.backFaceCulling) { + bufferBuilder = terrainBuilder.getBufferBuilder(QuadFacing.from(cullFace).ordinal()); + } + else { + bufferBuilder = terrainBuilder.getBufferBuilder(QuadFacing.NONE.ordinal()); + } + for (int i = 0; i < quads.size(); ++i) { BakedQuad bakedQuad = quads.get(i); QuadView quadView = (QuadView) bakedQuad; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java index 4ae8eca4a8..2e5011bf41 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java @@ -20,11 +20,13 @@ import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.util.Util; import net.vulkanmod.render.model.quad.ModelQuad; import net.vulkanmod.render.model.quad.ModelQuadFlags; import net.vulkanmod.render.model.quad.QuadUtils; import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.VertexUtil; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Vector3f; @@ -44,7 +46,7 @@ public void setResources(BuilderResources resources) { this.resources = resources; } - public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBufferBuilder vertexConsumer) { + public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBuilder vertexConsumer) { tessellate(blockState, fluidState, blockPos, vertexConsumer); } @@ -85,7 +87,7 @@ public BlockState getAdjBlockState(BlockAndTintGetter blockAndTintGetter, int x, return blockAndTintGetter.getBlockState(mBlockPos); } - public void tessellate(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBufferBuilder vertexConsumer) { + public void tessellate(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBuilder vertexConsumer) { BlockAndTintGetter region = this.resources.region; final FluidRenderHandler handler = getFluidRenderHandler(fluidState); @@ -423,12 +425,13 @@ private int calculateNormal(ModelQuad quad) { return VertexUtil.packNormal(normal.x(), normal.y(), normal.z()); } - private void putQuad(ModelQuad quad, TerrainBufferBuilder bufferBuilder, float xOffset, float yOffset, float zOffset, boolean flip) { + private void putQuad(ModelQuad quad, TerrainBuilder builder, float xOffset, float yOffset, float zOffset, boolean flip) { QuadLightData quadLightData = resources.quadLightData; // Rotate triangles if needed to fix AO anisotropy int k = QuadUtils.getIterationStartIdx(quadLightData.br); + TerrainBufferBuilder bufferBuilder = builder.getBufferBuilder(QuadFacing.NONE.ordinal()); bufferBuilder.ensureCapacity(); int i; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java b/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java index ae43f35441..2e5633f9d6 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java @@ -166,7 +166,7 @@ private void doSectionUpdate(CompileResult compileResult) { if(uploadBuffer != null) { drawBuffers.upload(section, uploadBuffer, renderType); } else { - section.getDrawParameters(renderType).reset(renderArea, renderType); + section.resetDrawParameters(renderType); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java b/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java index cd8b72404e..3254b19c42 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java @@ -1,7 +1,9 @@ package net.vulkanmod.render.chunk.build; +import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.util.BufferUtil; import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -10,32 +12,43 @@ public class UploadBuffer { public final int indexCount; public final boolean autoIndices; public final boolean indexOnly; - private final ByteBuffer vertexBuffer; + private final ByteBuffer[] vertexBuffers; private final ByteBuffer indexBuffer; - public UploadBuffer(TerrainBufferBuilder.RenderedBuffer renderedBuffer) { - TerrainBufferBuilder.DrawState drawState = renderedBuffer.drawState(); + public UploadBuffer(TerrainBuilder terrainBuilder, TerrainBuilder.DrawState drawState) { this.indexCount = drawState.indexCount(); this.autoIndices = drawState.sequentialIndex(); this.indexOnly = drawState.indexOnly(); - if (!this.indexOnly) - this.vertexBuffer = BufferUtil.clone(renderedBuffer.vertexBuffer()); - else - this.vertexBuffer = null; + if (!this.indexOnly) { + this.vertexBuffers = new ByteBuffer[QuadFacing.COUNT]; - if (!drawState.sequentialIndex()) - this.indexBuffer = BufferUtil.clone(renderedBuffer.indexBuffer()); - else + for (int i = 0; i < QuadFacing.COUNT; i++) { + var bufferBuilder = terrainBuilder.getBufferBuilder(i); + + if (bufferBuilder.getVertices() > 0) { + this.vertexBuffers[i] = BufferUtil.clone(bufferBuilder.getBuffer()); + } + } + } + else { + this.vertexBuffers = null; + } + + if (!drawState.sequentialIndex()) { + this.indexBuffer = BufferUtil.clone(terrainBuilder.getIndexBuffer()); + } + else { this.indexBuffer = null; + } } public int indexCount() { return indexCount; } - public ByteBuffer getVertexBuffer() { - return vertexBuffer; + public ByteBuffer[] getVertexBuffers() { + return vertexBuffers; } public ByteBuffer getIndexBuffer() { @@ -43,8 +56,12 @@ public ByteBuffer getIndexBuffer() { } public void release() { - if (vertexBuffer != null) - MemoryUtil.memFree(vertexBuffer); + if (vertexBuffers != null) + for (var vertexBuffer : vertexBuffers) { + if (vertexBuffer != null) + MemoryUtil.memFree(vertexBuffer); + } + if (indexBuffer != null) MemoryUtil.memFree(indexBuffer); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java index 6c104faa9f..6dd75fa6f3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java @@ -19,7 +19,8 @@ import net.vulkanmod.render.chunk.build.UploadBuffer; import net.vulkanmod.render.chunk.build.thread.BuilderResources; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; @@ -117,43 +118,45 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc FluidState fluidState = blockState.getFluidState(); TerrainRenderType renderType; - TerrainBufferBuilder bufferBuilder; + TerrainBuilder terrainBuilder; if (!fluidState.isEmpty()) { renderType = TerrainRenderType.get(ItemBlockRenderTypes.getRenderLayer(fluidState)); - bufferBuilder = getBufferBuilder(bufferBuilders, renderType); - bufferBuilder.setBlockAttributes(blockState); + terrainBuilder = getTerrainBuilder(bufferBuilders, renderType); + terrainBuilder.setBlockAttributes(blockState); - liquidRenderer.renderLiquid(blockState, fluidState, blockPos, bufferBuilder); + liquidRenderer.renderLiquid(blockState, fluidState, blockPos, terrainBuilder); } if (blockState.getRenderShape() == RenderShape.MODEL) { renderType = TerrainRenderType.get(ItemBlockRenderTypes.getChunkRenderType(blockState)); - bufferBuilder = getBufferBuilder(bufferBuilders, renderType); - bufferBuilder.setBlockAttributes(blockState); + terrainBuilder = getTerrainBuilder(bufferBuilders, renderType); + terrainBuilder.setBlockAttributes(blockState); pos.set(blockPos.getX() & 15, blockPos.getY() & 15, blockPos.getZ() & 15); - blockRenderer.renderBlock(blockState, blockPos, pos, bufferBuilder); + blockRenderer.renderBlock(blockState, blockPos, renderType, pos, terrainBuilder); } } } } - TerrainBufferBuilder translucentBufferBuilder = bufferBuilders.builder(TerrainRenderType.TRANSLUCENT); - if (!translucentBufferBuilder.isCurrentBatchEmpty()) { + TerrainBuilder translucentBufferBuilder = bufferBuilders.builder(TerrainRenderType.TRANSLUCENT); + if (translucentBufferBuilder.getBufferBuilder(QuadFacing.NONE.ordinal()).getVertices() > 0) { translucentBufferBuilder.setupQuadSortingPoints(); translucentBufferBuilder.setupQuadSorting(camX - (float) startBlockPos.getX(), camY - (float) startBlockPos.getY(), camZ - (float) startBlockPos.getZ()); compileResult.transparencyState = translucentBufferBuilder.getSortState(); } for (TerrainRenderType renderType : TerrainRenderType.VALUES) { - TerrainBufferBuilder.RenderedBuffer renderedBuffer = bufferBuilders.builder(renderType).end(); - if (renderedBuffer != null) { - UploadBuffer uploadBuffer = new UploadBuffer(renderedBuffer); - compileResult.renderedLayers.put(renderType, uploadBuffer); - renderedBuffer.release(); - } + TerrainBuilder builder = bufferBuilders.builder(renderType); + + TerrainBuilder.DrawState drawState = builder.endDrawing(); + + UploadBuffer uploadBuffer = new UploadBuffer(builder, drawState); + compileResult.renderedLayers.put(renderType, uploadBuffer); + + builder.clear(); } compileResult.visibilitySet = visGraph.resolve(); @@ -163,12 +166,12 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc private void setupBufferBuilders(ThreadBuilderPack builderPack) { for (TerrainRenderType renderType : TerrainRenderType.VALUES) { - TerrainBufferBuilder bufferBuilder = builderPack.builder(renderType); + TerrainBuilder bufferBuilder = builderPack.builder(renderType); bufferBuilder.begin(); } } - private TerrainBufferBuilder getBufferBuilder(ThreadBuilderPack bufferBuilders, TerrainRenderType renderType) { + private TerrainBuilder getTerrainBuilder(ThreadBuilderPack bufferBuilders, TerrainRenderType renderType) { renderType = compactRenderTypes(renderType); return bufferBuilders.builder(renderType); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java b/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java index c93de3a3c8..e233ab0a29 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java @@ -3,7 +3,6 @@ import com.google.common.collect.Lists; import net.minecraft.world.level.block.entity.BlockEntity; import net.vulkanmod.render.vertex.QuadSorter; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; import org.jetbrains.annotations.Nullable; import java.util.List; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java index 5f804c1a5a..122ab3751f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java @@ -7,7 +7,7 @@ import net.vulkanmod.render.chunk.build.thread.BuilderResources; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.vertex.QuadSorter; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; public class SortTransparencyTask extends ChunkTask { @@ -35,21 +35,23 @@ public Result runTask(BuilderResources context) { CompiledSection compiledSection = this.section.getCompiledSection(); QuadSorter.SortState transparencyState = compiledSection.transparencyState; - TerrainBufferBuilder bufferBuilder = builderPack.builder(TerrainRenderType.TRANSLUCENT); + TerrainBuilder bufferBuilder = builderPack.builder(TerrainRenderType.TRANSLUCENT); bufferBuilder.begin(); bufferBuilder.restoreSortState(transparencyState); bufferBuilder.setupQuadSorting(x - (float) this.section.xOffset(), y - (float) this.section.yOffset(), z - (float) this.section.zOffset()); - TerrainBufferBuilder.RenderedBuffer renderedBuffer = bufferBuilder.end(); + TerrainBuilder.DrawState drawState = bufferBuilder.endDrawing(); CompileResult compileResult = new CompileResult(this.section, false); - UploadBuffer uploadBuffer = new UploadBuffer(renderedBuffer); + UploadBuffer uploadBuffer = new UploadBuffer(bufferBuilder, drawState); compileResult.renderedLayers.put(TerrainRenderType.TRANSLUCENT, uploadBuffer); - renderedBuffer.release(); + + bufferBuilder.reset(); if (this.cancelled.get()) { return Result.CANCELLED; } + taskDispatcher.scheduleSectionUpdate(compileResult); return Result.SUCCESSFUL; } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java index 5517ce4ea8..84102838f4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java @@ -1,6 +1,6 @@ package net.vulkanmod.render.chunk.build.thread; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; import java.util.Arrays; @@ -9,20 +9,20 @@ import java.util.function.Function; public class ThreadBuilderPack { - private static Function terrainBuilderConstructor; + private static Function terrainBuilderConstructor; public static void defaultTerrainBuilderConstructor() { - terrainBuilderConstructor = renderType -> new TerrainBufferBuilder(TerrainRenderType.getRenderType(renderType).bufferSize()); + terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getRenderType(renderType).bufferSize()); } - public static void setTerrainBuilderConstructor(Function constructor) { + public static void setTerrainBuilderConstructor(Function constructor) { terrainBuilderConstructor = constructor; } - private final Map builders; + private final Map builders; public ThreadBuilderPack() { - var map = new EnumMap(TerrainRenderType.class); + var map = new EnumMap(TerrainRenderType.class); Arrays.stream(TerrainRenderType.values()).forEach( terrainRenderType -> map.put(terrainRenderType, terrainBuilderConstructor.apply(terrainRenderType)) @@ -30,12 +30,12 @@ public ThreadBuilderPack() { builders = map; } - public TerrainBufferBuilder builder(TerrainRenderType renderType) { + public TerrainBuilder builder(TerrainRenderType renderType) { return this.builders.get(renderType); } public void clearAll() { - this.builders.values().forEach(TerrainBufferBuilder::clear); + this.builders.values().forEach(TerrainBuilder::clear); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java new file mode 100644 index 0000000000..bc8e4ff17d --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java @@ -0,0 +1,27 @@ +package net.vulkanmod.render.chunk.cull; + +import net.minecraft.core.Direction; + +public enum QuadFacing { + X_POS, + X_NEG, + Y_POS, + Y_NEG, + Z_POS, + Z_NEG, + NONE; + + public static final QuadFacing[] VALUES = QuadFacing.values(); + public static final int COUNT = VALUES.length; + + public static QuadFacing from(Direction direction) { + return switch (direction) { + case DOWN -> Y_NEG; + case UP -> Y_POS; + case NORTH -> Z_NEG; + case SOUTH -> Z_POS; + case WEST -> X_NEG; + case EAST -> X_POS; + }; + } +} diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index d75fcdbd4e..3a1a22b0db 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -111,6 +111,9 @@ private List buildInfo() { list.add(String.format("FPS: %d Frametime: %.3f", fps, frametime)); list.add(""); + list.add(String.format("CPU fence wait time: %.3f", lastResults.getPartialResults().get(1).value)); + list.add(""); + for (Profiler.Result result : lastResults.getPartialResults()) { list.add(String.format("%s: %.3f", result.name, result.value)); } diff --git a/src/main/java/net/vulkanmod/render/vertex/QuadSorter.java b/src/main/java/net/vulkanmod/render/vertex/QuadSorter.java index fa6dd03dac..91c26a1293 100644 --- a/src/main/java/net/vulkanmod/render/vertex/QuadSorter.java +++ b/src/main/java/net/vulkanmod/render/vertex/QuadSorter.java @@ -15,6 +15,10 @@ public class QuadSorter { private VertexFormat format; private int vertexCount; + private int indexCount; + + private float[] distances; + private int[] sortingPointsIndices; public void setQuadSortOrigin(float x, float y, float z) { this.sortX = x; @@ -23,12 +27,14 @@ public void setQuadSortOrigin(float x, float y, float z) { } public SortState getSortState() { - return new SortState(this.vertexCount, this.sortingPoints); + return new SortState(this.vertexCount, this.sortingPoints, this.distances, this.sortingPointsIndices); } public void restoreSortState(QuadSorter.SortState sortState) { this.vertexCount = sortState.vertexCount; this.sortingPoints = sortState.sortingPoints; + this.distances = sortState.distances; + this.sortingPointsIndices = sortState.sortingPointsIndices; this.indexOnly = true; } @@ -80,9 +86,43 @@ public void setupQuadSortingPoints(long bufferPtr, int vertexCount, VertexFormat } this.sortingPoints = sortingPoints; + this.distances = new float[pointCount]; + this.sortingPointsIndices = new int[pointCount]; } public void putSortedQuadIndices(TerrainBufferBuilder bufferBuilder, VertexFormat.IndexType indexType) { + float[] distances = this.distances; + int[] sortingPointsIndices = this.sortingPointsIndices; + + for (int i = 0; i < this.sortingPoints.length; sortingPointsIndices[i] = i++) { + float dx = this.sortingPoints[i].x() - this.sortX; + float dy = this.sortingPoints[i].y() - this.sortY; + float dz = this.sortingPoints[i].z() - this.sortZ; + distances[i] = dx * dx + dy * dy + dz * dz; + } + + SortUtil.mergeSort(sortingPointsIndices, distances); + + long ptr = bufferBuilder.getPtr(); + + final int size = indexType.bytes; + final int stride = 4; // 4 vertices in a quad + for (int i = 0; i < sortingPointsIndices.length; ++i) { + final int quadIndex = sortingPointsIndices[i]; + final int baseVertex = quadIndex * stride; + + MemoryUtil.memPutInt(ptr + (size * 0L), baseVertex + 0); + MemoryUtil.memPutInt(ptr + (size * 1L), baseVertex + 1); + MemoryUtil.memPutInt(ptr + (size * 2L), baseVertex + 2); + MemoryUtil.memPutInt(ptr + (size * 3L), baseVertex + 2); + MemoryUtil.memPutInt(ptr + (size * 4L), baseVertex + 3); + MemoryUtil.memPutInt(ptr + (size * 5L), baseVertex + 0); + + ptr += size * 6L; + } + } + + public void putSortedQuadIndices(TerrainBuilder bufferBuilder, VertexFormat.IndexType indexType) { float[] distances = new float[this.sortingPoints.length]; int[] sortingPoints = new int[this.sortingPoints.length]; @@ -95,7 +135,7 @@ public void putSortedQuadIndices(TerrainBufferBuilder bufferBuilder, VertexForma SortUtil.mergeSort(sortingPoints, distances); - long ptr = bufferBuilder.getPtr(); + long ptr = bufferBuilder.indexBufferPtr; final int size = indexType.bytes; final int stride = 4; // 4 vertices in a quad @@ -114,14 +154,29 @@ public void putSortedQuadIndices(TerrainBufferBuilder bufferBuilder, VertexForma } } + public void reset() { + this.vertexCount = 0; + } + + public int getVertexCount() { + return vertexCount; + } + + public int getIndexCount() { + return indexCount; + } + public static class SortState { final int vertexCount; final Vector3f[] sortingPoints; + final float[] distances; + final int[] sortingPointsIndices; - SortState(int vertexCount, Vector3f[] sortingPoints) { + SortState(int vertexCount, Vector3f[] sortingPoints, float[] distances, int[] sortingPointsIndices) { this.vertexCount = vertexCount; this.sortingPoints = sortingPoints; - + this.distances = distances; + this.sortingPointsIndices = sortingPointsIndices; } } } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java index ca116035e7..e53f46694a 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java @@ -1,13 +1,8 @@ package net.vulkanmod.render.vertex; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.world.level.block.state.BlockState; import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; -import net.vulkanmod.render.util.SortUtil; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; -import org.joml.Vector3f; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -17,35 +12,30 @@ public class TerrainBufferBuilder { private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false); private int capacity; - protected long bufferPtr; - protected int nextElementByte; - private int vertexCount; - - private int renderedBufferCount; - private int renderedBufferPointer; - - private final VertexFormat format; + private int vertexSize; - private boolean building; + protected long bufferPtr; - private final QuadSorter quadSorter = new QuadSorter(); + protected int nextElementByte; + int vertices; - private boolean needsSorting; - private boolean indexOnly; + private VertexBuilder vertexBuilder; - protected VertexBuilder vertexBuilder; +// private int renderedBufferCount; +// private int renderedBufferPointer; - public TerrainBufferBuilder(int size) { + public TerrainBufferBuilder(int size, int vertexSize, VertexBuilder vertexBuilder) { this.bufferPtr = ALLOCATOR.malloc(size); this.capacity = size; + this.vertexSize = vertexSize; - this.format = PipelineManager.TERRAIN_VERTEX_FORMAT; +// this.format = PipelineManager.TERRAIN_VERTEX_FORMAT; this.vertexBuilder = PipelineManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); } public void ensureCapacity() { - this.ensureCapacity(this.format.getVertexSize() * 4); + this.ensureCapacity(this.vertexSize * 4); } private void ensureCapacity(int size) { @@ -66,129 +56,9 @@ private void resize(int i) { } } - public void setupQuadSorting(float x, float y, float z) { - this.quadSorter.setQuadSortOrigin(x, y, z); - this.needsSorting = true; - } - - public QuadSorter.SortState getSortState() { - return this.quadSorter.getSortState(); - } - - public void restoreSortState(QuadSorter.SortState sortState) { - this.vertexCount = sortState.vertexCount; - this.nextElementByte = this.renderedBufferPointer; - - this.quadSorter.restoreSortState(sortState); - - this.indexOnly = true; - } - - public void setIndexOnly() { - this.indexOnly = true; - } - - public void begin() { - if (this.building) { - throw new IllegalStateException("Already building!"); - } else { - this.building = true; - } - } - - public void setupQuadSortingPoints() { - this.quadSorter.setupQuadSortingPoints(this.bufferPtr + this.renderedBufferPointer, this.vertexCount, this.format); - } - - public boolean isCurrentBatchEmpty() { - return this.vertexCount == 0; - } - - @Nullable - public RenderedBuffer end() { - this.ensureDrawing(); - if (this.isCurrentBatchEmpty()) { - this.reset(); - return null; - } else { - RenderedBuffer renderedBuffer = this.storeRenderedBuffer(); - this.reset(); - return renderedBuffer; - } - } - - private void ensureDrawing() { - if (!this.building) { - throw new IllegalStateException("Not building!"); - } - } - - private RenderedBuffer storeRenderedBuffer() { - int indexCount = this.vertexCount / 4 * 6; - int vertexBufferSize = !this.indexOnly ? this.vertexCount * this.format.getVertexSize() : 0; - VertexFormat.IndexType indexType = VertexFormat.IndexType.least(indexCount); - - boolean sequentialIndexing; - int size; - - if (this.needsSorting) { - int indexBufferSize = indexCount * indexType.bytes; - this.ensureCapacity(indexBufferSize); - - this.quadSorter.putSortedQuadIndices(this, indexType); - - sequentialIndexing = false; - this.nextElementByte += indexBufferSize; - size = vertexBufferSize + indexBufferSize; - } else { - sequentialIndexing = true; - size = vertexBufferSize; - } - - int ptr = this.renderedBufferPointer; - this.renderedBufferPointer += size; - ++this.renderedBufferCount; - - DrawState drawState = new DrawState(this.format.getVertexSize(), this.vertexCount, indexCount, indexType, this.indexOnly, sequentialIndexing); - return new RenderedBuffer(ptr, drawState); - } - - public void reset() { - this.building = false; - this.vertexCount = 0; - - this.indexOnly = false; - this.needsSorting = false; - } - - void releaseRenderedBuffer() { - if (this.renderedBufferCount > 0 && --this.renderedBufferCount == 0) { - this.clear(); - } - - } - - public void clear() { - if (this.renderedBufferCount > 0) { - LOGGER.warn("Clearing BufferBuilder with unused batches"); - } - - this.discard(); - } - - public void discard() { - this.renderedBufferCount = 0; - this.renderedBufferPointer = 0; - this.nextElementByte = 0; - } - - public boolean building() { - return this.building; - } - public void endVertex() { - this.nextElementByte += this.vertexBuilder.getStride(); - ++this.vertexCount; + this.nextElementByte += this.vertexSize; + ++this.vertices; } public void vertex(float x, float y, float z, int color, float u, float v, int light, int packedNormal) { @@ -197,106 +67,29 @@ public void vertex(float x, float y, float z, int color, float u, float v, int l this.endVertex(); } - public void setBlockAttributes(BlockState blockState) { + public void end() { +// this.buffer.limit(this.nextElementByte); } - public long getPtr() { - return this.bufferPtr + this.nextElementByte; + public void clear() { + this.nextElementByte = 0; + this.vertices = 0; +// this.buffer.clear(); } - public int getVertexCount() { - return vertexCount; + public ByteBuffer getBuffer() { + return MemoryUtil.memByteBuffer(this.bufferPtr, this.vertices * this.vertexSize); } - public class RenderedBuffer { - private final int pointer; - private final DrawState drawState; - private boolean released; - - RenderedBuffer(int pointer, DrawState drawState) { - this.pointer = pointer; - this.drawState = drawState; - } - - public ByteBuffer vertexBuffer() { - int start = this.pointer + this.drawState.vertexBufferStart(); - int end = this.pointer + this.drawState.vertexBufferEnd(); - return MemoryUtil.memByteBuffer(TerrainBufferBuilder.this.bufferPtr + start, end - start); - } - - public ByteBuffer indexBuffer() { - int start = this.pointer + this.drawState.indexBufferStart(); - int end = this.pointer + this.drawState.indexBufferEnd(); - return MemoryUtil.memByteBuffer(TerrainBufferBuilder.this.bufferPtr + start, end - start); - } - - public DrawState drawState() { - return this.drawState; - } - - public boolean isEmpty() { - return this.drawState.vertexCount == 0; - } - - public void release() { - if (this.released) { - throw new IllegalStateException("Buffer has already been released!"); - } else { - TerrainBufferBuilder.this.releaseRenderedBuffer(); - this.released = true; - } - } + public long getPtr() { + return bufferPtr; } - public record DrawState(int vertexSize, int vertexCount, int indexCount, VertexFormat.IndexType indexType, - boolean indexOnly, boolean sequentialIndex) { - - public int vertexBufferSize() { - return this.vertexCount * this.vertexSize; - } - - public int vertexBufferStart() { - return 0; - } - - public int vertexBufferEnd() { - return this.vertexBufferSize(); - } - - public int indexBufferStart() { - return this.indexOnly ? 0 : this.vertexBufferEnd(); - } - - public int indexBufferEnd() { - return this.indexBufferStart() + this.indexBufferSize(); - } - - private int indexBufferSize() { - return this.sequentialIndex ? 0 : this.indexCount * this.indexType.bytes; - } - - public int bufferSize() { - return this.indexBufferEnd(); - } - - public int vertexCount() { - return this.vertexCount; - } - - public int indexCount() { - return this.indexCount; - } - - public VertexFormat.IndexType indexType() { - return this.indexType; - } - - public boolean indexOnly() { - return this.indexOnly; - } + public int getVertices() { + return vertices; + } - public boolean sequentialIndex() { - return this.sequentialIndex; - } + public int getNextElementByte() { + return nextElementByte; } } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java new file mode 100644 index 0000000000..55e379ff46 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -0,0 +1,219 @@ +package net.vulkanmod.render.vertex; + +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.world.level.block.state.BlockState; +import net.vulkanmod.Initializer; +import net.vulkanmod.render.PipelineManager; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import org.apache.logging.log4j.Logger; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +public class TerrainBuilder { + private static final Logger LOGGER = Initializer.LOGGER; + private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false); + + protected long indexBufferPtr; + + private int indexBufferCapacity; + protected long bufferPtr; + + private final VertexFormat format; + + private boolean building; + + private final QuadSorter quadSorter = new QuadSorter(); + + private boolean needsSorting; + private boolean indexOnly; + + protected VertexBuilder vertexBuilder; + + private final TerrainBufferBuilder[] bufferBuilders; + + public TerrainBuilder(int size) { + // TODO index buffer + this.indexBufferPtr = ALLOCATOR.malloc(size); + this.indexBufferCapacity = size; + + this.format = PipelineManager.TERRAIN_VERTEX_FORMAT; + this.vertexBuilder = PipelineManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN + ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); + + var bufferBuilders = new TerrainBufferBuilder[QuadFacing.COUNT]; + for (int i = 0; i < QuadFacing.COUNT; i++) { + bufferBuilders[i] = new TerrainBufferBuilder(size, this.format.getVertexSize(), this.vertexBuilder); + } + + this.bufferBuilders = bufferBuilders; + } + + public TerrainBufferBuilder getBufferBuilder(int i) { + return this.bufferBuilders[i]; + } + + private void ensureIndexCapacity(int size) { + if (size > this.indexBufferCapacity) { + int capacity = this.indexBufferCapacity; + int newSize = (capacity + size) * 2; + this.resizeIndexBuffer(newSize); + } + } + + private void resizeIndexBuffer(int i) { + this.bufferPtr = ALLOCATOR.realloc(this.bufferPtr, i); + LOGGER.debug("Needed to grow index buffer: Old size {} bytes, new size {} bytes.", this.indexBufferCapacity, i); + if (this.bufferPtr == 0L) { + throw new OutOfMemoryError("Failed to resize buffer from " + this.indexBufferCapacity + " bytes to " + i + " bytes"); + } else { + this.indexBufferCapacity = i; + } + } + + public void setupQuadSorting(float x, float y, float z) { + this.quadSorter.setQuadSortOrigin(x, y, z); + this.needsSorting = true; + } + + public QuadSorter.SortState getSortState() { + return this.quadSorter.getSortState(); + } + + public void restoreSortState(QuadSorter.SortState sortState) { + this.quadSorter.restoreSortState(sortState); + + this.indexOnly = true; + } + + public void setIndexOnly() { + this.indexOnly = true; + } + + public void begin() { + if (this.building) { + throw new IllegalStateException("Already building!"); + } else { + this.building = true; + } + } + + public void setupQuadSortingPoints() { + TerrainBufferBuilder bufferBuilder = bufferBuilders[QuadFacing.NONE.ordinal()]; + long bufferPtr = bufferBuilder.getPtr(); + int vertexCount = bufferBuilder.getVertices(); + + this.quadSorter.setupQuadSortingPoints(bufferPtr, vertexCount, this.format); + } + + public DrawState endDrawing() { + for (TerrainBufferBuilder bufferBuilder : this.bufferBuilders) { + bufferBuilder.end(); + } + + int vertexCount = this.quadSorter.getVertexCount(); + + int indexCount = vertexCount / 4 * 6; +// int vertexBufferSize = !this.indexOnly ? vertexCount * this.format.getVertexSize() : 0; + + VertexFormat.IndexType indexType = VertexFormat.IndexType.least(indexCount); + boolean sequentialIndexing; +// int size; + + // TODO sorting + if (this.needsSorting) { + int indexBufferSize = indexCount * indexType.bytes; + this.ensureIndexCapacity(indexBufferSize); + + this.quadSorter.putSortedQuadIndices(this, indexType); + + sequentialIndexing = false; +// this.nextElementByte += indexBufferSize; +// size = vertexBufferSize + indexBufferSize; + } else { + sequentialIndexing = true; +// size = vertexBufferSize; + } + +// this.indexBuffer.limit(this.indexCount * indexType.bytes); + +// int ptr = this.renderedBufferPointer; +// this.renderedBufferPointer += size; +// ++this.renderedBufferCount; + + return new DrawState(this.format.getVertexSize(), indexCount, indexType, this.indexOnly, sequentialIndexing); +// return new RenderedBuffer(ptr, drawState); + } + + // TODO hardcoded index type size + public ByteBuffer getIndexBuffer() { + TerrainBufferBuilder bufferBuilder = this.bufferBuilders[QuadFacing.NONE.ordinal()]; +// int indexCount = bufferBuilder.getVertices() * 6 / 4; + int indexCount = this.quadSorter.getVertexCount() * 6 / 4; + + return MemoryUtil.memByteBuffer(this.indexBufferPtr, indexCount * 2); + } + + private void ensureDrawing() { + if (!this.building) { + throw new IllegalStateException("Not building!"); + } + } + + public void reset() { + this.building = false; +// this.quadSorter.reset(); + + this.indexOnly = false; + this.needsSorting = false; + } + + public void clear() { + this.reset(); + + for (TerrainBufferBuilder bufferBuilder : this.bufferBuilders) { + bufferBuilder.clear(); + } + } + +// public void vertex(float x, float y, float z, int color, float u, float v, int light, int packedNormal) { +// final long ptr = this.bufferPtr + this.nextElementByte; +// this.vertexBuilder.vertex(ptr, x, y, z, color, u, v, light, packedNormal); +// this.endVertex(); +// } + + public void setBlockAttributes(BlockState blockState) { + } + +// public long getPtr() { +// return this.bufferPtr + this.nextElementByte; +// } +// +// public int getVertexCount() { +// return vertexCount; +// } + + public record DrawState(int vertexSize, int indexCount, VertexFormat.IndexType indexType, + boolean indexOnly, boolean sequentialIndex) { + + private int indexBufferSize() { + return this.sequentialIndex ? 0 : this.indexCount * this.indexType.bytes; + } + + public int indexCount() { + return this.indexCount; + } + + public VertexFormat.IndexType indexType() { + return this.indexType; + } + + public boolean indexOnly() { + return this.indexOnly; + } + + public boolean sequentialIndex() { + return this.sequentialIndex; + } + } +} From 845e86b98bbf2e072346f00344b65e05a7e1916f Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 20 Sep 2024 13:08:27 +0200 Subject: [PATCH 002/177] Use VertexBuffer usage to determine memory type --- .../vulkanmod/mixin/render/vertex/VertexBufferM.java | 2 +- src/main/java/net/vulkanmod/render/VBO.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java index e9da555003..e355ccadd5 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java @@ -20,7 +20,7 @@ public class VertexBufferM { @Inject(method = "", at = @At("RETURN")) private void constructor(VertexBuffer.Usage usage, CallbackInfo ci) { - vbo = new VBO(); + vbo = new VBO(usage); } @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenBuffers()I")) diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 1ebc59660f..59fb23ba09 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -9,10 +9,7 @@ import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.memory.AutoIndexBuffer; -import net.vulkanmod.vulkan.memory.IndexBuffer; -import net.vulkanmod.vulkan.memory.MemoryTypes; -import net.vulkanmod.vulkan.memory.VertexBuffer; +import net.vulkanmod.vulkan.memory.*; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -22,6 +19,7 @@ @Environment(EnvType.CLIENT) public class VBO { + private final MemoryType memoryType; private VertexBuffer vertexBuffer; private IndexBuffer indexBuffer; @@ -31,7 +29,9 @@ public class VBO { private boolean autoIndexed = false; - public VBO() {} + public VBO(com.mojang.blaze3d.vertex.VertexBuffer.Usage usage) { + this.memoryType = usage == com.mojang.blaze3d.vertex.VertexBuffer.Usage.STATIC ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; + } public void upload(MeshData meshData) { MeshData.DrawState parameters = meshData.drawState(); @@ -51,7 +51,7 @@ private void uploadVertexBuffer(MeshData.DrawState parameters, ByteBuffer data) if (this.vertexBuffer != null) this.vertexBuffer.freeBuffer(); - this.vertexBuffer = new VertexBuffer(data.remaining(), MemoryTypes.GPU_MEM); + this.vertexBuffer = new VertexBuffer(data.remaining(), this.memoryType); this.vertexBuffer.copyToVertexBuffer(parameters.format().getVertexSize(), parameters.vertexCount(), data); } } From 41c3d58a5a861a0f1b4a2f1c8222a58fdf6dcb88 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 20 Sep 2024 13:09:02 +0200 Subject: [PATCH 003/177] Improve clouds rendering --- .../mixin/render/clouds/LevelRendererM.java | 53 +++ .../vulkanmod/render/sky/CloudRenderer.java | 355 ++++++++++++++++++ src/main/resources/vulkanmod.mixins.json | 1 + 3 files changed, 409 insertions(+) create mode 100644 src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java create mode 100644 src/main/java/net/vulkanmod/render/sky/CloudRenderer.java diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java new file mode 100644 index 0000000000..feec45ac05 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -0,0 +1,53 @@ +package net.vulkanmod.mixin.render.clouds; + +import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; +import net.vulkanmod.render.sky.CloudRenderer; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.spongepowered.asm.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 abstract class LevelRendererM { + + @Shadow private int ticks; + @Shadow private @Nullable ClientLevel level; + @Shadow @Final protected static ResourceLocation CLOUDS_LOCATION; + + @Unique + private CloudRenderer cloudRenderer; + + /** + * @author + * @reason + */ + @Overwrite + public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float partialTicks, double camX, double camY, double camZ) { + if (this.cloudRenderer == null) { + this.cloudRenderer = new CloudRenderer(CLOUDS_LOCATION); + } + + this.cloudRenderer.renderClouds(this.level, poseStack, modelView, projection, this.ticks, partialTicks, camX, camY, camZ); + } + + @Inject(method = "allChanged", at = @At("RETURN")) + private void onAllChanged(CallbackInfo ci) { + if (this.cloudRenderer != null) { + this.cloudRenderer.reset(); + } + } + + @Inject(method = "onResourceManagerReload", at = @At("RETURN")) + private void onReload(ResourceManager resourceManager, CallbackInfo ci) { + if (this.cloudRenderer != null) { + this.cloudRenderer.loadTexture(CLOUDS_LOCATION); + } + } + +} diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java new file mode 100644 index 0000000000..d430bc744c --- /dev/null +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -0,0 +1,355 @@ +package net.vulkanmod.render.sky; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.CloudStatus; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.FogRenderer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.Vec3; +import net.vulkanmod.vulkan.util.ColorUtil; +import org.apache.commons.lang3.Validate; +import org.joml.Matrix4f; + +import java.io.IOException; + +public class CloudRenderer { + // TODO move to util + private static final int DIR_NEG_Y_BIT = 1 << 0; + private static final int DIR_POS_Y_BIT = 1 << 1; + private static final int DIR_NEG_X_BIT = 1 << 2; + private static final int DIR_POS_X_BIT = 1 << 3; + private static final int DIR_NEG_Z_BIT = 1 << 4; + private static final int DIR_POS_Z_BIT = 1 << 5; + + private static final int CELL_WIDTH = 12; + private static final int CELL_HEIGHT = 4; + + private CloudGrid cloudGrid; + + private int prevCloudX; + private int prevCloudY; + private int prevCloudZ; + + private CloudStatus prevCloudsType; + private boolean prevInsideClouds; + + private boolean generateClouds; + private VertexBuffer cloudBuffer; + + public CloudRenderer(ResourceLocation textureLocation) { + loadTexture(textureLocation); + } + + public void loadTexture(ResourceLocation location) { + this.cloudGrid = createCloudGrid(location); + } + + public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { + float cloudHeight = level.effects().getCloudHeight(); + + if (Float.isNaN(cloudHeight)) { + return; + } + + Minecraft minecraft = Minecraft.getInstance(); + + double timeOffset = (ticks + partialTicks) * 0.03F; + double centerX = (camX + timeOffset); + double centerZ = camZ + 0.33F * CELL_WIDTH; + double centerY = cloudHeight - (float) camY + 0.33F; + + int centerCellX = (int) Math.floor(centerX / CELL_WIDTH); + int centerCellZ = (int) Math.floor(centerZ / CELL_WIDTH); + + boolean insideClouds = (centerY >= -4.0f && centerY <= 0.0f); + + if (centerCellX != this.prevCloudX || centerCellZ != this.prevCloudZ + || (minecraft.options.getCloudsType() != this.prevCloudsType) + || (this.prevInsideClouds != insideClouds) + || this.cloudBuffer == null) { + this.prevCloudX = centerCellX; + this.prevCloudZ = centerCellZ; + this.prevCloudsType = minecraft.options.getCloudsType(); + this.prevInsideClouds = insideClouds; + this.generateClouds = true; + } + + if (this.generateClouds) { + this.generateClouds = false; + if (this.cloudBuffer != null) { + this.cloudBuffer.close(); + } + + this.cloudBuffer = new VertexBuffer(VertexBuffer.Usage.STATIC); + this.cloudBuffer.bind(); + + MeshData cloudsMesh = this.buildClouds(Tesselator.getInstance(), centerCellX, centerCellZ, centerY); + this.cloudBuffer.upload(cloudsMesh); + VertexBuffer.unbind(); + } + + FogRenderer.levelFogColor(); + + float xTranslation = (float)(centerX - (centerCellX * CELL_WIDTH)); + float yTranslation = (float) centerY; + float zTranslation = (float)(centerZ - (centerCellZ * CELL_WIDTH)); + + poseStack.pushPose(); + poseStack.mulPose(modelView); + poseStack.translate(-xTranslation, yTranslation, -zTranslation); + + Vec3 cloudColor = level.getCloudColor(partialTicks); + RenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); + + this.cloudBuffer.bind(); + + ShaderInstance shaderInstance = GameRenderer.getPositionColorShader(); + RenderSystem.enableBlend(); + RenderSystem.enableDepthTest(); + + boolean fastClouds = this.prevCloudsType == CloudStatus.FAST; + boolean disableCull = insideClouds || (fastClouds && centerY <= 0.0f); + + if (disableCull) { + RenderSystem.disableCull(); + } + + if (!fastClouds) { + RenderSystem.colorMask(false, false, false, false); + this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, shaderInstance); + + RenderSystem.colorMask(true, true, true, true); + } + + this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, shaderInstance); + + RenderSystem.enableCull(); + RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + + VertexBuffer.unbind(); + + poseStack.popPose(); + } + + public void reset() { + if (this.cloudBuffer != null) { + this.cloudBuffer.close(); + this.cloudBuffer = null; + } + } + + private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerCellZ, double cloudY) { + + final int upFaceColor = ColorUtil.RGBA.pack(1.0f, 1.0f, 1.0f, 1.0f); + final int xDirColor = ColorUtil.RGBA.pack(0.9f, 0.9f, 0.9f, 1.0f); + final int downFaceColor = ColorUtil.RGBA.pack(0.7f, 0.7f, 0.7f, 1.0f); + final int zDirColor = ColorUtil.RGBA.pack(0.8f, 0.8f, 0.8f, 1.0f); + + BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + int renderDistance = 32; + boolean insideClouds = this.prevInsideClouds; + + if (this.prevCloudsType == CloudStatus.FANCY) { + + for (int cellX = -renderDistance; cellX < renderDistance; ++cellX) { + for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { + int cellIdx = this.cloudGrid.getWrappedIdx(centerCellX + cellX, centerCellZ + cellZ); + byte renderFaces = this.cloudGrid.renderFaces[cellIdx]; + + float x = cellX * CELL_WIDTH; + float z = cellZ * CELL_WIDTH; + + if ((renderFaces & DIR_POS_Y_BIT) != 0 && cloudY <= 0.0f) { + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, upFaceColor); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, upFaceColor); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, upFaceColor); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, upFaceColor); + } + + if ((renderFaces & DIR_NEG_Y_BIT) != 0 && cloudY >= -CELL_HEIGHT) { + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, downFaceColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, downFaceColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, downFaceColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, downFaceColor); + } + + if ((renderFaces & DIR_POS_X_BIT) != 0 && (x < 1.0f || insideClouds)) { + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, xDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, xDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, xDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, xDirColor); + } + + if ((renderFaces & DIR_NEG_X_BIT) != 0 && (x > -1.0f || insideClouds)) { + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, xDirColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, xDirColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, xDirColor); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, xDirColor); + } + + if ((renderFaces & DIR_POS_Z_BIT) != 0 && (z < 1.0f || insideClouds)) { + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, zDirColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, zDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, zDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, zDirColor); + } + + if ((renderFaces & DIR_NEG_Z_BIT) != 0 && (z > -1.0f || insideClouds)) { + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, zDirColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, zDirColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, zDirColor); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, zDirColor); + } + + } + } + } else { + + for (int cellX = -renderDistance; cellX < renderDistance; ++cellX) { + for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { + int cellIdx = this.cloudGrid.getWrappedIdx(centerCellX + cellX, centerCellZ + cellZ); + byte renderFaces = this.cloudGrid.renderFaces[cellIdx]; + + float x = cellX * CELL_WIDTH; + float z = cellZ * CELL_WIDTH; + + if ((renderFaces & DIR_NEG_Y_BIT) != 0) { + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, upFaceColor); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, upFaceColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, upFaceColor); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, upFaceColor); + } + + } + } + } + + return bufferBuilder.buildOrThrow(); + } + + private static void putVertex(BufferBuilder bufferBuilder, float x, float y, float z, int color) { + bufferBuilder.addVertex(x, y, z).setColor(color); + } + + private static CloudGrid createCloudGrid(ResourceLocation textureLocation) { + ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); + + try { + Resource resource = resourceManager.getResourceOrThrow(textureLocation); + + try (var inputStream = resource.open()) { + NativeImage image = NativeImage.read(inputStream); + + int width = image.getWidth(); + int height = image.getHeight(); + Validate.isTrue(width == height, "Image width and height must be the same"); + + int[] pixels = image.getPixelsRGBA(); + + return new CloudGrid(pixels, width); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + static class CloudGrid { + final int width; + final int[] pixels; + final byte[] renderFaces; + + CloudGrid(int[] pixels, int width) { + this.pixels = pixels; + this.width = width; + + this.renderFaces = computeRenderFaces(); + } + + byte[] computeRenderFaces() { + byte[] renderFaces = new byte[pixels.length]; + + for (int z = 0; z < this.width; z++) { + for (int x = 0; x < this.width; x++) { + int idx = this.getIdx(x, z); + int pixel = this.pixels[idx]; + + if (!hasColor(pixel)) { + continue; + } + + byte faces = DIR_NEG_Y_BIT | DIR_POS_Y_BIT; + + int adjPixel; + + adjPixel = getTexelWrapped(x - 1, z); + if (pixel != adjPixel) { + faces |= DIR_NEG_X_BIT; + } + + adjPixel = getTexelWrapped(x + 1, z); + if (pixel != adjPixel) { + faces |= DIR_POS_X_BIT; + } + + adjPixel = getTexelWrapped(x, z - 1); + if (pixel != adjPixel) { + faces |= DIR_NEG_Z_BIT; + } + + adjPixel = getTexelWrapped(x, z + 1); + if (pixel != adjPixel) { + faces |= DIR_POS_Z_BIT; + } + + renderFaces[idx] = faces; + } + } + + return renderFaces; + } + + int getTexelWrapped(int x, int z) { + if (x < 0) { + x = this.width - 1; + } + + if (x > this.width - 1) { + x = 0; + } + + if (z < 0) { + z = this.width - 1; + } + + if (z > this.width - 1) { + z = 0; + } + + return this.pixels[getIdx(x, z)]; + } + + int getWrappedIdx(int x, int z) { + x = Math.floorMod(x, this.width); + z = Math.floorMod(z, this.width); + + return this.getIdx(x, z); + } + + int getIdx(int x, int z) { + return z * this.width + x; + } + + private static boolean hasColor(int pixel) { + return ((pixel >> 24) & 0xFF) > 1; + } + } +} diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 674e073981..5b3f2ff340 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -47,6 +47,7 @@ "render.RenderSystemMixin", "render.RenderTypeM", "render.ShaderInstanceM", + "render.clouds.LevelRendererM", "render.entity.EntityRendererM", "render.entity.LevelRendererM", "render.entity.model.ModelPartCubeM", From 5921d833fd80193b83de66c5d5527e9d33bc3a74 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 11 Oct 2024 11:25:03 +0200 Subject: [PATCH 004/177] Use sorted index buffer on immediate rendering if needed --- .../mixin/render/BufferUploaderM.java | 5 +- .../mixin/render/RenderSystemMixin.java | 8 +- .../java/net/vulkanmod/vulkan/Drawer.java | 88 +++++++++++-------- .../vulkan/memory/AutoIndexBuffer.java | 23 +++-- 4 files changed, 75 insertions(+), 49 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java index 232c0a436e..a381125a6c 100644 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java @@ -56,7 +56,8 @@ public static void drawWithShader(MeshData meshData) { renderer.bindGraphicsPipeline(pipeline); VTextureSelector.bindShaderTextures(pipeline); renderer.uploadAndBindUBOs(pipeline); - Renderer.getDrawer().draw(meshData.vertexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); + + Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); } meshData.close(); @@ -74,7 +75,7 @@ public static void draw(MeshData meshData) { Pipeline pipeline = renderer.getBoundPipeline(); renderer.uploadAndBindUBOs(pipeline); - Renderer.getDrawer().draw(meshData.vertexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); + Renderer.getDrawer().draw(meshData.vertexBuffer(), null, parameters.mode(), parameters.format(), parameters.vertexCount()); } meshData.close(); diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 4a431ca1cf..03fcbd0f07 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -29,14 +29,17 @@ public abstract class RenderSystemMixin { @Shadow @Final private static Matrix4fStack modelViewStack; @Shadow private static Matrix4f modelViewMatrix; @Shadow private static Matrix4f textureMatrix; + @Shadow @Final private static int[] shaderTextures; @Shadow @Final private static float[] shaderColor; @Shadow @Final private static Vector3f[] shaderLightDirections; - @Shadow @Final private static float[] shaderFogColor; @Shadow private static @Nullable Thread renderThread; + @Shadow public static VertexSorting vertexSorting; + @Shadow private static VertexSorting savedVertexSorting; + @Shadow public static void assertOnRenderThread() { } @@ -372,12 +375,14 @@ public static void setProjectionMatrix(Matrix4f projectionMatrix, VertexSorting if (!isOnRenderThread()) { recordRenderCall(() -> { RenderSystemMixin.projectionMatrix = matrix4f; + RenderSystem.vertexSorting = vertexSorting; VRenderSystem.applyProjectionMatrix(matrix4f); VRenderSystem.calculateMVP(); }); } else { RenderSystemMixin.projectionMatrix = matrix4f; + RenderSystem.vertexSorting = vertexSorting; VRenderSystem.applyProjectionMatrix(matrix4f); VRenderSystem.calculateMVP(); @@ -443,6 +448,7 @@ public static void applyModelViewMatrix() { @Overwrite(remap = false) private static void _restoreProjectionMatrix() { projectionMatrix = savedProjectionMatrix; + vertexSorting = savedVertexSorting; VRenderSystem.applyProjectionMatrix(projectionMatrix); VRenderSystem.calculateMVP(); diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index 40b88274b1..74461c3854 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -23,12 +23,15 @@ public class Drawer { private int framesNum; private VertexBuffer[] vertexBuffers; + private IndexBuffer[] indexBuffers; + private final AutoIndexBuffer quadsIndexBuffer; private final AutoIndexBuffer quadsIntIndexBuffer; private final AutoIndexBuffer linesIndexBuffer; private final AutoIndexBuffer debugLineStripIndexBuffer; private final AutoIndexBuffer triangleFanIndexBuffer; private final AutoIndexBuffer triangleStripIndexBuffer; + private UniformBuffer[] uniformBuffers; private int currentFrame; @@ -58,6 +61,14 @@ public void createResources(int framesNum) { this.vertexBuffers = new VertexBuffer[framesNum]; Arrays.setAll(this.vertexBuffers, i -> new VertexBuffer(INITIAL_VB_SIZE, MemoryTypes.HOST_MEM)); + if (this.indexBuffers != null) { + Arrays.stream(this.indexBuffers).iterator().forEachRemaining( + Buffer::freeBuffer + ); + } + this.indexBuffers = new IndexBuffer[framesNum]; + Arrays.setAll(this.indexBuffers, i -> new IndexBuffer(INITIAL_UB_SIZE, MemoryTypes.HOST_MEM)); + if (this.uniformBuffers != null) { Arrays.stream(this.uniformBuffers).iterator().forEachRemaining( Buffer::freeBuffer @@ -69,54 +80,38 @@ public void createResources(int framesNum) { public void resetBuffers(int currentFrame) { this.vertexBuffers[currentFrame].reset(); + this.indexBuffers[currentFrame].reset(); this.uniformBuffers[currentFrame].reset(); } - public void draw(ByteBuffer buffer, VertexFormat.Mode mode, VertexFormat vertexFormat, int vertexCount) { - AutoIndexBuffer autoIndexBuffer; - int indexCount; + public void draw(ByteBuffer vertexData, VertexFormat.Mode mode, VertexFormat vertexFormat, int vertexCount) { + draw(vertexData, null, mode, vertexFormat, vertexCount); + } + public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode mode, VertexFormat vertexFormat, int vertexCount) { VertexBuffer vertexBuffer = this.vertexBuffers[this.currentFrame]; - vertexBuffer.copyToVertexBuffer(vertexFormat.getVertexSize(), vertexCount, buffer); + vertexBuffer.copyToVertexBuffer(vertexFormat.getVertexSize(), vertexCount, vertexData); - switch (mode) { - case QUADS -> { - indexCount = vertexCount * 3 / 2; + if (indexData != null) { + IndexBuffer indexBuffer = this.indexBuffers[this.currentFrame]; + indexBuffer.copyBuffer(indexData); - autoIndexBuffer = indexCount > AutoIndexBuffer.U16_MAX_INDEX_COUNT - ? this.quadsIntIndexBuffer : this.quadsIndexBuffer; - } - case LINES -> { - autoIndexBuffer = this.linesIndexBuffer; - indexCount = vertexCount * 3 / 2; - } - case TRIANGLE_FAN -> { - autoIndexBuffer = this.triangleFanIndexBuffer; - indexCount = (vertexCount - 2) * 3; - } - case TRIANGLE_STRIP, LINE_STRIP -> { - autoIndexBuffer = this.triangleStripIndexBuffer; - indexCount = (vertexCount - 2) * 3; - } - case DEBUG_LINE_STRIP -> { - autoIndexBuffer = this.debugLineStripIndexBuffer; - indexCount = (vertexCount - 1) * 2; - } - case TRIANGLES, DEBUG_LINES -> { - indexCount = 0; - autoIndexBuffer = null; - } - default -> throw new RuntimeException(String.format("unknown drawMode: %s", mode)); + int indexCount = vertexCount * 3 / 2; + + drawIndexed(vertexBuffer, indexBuffer, indexCount); } + else { + AutoIndexBuffer autoIndexBuffer = getAutoIndexBuffer(mode, vertexCount); - if (indexCount > 0) { - autoIndexBuffer.checkCapacity(vertexCount); + if (autoIndexBuffer != null) { + int indexCount = autoIndexBuffer.getIndexCount(vertexCount); - drawIndexed(vertexBuffer, autoIndexBuffer.getIndexBuffer(), indexCount); - } else { - draw(vertexBuffer, vertexCount); + drawIndexed(vertexBuffer, autoIndexBuffer.getIndexBuffer(), indexCount); + } + else { + draw(vertexBuffer, vertexCount); + } } - } public void drawIndexed(VertexBuffer vertexBuffer, IndexBuffer indexBuffer, int indexCount) { @@ -150,9 +145,11 @@ public void cleanUpResources() { buffer = this.vertexBuffers[i]; MemoryManager.freeBuffer(buffer.getId(), buffer.getAllocation()); - buffer = this.uniformBuffers[i]; + buffer = this.indexBuffers[i]; MemoryManager.freeBuffer(buffer.getId(), buffer.getAllocation()); + buffer = this.uniformBuffers[i]; + MemoryManager.freeBuffer(buffer.getId(), buffer.getAllocation()); } this.quadsIndexBuffer.freeBuffer(); @@ -185,4 +182,19 @@ public UniformBuffer getUniformBuffer() { return this.uniformBuffers[this.currentFrame]; } + private AutoIndexBuffer getAutoIndexBuffer(VertexFormat.Mode mode, int vertexCount) { + return switch (mode) { + case QUADS -> { + int indexCount = vertexCount * 3 / 2; + + yield indexCount > AutoIndexBuffer.U16_MAX_INDEX_COUNT + ? this.quadsIntIndexBuffer : this.quadsIndexBuffer; + } + case LINES -> this.linesIndexBuffer; + case TRIANGLE_FAN -> this.triangleFanIndexBuffer; + case TRIANGLE_STRIP, LINE_STRIP -> this.triangleStripIndexBuffer; + case DEBUG_LINE_STRIP -> this.debugLineStripIndexBuffer; + case TRIANGLES, DEBUG_LINES -> null; + }; + } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java index 98795ff19e..7ac57e683f 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java @@ -50,6 +50,21 @@ private void createIndexBuffer(int vertexCount) { MemoryUtil.memFree(buffer); } + public int getIndexCount(int vertexCount) { + switch (this.drawType) { + case QUADS, LINES -> { + return vertexCount * 3 / 2; + } + case TRIANGLE_FAN, TRIANGLE_STRIP -> { + return (vertexCount - 2) * 3; + } + case DEBUG_LINE_STRIP -> { + return (vertexCount - 1) * 2; + } + default -> throw new RuntimeException(String.format("unknown drawMode: %s", this.drawType)); + } + } + public void checkCapacity(int vertexCount) { if(vertexCount > this.vertexCount) { int newVertexCount = this.vertexCount * 2; @@ -202,14 +217,6 @@ public enum DrawType { this.n = n; } - public static int getIndexCount(DrawType drawType, int vertexCount) { - return switch (drawType) { - case QUADS, LINES -> vertexCount * 3 / 2; - case TRIANGLE_FAN, TRIANGLE_STRIP -> (vertexCount - 2) * 3; - default -> 0; - }; - } - public static int getQuadIndexCount(int vertexCount) { return vertexCount * 3 / 2; } From 863eaeb944ff5cb7040c05e655f83ee669e6bd6f Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 12 Oct 2024 11:48:12 +0200 Subject: [PATCH 005/177] Refactor skip allocation mixin to prevent null pointer exception --- .../vulkanmod/mixin/chunk/RenderBuffersM.java | 16 ---------------- .../mixin/chunk/SectionBufferBuilderPoolM.java | 15 +++++++++++++++ src/main/resources/vulkanmod.mixins.json | 2 +- 3 files changed, 16 insertions(+), 17 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/mixin/chunk/RenderBuffersM.java create mode 100644 src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java diff --git a/src/main/java/net/vulkanmod/mixin/chunk/RenderBuffersM.java b/src/main/java/net/vulkanmod/mixin/chunk/RenderBuffersM.java deleted file mode 100644 index 743885028b..0000000000 --- a/src/main/java/net/vulkanmod/mixin/chunk/RenderBuffersM.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.vulkanmod.mixin.chunk; - -import net.minecraft.client.renderer.RenderBuffers; -import net.minecraft.client.renderer.SectionBufferBuilderPool; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(RenderBuffers.class) -public class RenderBuffersM { - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/SectionBufferBuilderPool;allocate(I)Lnet/minecraft/client/renderer/SectionBufferBuilderPool;")) - private SectionBufferBuilderPool red2(int i) { - return null; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java b/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java new file mode 100644 index 0000000000..18e653849b --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java @@ -0,0 +1,15 @@ +package net.vulkanmod.mixin.chunk; + +import net.minecraft.client.renderer.SectionBufferBuilderPool; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(SectionBufferBuilderPool.class) +public class SectionBufferBuilderPoolM { + + @ModifyVariable(method = "allocate", at = @At("STORE"), ordinal = 1) + private static int skipAllocation(int value) { + return 0; + } +} diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 5b3f2ff340..fafeb90adf 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -15,7 +15,7 @@ "chunk.DirectionMixin", "chunk.FrustumMixin", "chunk.LevelRendererMixin", - "chunk.RenderBuffersM", + "chunk.SectionBufferBuilderPoolM", "chunk.SectionRenderDispatcherM", "chunk.ViewAreaM", "chunk.VisibilitySetMixin", From 5774bf319e5f49ccb14825ed8a28c5505101ef94 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:51:04 +0200 Subject: [PATCH 006/177] Implement Fabric Rendering API - Refactor - Fix biome blending not applied in some cases --- build.gradle | 4 +- gradle.properties | 2 +- src/main/java/net/vulkanmod/Initializer.java | 4 + .../net/vulkanmod/config/option/Options.java | 2 + .../mixin/render/block/BakedQuadM.java | 37 +- .../mixin/render/entity/model/ModelPartM.java | 4 +- .../mixin/render/frapi/BakedModelM.java | 29 ++ .../render/frapi/ItemRendererAccessor.java | 14 + .../mixin/render/frapi/ItemRendererMixin.java | 53 +++ .../render/frapi/ModelBlockRendererM.java | 50 +++ .../frapi/fluid/FluidRenderingImplMixin.java | 26 ++ .../mixin/render/vertex/BufferBuilderM.java | 4 +- .../mixin/render/vertex/VertexConsumerM.java | 1 - .../mixin/vertex/VertexMultiConsumersM.java | 8 +- .../render/chunk/ChunkAreaManager.java | 2 + .../vulkanmod/render/chunk/RenderSection.java | 2 +- .../vulkanmod/render/chunk/WorldRenderer.java | 6 +- .../render/chunk/buffer/DrawBuffers.java | 75 ++-- .../render/chunk/build/BlockRenderer.java | 235 ------------ .../render/chunk/build/RenderRegion.java | 1 + .../chunk/build/{biome => color}/BoxBlur.java | 4 +- .../chunk/build/{ => color}/TintCache.java | 38 +- .../chunk/build/frapi/VulkanModRenderer.java | 55 +++ .../chunk/build/frapi/helper/ColorHelper.java | 116 ++++++ .../build/frapi/helper/GeometryHelper.java | 239 +++++++++++++ .../build/frapi/helper/NormalHelper.java | 191 ++++++++++ .../build/frapi/helper/TextureHelper.java | 110 ++++++ .../frapi/material/MaterialFinderImpl.java | 112 ++++++ .../frapi/material/MaterialViewImpl.java | 118 ++++++ .../frapi/material/RenderMaterialImpl.java | 52 +++ .../build/frapi/mesh/EncodingFormat.java | 152 ++++++++ .../build/frapi/mesh/MeshBuilderImpl.java | 84 +++++ .../chunk/build/frapi/mesh/MeshImpl.java | 78 ++++ .../build/frapi/mesh/MutableQuadViewImpl.java | 227 ++++++++++++ .../chunk/build/frapi/mesh/QuadViewImpl.java | 337 ++++++++++++++++++ .../render/AbstractBlockRenderContext.java | 296 +++++++++++++++ .../frapi/render/AbstractRenderContext.java | 131 +++++++ .../frapi/render/BlockRenderContext.java | 109 ++++++ .../build/frapi/render/ItemRenderContext.java | 333 +++++++++++++++++ .../chunk/build/light/LightPipeline.java | 4 +- .../build/light/data/ArrayLightDataCache.java | 10 + .../build/light/flat/FlatLightPipeline.java | 4 +- .../light/smooth/NewSmoothLightPipeline.java | 12 +- .../light/smooth/SmoothLightPipeline.java | 12 +- .../chunk/build/renderer/BlockRenderer.java | 147 ++++++++ .../build/renderer/DefaultFluidRenderers.java | 17 + .../FluidRenderer.java} | 61 ++-- .../render/chunk/build/task/BuildTask.java | 33 +- .../render/chunk/build/task/ChunkTask.java | 1 - .../build/{ => task}/TaskDispatcher.java | 5 +- .../chunk/build/thread/BuilderResources.java | 44 ++- .../render/chunk/cull/QuadFacing.java | 34 +- .../render/chunk/graph/SectionGraph.java | 2 +- .../render/model/quad/ModelQuad.java | 26 +- .../render/model/quad/ModelQuadFlags.java | 10 +- .../{QuadView.java => ModelQuadView.java} | 9 +- .../render/vertex/TerrainBufferBuilder.java | 68 +++- .../render/vertex/TerrainBuilder.java | 31 +- .../render/vertex/TerrainRenderType.java | 23 ++ .../render/vertex/VertexBuilder.java | 69 ++++ .../I32_SNorm.java} | 12 +- .../net/vulkanmod/vulkan/util/ColorUtil.java | 5 +- src/main/resources/fabric.mod.json | 6 +- src/main/resources/vulkanmod.mixins.json | 8 +- 64 files changed, 3527 insertions(+), 467 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java rename src/main/java/net/vulkanmod/render/chunk/build/{biome => color}/BoxBlur.java (96%) rename src/main/java/net/vulkanmod/render/chunk/build/{ => color}/TintCache.java (81%) create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java rename src/main/java/net/vulkanmod/render/chunk/build/{LiquidRenderer.java => renderer/FluidRenderer.java} (88%) rename src/main/java/net/vulkanmod/render/chunk/build/{ => task}/TaskDispatcher.java (97%) rename src/main/java/net/vulkanmod/render/model/quad/{QuadView.java => ModelQuadView.java} (71%) rename src/main/java/net/vulkanmod/render/vertex/{VertexUtil.java => format/I32_SNorm.java} (73%) diff --git a/build.gradle b/build.gradle index 2f68c914c2..d7efdffb06 100644 --- a/build.gradle +++ b/build.gradle @@ -23,7 +23,6 @@ dependencies { // Fabric API. This is technically optional, but you probably want it anyway. modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - // Needed in order to load mod namespace ext.includeModule = { name -> var module = fabricApi.module(name, project.fabric_version) modImplementation(module) @@ -32,8 +31,9 @@ dependencies { includeModule("fabric-api-base") includeModule("fabric-resource-loader-v0") - includeModule("fabric-rendering-fluids-v1") includeModule("fabric-rendering-v1") + includeModule("fabric-renderer-api-v1") + includeModule("fabric-rendering-fluids-v1") } project.ext.lwjglVersion = "3.3.3" diff --git a/gradle.properties b/gradle.properties index 83d8ea876c..d0a493533a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version=0.16.5 fabric_version=0.102.0+1.21 # Mod Properties -mod_version = 0.4.8_dev +mod_version = 0.5.0_dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21 diff --git a/src/main/java/net/vulkanmod/Initializer.java b/src/main/java/net/vulkanmod/Initializer.java index e99a46eb1d..ea9360265c 100644 --- a/src/main/java/net/vulkanmod/Initializer.java +++ b/src/main/java/net/vulkanmod/Initializer.java @@ -1,10 +1,12 @@ package net.vulkanmod; import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.renderer.v1.RendererAccess; import net.fabricmc.loader.api.FabricLoader; import net.vulkanmod.config.Config; import net.vulkanmod.config.Platform; import net.vulkanmod.config.video.VideoModeManager; +import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -35,6 +37,8 @@ public void onInitializeClient() { .resolve("vulkanmod_settings.json"); CONFIG = loadConfig(configPath); + + RendererAccess.INSTANCE.registerRenderer(VulkanModRenderer.INSTANCE); } private static Config loadConfig(Path path) { diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index 5e34dc547e..af6b99e430 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -9,6 +9,7 @@ import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.video.VideoModeSet; import net.vulkanmod.render.chunk.build.light.LightMode; +import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.device.DeviceManager; @@ -252,6 +253,7 @@ public static OptionBlock[] getOptimizationOpts() { new SwitchOption(Component.translatable("vulkanmod.options.uniqueOpaqueLayer"), value -> { config.uniqueOpaqueLayer = value; + TerrainRenderType.updateMapping(); minecraft.levelRenderer.allChanged(); }, () -> config.uniqueOpaqueLayer) diff --git a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java index 9c315f1bec..39a05b21c1 100644 --- a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java +++ b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java @@ -3,7 +3,9 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; -import net.vulkanmod.render.model.quad.QuadView; +import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.model.quad.ModelQuadFlags; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -15,16 +17,28 @@ import static net.vulkanmod.render.model.quad.ModelQuad.VERTEX_SIZE; @Mixin(BakedQuad.class) -public class BakedQuadM implements QuadView { +public class BakedQuadM implements ModelQuadView { @Shadow @Final protected int[] vertices; @Shadow @Final protected Direction direction; @Shadow @Final protected int tintIndex; + private int flags; + private int normal; + private QuadFacing facing; @Inject(method = "", at = @At("RETURN")) - private void onInit(int[] vertices, int tintIndex, Direction direction, TextureAtlasSprite textureAtlasSprite, boolean shade, CallbackInfo ci) { - this.flags = ModelQuadFlags.getQuadFlags(vertices, direction); + private void onInit(int[] vertices, int tintIndex, Direction face, TextureAtlasSprite textureAtlasSprite, boolean shade, CallbackInfo ci) { + this.flags = ModelQuadFlags.getQuadFlags(this, face); + + if (face != null) { + this.facing = QuadFacing.fromDirection(face); + this.normal = NormalHelper.packedNormalFromDirection(face); + } else { + int packedNormal = NormalHelper.computePackedNormal(this); + this.facing = QuadFacing.fromNormal(packedNormal); + this.normal = packedNormal; + } } @Override @@ -67,11 +81,26 @@ public int getColorIndex() { return this.tintIndex; } + @Override + public Direction lightFace() { + return this.direction; + } + @Override public Direction getFacingDirection() { return this.direction; } + @Override + public QuadFacing getQuadFacing() { + return this.facing; + } + + @Override + public int getNormal() { + return this.normal; + } + @Override public boolean isTinted() { return this.tintIndex != -1; diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java index 7ad232bbc8..ecb2ffe272 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java @@ -6,7 +6,7 @@ import net.vulkanmod.interfaces.ExtendedVertexBuilder; import net.vulkanmod.interfaces.ModelPartCubeMixed; import net.vulkanmod.render.model.CubeModel; -import net.vulkanmod.render.vertex.VertexUtil; +import net.vulkanmod.render.vertex.format.I32_SNorm; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -52,7 +52,7 @@ public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int matrix3f.transform(this.normal.set(polygon.normal)); this.normal.normalize(); - int packedNormal = VertexUtil.packNormal(normal.x(), normal.y(), normal.z()); + int packedNormal = I32_SNorm.packNormal(normal.x(), normal.y(), normal.z()); ModelPart.Vertex[] vertices = polygon.vertices; diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java new file mode 100644 index 0000000000..b8decdc335 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java @@ -0,0 +1,29 @@ +package net.vulkanmod.mixin.render.frapi; + +import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; +import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext; +import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; +import org.spongepowered.asm.mixin.Mixin; + +import java.util.function.Supplier; + +@Mixin(BakedModel.class) +public interface BakedModelM extends FabricBakedModel { + + @Override + default void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { + ((AbstractBlockRenderContext) context).emitBlockQuads((BakedModel) this, state, randomSupplier, context); + } + + @Override + default void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { + ((ItemRenderContext) context).emitItemQuads((BakedModel) this, null, randomSupplier); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java new file mode 100644 index 0000000000..1eca3abcfc --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java @@ -0,0 +1,14 @@ +package net.vulkanmod.mixin.render.frapi; + +import net.minecraft.client.renderer.entity.ItemRenderer; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(ItemRenderer.class) +public interface ItemRendererAccessor { + @Invoker("hasAnimatedTexture") + static boolean hasAnimatedTexture(ItemStack stack) { + throw new AssertionError(); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java new file mode 100644 index 0000000000..5ab6450913 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.mixin.render.frapi; + +import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +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.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import net.minecraft.client.color.item.ItemColors; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.ItemRenderer; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import com.mojang.blaze3d.vertex.PoseStack; + +@Mixin(ItemRenderer.class) +public abstract class ItemRendererMixin { + @Final + @Shadow + private ItemColors itemColors; + + @Unique + private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(() -> new ItemRenderContext(itemColors)); + + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/resources/model/BakedModel;isCustomRenderer()Z"), method = "render", cancellable = true) + public void hook_renderItem(ItemStack stack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int light, int overlay, BakedModel model, CallbackInfo ci) { + if (!model.isVanillaAdapter()) { + fabric_contexts.get().renderModel(stack, transformMode, invert, matrixStack, vertexConsumerProvider, light, overlay, model); + matrixStack.popPose(); + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java new file mode 100644 index 0000000000..d89759594f --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.mixin.render.frapi; + +import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +@Mixin(ModelBlockRenderer.class) +public abstract class ModelBlockRendererM { + + // TODO ThreadLocal look ups are slow, same goes for ItemRendererMixin + @Unique + private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(BlockRenderContext::new); + + @Inject(at = @At("HEAD"), method = "tesselateBlock", cancellable = true) + private void hookRender(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrix, VertexConsumer buffer, boolean cull, RandomSource rand, long seed, int overlay, CallbackInfo ci) { + if (!model.isVanillaAdapter()) { + BlockRenderContext context = fabric_contexts.get(); + context.render(blockView, model, state, pos, matrix, buffer, cull, rand, seed, overlay); + ci.cancel(); + } + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java new file mode 100644 index 0000000000..4565922c98 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java @@ -0,0 +1,26 @@ +package net.vulkanmod.mixin.render.frapi.fluid; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler; +import net.fabricmc.fabric.impl.client.rendering.fluid.FluidRenderingImpl; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.vulkanmod.render.chunk.build.renderer.DefaultFluidRenderers; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@SuppressWarnings("UnstableApiUsage") +@Mixin(FluidRenderingImpl.class) +public class FluidRenderingImplMixin { + + /** + * @author + * @reason + */ + @Overwrite + public static void renderDefault(FluidRenderHandler handler, BlockAndTintGetter world, BlockPos pos, VertexConsumer vertexConsumer, BlockState blockState, FluidState fluidState) { + DefaultFluidRenderers.add(handler); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java index 4f7335a4c4..8187882fd3 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java @@ -2,7 +2,7 @@ import com.mojang.blaze3d.vertex.*; import net.vulkanmod.interfaces.ExtendedVertexBuilder; -import net.vulkanmod.render.vertex.VertexUtil; +import net.vulkanmod.render.vertex.format.I32_SNorm; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -143,7 +143,7 @@ public void addVertex(float x, float y, float z, int color, float u, float v, in MemoryUtil.memPutInt(ptr + i, light); - int temp = VertexUtil.packNormal(normalX, normalY, normalZ); + int temp = I32_SNorm.packNormal(normalX, normalY, normalZ); MemoryUtil.memPutInt(ptr + i + 4, temp); } else { VertexConsumer.super.addVertex(x, y, z, color, u, v, overlay, light, normalX, normalY, normalZ); diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java index c3ec70b349..4c158910a8 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java @@ -4,7 +4,6 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Vec3i; -import net.vulkanmod.render.vertex.VertexUtil; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Matrix4f; import org.joml.Vector3f; diff --git a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java index 280f914d08..842c44fd2b 100644 --- a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java +++ b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java @@ -5,7 +5,7 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.core.Direction; import net.vulkanmod.interfaces.ExtendedVertexBuilder; -import net.vulkanmod.render.vertex.VertexUtil; +import net.vulkanmod.render.vertex.format.I32_SNorm; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; @@ -115,9 +115,9 @@ private void checkDelegates(VertexConsumer vertexConsumer, PoseStack.Pose pose, @Override public void vertex(float x, float y, float z, int packedColor, float u, float v, int overlay, int light, int packedNormal) { - float nx = VertexUtil.unpackN1(packedNormal); - float ny = VertexUtil.unpackN2(packedNormal); - float nz = VertexUtil.unpackN3(packedNormal); + float nx = I32_SNorm.unpackX(packedNormal); + float ny = I32_SNorm.unpackY(packedNormal); + float nz = I32_SNorm.unpackZ(packedNormal); normal.set(nx, ny, nz); position.set(x, y , z, 1.0f); diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java index aa17b50478..0541706363 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java @@ -12,6 +12,8 @@ public class ChunkAreaManager { public static final int WIDTH = 8; public static final int HEIGHT = 8; + public static final int AREA_SIZE = WIDTH * WIDTH * HEIGHT; + public static final int AREA_SH_XZ = Util.flooredLog(WIDTH); public static final int AREA_SH_Y = Util.flooredLog(HEIGHT); diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index 5618f6c94a..f6f13d0524 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -9,7 +9,7 @@ import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; -import net.vulkanmod.render.chunk.build.TaskDispatcher; +import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.build.task.BuildTask; import net.vulkanmod.render.chunk.build.task.ChunkTask; import net.vulkanmod.render.chunk.build.task.CompiledSection; diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index dca14f636d..7385f7db8c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -26,9 +26,8 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.buffer.DrawBuffers; -import net.vulkanmod.render.chunk.build.BlockRenderer; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; -import net.vulkanmod.render.chunk.build.TaskDispatcher; +import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.build.task.ChunkTask; import net.vulkanmod.render.chunk.graph.SectionGraph; import net.vulkanmod.render.profiling.BuildTimeProfiler; @@ -92,8 +91,7 @@ private WorldRenderer(RenderBuffers renderBuffers) { this.taskDispatcher = new TaskDispatcher(); ChunkTask.setTaskDispatcher(this.taskDispatcher); allocateIndirectBuffers(); - - BlockRenderer.setBlockColors(this.minecraft.getBlockColors()); + TerrainRenderType.updateMapping(); Renderer.getInstance().addOnResizeCallback(() -> { if (this.indirectBuffers.length != Renderer.getFramesNum()) diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 3d562d1435..10b3b79b3b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -1,9 +1,9 @@ package net.vulkanmod.render.chunk.buffer; import net.minecraft.world.phys.Vec3; -import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.ChunkArea; +import net.vulkanmod.render.chunk.ChunkAreaManager; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.build.UploadBuffer; import net.vulkanmod.render.chunk.cull.QuadFacing; @@ -26,6 +26,11 @@ public class DrawBuffers { private static final int VERTEX_SIZE = PipelineManager.TERRAIN_VERTEX_FORMAT.getVertexSize(); private static final int INDEX_SIZE = Short.BYTES; + + private static final int CMD_STRIDE = 32; + + private static final long cmdBufferPtr = MemoryUtil.nmemAlignedAlloc(CMD_STRIDE, (long) ChunkAreaManager.AREA_SIZE * QuadFacing.COUNT * CMD_STRIDE); + private final int index; private final Vector3i origin; private final int minHeight; @@ -45,7 +50,7 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType var vertexBuffers = buffer.getVertexBuffers(); if (buffer.indexOnly) { - DrawParameters drawParameters = section.getDrawParameters(renderType, QuadFacing.NONE.ordinal()); + DrawParameters drawParameters = section.getDrawParameters(renderType, QuadFacing.UNDEFINED.ordinal()); AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); drawParameters.firstIndex = segment.offset / INDEX_SIZE; @@ -70,7 +75,7 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType indexCount = vertexBuffer.limit() / VERTEX_SIZE * 6 / 4; } - if (i == QuadFacing.NONE.ordinal() && !buffer.autoIndices) { + if (i == QuadFacing.UNDEFINED.ordinal() && !buffer.autoIndices) { if (this.indexBuffer == null) { this.indexBuffer = new AreaBuffer(AreaBuffer.Usage.INDEX, 60000, INDEX_SIZE); } @@ -79,10 +84,8 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType firstIndex = segment.offset / INDEX_SIZE; } -// drawParameters.indexCount = buffer.indexCount; drawParameters.firstIndex = firstIndex; drawParameters.vertexOffset = vertexOffset; - drawParameters.indexCount = indexCount; } @@ -135,51 +138,45 @@ private void updateChunkAreaOrigin(VkCommandBuffer commandBuffer, Pipeline pipel } public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuffer, StaticQueue queue, TerrainRenderType terrainRenderType) { + long bufferPtr = cmdBufferPtr; - try (MemoryStack stack = MemoryStack.stackPush()) { - - ByteBuffer byteBuffer = stack.malloc(20 * queue.size() * 7); - long bufferPtr = MemoryUtil.memAddress0(byteBuffer); + boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; - boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; - - int drawCount = 0; - for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { + int drawCount = 0; + for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { - final RenderSection section = iterator.next(); + final RenderSection section = iterator.next(); - int mask = getMask(cameraPos, section); + int mask = getMask(cameraPos, section); - for (int i = 0; i < QuadFacing.COUNT; i++) { + for (int i = 0; i < QuadFacing.COUNT; i++) { - if((mask & 1 << i) == 0) - continue; + if ((mask & 1 << i) == 0) + continue; - final DrawParameters drawParameters = section.getDrawParameters(terrainRenderType, i); + final DrawParameters drawParameters = section.getDrawParameters(terrainRenderType, i); - if (drawParameters.indexCount <= 0) - continue; + if (drawParameters.indexCount <= 0) + continue; - long ptr = bufferPtr + (drawCount * 20L); - MemoryUtil.memPutInt(ptr, drawParameters.indexCount); - MemoryUtil.memPutInt(ptr + 4, 1); - MemoryUtil.memPutInt(ptr + 8, drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex); - MemoryUtil.memPutInt(ptr + 12, drawParameters.vertexOffset); - MemoryUtil.memPutInt(ptr + 16, drawParameters.baseInstance); + long ptr = bufferPtr + ((long) drawCount * CMD_STRIDE); + MemoryUtil.memPutInt(ptr, drawParameters.indexCount); + MemoryUtil.memPutInt(ptr + 4, 1); + MemoryUtil.memPutInt(ptr + 8, drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex); + MemoryUtil.memPutInt(ptr + 12, drawParameters.vertexOffset); + MemoryUtil.memPutInt(ptr + 16, drawParameters.baseInstance); - drawCount++; - } + drawCount++; } - - if (drawCount == 0) return; - - indirectBuffer.recordCopyCmd(byteBuffer.position(0)); - - - vkCmdDrawIndexedIndirect(Renderer.getCommandBuffer(), indirectBuffer.getId(), indirectBuffer.getOffset(), drawCount, 20); } + if (drawCount == 0) + return; + + ByteBuffer byteBuffer = MemoryUtil.memByteBuffer(cmdBufferPtr, queue.size() * QuadFacing.COUNT * CMD_STRIDE); + indirectBuffer.recordCopyCmd(byteBuffer.position(0)); + vkCmdDrawIndexedIndirect(Renderer.getCommandBuffer(), indirectBuffer.getId(), indirectBuffer.getOffset(), drawCount, CMD_STRIDE); } public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue queue, TerrainRenderType renderType) { @@ -213,7 +210,7 @@ private int getMask(Vec3 camera, RenderSection section) { final int secY = section.yOffset; final int secZ = section.zOffset; - int mask = 1 << QuadFacing.NONE.ordinal(); + int mask = 1 << QuadFacing.UNDEFINED.ordinal(); mask |= camera.x - secX >= 0 ? 1 << QuadFacing.X_POS.ordinal() : 0; mask |= camera.y - secY >= 0 ? 1 << QuadFacing.Y_POS.ordinal() : 0; @@ -223,22 +220,18 @@ private int getMask(Vec3 camera, RenderSection section) { mask |= camera.z - (secZ + 16) < 0 ? 1 << QuadFacing.Z_NEG.ordinal() : 0; return mask; -// return 0xFF; } public void bindBuffers(VkCommandBuffer commandBuffer, Pipeline pipeline, TerrainRenderType terrainRenderType, double camX, double camY, double camZ) { - try (MemoryStack stack = MemoryStack.stackPush()) { var vertexBuffer = getAreaBuffer(terrainRenderType); nvkCmdBindVertexBuffers(commandBuffer, 0, 1, stack.npointer(vertexBuffer.getId()), stack.npointer(0)); updateChunkAreaOrigin(commandBuffer, pipeline, camX, camY, camZ, stack); } - // TODO index buffer if (terrainRenderType == TerrainRenderType.TRANSLUCENT && this.indexBuffer != null) { vkCmdBindIndexBuffer(commandBuffer, this.indexBuffer.getId(), 0, VK_INDEX_TYPE_UINT16); } - } public void releaseBuffers() { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java deleted file mode 100644 index 592a7055c9..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/BlockRenderer.java +++ /dev/null @@ -1,235 +0,0 @@ -package net.vulkanmod.render.chunk.build; - -import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.BooleanOp; -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; -import net.vulkanmod.Initializer; -import net.vulkanmod.render.chunk.build.light.LightPipeline; -import net.vulkanmod.render.chunk.build.light.data.QuadLightData; -import net.vulkanmod.render.chunk.build.thread.BuilderResources; -import net.vulkanmod.render.chunk.cull.QuadFacing; -import net.vulkanmod.render.model.quad.QuadUtils; -import net.vulkanmod.render.model.quad.QuadView; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; -import net.vulkanmod.render.vertex.TerrainBuilder; -import net.vulkanmod.render.vertex.TerrainRenderType; -import net.vulkanmod.render.vertex.VertexUtil; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Vector3f; - -import java.util.List; - -public class BlockRenderer { - - static final Direction[] DIRECTIONS = Direction.values(); - private static BlockColors blockColors; - - RandomSource randomSource = RandomSource.createNewThreadLocalInstance(); - - Vector3f pos; - BlockPos blockPos; - BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos(); - - BuilderResources resources; - - BlockState blockState; - - final boolean backFaceCulling = Initializer.CONFIG.backFaceCulling; - - private TerrainRenderType renderType; - - public void setResources(BuilderResources resources) { - this.resources = resources; - } - - final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { - protected void rehash(int i) { - } - }; - - public BlockRenderer() { - occlusionCache.defaultReturnValue((byte) 127); - } - - public static void setBlockColors(BlockColors blockColors) { - BlockRenderer.blockColors = blockColors; - } - - public void renderBlock(BlockState blockState, BlockPos blockPos, TerrainRenderType renderType, Vector3f pos, TerrainBuilder bufferBuilder) { - this.pos = pos; - this.blockPos = blockPos; - this.blockState = blockState; - this.renderType = renderType; - - long seed = blockState.getSeed(blockPos); - - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); - tessellateBlock(model, bufferBuilder, seed); - } - - public void tessellateBlock(BakedModel bakedModel, TerrainBuilder bufferBuilder, long seed) { - Vec3 offset = blockState.getOffset(resources.region, blockPos); - - pos.add((float) offset.x, (float) offset.y, (float) offset.z); - - boolean useAO = Minecraft.useAmbientOcclusion() && blockState.getLightEmission() == 0 && bakedModel.useAmbientOcclusion(); - LightPipeline lightPipeline = useAO ? resources.smoothLightPipeline : resources.flatLightPipeline; - - //noinspection ForLoopReplaceableByForEach - for (int i = 0; i < DIRECTIONS.length; ++i) { - Direction direction = DIRECTIONS[i]; - - randomSource.setSeed(seed); - List quads = bakedModel.getQuads(blockState, direction, randomSource); - - if (!quads.isEmpty()) { - mutableBlockPos.setWithOffset(blockPos, direction); - if (shouldRenderFace(blockState, direction, mutableBlockPos)) { - renderModelFace(bufferBuilder, quads, lightPipeline, direction); - } - } - } - - randomSource.setSeed(seed); - List quads = bakedModel.getQuads(blockState, null, randomSource); - if (!quads.isEmpty()) { - renderModelFace(bufferBuilder, quads, lightPipeline, null); - } - } - - private void renderModelFace(TerrainBuilder terrainBuilder, List quads, LightPipeline lightPipeline, Direction cullFace) { - QuadLightData quadLightData = resources.quadLightData; - - TerrainBufferBuilder bufferBuilder; - - if (cullFace != null && renderType != TerrainRenderType.TRANSLUCENT && this.backFaceCulling) { - bufferBuilder = terrainBuilder.getBufferBuilder(QuadFacing.from(cullFace).ordinal()); - } - else { - bufferBuilder = terrainBuilder.getBufferBuilder(QuadFacing.NONE.ordinal()); - } - - for (int i = 0; i < quads.size(); ++i) { - BakedQuad bakedQuad = quads.get(i); - QuadView quadView = (QuadView) bakedQuad; - lightPipeline.calculate(quadView, blockPos, quadLightData, cullFace, bakedQuad.getDirection(), bakedQuad.isShade()); - putQuadData(bufferBuilder, quadView, quadLightData); - } - } - - private void putQuadData(TerrainBufferBuilder bufferBuilder, QuadView quadView, QuadLightData quadLightData) { - float r, g, b; - if (quadView.isTinted()) { - int color = blockColors.getColor(blockState, resources.region, blockPos, quadView.getColorIndex()); - r = ColorUtil.ARGB.unpackR(color); - g = ColorUtil.ARGB.unpackG(color); - b = ColorUtil.ARGB.unpackB(color); - } else { - r = 1.0F; - g = 1.0F; - b = 1.0F; - } - - putQuadData(bufferBuilder, pos, quadView, quadLightData, r, g, b); - } - - public static void putQuadData(TerrainBufferBuilder bufferBuilder, Vector3f pos, QuadView quad, QuadLightData quadLightData, float red, float green, float blue) { - Vec3i normal = quad.getFacingDirection().getNormal(); - int packedNormal = VertexUtil.packNormal(normal.getX(), normal.getY(), normal.getZ()); - - float[] brightnessArr = quadLightData.br; - int[] lights = quadLightData.lm; - - // Rotate triangles if needed to fix AO anisotropy - int idx = QuadUtils.getIterationStartIdx(brightnessArr, lights); - - bufferBuilder.ensureCapacity(); - - for (byte i = 0; i < 4; ++i) { - final float x = pos.x() + quad.getX(idx); - final float y = pos.y() + quad.getY(idx); - final float z = pos.z() + quad.getZ(idx); - - final float r, g, b; - final float quadR, quadG, quadB; - - final int quadColor = quad.getColor(idx); - quadR = ColorUtil.RGBA.unpackR(quadColor); - quadG = ColorUtil.RGBA.unpackG(quadColor); - quadB = ColorUtil.RGBA.unpackB(quadColor); - - final float brightness = brightnessArr[idx]; - r = quadR * brightness * red; - g = quadG * brightness * green; - b = quadB * brightness * blue; - - final int color = ColorUtil.RGBA.pack(r, g, b, 1.0f); - final int light = lights[idx]; - final float u = quad.getU(idx); - final float v = quad.getV(idx); - - bufferBuilder.vertex(x, y, z, color, u, v, light, packedNormal); - - idx = (idx + 1) & 0b11; - } - - } - - public boolean shouldRenderFace(BlockState blockState, Direction direction, BlockPos adjPos) { - BlockGetter blockGetter = resources.region; - BlockState adjBlockState = blockGetter.getBlockState(adjPos); - - if (blockState.skipRendering(adjBlockState, direction)) { - return false; - } - - if (adjBlockState.canOcclude()) { - VoxelShape shape = blockState.getFaceOcclusionShape(blockGetter, blockPos, direction); - - if (shape.isEmpty()) - return true; - - VoxelShape adjShape = adjBlockState.getFaceOcclusionShape(blockGetter, adjPos, direction.getOpposite()); - - if (adjShape.isEmpty()) - return true; - - if (shape == Shapes.block() && adjShape == Shapes.block()) { - return false; - } - - Block.BlockStatePairKey blockStatePairKey = new Block.BlockStatePairKey(blockState, adjBlockState, direction); - - byte b = occlusionCache.getAndMoveToFirst(blockStatePairKey); - if (b != 127) { - return b != 0; - } else { - boolean bl = Shapes.joinIsNotEmpty(shape, adjShape, BooleanOp.ONLY_FIRST); - - if (occlusionCache.size() == 2048) { - occlusionCache.removeLastByte(); - } - - occlusionCache.putAndMoveToFirst(blockStatePairKey, (byte) (bl ? 1 : 0)); - return bl; - } - } - - return true; - } -} - diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 79a65a1521..4623a8abff 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.levelgen.DebugLevelSource; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.material.FluidState; +import net.vulkanmod.render.chunk.build.color.TintCache; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/biome/BoxBlur.java b/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java similarity index 96% rename from src/main/java/net/vulkanmod/render/chunk/build/biome/BoxBlur.java rename to src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java index 7c484acf8c..f86333de7b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/biome/BoxBlur.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java @@ -1,6 +1,6 @@ -package net.vulkanmod.render.chunk.build.biome; +package net.vulkanmod.render.chunk.build.color; -public class BoxBlur { +public abstract class BoxBlur { public static void blur(int[] buffer, int[] temp, int width, int filterRadius) { horizontalBlur(buffer, temp, 0, width, filterRadius); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/TintCache.java b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java similarity index 81% rename from src/main/java/net/vulkanmod/render/chunk/build/TintCache.java rename to src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java index 2c296f955d..357b23edb8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/TintCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java @@ -1,17 +1,14 @@ -package net.vulkanmod.render.chunk.build; +package net.vulkanmod.render.chunk.build.color; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BiomeColors; import net.minecraft.core.BlockPos; -import net.minecraft.util.Mth; import net.minecraft.world.level.ColorResolver; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.render.chunk.build.biome.BoxBlur; import java.util.Arrays; -import java.util.function.BiFunction; public class TintCache { private static final int SECTION_WIDTH = 16; @@ -78,16 +75,11 @@ public void calculateLayer(int y) { BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(); int absY = (secY << 4) + y; - Biome tB = level.getBiome(blockPos.set(minX, absY, minZ)).value(); - boolean mixed = false; for (int absZ = minZ; absZ < maxZ ; absZ++) { for (int absX = minX; absX < maxX ; absX++) { blockPos.set(absX, absY, absZ); Biome biome = level.getBiome(blockPos).value(); - if (biome != tB) - mixed = true; - final int idx = (absX - minX) + (absZ - minZ) * totalWidth; layer.grass[idx] = biome.getGrassColor(absX, absZ); layer.foliage[idx] = biome.getFoliageColor(); @@ -95,15 +87,29 @@ public void calculateLayer(int y) { } } - if(mixed && blendRadius > 0) { - BoxBlur.blur(layer.grass, temp, SECTION_WIDTH, blendRadius); - BoxBlur.blur(layer.foliage, temp, SECTION_WIDTH, blendRadius); - BoxBlur.blur(layer.water, temp, SECTION_WIDTH, blendRadius); + if (blendRadius > 0) { + this.applyBlur(layer.grass); + this.applyBlur(layer.foliage); + this.applyBlur(layer.water); } layer.invalidated = false; } + private void applyBlur(int[] buffer) { + int value = buffer[0]; + boolean needsBlur = false; + for (int i = 1; i < buffer.length; ++i) { + if (value != buffer[i]) { + needsBlur = true; + break; + } + } + + if (needsBlur) + BoxBlur.blur(buffer, temp, SECTION_WIDTH, blendRadius); + } + static class Layer { private boolean invalidated = true; @@ -123,11 +129,11 @@ void invalidate() { } public int[] getValues(ColorResolver colorResolver) { - if(colorResolver == BiomeColors.GRASS_COLOR_RESOLVER) + if (colorResolver == BiomeColors.GRASS_COLOR_RESOLVER) return grass; - else if(colorResolver == BiomeColors.FOLIAGE_COLOR_RESOLVER) + else if (colorResolver == BiomeColors.FOLIAGE_COLOR_RESOLVER) return foliage; - else if(colorResolver == BiomeColors.WATER_COLOR_RESOLVER) + else if (colorResolver == BiomeColors.WATER_COLOR_RESOLVER) return water; throw new IllegalArgumentException("Unexpected resolver: " + colorResolver.toString()); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java new file mode 100644 index 0000000000..e2a3351097 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java @@ -0,0 +1,55 @@ +package net.vulkanmod.render.chunk.build.frapi; + +import java.util.HashMap; + +import net.minecraft.resources.ResourceLocation; + +import net.fabricmc.fabric.api.renderer.v1.Renderer; +import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; +import net.vulkanmod.render.chunk.build.frapi.material.MaterialFinderImpl; +import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; +import net.vulkanmod.render.chunk.build.frapi.mesh.MeshBuilderImpl; + +/** + * The Fabric default renderer implementation. Supports all + * features defined in the API except shaders and offers no special materials. + */ +public class VulkanModRenderer implements Renderer { + public static final VulkanModRenderer INSTANCE = new VulkanModRenderer(); + + public static final RenderMaterial MATERIAL_STANDARD = INSTANCE.materialFinder().find(); + + static { + INSTANCE.registerMaterial(RenderMaterial.MATERIAL_STANDARD, MATERIAL_STANDARD); + } + + private final HashMap materialMap = new HashMap<>(); + + private VulkanModRenderer() {} + + @Override + public MeshBuilder meshBuilder() { + return new MeshBuilderImpl(); + } + + @Override + public MaterialFinder materialFinder() { + return new MaterialFinderImpl(); + } + + @Override + public RenderMaterial materialById(ResourceLocation id) { + return materialMap.get(id); + } + + @Override + public boolean registerMaterial(ResourceLocation id, RenderMaterial material) { + if (materialMap.containsKey(id)) return false; + + // cast to prevent acceptance of impostor implementations + materialMap.put(id, (RenderMaterialImpl) material); + return true; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java new file mode 100644 index 0000000000..2723331b2e --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.helper; + +import java.nio.ByteOrder; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class ColorHelper { + private ColorHelper() { } + + private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + + /** Component-wise multiply. Components need to be in same order in both inputs! */ + public static int multiplyColor(int color1, int color2) { + if (color1 == -1) { + return color2; + } else if (color2 == -1) { + return color1; + } + + final int alpha = ((color1 >>> 24) & 0xFF) * ((color2 >>> 24) & 0xFF) / 0xFF; + final int red = ((color1 >>> 16) & 0xFF) * ((color2 >>> 16) & 0xFF) / 0xFF; + final int green = ((color1 >>> 8) & 0xFF) * ((color2 >>> 8) & 0xFF) / 0xFF; + final int blue = (color1 & 0xFF) * (color2 & 0xFF) / 0xFF; + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + /** Multiplies three lowest components by shade. High byte (usually alpha) unchanged. */ + public static int multiplyRGB(int color, float shade) { + final int alpha = ((color >>> 24) & 0xFF); + final int red = (int) (((color >>> 16) & 0xFF) * shade); + final int green = (int) (((color >>> 8) & 0xFF) * shade); + final int blue = (int) ((color & 0xFF) * shade); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + /** + * Component-wise max. + */ + public static int maxBrightness(int b0, int b1) { + if (b0 == 0) return b1; + if (b1 == 0) return b0; + + return Math.max(b0 & 0xFFFF, b1 & 0xFFFF) | Math.max(b0 & 0xFFFF0000, b1 & 0xFFFF0000); + } + + /* + Renderer color format: ARGB (0xAARRGGBB) + Vanilla color format (little endian): ABGR (0xAABBGGRR) + Vanilla color format (big endian): RGBA (0xRRGGBBAA) + + Why does the vanilla color format change based on endianness? + See VertexConsumer#quad. Quad data is loaded as integers into + a native byte order buffer. Color is read directly from bytes + 12, 13, 14 of each vertex. A different byte order will yield + different results. + + The renderer always uses ARGB because the API color methods + always consume and return ARGB. Vanilla block and item colors + also use ARGB. + */ + + /** + * Converts from ARGB color to ABGR color if little endian or RGBA color if big endian. + */ + public static int toVanillaColor(int color) { + if (color == -1) { + return -1; + } + + if (BIG_ENDIAN) { + // ARGB to RGBA + return ((color & 0x00FFFFFF) << 8) | ((color & 0xFF000000) >>> 24); + } else { + // ARGB to ABGR + return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); + } + } + + /** + * Converts to ARGB color from ABGR color if little endian or RGBA color if big endian. + */ + public static int fromVanillaColor(int color) { + if (color == -1) { + return -1; + } + + if (BIG_ENDIAN) { + // RGBA to ARGB + return ((color & 0xFFFFFF00) >>> 8) | ((color & 0x000000FF) << 24); + } else { + // ABGR to ARGB + return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java new file mode 100644 index 0000000000..66e8a805e4 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.helper; + +import static net.minecraft.util.Mth.equal; + +import org.joml.Vector3f; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraft.core.Direction.Axis; +import net.minecraft.core.Direction.AxisDirection; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class GeometryHelper { + private GeometryHelper() { } + + /** set when a quad touches all four corners of a unit cube. */ + public static final int CUBIC_FLAG = 1; + + /** set when a quad is parallel to (but not necessarily on) a its light face. */ + public static final int AXIS_ALIGNED_FLAG = CUBIC_FLAG << 1; + + /** set when a quad is coplanar with its light face. Implies {@link #AXIS_ALIGNED_FLAG} */ + public static final int LIGHT_FACE_FLAG = AXIS_ALIGNED_FLAG << 1; + + /** how many bits quad header encoding should reserve for encoding geometry flags. */ + public static final int FLAG_BIT_COUNT = 3; + + private static final float EPS_MIN = 0.0001f; + private static final float EPS_MAX = 1.0f - EPS_MIN; + + /** + * Analyzes the quad and returns a value with some combination + * of {@link #AXIS_ALIGNED_FLAG}, {@link #LIGHT_FACE_FLAG} and {@link #CUBIC_FLAG}. + * Intended use is to optimize lighting when the geometry is regular. + * Expects convex quads with all points co-planar. + */ + public static int computeShapeFlags(QuadView quad) { + Direction lightFace = quad.lightFace(); + int bits = 0; + + if (isQuadParallelToFace(lightFace, quad)) { + bits |= AXIS_ALIGNED_FLAG; + + if (isParallelQuadOnFace(lightFace, quad)) { + bits |= LIGHT_FACE_FLAG; + } + } + + if (isQuadCubic(lightFace, quad)) { + bits |= CUBIC_FLAG; + } + + return bits; + } + + /** + * Returns true if quad is parallel to the given face. + * Does not validate quad winding order. + * Expects convex quads with all points co-planar. + */ + public static boolean isQuadParallelToFace(Direction face, QuadView quad) { + int i = face.getAxis().ordinal(); + final float val = quad.posByIndex(0, i); + return equal(val, quad.posByIndex(1, i)) && equal(val, quad.posByIndex(2, i)) && equal(val, quad.posByIndex(3, i)); + } + + /** + * True if quad - already known to be parallel to a face - is actually coplanar with it. + * For compatibility with vanilla resource packs, also true if quad is outside the face. + * + *

Test will be unreliable if not already parallel, use {@link #isQuadParallelToFace(Direction, QuadView)} + * for that purpose. Expects convex quads with all points co-planar. + */ + public static boolean isParallelQuadOnFace(Direction lightFace, QuadView quad) { + final float x = quad.posByIndex(0, lightFace.getAxis().ordinal()); + return lightFace.getAxisDirection() == AxisDirection.POSITIVE ? x >= EPS_MAX : x <= EPS_MIN; + } + + /** + * Returns true if quad is truly a quad (not a triangle) and fills a full block cross-section. + * If known to be true, allows use of a simpler/faster AO lighting algorithm. + * + *

Does not check if quad is actually coplanar with the light face, nor does it check that all + * quad vertices are coplanar with each other. + * + *

Expects convex quads with all points co-planar. + */ + public static boolean isQuadCubic(Direction lightFace, QuadView quad) { + int a, b; + + switch (lightFace) { + case EAST: + case WEST: + a = 1; + b = 2; + break; + case UP: + case DOWN: + a = 0; + b = 2; + break; + case SOUTH: + case NORTH: + a = 1; + b = 0; + break; + default: + // handle WTF case + return false; + } + + return confirmSquareCorners(a, b, quad); + } + + /** + * Used by {@link #isQuadCubic(Direction, QuadView)}. + * True if quad touches all four corners of unit square. + * + *

For compatibility with resource packs that contain models with quads exceeding + * block boundaries, considers corners outside the block to be at the corners. + */ + private static boolean confirmSquareCorners(int aCoordinate, int bCoordinate, QuadView quad) { + int flags = 0; + + for (int i = 0; i < 4; i++) { + final float a = quad.posByIndex(i, aCoordinate); + final float b = quad.posByIndex(i, bCoordinate); + + if (a <= EPS_MIN) { + if (b <= EPS_MIN) { + flags |= 1; + } else if (b >= EPS_MAX) { + flags |= 2; + } else { + return false; + } + } else if (a >= EPS_MAX) { + if (b <= EPS_MIN) { + flags |= 4; + } else if (b >= EPS_MAX) { + flags |= 8; + } else { + return false; + } + } else { + return false; + } + } + + return flags == 15; + } + + /** + * Identifies the face to which the quad is most closely aligned. + * This mimics the value that {@link BakedQuad#getDirection()} returns, and is + * used in the vanilla renderer for all diffuse lighting. + * + *

Derived from the quad face normal and expects convex quads with all points co-planar. + */ + public static Direction lightFace(QuadView quad) { + final Vector3f normal = quad.faceNormal(); + switch (GeometryHelper.longestAxis(normal)) { + case X: + return normal.x() > 0 ? Direction.EAST : Direction.WEST; + + case Y: + return normal.y() > 0 ? Direction.UP : Direction.DOWN; + + case Z: + return normal.z() > 0 ? Direction.SOUTH : Direction.NORTH; + + default: + // handle WTF case + return Direction.UP; + } + } + + /** + * Simple 4-way compare, doesn't handle NaN values. + */ + public static float min(float a, float b, float c, float d) { + final float x = a < b ? a : b; + final float y = c < d ? c : d; + return x < y ? x : y; + } + + /** + * Simple 4-way compare, doesn't handle NaN values. + */ + public static float max(float a, float b, float c, float d) { + final float x = a > b ? a : b; + final float y = c > d ? c : d; + return x > y ? x : y; + } + + /** + * @see #longestAxis(float, float, float) + */ + public static Axis longestAxis(Vector3f vec) { + return longestAxis(vec.x(), vec.y(), vec.z()); + } + + /** + * Identifies the largest (max absolute magnitude) component (X, Y, Z) in the given vector. + */ + public static Axis longestAxis(float normalX, float normalY, float normalZ) { + Axis result = Axis.Y; + float longest = Math.abs(normalY); + float a = Math.abs(normalX); + + if (a > longest) { + result = Axis.X; + longest = a; + } + + return Math.abs(normalZ) > longest + ? Axis.Z : result; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java new file mode 100644 index 0000000000..280ac96b1e --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.helper; + +import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.vertex.format.I32_SNorm; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import net.minecraft.core.Direction; +import net.minecraft.core.Vec3i; +import net.minecraft.util.Mth; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class NormalHelper { + private NormalHelper() { } + + private static final float PACK = 127.0f; + private static final float UNPACK = 1.0f / PACK; + + /** + * Stores a normal plus an extra value as a quartet of signed bytes. + * This is the same normal format that vanilla rendering expects. + * The extra value is for use by shaders. + */ + public static int packNormal(float x, float y, float z, float w) { + x = Mth.clamp(x, -1, 1); + y = Mth.clamp(y, -1, 1); + z = Mth.clamp(z, -1, 1); + w = Mth.clamp(w, -1, 1); + + return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16) | (((int) (w * PACK) & 0xFF) << 24); + } + + /** + * Version of {@link #packNormal(float, float, float, float)} that accepts a vector type. + */ + public static int packNormal(Vector3f normal, float w) { + return packNormal(normal.x(), normal.y(), normal.z(), w); + } + + /** + * Like {@link #packNormal(float, float, float, float)}, but without a {@code w} value. + */ + public static int packNormal(float x, float y, float z) { + x = Mth.clamp(x, -1, 1); + y = Mth.clamp(y, -1, 1); + z = Mth.clamp(z, -1, 1); + + return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16); + } + + /** + * Like {@link #packNormal(Vector3f, float)}, but without a {@code w} value. + */ + public static int packNormal(Vector3f normal) { + return packNormal(normal.x(), normal.y(), normal.z()); + } + + public static float unpackNormalX(int packedNormal) { + return ((byte) (packedNormal & 0xFF)) * UNPACK; + } + + public static float unpackNormalY(int packedNormal) { + return ((byte) ((packedNormal >>> 8) & 0xFF)) * UNPACK; + } + + public static float unpackNormalZ(int packedNormal) { + return ((byte) ((packedNormal >>> 16) & 0xFF)) * UNPACK; + } + + public static float unpackNormalW(int packedNormal) { + return ((byte) ((packedNormal >>> 24) & 0xFF)) * UNPACK; + } + + public static void unpackNormal(int packedNormal, Vector3f target) { + target.set(unpackNormalX(packedNormal), unpackNormalY(packedNormal), unpackNormalZ(packedNormal)); + } + + /** + * Computes the face normal of the given quad and saves it in the provided non-null vector. + * If {@link QuadView#nominalFace()} is set will optimize by confirming quad is parallel to that + * face and, if so, use the standard normal for that face direction. + * + *

Will work with triangles also. Assumes counter-clockwise winding order, which is the norm. + * Expects convex quads with all points co-planar. + */ + public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { + final Direction nominalFace = q.nominalFace(); + + if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) { + Vec3i vec = nominalFace.getNormal(); + saveTo.set(vec.getX(), vec.getY(), vec.getZ()); + return; + } + + final float x0 = q.x(0); + final float y0 = q.y(0); + final float z0 = q.z(0); + final float x1 = q.x(1); + final float y1 = q.y(1); + final float z1 = q.z(1); + final float x2 = q.x(2); + final float y2 = q.y(2); + final float z2 = q.z(2); + final float x3 = q.x(3); + final float y3 = q.y(3); + final float z3 = q.z(3); + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + saveTo.set(normX, normY, normZ); + } + + public static int computePackedNormal(ModelQuadView q) { + final float x0 = q.getX(0); + final float y0 = q.getY(0); + final float z0 = q.getZ(0); + final float x1 = q.getX(1); + final float y1 = q.getY(1); + final float z1 = q.getZ(1); + final float x2 = q.getX(2); + final float y2 = q.getY(2); + final float z2 = q.getZ(2); + final float x3 = q.getX(3); + final float y3 = q.getY(3); + final float z3 = q.getZ(3); + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + return I32_SNorm.packNormal(normX, normY, normZ); + } + + public static int packedNormalFromDirection(Direction direction) { + Vec3i normal = direction.getNormal(); + + return I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java new file mode 100644 index 0000000000..bc622cd920 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.helper; + +import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; + +/** + * Handles most texture-baking use cases for model loaders and model libraries + * via {@link #bakeSprite(MutableQuadView, TextureAtlasSprite, int)}. Also used by the API + * itself to implement automatic block-breaking models for enhanced models. + */ +public class TextureHelper { + private TextureHelper() { } + + private static final float NORMALIZER = 1f / 16f; + + /** + * Bakes textures in the provided vertex data, handling UV locking, + * rotation, interpolation, etc. Textures must not be already baked. + */ + public static void bakeSprite(MutableQuadView quad, TextureAtlasSprite sprite, int bakeFlags) { + if (quad.nominalFace() != null && (MutableQuadView.BAKE_LOCK_UV & bakeFlags) != 0) { + // Assigns normalized UV coordinates based on vertex positions + applyModifier(quad, UVLOCKERS[quad.nominalFace().get3DDataValue()]); + } else if ((MutableQuadView.BAKE_NORMALIZED & bakeFlags) == 0) { // flag is NOT set, UVs are assumed to not be normalized yet as is the default, normalize through dividing by 16 + // Scales from 0-16 to 0-1 + applyModifier(quad, (q, i) -> q.uv(i, q.u(i) * NORMALIZER, q.v(i) * NORMALIZER)); + } + + final int rotation = bakeFlags & 3; + + if (rotation != 0) { + // Rotates texture around the center of sprite. + // Assumes normalized coordinates. + applyModifier(quad, ROTATIONS[rotation]); + } + + if ((MutableQuadView.BAKE_FLIP_U & bakeFlags) != 0) { + // Inverts U coordinates. Assumes normalized (0-1) values. + applyModifier(quad, (q, i) -> q.uv(i, 1 - q.u(i), q.v(i))); + } + + if ((MutableQuadView.BAKE_FLIP_V & bakeFlags) != 0) { + // Inverts V coordinates. Assumes normalized (0-1) values. + applyModifier(quad, (q, i) -> q.uv(i, q.u(i), 1 - q.v(i))); + } + + interpolate(quad, sprite); + } + + /** + * Faster than sprite method. Sprite computes span and normalizes inputs each call, + * so we'd have to denormalize before we called, only to have the sprite renormalize immediately. + */ + private static void interpolate(MutableQuadView q, TextureAtlasSprite sprite) { + final float uMin = sprite.getU0(); + final float uSpan = sprite.getU1() - uMin; + final float vMin = sprite.getV0(); + final float vSpan = sprite.getV1() - vMin; + + for (int i = 0; i < 4; i++) { + q.uv(i, uMin + q.u(i) * uSpan, vMin + q.v(i) * vSpan); + } + } + + @FunctionalInterface + private interface VertexModifier { + void apply(MutableQuadView quad, int vertexIndex); + } + + private static void applyModifier(MutableQuadView quad, VertexModifier modifier) { + for (int i = 0; i < 4; i++) { + modifier.apply(quad, i); + } + } + + private static final VertexModifier[] ROTATIONS = new VertexModifier[] { + null, + (q, i) -> q.uv(i, q.v(i), 1 - q.u(i)), //90 + (q, i) -> q.uv(i, 1 - q.u(i), 1 - q.v(i)), //180 + (q, i) -> q.uv(i, 1 - q.v(i), q.u(i)) // 270 + }; + + private static final VertexModifier[] UVLOCKERS = new VertexModifier[6]; + + static { + UVLOCKERS[Direction.EAST.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.z(i), 1 - q.y(i)); + UVLOCKERS[Direction.WEST.get3DDataValue()] = (q, i) -> q.uv(i, q.z(i), 1 - q.y(i)); + UVLOCKERS[Direction.NORTH.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.x(i), 1 - q.y(i)); + UVLOCKERS[Direction.SOUTH.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.y(i)); + UVLOCKERS[Direction.DOWN.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.z(i)); + UVLOCKERS[Direction.UP.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), q.z(i)); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java new file mode 100644 index 0000000000..91b510452e --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.material; + +import java.util.Objects; + +import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; +import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; + +public class MaterialFinderImpl extends MaterialViewImpl implements MaterialFinder { + private static int defaultBits = 0; + + static { + MaterialFinderImpl finder = new MaterialFinderImpl(); + finder.ambientOcclusion(TriState.DEFAULT); + finder.glint(TriState.DEFAULT); + defaultBits = finder.bits; + + if (!areBitsValid(defaultBits)) { + throw new AssertionError("Default MaterialFinder bits are not valid!"); + } + } + + public MaterialFinderImpl() { + super(defaultBits); + } + + @Override + public MaterialFinder blendMode(BlendMode blendMode) { + Objects.requireNonNull(blendMode, "BlendMode may not be null"); + + bits = (bits & ~BLEND_MODE_MASK) | (blendMode.ordinal() << BLEND_MODE_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder disableColorIndex(boolean disable) { + bits = disable ? (bits | COLOR_DISABLE_FLAG) : (bits & ~COLOR_DISABLE_FLAG); + return this; + } + + @Override + public MaterialFinder emissive(boolean isEmissive) { + bits = isEmissive ? (bits | EMISSIVE_FLAG) : (bits & ~EMISSIVE_FLAG); + return this; + } + + @Override + public MaterialFinder disableDiffuse(boolean disable) { + bits = disable ? (bits | DIFFUSE_FLAG) : (bits & ~DIFFUSE_FLAG); + return this; + } + + @Override + public MaterialFinder ambientOcclusion(TriState mode) { + Objects.requireNonNull(mode, "ambient occlusion TriState may not be null"); + + bits = (bits & ~AO_MASK) | (mode.ordinal() << AO_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder glint(TriState mode) { + Objects.requireNonNull(mode, "glint TriState may not be null"); + + bits = (bits & ~GLINT_MASK) | (mode.ordinal() << GLINT_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder shadeMode(ShadeMode mode) { + Objects.requireNonNull(mode, "ShadeMode may not be null"); + + bits = (bits & ~SHADE_MODE_MASK) | (mode.ordinal() << SHADE_MODE_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder copyFrom(MaterialView material) { + bits = ((MaterialViewImpl) material).bits; + return this; + } + + @Override + public MaterialFinder clear() { + bits = defaultBits; + return this; + } + + @Override + public RenderMaterial find() { + return RenderMaterialImpl.byIndex(bits); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java new file mode 100644 index 0000000000..0ae0705742 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.material; + +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.bitMask; + +import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; +import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.util.Mth; + +/** + * Default implementation of the standard render materials. + * The underlying representation is simply an int with bit-wise + * packing of the various material properties. This offers + * easy/fast interning via int/object hashmap. + */ +public class MaterialViewImpl implements MaterialView { + private static final BlendMode[] BLEND_MODES = BlendMode.values(); + private static final int BLEND_MODE_COUNT = BLEND_MODES.length; + private static final TriState[] TRI_STATES = TriState.values(); + private static final int TRI_STATE_COUNT = TRI_STATES.length; + private static final ShadeMode[] SHADE_MODES = ShadeMode.values(); + private static final int SHADE_MODE_COUNT = SHADE_MODES.length; + + protected static final int BLEND_MODE_BIT_LENGTH = Mth.ceillog2(BLEND_MODE_COUNT); + protected static final int COLOR_DISABLE_BIT_LENGTH = 1; + protected static final int EMISSIVE_BIT_LENGTH = 1; + protected static final int DIFFUSE_BIT_LENGTH = 1; + protected static final int AO_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); + protected static final int GLINT_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); + protected static final int SHADE_MODE_BIT_LENGTH = Mth.ceillog2(SHADE_MODE_COUNT); + + protected static final int BLEND_MODE_BIT_OFFSET = 0; + protected static final int COLOR_DISABLE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; + protected static final int EMISSIVE_BIT_OFFSET = COLOR_DISABLE_BIT_OFFSET + COLOR_DISABLE_BIT_LENGTH; + protected static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; + protected static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; + protected static final int GLINT_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; + protected static final int SHADE_MODE_BIT_OFFSET = GLINT_BIT_OFFSET + GLINT_BIT_LENGTH; + public static final int TOTAL_BIT_LENGTH = SHADE_MODE_BIT_OFFSET + SHADE_MODE_BIT_LENGTH; + + protected static final int BLEND_MODE_MASK = bitMask(BLEND_MODE_BIT_LENGTH, BLEND_MODE_BIT_OFFSET); + protected static final int COLOR_DISABLE_FLAG = bitMask(COLOR_DISABLE_BIT_LENGTH, COLOR_DISABLE_BIT_OFFSET); + protected static final int EMISSIVE_FLAG = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); + protected static final int DIFFUSE_FLAG = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); + protected static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); + protected static final int GLINT_MASK = bitMask(GLINT_BIT_LENGTH, GLINT_BIT_OFFSET); + protected static final int SHADE_MODE_MASK = bitMask(SHADE_MODE_BIT_LENGTH, SHADE_MODE_BIT_OFFSET); + + protected static boolean areBitsValid(int bits) { + int blendMode = (bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET; + int ao = (bits & AO_MASK) >>> AO_BIT_OFFSET; + int glint = (bits & GLINT_MASK) >>> GLINT_BIT_OFFSET; + int shadeMode = (bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET; + + return blendMode < BLEND_MODE_COUNT + && ao < TRI_STATE_COUNT + && glint < TRI_STATE_COUNT + && shadeMode < SHADE_MODE_COUNT; + } + + protected int bits; + + protected MaterialViewImpl(int bits) { + this.bits = bits; + } + + @Override + public BlendMode blendMode() { + return BLEND_MODES[(bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET]; + } + + @Override + public boolean disableColorIndex() { + return (bits & COLOR_DISABLE_FLAG) != 0; + } + + @Override + public boolean emissive() { + return (bits & EMISSIVE_FLAG) != 0; + } + + @Override + public boolean disableDiffuse() { + return (bits & DIFFUSE_FLAG) != 0; + } + + @Override + public TriState ambientOcclusion() { + return TRI_STATES[(bits & AO_MASK) >>> AO_BIT_OFFSET]; + } + + @Override + public TriState glint() { + return TRI_STATES[(bits & GLINT_MASK) >>> GLINT_BIT_OFFSET]; + } + + @Override + public ShadeMode shadeMode() { + return SHADE_MODES[(bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET]; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java new file mode 100644 index 0000000000..17e4602bb1 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.material; + +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; + +public class RenderMaterialImpl extends MaterialViewImpl implements RenderMaterial { + public static final int VALUE_COUNT = 1 << TOTAL_BIT_LENGTH; + private static final RenderMaterialImpl[] BY_INDEX = new RenderMaterialImpl[VALUE_COUNT]; + + static { + for (int i = 0; i < VALUE_COUNT; i++) { + if (areBitsValid(i)) { + BY_INDEX[i] = new RenderMaterialImpl(i); + } + } + } + + private RenderMaterialImpl(int bits) { + super(bits); + } + + public int index() { + return bits; + } + + public static RenderMaterialImpl byIndex(int index) { + return BY_INDEX[index]; + } + + public static RenderMaterialImpl setDisableDiffuse(RenderMaterialImpl material, boolean disable) { + if (material.disableDiffuse() != disable) { + return byIndex(disable ? (material.bits | DIFFUSE_FLAG) : (material.bits & ~DIFFUSE_FLAG)); + } + + return material; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java new file mode 100644 index 0000000000..f1cf763cce --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import com.google.common.base.Preconditions; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import org.jetbrains.annotations.Nullable; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; +import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; +import net.vulkanmod.render.chunk.build.frapi.material.MaterialViewImpl; +import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; + +/** + * Holds all the array offsets and bit-wise encoders/decoders for + * packing/unpacking quad data in an array of integers. + * All of this is implementation-specific - that's why it isn't a "helper" class. + */ +public abstract class EncodingFormat { + private EncodingFormat() { } + + static final int HEADER_BITS = 0; + static final int HEADER_FACE_NORMAL = 1; + static final int HEADER_COLOR_INDEX = 2; + static final int HEADER_TAG = 3; + public static final int HEADER_STRIDE = 4; + + static final int VERTEX_X; + static final int VERTEX_Y; + static final int VERTEX_Z; + static final int VERTEX_COLOR; + static final int VERTEX_U; + static final int VERTEX_V; + static final int VERTEX_LIGHTMAP; + static final int VERTEX_NORMAL; + public static final int VERTEX_STRIDE; + + public static final int QUAD_STRIDE; + public static final int QUAD_STRIDE_BYTES; + public static final int TOTAL_STRIDE; + + static { + final VertexFormat format = DefaultVertexFormat.BLOCK; + VERTEX_X = HEADER_STRIDE + 0; + VERTEX_Y = HEADER_STRIDE + 1; + VERTEX_Z = HEADER_STRIDE + 2; + VERTEX_COLOR = HEADER_STRIDE + 3; + VERTEX_U = HEADER_STRIDE + 4; + VERTEX_V = VERTEX_U + 1; + VERTEX_LIGHTMAP = HEADER_STRIDE + 6; + VERTEX_NORMAL = HEADER_STRIDE + 7; + VERTEX_STRIDE = format.getVertexSize() / 4; + QUAD_STRIDE = VERTEX_STRIDE * 4; + QUAD_STRIDE_BYTES = QUAD_STRIDE * 4; + TOTAL_STRIDE = HEADER_STRIDE + QUAD_STRIDE; + + Preconditions.checkState(VERTEX_STRIDE == QuadView.VANILLA_VERTEX_STRIDE, "Indigo vertex stride (%s) mismatched with rendering API (%s)", VERTEX_STRIDE, QuadView.VANILLA_VERTEX_STRIDE); + Preconditions.checkState(QUAD_STRIDE == QuadView.VANILLA_QUAD_STRIDE, "Indigo quad stride (%s) mismatched with rendering API (%s)", QUAD_STRIDE, QuadView.VANILLA_QUAD_STRIDE); + } + + /** used for quick clearing of quad buffers. */ + static final int[] EMPTY = new int[TOTAL_STRIDE]; + + private static final int DIRECTION_COUNT = Direction.values().length; + private static final int NULLABLE_DIRECTION_COUNT = DIRECTION_COUNT + 1; + + private static final int CULL_BIT_LENGTH = Mth.ceillog2(NULLABLE_DIRECTION_COUNT); + private static final int LIGHT_BIT_LENGTH = Mth.ceillog2(DIRECTION_COUNT); + private static final int NORMALS_BIT_LENGTH = 4; + private static final int GEOMETRY_BIT_LENGTH = GeometryHelper.FLAG_BIT_COUNT; + private static final int MATERIAL_BIT_LENGTH = MaterialViewImpl.TOTAL_BIT_LENGTH; + + private static final int CULL_BIT_OFFSET = 0; + private static final int LIGHT_BIT_OFFSET = CULL_BIT_OFFSET + CULL_BIT_LENGTH; + private static final int NORMALS_BIT_OFFSET = LIGHT_BIT_OFFSET + LIGHT_BIT_LENGTH; + private static final int GEOMETRY_BIT_OFFSET = NORMALS_BIT_OFFSET + NORMALS_BIT_LENGTH; + private static final int MATERIAL_BIT_OFFSET = GEOMETRY_BIT_OFFSET + GEOMETRY_BIT_LENGTH; + private static final int TOTAL_BIT_LENGTH = MATERIAL_BIT_OFFSET + MATERIAL_BIT_LENGTH; + + private static final int CULL_MASK = bitMask(CULL_BIT_LENGTH, CULL_BIT_OFFSET); + private static final int LIGHT_MASK = bitMask(LIGHT_BIT_LENGTH, LIGHT_BIT_OFFSET); + private static final int NORMALS_MASK = bitMask(NORMALS_BIT_LENGTH, NORMALS_BIT_OFFSET); + private static final int GEOMETRY_MASK = bitMask(GEOMETRY_BIT_LENGTH, GEOMETRY_BIT_OFFSET); + private static final int MATERIAL_MASK = bitMask(MATERIAL_BIT_LENGTH, MATERIAL_BIT_OFFSET); + + static { + Preconditions.checkArgument(TOTAL_BIT_LENGTH <= 32, "Indigo header encoding bit count (%s) exceeds integer bit length)", TOTAL_STRIDE); + } + + public static int bitMask(int bitLength, int bitOffset) { + return ((1 << bitLength) - 1) << bitOffset; + } + + @Nullable + static Direction cullFace(int bits) { + return ModelHelper.faceFromIndex((bits & CULL_MASK) >>> CULL_BIT_OFFSET); + } + + static int cullFace(int bits, @Nullable Direction face) { + return (bits & ~CULL_MASK) | (ModelHelper.toFaceIndex(face) << CULL_BIT_OFFSET); + } + + static Direction lightFace(int bits) { + return ModelHelper.faceFromIndex((bits & LIGHT_MASK) >>> LIGHT_BIT_OFFSET); + } + + static int lightFace(int bits, Direction face) { + return (bits & ~LIGHT_MASK) | (ModelHelper.toFaceIndex(face) << LIGHT_BIT_OFFSET); + } + + /** indicate if vertex normal has been set - bits correspond to vertex ordinals. */ + static int normalFlags(int bits) { + return (bits & NORMALS_MASK) >>> NORMALS_BIT_OFFSET; + } + + static int normalFlags(int bits, int normalFlags) { + return (bits & ~NORMALS_MASK) | ((normalFlags << NORMALS_BIT_OFFSET) & NORMALS_MASK); + } + + static int geometryFlags(int bits) { + return (bits & GEOMETRY_MASK) >>> GEOMETRY_BIT_OFFSET; + } + + static int geometryFlags(int bits, int geometryFlags) { + return (bits & ~GEOMETRY_MASK) | ((geometryFlags << GEOMETRY_BIT_OFFSET) & GEOMETRY_MASK); + } + + static RenderMaterialImpl material(int bits) { + return RenderMaterialImpl.byIndex((bits & MATERIAL_MASK) >>> MATERIAL_BIT_OFFSET); + } + + static int material(int bits, RenderMaterialImpl material) { + return (bits & ~MATERIAL_MASK) | (material.index() << MATERIAL_BIT_OFFSET); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java new file mode 100644 index 0000000000..b5119de51b --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; + +/** + * Our implementation of {@link MeshBuilder}, used for static mesh creation and baking. + * Not much to it - mainly it just needs to grow the int[] array as quads are appended + * and maintain/provide a properly-configured {@link net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView} instance. + * All the encoding and other work is handled in the quad base classes. + * The one interesting bit is in {@link Maker#emitDirectly()}. + */ +public class MeshBuilderImpl implements MeshBuilder { + private int[] data = new int[256]; + private int index = 0; + private int limit = data.length; + private final Maker maker = new Maker(); + + public MeshBuilderImpl() { + ensureCapacity(EncodingFormat.TOTAL_STRIDE); + maker.data = data; + maker.baseIndex = index; + maker.clear(); + } + + protected void ensureCapacity(int stride) { + if (stride > limit - index) { + limit *= 2; + final int[] bigger = new int[limit]; + System.arraycopy(data, 0, bigger, 0, index); + data = bigger; + maker.data = data; + } + } + + @Override + public QuadEmitter getEmitter() { + maker.clear(); + return maker; + } + + @Override + public Mesh build() { + final int[] packed = new int[index]; + System.arraycopy(data, 0, packed, 0, index); + index = 0; + maker.baseIndex = index; + maker.clear(); + return new MeshImpl(packed); + } + + /** + * Our base classes are used differently so we define final + * encoding steps in subtypes. This will be a static mesh used + * at render time so we want to capture all geometry now and + * apply non-location-dependent lighting. + */ + private class Maker extends MutableQuadViewImpl { + @Override + public void emitDirectly() { + computeGeometry(); + index += EncodingFormat.TOTAL_STRIDE; + ensureCapacity(EncodingFormat.TOTAL_STRIDE); + baseIndex = index; + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java new file mode 100644 index 0000000000..ff23f44f77 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import java.util.function.Consumer; + +import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; + +/** + * Implementation of {@link Mesh}. + * The way we encode meshes makes it very simple. + */ +public class MeshImpl implements Mesh { + /** Used to satisfy external calls to {@link #forEach(Consumer)}. */ + private final ThreadLocal cursorPool = ThreadLocal.withInitial(QuadViewImpl::new); + + final int[] data; + + MeshImpl(int[] data) { + this.data = data; + } + + @Override + public void forEach(Consumer consumer) { + forEach(consumer, cursorPool.get()); + } + + /** + * The renderer can call this with its own cursor + * to avoid the performance hit of a thread-local lookup. + * Also means renderer can hold final references to quad buffers. + */ + void forEach(Consumer consumer, QuadViewImpl cursor) { + final int limit = data.length; + int index = 0; + cursor.data = this.data; + + while (index < limit) { + cursor.baseIndex = index; + cursor.load(); + consumer.accept(cursor); + index += EncodingFormat.TOTAL_STRIDE; + } + } + + @Override + public void outputTo(QuadEmitter emitter) { + MutableQuadViewImpl e = (MutableQuadViewImpl) emitter; + final int[] data = this.data; + final int limit = data.length; + int index = 0; + + while (index < limit) { + System.arraycopy(data, index, e.data, e.baseIndex, EncodingFormat.TOTAL_STRIDE); + e.load(); + e.emitDirectly(); + index += EncodingFormat.TOTAL_STRIDE; + } + + e.clear(); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java new file mode 100644 index 0000000000..297d573aef --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; +import net.vulkanmod.render.model.quad.ModelQuadView; +import org.jetbrains.annotations.Nullable; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; +import net.vulkanmod.render.chunk.build.frapi.helper.TextureHelper; +import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; + +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.*; + +/** + * Almost-concrete implementation of a mutable quad. The only missing part is {@link #emitDirectly()}, + * because that depends on where/how it is used. (Mesh encoding vs. render-time transformation). + * + *

In many cases an instance of this class is used as an "editor quad". The editor quad's + * {@link #emitDirectly()} method calls some other internal method that transforms the quad + * data and then buffers it. Transformations should be the same as they would be in a vanilla + * render - the editor is serving mainly as a way to access vertex data without magical + * numbers. It also allows for a consistent interface for those transformations. + */ +public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter { + public void clear() { + System.arraycopy(EMPTY, 0, data, baseIndex, EncodingFormat.TOTAL_STRIDE); + isGeometryInvalid = true; + nominalFace = null; + normalFlags(0); + tag(0); + colorIndex(-1); + cullFace(null); + material(VulkanModRenderer.MATERIAL_STANDARD); + } + + @Override + public MutableQuadViewImpl pos(int vertexIndex, float x, float y, float z) { + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; + data[index] = Float.floatToRawIntBits(x); + data[index + 1] = Float.floatToRawIntBits(y); + data[index + 2] = Float.floatToRawIntBits(z); + isGeometryInvalid = true; + return this; + } + + @Override + public MutableQuadViewImpl color(int vertexIndex, int color) { + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR] = color; + return this; + } + + @Override + public MutableQuadViewImpl uv(int vertexIndex, float u, float v) { + final int i = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; + data[i] = Float.floatToRawIntBits(u); + data[i + 1] = Float.floatToRawIntBits(v); + return this; + } + + @Override + public MutableQuadViewImpl spriteBake(TextureAtlasSprite sprite, int bakeFlags) { + TextureHelper.bakeSprite(this, sprite, bakeFlags); + return this; + } + + @Override + public MutableQuadViewImpl lightmap(int vertexIndex, int lightmap) { + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP] = lightmap; + return this; + } + + protected void normalFlags(int flags) { + data[baseIndex + HEADER_BITS] = EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS], flags); + } + + @Override + public MutableQuadViewImpl normal(int vertexIndex, float x, float y, float z) { + normalFlags(normalFlags() | (1 << vertexIndex)); + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL] = NormalHelper.packNormal(x, y, z); + return this; + } + + /** + * Internal helper method. Copies face normals to vertex normals lacking one. + */ + public final void populateMissingNormals() { + final int normalFlags = this.normalFlags(); + + if (normalFlags == 0b1111) return; + + final int packedFaceNormal = packedFaceNormal(); + + for (int v = 0; v < 4; v++) { + if ((normalFlags & (1 << v)) == 0) { + data[baseIndex + v * VERTEX_STRIDE + VERTEX_NORMAL] = packedFaceNormal; + } + } + + normalFlags(0b1111); + } + + @Override + public final MutableQuadViewImpl cullFace(@Nullable Direction face) { + data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(data[baseIndex + HEADER_BITS], face); + nominalFace(face); + return this; + } + + @Override + public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { + nominalFace = face; + return this; + } + + @Override + public final MutableQuadViewImpl material(RenderMaterial material) { + if (material == null) { + material = VulkanModRenderer.MATERIAL_STANDARD; + } + + data[baseIndex + HEADER_BITS] = EncodingFormat.material(data[baseIndex + HEADER_BITS], (RenderMaterialImpl) material); + return this; + } + + @Override + public final MutableQuadViewImpl colorIndex(int colorIndex) { + data[baseIndex + HEADER_COLOR_INDEX] = colorIndex; + return this; + } + + @Override + public final MutableQuadViewImpl tag(int tag) { + data[baseIndex + HEADER_TAG] = tag; + return this; + } + + @Override + public MutableQuadViewImpl copyFrom(QuadView quad) { + final QuadViewImpl q = (QuadViewImpl) quad; + q.computeGeometry(); + + System.arraycopy(q.data, q.baseIndex, data, baseIndex, EncodingFormat.TOTAL_STRIDE); + faceNormal.set(q.faceNormal); + nominalFace = q.nominalFace; + isGeometryInvalid = false; + return this; + } + + @Override + public final MutableQuadViewImpl fromVanilla(int[] quadData, int startIndex) { + System.arraycopy(quadData, startIndex, data, baseIndex + HEADER_STRIDE, VANILLA_QUAD_STRIDE); + isGeometryInvalid = true; + + int colorIndex = baseIndex + VERTEX_COLOR; + + for (int i = 0; i < 4; i++) { + data[colorIndex] = ColorHelper.fromVanillaColor(data[colorIndex]); + colorIndex += VERTEX_STRIDE; + } + + return this; + } + + @Override + public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial material, @Nullable Direction cullFace) { + fromVanilla(quad.getVertices(), 0); + data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); + nominalFace(quad.getDirection()); + colorIndex(quad.getTintIndex()); + + if (!quad.isShade()) { + material = RenderMaterialImpl.setDisableDiffuse((RenderMaterialImpl) material, true); + } + + material(material); + tag(0); + + // Copy data from BakedQuad instead of calculating properties + ModelQuadView quadView = (ModelQuadView) quad; + int normal = quadView.getNormal(); + data[baseIndex + HEADER_FACE_NORMAL] = normal; + + Direction lightFace = quadView.lightFace(); + data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); + + data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], quadView.getFlags()); + + this.facing = quadView.getQuadFacing(); + + this.isGeometryInvalid = false; + return this; + } + + /** + * Emit the quad without clearing the underlying data. + * Geometry is not guaranteed to be valid when called, but can be computed by calling {@link #computeGeometry()}. + */ + public abstract void emitDirectly(); + + @Override + public final MutableQuadViewImpl emit() { + emitDirectly(); + clear(); + return this; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java new file mode 100644 index 0000000000..a6a3ac29a5 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_BITS; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_COLOR_INDEX; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_FACE_NORMAL; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_STRIDE; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_TAG; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.QUAD_STRIDE; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_COLOR; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_LIGHTMAP; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_NORMAL; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_STRIDE; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_U; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_V; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_X; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Y; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Z; + +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector2f; +import org.joml.Vector3f; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; +import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; +import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; +import net.minecraft.core.Direction; + +/** + * Base class for all quads / quad makers. Handles the ugly bits + * of maintaining and encoding the quad state. + */ +public class QuadViewImpl implements QuadView, ModelQuadView { + @Nullable + protected Direction nominalFace; + /** True when face normal, light face, or geometry flags may not match geometry. */ + protected boolean isGeometryInvalid = true; + protected final Vector3f faceNormal = new Vector3f(); + + /** Size and where it comes from will vary in subtypes. But in all cases quad is fully encoded to array. */ + protected int[] data; + + /** Beginning of the quad. Also the header index. */ + protected int baseIndex = 0; + + protected QuadFacing facing; + + /** + * Decodes necessary state from the backing data array. + * The encoded data must contain valid computed geometry. + */ + public void load() { + isGeometryInvalid = false; + nominalFace = lightFace(); + NormalHelper.unpackNormal(packedFaceNormal(), faceNormal); + facing = QuadFacing.fromDirection(lightFace()); + } + + protected void computeGeometry() { + if (isGeometryInvalid) { + isGeometryInvalid = false; + + NormalHelper.computeFaceNormal(faceNormal, this); + data[baseIndex + HEADER_FACE_NORMAL] = NormalHelper.packNormal(faceNormal); + + // depends on face normal + Direction lightFace = GeometryHelper.lightFace(this); + data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); + + // depends on light face + data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], ModelQuadFlags.getQuadFlags(this, lightFace)); + + facing = QuadFacing.fromDirection(lightFace); + } + } + + /** gets flags used for lighting - lazily computed via {@link GeometryHelper#computeShapeFlags(QuadView)}. */ + public int geometryFlags() { + computeGeometry(); + return EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS]); + } + + public boolean hasShade() { + return !material().disableDiffuse(); + } + + @Override + public float x(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X]); + } + + @Override + public float y(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Y]); + } + + @Override + public float z(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Z]); + } + + @Override + public float posByIndex(int vertexIndex, int coordinateIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X + coordinateIndex]); + } + + @Override + public Vector3f copyPos(int vertexIndex, @Nullable Vector3f target) { + if (target == null) { + target = new Vector3f(); + } + + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; + target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1]), Float.intBitsToFloat(data[index + 2])); + return target; + } + + @Override + public int color(int vertexIndex) { + return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR]; + } + + @Override + public float u(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U]); + } + + @Override + public float v(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_V]); + } + + @Override + public Vector2f copyUv(int vertexIndex, @Nullable Vector2f target) { + if (target == null) { + target = new Vector2f(); + } + + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; + target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1])); + return target; + } + + @Override + public int lightmap(int vertexIndex) { + return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP]; + } + + public int normalFlags() { + return EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS]); + } + + @Override + public boolean hasNormal(int vertexIndex) { + return (normalFlags() & (1 << vertexIndex)) != 0; + } + + /** True if any vertex normal has been set. */ + public boolean hasVertexNormals() { + return normalFlags() != 0; + } + + /** True if all vertex normals have been set. */ + public boolean hasAllVertexNormals() { + return (normalFlags() & 0b1111) == 0b1111; + } + + protected final int normalIndex(int vertexIndex) { + return baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL; + } + + @Override + public float normalX(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalX(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + public float normalY(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalY(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + public float normalZ(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalZ(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + @Nullable + public Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { + if (hasNormal(vertexIndex)) { + if (target == null) { + target = new Vector3f(); + } + + final int normal = data[normalIndex(vertexIndex)]; + NormalHelper.unpackNormal(normal, target); + return target; + } else { + return null; + } + } + + @Override + @Nullable + public final Direction cullFace() { + return EncodingFormat.cullFace(data[baseIndex + HEADER_BITS]); + } + + @Override + @NotNull + public final Direction lightFace() { + computeGeometry(); + return EncodingFormat.lightFace(data[baseIndex + HEADER_BITS]); + } + + @Override + @Nullable + public final Direction nominalFace() { + return nominalFace; + } + + public final int packedFaceNormal() { + computeGeometry(); + return data[baseIndex + HEADER_FACE_NORMAL]; + } + + @Override + public final Vector3f faceNormal() { + computeGeometry(); + return faceNormal; + } + + @Override + public final RenderMaterialImpl material() { + return EncodingFormat.material(data[baseIndex + HEADER_BITS]); + } + + @Override + public final int colorIndex() { + return data[baseIndex + HEADER_COLOR_INDEX]; + } + + @Override + public final int tag() { + return data[baseIndex + HEADER_TAG]; + } + + @Override + public final void toVanilla(int[] target, int targetIndex) { + System.arraycopy(data, baseIndex + HEADER_STRIDE, target, targetIndex, QUAD_STRIDE); + + // The color is the fourth integer in each vertex. + // EncodingFormat.VERTEX_COLOR is not used because it also + // contains the header size; vanilla quads do not have a header. + int colorIndex = targetIndex + 3; + + for (int i = 0; i < 4; i++) { + target[colorIndex] = ColorHelper.toVanillaColor(target[colorIndex]); + colorIndex += VANILLA_VERTEX_STRIDE; + } + } + + @Override + public int getFlags() { + return geometryFlags(); + } + + @Override + public float getX(int idx) { + return this.x(idx); + } + + @Override + public float getY(int idx) { + return this.y(idx); + } + + @Override + public float getZ(int idx) { + return this.z(idx); + } + + @Override + public int getColor(int idx) { + return this.color(idx); + } + + @Override + public float getU(int idx) { + return this.u(idx); + } + + @Override + public float getV(int idx) { + return this.v(idx); + } + + @Override + public int getColorIndex() { + return this.colorIndex(); + } + + @Override + public Direction getFacingDirection() { + return this.lightFace(); + } + + @Override + public int getNormal() { + return packedFaceNormal(); + } + + @Override + public QuadFacing getQuadFacing() { + return this.facing; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java new file mode 100644 index 0000000000..6ac3fcf9a3 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -0,0 +1,296 @@ +package net.vulkanmod.render.chunk.build.frapi.render; + +import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; +import net.fabricmc.fabric.api.renderer.v1.Renderer; +import net.fabricmc.fabric.api.renderer.v1.RendererAccess; +import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; +import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; +import net.minecraft.client.Minecraft; +import net.minecraft.client.color.block.BlockColors; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.phys.shapes.BooleanOp; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import org.jetbrains.annotations.Nullable; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.util.TriState; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.List; +import java.util.function.Supplier; + +public abstract class AbstractBlockRenderContext extends AbstractRenderContext { + private static final Renderer RENDERER = RendererAccess.INSTANCE.getRenderer(); + protected static final RenderMaterial STANDARD_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).find(); + protected static final RenderMaterial NO_AO_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).ambientOcclusion(TriState.FALSE).find(); + + protected final BlockColors blockColors; + + private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { + { + data = new int[EncodingFormat.TOTAL_STRIDE]; + clear(); + } + + @Override + public void emitDirectly() { + renderQuad(this); + } + }; + + protected BlockState blockState; + protected BlockPos blockPos; + protected BlockPos.MutableBlockPos tempPos = new BlockPos.MutableBlockPos(); + + protected BlockAndTintGetter renderRegion; + + protected final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { + protected void rehash(int i) { + } + }; + + protected final QuadLightData quadLightData = new QuadLightData(); + protected LightPipeline smoothLightPipeline; + protected LightPipeline flatLightPipeline; + + protected boolean useAO; + protected boolean defaultAO; + + protected long seed; + protected RandomSource random; + public final Supplier randomSupplier = () -> { + long seed = this.seed; + + random.setSeed(seed); + return random; + }; + + protected boolean enableCulling = true; + protected int cullCompletionFlags; + protected int cullResultFlags; + + protected AbstractBlockRenderContext() { + this.occlusionCache.defaultReturnValue((byte) 127); + + this.blockColors = Minecraft.getInstance().getBlockColors(); + } + + protected void setupLightPipelines(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { + this.flatLightPipeline = flatLightPipeline; + this.smoothLightPipeline = smoothLightPipeline; + } + + @Override + public QuadEmitter getEmitter() { + editorQuad.clear(); + return editorQuad; + } + + @Override + public ItemDisplayContext itemTransformationMode() { + throw new IllegalStateException("itemTransformationMode() can only be called on an item render context."); + } + + @SuppressWarnings("removal") + @Override + public BakedModelConsumer bakedModelConsumer() { + return null; + } + + public void prepareForWorld(BlockAndTintGetter blockView, boolean enableCulling) { + this.renderRegion = blockView; + this.enableCulling = enableCulling; + } + + public void prepareForBlock(BlockState blockState, BlockPos blockPos, boolean modelAo) { + this.blockPos = blockPos; + this.blockState = blockState; + + this.useAO = Minecraft.useAmbientOcclusion(); + this.defaultAO = this.useAO && modelAo && blockState.getLightEmission() == 0; + + this.cullCompletionFlags = 0; + this.cullResultFlags = 0; + } + + @Override + public boolean isFaceCulled(@Nullable Direction face) { + return !this.shouldRenderFace(face); + } + + public boolean shouldRenderFace(Direction face) { + if (face == null || !enableCulling) { + return true; + } + + final int mask = 1 << face.get3DDataValue(); + + if ((cullCompletionFlags & mask) == 0) { + cullCompletionFlags |= mask; + + if (this.faceNotOccluded(blockState, face)) { + cullResultFlags |= mask; + return true; + } else { + return false; + } + } else { + return (cullResultFlags & mask) != 0; + } + } + + public boolean faceNotOccluded(BlockState blockState, Direction face) { + BlockGetter blockGetter = this.renderRegion; + + BlockPos adjPos = tempPos.setWithOffset(blockPos, face); + BlockState adjBlockState = blockGetter.getBlockState(adjPos); + + if (blockState.skipRendering(adjBlockState, face)) { + return false; + } + + if (adjBlockState.canOcclude()) { + VoxelShape shape = blockState.getFaceOcclusionShape(blockGetter, blockPos, face); + + if (shape.isEmpty()) + return true; + + VoxelShape adjShape = adjBlockState.getFaceOcclusionShape(blockGetter, adjPos, face.getOpposite()); + + if (adjShape.isEmpty()) + return true; + + if (shape == Shapes.block() && adjShape == Shapes.block()) { + return false; + } + + Block.BlockStatePairKey blockStatePairKey = new Block.BlockStatePairKey(blockState, adjBlockState, face); + + byte b = occlusionCache.getAndMoveToFirst(blockStatePairKey); + if (b != 127) { + return b != 0; + } else { + boolean bl = Shapes.joinIsNotEmpty(shape, adjShape, BooleanOp.ONLY_FIRST); + + if (occlusionCache.size() == 2048) { + occlusionCache.removeLastByte(); + } + + occlusionCache.putAndMoveToFirst(blockStatePairKey, (byte) (bl ? 1 : 0)); + return bl; + } + } + + return true; + } + + private void renderQuad(MutableQuadViewImpl quad) { + if (!transform(quad)) { + return; + } + + if (isFaceCulled(quad.cullFace())) { + return; + } + + endRenderQuad(quad); + } + + protected void endRenderQuad(MutableQuadViewImpl quad) {} + + /** handles block color, common to all renders. */ + protected void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { + if (colorIndex != -1) { + final int blockColor = getBlockColor(this.renderRegion, colorIndex); + + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyColor(blockColor, quad.color(i))); + } + } + } + + private int getBlockColor(BlockAndTintGetter region, int colorIndex) { + return 0xFF000000 | blockColors.getColor(blockState, region, blockPos, colorIndex); + } + + protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, boolean emissive, boolean vanillaShade) { + QuadLightData data = this.quadLightData; + + // TODO: enhanced AO + lightPipeline.calculate(quad, this.blockPos, data, quad.cullFace(), quad.lightFace(), quad.hasShade()); + + if (emissive) { + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); + quad.lightmap(i, LightTexture.FULL_BRIGHT); + } + } else { + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); + quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i])); + } + } + } + + public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, RenderContext context) { + MutableQuadViewImpl quad = this.editorQuad; + final RenderMaterial defaultMaterial = model.useAmbientOcclusion() ? STANDARD_MATERIAL : NO_AO_MATERIAL; + + boolean noTransform = !this.hasTransform(); + + if (noTransform) { + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + + if (context.isFaceCulled(cullFace)) { + // Skip entire quad list if possible. + continue; + } + + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); + + //noinspection ForLoopReplaceableByForEach + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + quad.fromVanilla(q, defaultMaterial, cullFace); + + this.endRenderQuad(quad); + } + } + } else { + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); + + //noinspection ForLoopReplaceableByForEach + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + quad.fromVanilla(q, defaultMaterial, cullFace); + + this.renderQuad(quad); + } + } + } + + } + +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java new file mode 100644 index 0000000000..5048e0874b --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.render; + +import java.util.function.Consumer; +import com.mojang.blaze3d.vertex.VertexConsumer; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.joml.Vector4f; +import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; +import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; +import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; + +abstract class AbstractRenderContext implements RenderContext { + private static final QuadTransform NO_TRANSFORM = q -> true; + + private QuadTransform activeTransform = NO_TRANSFORM; + private final ObjectArrayList transformStack = new ObjectArrayList<>(); + private final QuadTransform stackTransform = q -> { + int i = transformStack.size() - 1; + + while (i >= 0) { + if (!transformStack.get(i--).transform(q)) { + return false; + } + } + + return true; + }; + + @Deprecated + private final Consumer meshConsumer = mesh -> mesh.outputTo(getEmitter()); + + protected Matrix4f matrix; + protected Matrix3f normalMatrix; + protected int overlay; + private final Vector4f posVec = new Vector4f(); + private final Vector3f normalVec = new Vector3f(); + + protected final boolean transform(MutableQuadView q) { + return activeTransform.transform(q); + } + + @Override + public boolean hasTransform() { + return activeTransform != NO_TRANSFORM; + } + + @Override + public void pushTransform(QuadTransform transform) { + if (transform == null) { + throw new NullPointerException("Renderer received null QuadTransform."); + } + + transformStack.push(transform); + + if (transformStack.size() == 1) { + activeTransform = transform; + } else if (transformStack.size() == 2) { + activeTransform = stackTransform; + } + } + + @Override + public void popTransform() { + transformStack.pop(); + + if (transformStack.size() == 0) { + activeTransform = NO_TRANSFORM; + } else if (transformStack.size() == 1) { + activeTransform = transformStack.get(0); + } + } + + // Overridden to prevent allocating a lambda every time this method is called. + @Deprecated + @Override + public Consumer meshConsumer() { + return meshConsumer; + } + + /** final output step, common to all renders. */ + protected void bufferQuad(MutableQuadViewImpl quad, VertexConsumer vertexConsumer) { + final Vector4f posVec = this.posVec; + final Vector3f normalVec = this.normalVec; + final boolean useNormals = quad.hasVertexNormals(); + + if (useNormals) { + quad.populateMissingNormals(); + } else { + normalVec.set(quad.faceNormal()); + normalVec.mul(normalMatrix); + } + + for (int i = 0; i < 4; i++) { + posVec.set(quad.x(i), quad.y(i), quad.z(i), 1.0f); + posVec.mul(matrix); + vertexConsumer.addVertex(posVec.x(), posVec.y(), posVec.z()); + + final int color = quad.color(i); + vertexConsumer.setColor(color); + vertexConsumer.setUv(quad.u(i), quad.v(i)); + vertexConsumer.setOverlay(overlay); + vertexConsumer.setLight(quad.lightmap(i)); + + if (useNormals) { + quad.copyNormal(i, normalVec); + normalVec.mul(normalMatrix); + } + + vertexConsumer.setNormal(normalVec.x(), normalVec.y(), normalVec.z()); + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java new file mode 100644 index 0000000000..b00e6be85a --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.CrashReport; +import net.minecraft.CrashReportCategory; +import net.minecraft.ReportedException; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; +import net.vulkanmod.Initializer; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import net.vulkanmod.render.chunk.build.light.LightMode; +import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.ArrayLightDataCache; +import net.vulkanmod.render.chunk.build.light.flat.FlatLightPipeline; +import net.vulkanmod.render.chunk.build.light.smooth.NewSmoothLightPipeline; +import net.vulkanmod.render.chunk.build.light.smooth.SmoothLightPipeline; + +/** + * Context for non-terrain block rendering. + */ +public class BlockRenderContext extends AbstractBlockRenderContext { + private VertexConsumer vertexConsumer; + + private final ArrayLightDataCache lightDataCache = new ArrayLightDataCache(); + + public BlockRenderContext() { + LightPipeline flatLightPipeline = new FlatLightPipeline(this.lightDataCache); + + LightPipeline smoothLightPipeline; + if (Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK) { + smoothLightPipeline = new NewSmoothLightPipeline(lightDataCache); + } + else { + smoothLightPipeline = new SmoothLightPipeline(lightDataCache); + } + + this.setupLightPipelines(flatLightPipeline, smoothLightPipeline); + } + + public void render(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrixStack, VertexConsumer buffer, boolean cull, RandomSource random, long seed, int overlay) { + try { + Vec3 offset = state.getOffset(blockView, pos); + matrixStack.translate(offset.x, offset.y, offset.z); + + this.blockPos = pos; + this.vertexConsumer = buffer; + this.matrix = matrixStack.last().pose(); + this.normalMatrix = matrixStack.last().normal(); + this.overlay = overlay; + + this.random = random; + this.seed = seed; + + this.lightDataCache.reset(blockView, pos); + + this.prepareForWorld(blockView, cull); + this.prepareForBlock(state, pos, model.useAmbientOcclusion()); + + model.emitBlockQuads(blockView, state, pos, this.randomSupplier, this); + } catch (Throwable throwable) { + CrashReport crashReport = CrashReport.forThrowable(throwable, "Tessellating block model - Indigo Renderer"); + CrashReportCategory crashReportSection = crashReport.addCategory("Block model being tessellated"); + CrashReportCategory.populateBlockDetails(crashReportSection, blockView, pos, state); + throw new ReportedException(crashReport); + } finally { + this.vertexConsumer = null; + } + } + + protected void endRenderQuad(MutableQuadViewImpl quad) { + final RenderMaterial mat = quad.material(); + final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); + final TriState aoMode = mat.ambientOcclusion(); + final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); + final boolean emissive = mat.emissive(); + final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; + + LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; + + colorizeQuad(quad, colorIndex); + shadeQuad(quad, lightPipeline, emissive, vanillaShade); + bufferQuad(quad, vertexConsumer); + } + +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java new file mode 100644 index 0000000000..6ece16a2d0 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -0,0 +1,333 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.MatrixUtil; + +import java.util.List; +import java.util.function.Supplier; + +import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; +import org.jetbrains.annotations.Nullable; +import net.minecraft.client.Minecraft; +import net.minecraft.client.color.item.ItemColors; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.entity.ItemRenderer; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.util.TriState; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import net.fabricmc.fabric.impl.renderer.VanillaModelEncoder; + +import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; + +/** + * The render context used for item rendering. + */ +@SuppressWarnings("removal") +public class ItemRenderContext extends AbstractRenderContext { + /** Value vanilla uses for item rendering. The only sensible choice, of course. */ + private static final long ITEM_RANDOM_SEED = 42L; + + private final ItemColors itemColors; + private final RandomSource random = RandomSource.create(); + private final Supplier randomSupplier = () -> { + random.setSeed(ITEM_RANDOM_SEED); + return random; + }; + + private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { + { + data = new int[EncodingFormat.TOTAL_STRIDE]; + clear(); + } + + @Override + public void emitDirectly() { + renderQuad(this); + } + }; + + private final BakedModelConsumerImpl vanillaModelConsumer = new BakedModelConsumerImpl(); + + private ItemStack itemStack; + private ItemDisplayContext transformMode; + private PoseStack matrixStack; + private MultiBufferSource vertexConsumerProvider; + private int lightmap; + + private boolean isDefaultTranslucent; + private boolean isTranslucentDirect; + private boolean isDefaultGlint; + private boolean isGlintDynamicDisplay; + + private PoseStack.Pose dynamicDisplayGlintEntry; + private VertexConsumer translucentVertexConsumer; + private VertexConsumer cutoutVertexConsumer; + private VertexConsumer translucentGlintVertexConsumer; + private VertexConsumer cutoutGlintVertexConsumer; + + public ItemRenderContext(ItemColors itemColors) { + this.itemColors = itemColors; + } + + @Override + public QuadEmitter getEmitter() { + editorQuad.clear(); + return editorQuad; + } + + @Override + public boolean isFaceCulled(@Nullable Direction face) { + throw new IllegalStateException("isFaceCulled can only be called on a block render context."); + } + + @Override + public ItemDisplayContext itemTransformationMode() { + return transformMode; + } + + @Override + public BakedModelConsumer bakedModelConsumer() { + return vanillaModelConsumer; + } + + public void renderModel(ItemStack itemStack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int lightmap, int overlay, BakedModel model) { + this.itemStack = itemStack; + this.transformMode = transformMode; + this.matrixStack = matrixStack; + this.vertexConsumerProvider = vertexConsumerProvider; + this.lightmap = lightmap; + this.overlay = overlay; + computeOutputInfo(); + + matrix = matrixStack.last().pose(); + normalMatrix = matrixStack.last().normal(); + + model.emitItemQuads(itemStack, randomSupplier, this); + + this.itemStack = null; + this.matrixStack = null; + this.vertexConsumerProvider = null; + + dynamicDisplayGlintEntry = null; + translucentVertexConsumer = null; + cutoutVertexConsumer = null; + translucentGlintVertexConsumer = null; + cutoutGlintVertexConsumer = null; + } + + public void emitItemQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier) { + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); + + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); + + endRenderQuad(editorQuad); + } + } + } + + private void computeOutputInfo() { + isDefaultTranslucent = true; + isTranslucentDirect = true; + + Item item = itemStack.getItem(); + + if (item instanceof BlockItem blockItem) { + BlockState state = blockItem.getBlock().defaultBlockState(); + RenderType renderLayer = ItemBlockRenderTypes.getChunkRenderType(state); + + if (renderLayer != RenderType.translucent()) { + isDefaultTranslucent = false; + } + + if (transformMode != ItemDisplayContext.GUI && !transformMode.firstPerson()) { + isTranslucentDirect = false; + } + } + + isDefaultGlint = itemStack.hasFoil(); + isGlintDynamicDisplay = ItemRendererAccessor.hasAnimatedTexture(itemStack); + } + + private void renderQuad(MutableQuadViewImpl quad) { + if (!transform(quad)) { + return; + } + + endRenderQuad(quad); + } + + private void endRenderQuad(MutableQuadViewImpl quad) { + final RenderMaterial mat = quad.material(); + final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); + final boolean emissive = mat.emissive(); + final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glint()); + + colorizeQuad(quad, colorIndex); + shadeQuad(quad, emissive); + bufferQuad(quad, vertexConsumer); + } + + private void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { + if (colorIndex != -1) { + final int itemColor = itemColors.getColor(itemStack, colorIndex); + + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyColor(itemColor, quad.color(i))); + } + } + } + + private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { + if (emissive) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, LightTexture.FULL_BRIGHT); + } + } else { + final int lightmap = this.lightmap; + + for (int i = 0; i < 4; i++) { + quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); + } + } + } + + /** + * Caches custom blend mode / vertex consumers and mimics the logic + * in {@code RenderLayers.getEntityBlockLayer}. Layers other than + * translucent are mapped to cutout. + */ + private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode) { + boolean translucent; + boolean glint; + + if (blendMode == BlendMode.DEFAULT) { + translucent = isDefaultTranslucent; + } else { + translucent = blendMode == BlendMode.TRANSLUCENT; + } + + if (glintMode == TriState.DEFAULT) { + glint = isDefaultGlint; + } else { + glint = glintMode == TriState.TRUE; + } + + if (translucent) { + if (glint) { + if (translucentGlintVertexConsumer == null) { + translucentGlintVertexConsumer = createTranslucentVertexConsumer(true); + } + + return translucentGlintVertexConsumer; + } else { + if (translucentVertexConsumer == null) { + translucentVertexConsumer = createTranslucentVertexConsumer(false); + } + + return translucentVertexConsumer; + } + } else { + if (glint) { + if (cutoutGlintVertexConsumer == null) { + cutoutGlintVertexConsumer = createCutoutVertexConsumer(true); + } + + return cutoutGlintVertexConsumer; + } else { + if (cutoutVertexConsumer == null) { + cutoutVertexConsumer = createCutoutVertexConsumer(false); + } + + return cutoutVertexConsumer; + } + } + } + + private VertexConsumer createTranslucentVertexConsumer(boolean glint) { + if (glint && isGlintDynamicDisplay) { + return createDynamicDisplayGlintVertexConsumer(Minecraft.useShaderTransparency() && !isTranslucentDirect ? Sheets.translucentItemSheet() : Sheets.translucentCullBlockSheet()); + } + + if (isTranslucentDirect) { + return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); + } else if (Minecraft.useShaderTransparency()) { + return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentItemSheet(), true, glint); + } else { + return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); + } + } + + private VertexConsumer createCutoutVertexConsumer(boolean glint) { + if (glint && isGlintDynamicDisplay) { + return createDynamicDisplayGlintVertexConsumer(Sheets.cutoutBlockSheet()); + } + + return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.cutoutBlockSheet(), true, glint); + } + + private VertexConsumer createDynamicDisplayGlintVertexConsumer(RenderType layer) { + if (dynamicDisplayGlintEntry == null) { + dynamicDisplayGlintEntry = matrixStack.last().copy(); + + if (transformMode == ItemDisplayContext.GUI) { + MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.5F); + } else if (transformMode.firstPerson()) { + MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.75F); + } + } + + return ItemRenderer.getCompassFoilBuffer(vertexConsumerProvider, layer, dynamicDisplayGlintEntry); + } + + private class BakedModelConsumerImpl implements BakedModelConsumer { + @Override + public void accept(BakedModel model) { + accept(model, null); + } + + @Override + public void accept(BakedModel model, @Nullable BlockState state) { + VanillaModelEncoder.emitItemQuads(model, state, randomSupplier, ItemRenderContext.this); + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java index ba0fa8a7ba..69d3c184e3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java @@ -2,7 +2,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.vulkanmod.render.model.quad.QuadView; +import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; /** @@ -19,5 +19,5 @@ public interface LightPipeline { * @param lightFace The light face of the quad * @param shade True if the block is shaded by ambient occlusion */ - void calculate(QuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade); + void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java index 1fbde68f7f..74e9a2b9ca 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java @@ -34,6 +34,16 @@ public void reset(BlockAndTintGetter blockAndTintGetter, int x, int y, int z) { Arrays.fill(this.light, 0); } + public void reset(BlockAndTintGetter blockAndTintGetter, BlockPos origin) { + this.world = blockAndTintGetter; + + this.xOffset = origin.getX() - NEIGHBOR_BLOCK_RADIUS; + this.yOffset = origin.getY() - NEIGHBOR_BLOCK_RADIUS; + this.zOffset = origin.getZ() - NEIGHBOR_BLOCK_RADIUS; + + Arrays.fill(this.light, 0); + } + public void reset(SectionPos origin) { this.xOffset = origin.minBlockX() - NEIGHBOR_BLOCK_RADIUS; this.yOffset = origin.minBlockY() - NEIGHBOR_BLOCK_RADIUS; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java index 2472ac4b88..ac350f6933 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java @@ -4,7 +4,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.QuadView; +import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; @@ -29,7 +29,7 @@ public FlatLightPipeline(LightDataAccess lightCache) { } @Override - public void calculate(QuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade) { + public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade) { int lightmap; // To match vanilla behavior, use the cull face if it exists/is available diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java index 32cdabcb99..45ff919c5d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java @@ -4,7 +4,7 @@ import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.QuadView; +import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; @@ -42,7 +42,7 @@ public NewSmoothLightPipeline(LightDataAccess cache) { } @Override - public void calculate(QuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { + public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { this.updateCachedData(pos.asLong()); int flags = quad.getFlags(); @@ -85,7 +85,7 @@ private void applyAlignedFullFace(AoNeighborInfo neighborInfo, BlockPos pos, Sim * Calculates the light data for a grid-aligned quad that does not cover the entire block volume's face. * Flags: IS_ALIGNED, IS_PARTIAL */ - private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { // TODO stair lighting is inconsistent // A solution might be an interpolation grid // this.self.calculatePartialAlignedFace(this.lightCache, pos, dir); @@ -104,13 +104,13 @@ private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, QuadView quad, } /** - * This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, QuadView, BlockPos, SimpleDirection, + * This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, ModelQuadView, BlockPos, SimpleDirection, * QuadLightData)} but with the check for a depth of approximately 0 removed. If the quad is parallel but not * aligned, all of its vertices will have the same depth and this depth must be approximately greater than 0, * meaning the check for 0 will always return false. * Flags: !IS_ALIGNED, IS_PARALLEL */ - private void applyParallelFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { this.self.calculateSelfOcclusion(this.lightCache, pos, dir); for (int i = 0; i < 4; i++) { @@ -139,7 +139,7 @@ private void applyParallelFace(AoNeighborInfo neighborInfo, QuadView quad, Block /** * Flags: !IS_ALIGNED, !IS_PARALLEL */ - private void applyNonParallelFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyNonParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting float cx = clamp(quad.getX(i)); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java index 62993e312d..b33d6cf3ae 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java @@ -4,7 +4,7 @@ import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.QuadView; +import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; @@ -67,7 +67,7 @@ public SmoothLightPipeline(LightDataAccess cache) { } @Override - public void calculate(QuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { + public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { this.updateCachedData(pos.asLong()); int flags = quad.getFlags(); @@ -110,7 +110,7 @@ private void applyAlignedFullFace(AoNeighborInfo neighborInfo, BlockPos pos, Sim * Calculates the light data for a grid-aligned quad that does not cover the entire block volume's face. * Flags: IS_ALIGNED, IS_PARTIAL */ - private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting float cx = clamp(quad.getX(i)); @@ -124,13 +124,13 @@ private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, QuadView quad, } /** - * This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, QuadView, BlockPos, SimpleDirection, + * This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, ModelQuadView, BlockPos, SimpleDirection, * QuadLightData)} but with the check for a depth of approximately 0 removed. If the quad is parallel but not * aligned, all of its vertices will have the same depth and this depth must be approximately greater than 0, * meaning the check for 0 will always return false. * Flags: !IS_ALIGNED, IS_PARALLEL */ - private void applyParallelFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting float cx = clamp(quad.getX(i)); @@ -157,7 +157,7 @@ private void applyParallelFace(AoNeighborInfo neighborInfo, QuadView quad, Block /** * Flags: !IS_ALIGNED, !IS_PARALLEL */ - private void applyNonParallelFace(AoNeighborInfo neighborInfo, QuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { + private void applyNonParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, SimpleDirection dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting float cx = clamp(quad.getX(i)); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java new file mode 100644 index 0000000000..f04244f3fa --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -0,0 +1,147 @@ +package net.vulkanmod.render.chunk.build.renderer; + +import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Vec3i; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.SingleThreadedRandomSource; +import net.minecraft.world.phys.Vec3; +import net.vulkanmod.Initializer; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext; +import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.model.quad.QuadUtils; +import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.vertex.TerrainBufferBuilder; +import net.vulkanmod.render.vertex.TerrainBuilder; +import net.vulkanmod.render.vertex.TerrainRenderType; +import net.vulkanmod.render.vertex.format.I32_SNorm; +import net.vulkanmod.vulkan.util.ColorUtil; +import org.joml.Vector3f; + +public class BlockRenderer extends AbstractBlockRenderContext { + private Vector3f pos; + + private BuilderResources resources; + private TerrainBuilder terrainBuilder; + + final boolean backFaceCulling = Initializer.CONFIG.backFaceCulling; + + private TerrainRenderType renderType; + + public void setResources(BuilderResources resources) { + this.resources = resources; + } + + public BlockRenderer(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { + super(); + this.setupLightPipelines(flatLightPipeline, smoothLightPipeline); + + this.random = new SingleThreadedRandomSource(42L); + } + + public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) { + this.pos = pos; + this.blockPos = blockPos; + this.blockState = blockState; + this.seed = blockState.getSeed(blockPos); + + TerrainRenderType renderType = TerrainRenderType.get(ItemBlockRenderTypes.getChunkRenderType(blockState)); + renderType = TerrainRenderType.getRemapped(renderType); + this.renderType = renderType; + this.terrainBuilder = this.resources.builderPack.builder(renderType); + this.terrainBuilder.setBlockAttributes(blockState); + + BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); + + BlockAndTintGetter renderRegion = this.renderRegion; + Vec3 offset = blockState.getOffset(renderRegion, blockPos); + pos.add((float) offset.x, (float) offset.y, (float) offset.z); + + this.prepareForBlock(blockState, blockPos, model.useAmbientOcclusion()); + + model.emitBlockQuads(renderRegion, blockState, blockPos, this.randomSupplier, this); + } + + protected void endRenderQuad(MutableQuadViewImpl quad) { + final RenderMaterial mat = quad.material(); + final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); + final TriState aoMode = mat.ambientOcclusion(); + final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); + final boolean emissive = mat.emissive(); + final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; + + TerrainBuilder terrainBuilder = getBufferBuilder(mat.blendMode()); + + LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; + + colorizeQuad(quad, colorIndex); + shadeQuad(quad, lightPipeline, emissive, vanillaShade); + bufferQuad(terrainBuilder, this.pos, quad, this.quadLightData); + } + + private TerrainBuilder getBufferBuilder(BlendMode blendMode) { + if (blendMode == BlendMode.DEFAULT) { + return this.terrainBuilder; + } else { + TerrainRenderType renderType = TerrainRenderType.get(blendMode.blockRenderLayer); + renderType = TerrainRenderType.getRemapped(renderType); + TerrainBuilder bufferBuilder = this.resources.builderPack.builder(renderType); + bufferBuilder.setBlockAttributes(this.blockState); + + return bufferBuilder; + } + } + + public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadView quad, QuadLightData quadLightData) { + QuadFacing quadFacing = quad.getQuadFacing(); + + if (renderType == TerrainRenderType.TRANSLUCENT || !this.backFaceCulling) { + quadFacing = QuadFacing.UNDEFINED; + } + + TerrainBufferBuilder bufferBuilder = terrainBuilder.getBufferBuilder(quadFacing.ordinal()); + + Vec3i normal = quad.getFacingDirection().getNormal(); + int packedNormal = I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); + + float[] brightnessArr = quadLightData.br; + int[] lights = quadLightData.lm; + + // Rotate triangles if needed to fix AO anisotropy + int idx = QuadUtils.getIterationStartIdx(brightnessArr, lights); + + bufferBuilder.ensureCapacity(); + + for (byte i = 0; i < 4; ++i) { + final float x = pos.x() + quad.getX(idx); + final float y = pos.y() + quad.getY(idx); + final float z = pos.z() + quad.getZ(idx); + + final int quadColor = quad.getColor(idx); + + int color = ColorUtil.ARGB.toRGBA(quadColor); + + final int light = lights[idx]; + final float u = quad.getU(idx); + final float v = quad.getV(idx); + + bufferBuilder.vertex(x, y, z, color, u, v, light, packedNormal); + + idx = (idx + 1) & 0b11; + } + + } + +} + diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java new file mode 100644 index 0000000000..0fbbe54154 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java @@ -0,0 +1,17 @@ +package net.vulkanmod.render.chunk.build.renderer; + +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; +import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler; + +public abstract class DefaultFluidRenderers { + + private static final ReferenceOpenHashSet set = new ReferenceOpenHashSet<>(); + + public static void add(FluidRenderHandler handler) { + set.add(handler); + } + + public static boolean has(FluidRenderHandler handler) { + return set.contains(handler); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java similarity index 88% rename from src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java rename to src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java index 2e5011bf41..b70970f410 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/LiquidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java @@ -1,12 +1,12 @@ -package net.vulkanmod.render.chunk.build; +package net.vulkanmod.render.chunk.build.renderer; import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler; import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandlerRegistry; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.tags.FluidTags; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.BlockGetter; @@ -26,12 +26,12 @@ import net.vulkanmod.render.model.quad.ModelQuadFlags; import net.vulkanmod.render.model.quad.QuadUtils; import net.vulkanmod.render.vertex.TerrainBufferBuilder; -import net.vulkanmod.render.vertex.TerrainBuilder; -import net.vulkanmod.render.vertex.VertexUtil; +import net.vulkanmod.render.vertex.TerrainRenderType; +import net.vulkanmod.render.vertex.format.I32_SNorm; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Vector3f; -public class LiquidRenderer { +public class FluidRenderer { private static final float MAX_FLUID_HEIGHT = 0.8888889F; private final BlockPos.MutableBlockPos mBlockPos = new BlockPos.MutableBlockPos(); @@ -40,14 +40,34 @@ public class LiquidRenderer { BuilderResources resources; + private final LightPipeline smoothLightPipeline; + private final LightPipeline flatLightPipeline; + private final int[] quadColors = new int[4]; + public FluidRenderer(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { + this.smoothLightPipeline = smoothLightPipeline; + this.flatLightPipeline = flatLightPipeline; + } + public void setResources(BuilderResources resources) { this.resources = resources; } - public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBuilder vertexConsumer) { - tessellate(blockState, fluidState, blockPos, vertexConsumer); + public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos blockPos) { + FluidRenderHandler handler = FluidRenderHandlerRegistry.INSTANCE.get(fluidState.getType()); + + TerrainRenderType renderType = TerrainRenderType.get(ItemBlockRenderTypes.getRenderLayer(fluidState)); + renderType = TerrainRenderType.getRemapped(renderType); + TerrainBufferBuilder bufferBuilder = this.resources.builderPack.builder(renderType).getBufferBuilder(QuadFacing.UNDEFINED.ordinal()); + + if (handler != null) { + handler.renderFluid(blockPos, this.resources.getRegion(), bufferBuilder, blockState, fluidState); + } + + if (DefaultFluidRenderers.has(handler)) { + tessellate(blockState, fluidState, blockPos, bufferBuilder); + } } private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Direction direction, BlockPos blockPos, BlockState blockState) { @@ -87,8 +107,8 @@ public BlockState getAdjBlockState(BlockAndTintGetter blockAndTintGetter, int x, return blockAndTintGetter.getBlockState(mBlockPos); } - public void tessellate(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBuilder vertexConsumer) { - BlockAndTintGetter region = this.resources.region; + public void tessellate(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBufferBuilder bufferBuilder) { + BlockAndTintGetter region = this.resources.getRegion(); final FluidRenderHandler handler = getFluidRenderHandler(fluidState); int color = handler.getFluidColor(region, blockPos, fluidState); @@ -104,7 +124,7 @@ public void tessellate(BlockState blockState, FluidState fluidState, BlockPos bl final int posZ = blockPos.getZ(); boolean useAO = blockState.getLightEmission() == 0 && Minecraft.useAmbientOcclusion(); - LightPipeline lightPipeline = useAO ? this.resources.smoothLightPipeline : this.resources.flatLightPipeline; + LightPipeline lightPipeline = useAO ? this.smoothLightPipeline : this.flatLightPipeline; BlockState downState = getAdjBlockState(region, posX, posY, posZ, Direction.DOWN); BlockState upState = getAdjBlockState(region, posX, posY, posZ, Direction.UP); @@ -216,10 +236,10 @@ public void tessellate(BlockState blockState, FluidState fluidState, BlockPos bl updateQuad(this.modelQuad, blockPos, lightPipeline, Direction.UP); updateColor(r, g, b, brightness); - putQuad(modelQuad, vertexConsumer, x0, y0, z0, false); + putQuad(modelQuad, bufferBuilder, x0, y0, z0, false); if (fluidState.shouldRenderBackwardUpFace(region, blockPos.above())) { - putQuad(modelQuad, vertexConsumer, x0, y0, z0, true); + putQuad(modelQuad, bufferBuilder, x0, y0, z0, true); } } @@ -242,8 +262,7 @@ public void tessellate(BlockState blockState, FluidState fluidState, BlockPos bl updateQuad(this.modelQuad, blockPos, lightPipeline, Direction.DOWN); updateColor(r, g, b, brightness); - putQuad(modelQuad, vertexConsumer, x0, y0, z0, false); - + putQuad(modelQuad, bufferBuilder, x0, y0, z0, false); } modelQuad.setFlags(ModelQuadFlags.IS_PARALLEL | ModelQuadFlags.IS_ALIGNED); @@ -349,10 +368,10 @@ public void tessellate(BlockState blockState, FluidState fluidState, BlockPos bl updateQuad(this.modelQuad, blockPos, lightPipeline, direction); updateColor(r, g, b, brightness); - putQuad(modelQuad, vertexConsumer, x0, y0, z0, false); + putQuad(modelQuad, bufferBuilder, x0, y0, z0, false); if (!isOverlay) { - putQuad(modelQuad, vertexConsumer, x0, y0, z0, true); + putQuad(modelQuad, bufferBuilder, x0, y0, z0, true); } } @@ -422,16 +441,15 @@ private int calculateNormal(ModelQuad quad) { .cross(quad.getX(3), quad.getY(3), quad.getZ(3)); normal.normalize(); - return VertexUtil.packNormal(normal.x(), normal.y(), normal.z()); + return I32_SNorm.packNormal(normal.x(), normal.y(), normal.z()); } - private void putQuad(ModelQuad quad, TerrainBuilder builder, float xOffset, float yOffset, float zOffset, boolean flip) { + private void putQuad(ModelQuad quad, TerrainBufferBuilder bufferBuilder, float xOffset, float yOffset, float zOffset, boolean flip) { QuadLightData quadLightData = resources.quadLightData; // Rotate triangles if needed to fix AO anisotropy int k = QuadUtils.getIterationStartIdx(quadLightData.br); - TerrainBufferBuilder bufferBuilder = builder.getBufferBuilder(QuadFacing.NONE.ordinal()); bufferBuilder.ensureCapacity(); int i; @@ -458,11 +476,8 @@ private void setVertex(ModelQuad quad, int i, float x, float y, float z, float u quad.setV(i, v); } - private void updateQuad(ModelQuad quad, BlockPos blockPos, - LightPipeline lightPipeline, Direction dir) { - + private void updateQuad(ModelQuad quad, BlockPos blockPos, LightPipeline lightPipeline, Direction dir) { lightPipeline.calculate(quad, blockPos, resources.quadLightData, null, dir, false); - } private void updateColor(float r, float g, float b, float brightness) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java index 6dd75fa6f3..068700b6d0 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java @@ -1,7 +1,6 @@ package net.vulkanmod.render.chunk.build.task; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.chunk.VisGraph; import net.minecraft.core.BlockPos; @@ -13,8 +12,8 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.render.chunk.build.BlockRenderer; -import net.vulkanmod.render.chunk.build.LiquidRenderer; +import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; +import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.UploadBuffer; import net.vulkanmod.render.chunk.build.thread.BuilderResources; @@ -95,7 +94,7 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc BlockRenderer blockRenderer = builderResources.blockRenderer; - LiquidRenderer liquidRenderer = builderResources.liquidRenderer; + FluidRenderer fluidRenderer = builderResources.fluidRenderer; BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(); @@ -117,35 +116,23 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc } FluidState fluidState = blockState.getFluidState(); - TerrainRenderType renderType; - TerrainBuilder terrainBuilder; if (!fluidState.isEmpty()) { - renderType = TerrainRenderType.get(ItemBlockRenderTypes.getRenderLayer(fluidState)); - - terrainBuilder = getTerrainBuilder(bufferBuilders, renderType); - terrainBuilder.setBlockAttributes(blockState); - - liquidRenderer.renderLiquid(blockState, fluidState, blockPos, terrainBuilder); + fluidRenderer.renderLiquid(blockState, fluidState, blockPos); } if (blockState.getRenderShape() == RenderShape.MODEL) { - renderType = TerrainRenderType.get(ItemBlockRenderTypes.getChunkRenderType(blockState)); - - terrainBuilder = getTerrainBuilder(bufferBuilders, renderType); - terrainBuilder.setBlockAttributes(blockState); - pos.set(blockPos.getX() & 15, blockPos.getY() & 15, blockPos.getZ() & 15); - blockRenderer.renderBlock(blockState, blockPos, renderType, pos, terrainBuilder); + blockRenderer.renderBlock(blockState, blockPos, pos); } } } } - TerrainBuilder translucentBufferBuilder = bufferBuilders.builder(TerrainRenderType.TRANSLUCENT); - if (translucentBufferBuilder.getBufferBuilder(QuadFacing.NONE.ordinal()).getVertices() > 0) { - translucentBufferBuilder.setupQuadSortingPoints(); - translucentBufferBuilder.setupQuadSorting(camX - (float) startBlockPos.getX(), camY - (float) startBlockPos.getY(), camZ - (float) startBlockPos.getZ()); - compileResult.transparencyState = translucentBufferBuilder.getSortState(); + TerrainBuilder trasnlucentTerrainBuilder = bufferBuilders.builder(TerrainRenderType.TRANSLUCENT); + if (trasnlucentTerrainBuilder.getBufferBuilder(QuadFacing.UNDEFINED.ordinal()).getVertices() > 0) { + trasnlucentTerrainBuilder.setupQuadSortingPoints(); + trasnlucentTerrainBuilder.setupQuadSorting(camX - (float) startBlockPos.getX(), camY - (float) startBlockPos.getY(), camZ - (float) startBlockPos.getZ()); + compileResult.transparencyState = trasnlucentTerrainBuilder.getSortState(); } for (TerrainRenderType renderType : TerrainRenderType.VALUES) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java index 13d416da6c..c1acc33dfc 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java @@ -2,7 +2,6 @@ import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.build.RenderRegion; -import net.vulkanmod.render.chunk.build.TaskDispatcher; import net.vulkanmod.render.chunk.build.thread.BuilderResources; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java similarity index 97% rename from src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java rename to src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java index 2e5633f9d6..0a3cf4def9 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/TaskDispatcher.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java @@ -1,4 +1,4 @@ -package net.vulkanmod.render.chunk.build; +package net.vulkanmod.render.chunk.build.task; import com.google.common.collect.Queues; import net.vulkanmod.render.chunk.ChunkArea; @@ -6,8 +6,7 @@ import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.buffer.DrawBuffers; -import net.vulkanmod.render.chunk.build.task.ChunkTask; -import net.vulkanmod.render.chunk.build.task.CompileResult; +import net.vulkanmod.render.chunk.build.UploadBuffer; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.chunk.build.thread.BuilderResources; import net.vulkanmod.render.vertex.TerrainRenderType; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java index 41a05af957..fd6e69f114 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java @@ -2,10 +2,10 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.RenderSection; -import net.vulkanmod.render.chunk.build.BlockRenderer; -import net.vulkanmod.render.chunk.build.LiquidRenderer; +import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; +import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; import net.vulkanmod.render.chunk.build.RenderRegion; -import net.vulkanmod.render.chunk.build.TintCache; +import net.vulkanmod.render.chunk.build.color.TintCache; import net.vulkanmod.render.chunk.build.light.LightMode; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.ArrayLightDataCache; @@ -16,37 +16,41 @@ public class BuilderResources { public final ThreadBuilderPack builderPack = new ThreadBuilderPack(); - public final BlockRenderer blockRenderer = new BlockRenderer(); - public final LiquidRenderer liquidRenderer = new LiquidRenderer(); - public final TintCache tintCache = new TintCache(); - public RenderRegion region; + public final BlockRenderer blockRenderer; + public final FluidRenderer fluidRenderer; public final ArrayLightDataCache lightDataCache = new ArrayLightDataCache(); public final QuadLightData quadLightData = new QuadLightData(); - public final LightPipeline smoothLightPipeline; - public final LightPipeline flatLightPipeline; + private RenderRegion region; private int totalBuildTime = 0, buildCount = 0; public BuilderResources() { - this.flatLightPipeline = new FlatLightPipeline(lightDataCache); + LightPipeline flatLightPipeline = new FlatLightPipeline(this.lightDataCache); + + LightPipeline smoothLightPipeline; + if (Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK) { + smoothLightPipeline = new NewSmoothLightPipeline(lightDataCache); + } + else { + smoothLightPipeline = new SmoothLightPipeline(lightDataCache); + } + + this.blockRenderer = new BlockRenderer(flatLightPipeline, smoothLightPipeline); + this.fluidRenderer = new FluidRenderer(flatLightPipeline, smoothLightPipeline); - if(Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK) - this.smoothLightPipeline = new NewSmoothLightPipeline(lightDataCache); - else - this.smoothLightPipeline = new SmoothLightPipeline(lightDataCache); + this.blockRenderer.setResources(this); + this.fluidRenderer.setResources(this); } public void update(RenderRegion region, RenderSection renderSection) { this.region = region; + this.blockRenderer.prepareForWorld(region, true); - lightDataCache.reset(region, renderSection.xOffset(), renderSection.yOffset(), renderSection.zOffset()); - - blockRenderer.setResources(this); - liquidRenderer.setResources(this); + this.lightDataCache.reset(region, renderSection.xOffset(), renderSection.yOffset(), renderSection.zOffset()); } public void clear() { @@ -58,6 +62,10 @@ public void updateBuildStats(int buildTime) { this.totalBuildTime += buildTime; } + public RenderRegion getRegion() { + return region; + } + public int getTotalBuildTime() { return totalBuildTime; } diff --git a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java index bc8e4ff17d..6423968e4d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java +++ b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java @@ -1,6 +1,8 @@ package net.vulkanmod.render.chunk.cull; import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.vulkanmod.render.vertex.format.I32_SNorm; public enum QuadFacing { X_POS, @@ -9,12 +11,12 @@ public enum QuadFacing { Y_NEG, Z_POS, Z_NEG, - NONE; + UNDEFINED; public static final QuadFacing[] VALUES = QuadFacing.values(); public static final int COUNT = VALUES.length; - public static QuadFacing from(Direction direction) { + public static QuadFacing fromDirection(Direction direction) { return switch (direction) { case DOWN -> Y_NEG; case UP -> Y_POS; @@ -24,4 +26,32 @@ public static QuadFacing from(Direction direction) { case EAST -> X_POS; }; } + + public static QuadFacing fromNormal(int packedNormal) { + final float x = I32_SNorm.unpackX(packedNormal); + final float y = I32_SNorm.unpackY(packedNormal); + final float z = I32_SNorm.unpackZ(packedNormal); + + final float absX = Math.abs(x); + final float absY = Math.abs(y); + final float absZ = Math.abs(z); + + float sum = absX + absY + absZ; + + if (Mth.equal(sum, 1.0f)) { + if (Mth.equal(absX, 1.0f)) { + return x > 0.0f ? QuadFacing.X_POS : QuadFacing.X_NEG; + } + + if (Mth.equal(absY, 1.0f)) { + return y > 0.0f ? QuadFacing.Y_POS : QuadFacing.Y_NEG; + } + + if (Mth.equal(absZ, 1.0f)) { + return z > 0.0f ? QuadFacing.Z_POS : QuadFacing.Z_NEG; + } + } + + return QuadFacing.UNDEFINED; + } } diff --git a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java index f3758feda9..8a3d641beb 100644 --- a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java +++ b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java @@ -13,7 +13,7 @@ import net.vulkanmod.interfaces.FrustumMixed; import net.vulkanmod.render.chunk.*; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; -import net.vulkanmod.render.chunk.build.TaskDispatcher; +import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.frustum.VFrustum; import net.vulkanmod.render.chunk.util.AreaSetQueue; import net.vulkanmod.render.chunk.util.ResettableQueue; diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java index efeebc0bda..e560006e9b 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java @@ -2,10 +2,15 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.vulkanmod.render.chunk.cull.QuadFacing; -public class ModelQuad implements QuadView { +public class ModelQuad implements ModelQuadView { public static final int VERTEX_SIZE = 8; + public static int vertexOffset(int vertexIndex) { + return vertexIndex * VERTEX_SIZE; + } + private final int[] data = new int[4 * VERTEX_SIZE]; Direction direction; @@ -58,6 +63,21 @@ public Direction getFacingDirection() { return this.direction; } + @Override + public Direction lightFace() { + return this.direction; + } + + @Override + public QuadFacing getQuadFacing() { + return QuadFacing.UNDEFINED; + } + + @Override + public int getNormal() { + return 0; + } + public float setX(int idx, float f) { return this.data[vertexOffset(idx)] = Float.floatToRawIntBits(f); } @@ -88,8 +108,4 @@ public void setFlags(int f) { public void setSprite(TextureAtlasSprite sprite) { this.sprite = sprite; } - - private static int vertexOffset(int vertexIndex) { - return vertexIndex * VERTEX_SIZE; - } } diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java index 9016cb4aa0..bb1dc0cca5 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java @@ -2,8 +2,6 @@ import net.minecraft.core.Direction; -import static net.vulkanmod.render.model.quad.ModelQuad.VERTEX_SIZE; - public class ModelQuadFlags { /** * Indicates that the quad does not fully cover the given face for the model. @@ -25,7 +23,7 @@ public static boolean contains(int flags, int mask) { return (flags & mask) != 0; } - public static int getQuadFlags(int[] vertices, Direction face) { + public static int getQuadFlags(ModelQuadView quad, Direction face) { float minX = 32.0F; float minY = 32.0F; float minZ = 32.0F; @@ -35,9 +33,9 @@ public static int getQuadFlags(int[] vertices, Direction face) { float maxZ = -32.0F; for (int i = 0; i < 4; ++i) { - float x = Float.intBitsToFloat(vertices[i * VERTEX_SIZE]); - float y = Float.intBitsToFloat(vertices[i * VERTEX_SIZE + 1]); - float z = Float.intBitsToFloat(vertices[i * VERTEX_SIZE + 2]); + float x = quad.getX(i); + float y = quad.getY(i); + float z = quad.getZ(i); minX = Math.min(minX, x); minY = Math.min(minY, y); diff --git a/src/main/java/net/vulkanmod/render/model/quad/QuadView.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java similarity index 71% rename from src/main/java/net/vulkanmod/render/model/quad/QuadView.java rename to src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java index 883c4b3156..ac791d9a59 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/QuadView.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java @@ -1,8 +1,9 @@ package net.vulkanmod.render.model.quad; import net.minecraft.core.Direction; +import net.vulkanmod.render.chunk.cull.QuadFacing; -public interface QuadView { +public interface ModelQuadView { int getFlags(); @@ -22,6 +23,12 @@ public interface QuadView { Direction getFacingDirection(); + Direction lightFace(); + + QuadFacing getQuadFacing(); + + int getNormal(); + default boolean isTinted() { return this.getColorIndex() != -1; } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java index e53f46694a..9e8651dae0 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java @@ -1,13 +1,14 @@ package net.vulkanmod.render.vertex; +import com.mojang.blaze3d.vertex.VertexConsumer; import net.vulkanmod.Initializer; -import net.vulkanmod.render.PipelineManager; +import net.vulkanmod.render.vertex.format.I32_SNorm; import org.apache.logging.log4j.Logger; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; -public class TerrainBufferBuilder { +public class TerrainBufferBuilder implements VertexConsumer { private static final Logger LOGGER = Initializer.LOGGER; private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false); @@ -19,19 +20,15 @@ public class TerrainBufferBuilder { protected int nextElementByte; int vertices; - private VertexBuilder vertexBuilder; + private long elementPtr; -// private int renderedBufferCount; -// private int renderedBufferPointer; + private VertexBuilder vertexBuilder; public TerrainBufferBuilder(int size, int vertexSize, VertexBuilder vertexBuilder) { this.bufferPtr = ALLOCATOR.malloc(size); this.capacity = size; this.vertexSize = vertexSize; - -// this.format = PipelineManager.TERRAIN_VERTEX_FORMAT; - this.vertexBuilder = PipelineManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN - ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); + this.vertexBuilder = vertexBuilder; } public void ensureCapacity() { @@ -68,13 +65,11 @@ public void vertex(float x, float y, float z, int color, float u, float v, int l } public void end() { -// this.buffer.limit(this.nextElementByte); } public void clear() { this.nextElementByte = 0; this.vertices = 0; -// this.buffer.clear(); } public ByteBuffer getBuffer() { @@ -92,4 +87,55 @@ public int getVertices() { public int getNextElementByte() { return nextElementByte; } + + @Override + public VertexConsumer addVertex(float x, float y, float z) { + this.elementPtr = this.bufferPtr + this.nextElementByte; + this.endVertex(); + + this.vertexBuilder.position(this.elementPtr, x, y, z); + + return this; + } + + @Override + public VertexConsumer setColor(int r, int g, int b, int a) { + int color = (a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF); + + this.vertexBuilder.color(this.elementPtr, color); + + return this; + } + + @Override + public VertexConsumer setUv(float u, float v) { + this.vertexBuilder.uv(this.elementPtr, u, v); + + return this; + } + + public VertexConsumer setLight(int i) { + this.vertexBuilder.light(this.elementPtr, i); + + return this; + } + + @Override + public VertexConsumer setNormal(float f, float g, float h) { + int packedNormal = I32_SNorm.packNormal(f, g, h); + + this.vertexBuilder.normal(this.elementPtr, packedNormal); + + return this; + } + + @Override + public VertexConsumer setUv1(int i, int j) { + return this; + } + + @Override + public VertexConsumer setUv2(int i, int j) { + return this; + } } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index 55e379ff46..e09264a682 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -99,7 +99,7 @@ public void begin() { } public void setupQuadSortingPoints() { - TerrainBufferBuilder bufferBuilder = bufferBuilders[QuadFacing.NONE.ordinal()]; + TerrainBufferBuilder bufferBuilder = bufferBuilders[QuadFacing.UNDEFINED.ordinal()]; long bufferPtr = bufferBuilder.getPtr(); int vertexCount = bufferBuilder.getVertices(); @@ -114,11 +114,9 @@ public DrawState endDrawing() { int vertexCount = this.quadSorter.getVertexCount(); int indexCount = vertexCount / 4 * 6; -// int vertexBufferSize = !this.indexOnly ? vertexCount * this.format.getVertexSize() : 0; VertexFormat.IndexType indexType = VertexFormat.IndexType.least(indexCount); boolean sequentialIndexing; -// int size; // TODO sorting if (this.needsSorting) { @@ -128,27 +126,15 @@ public DrawState endDrawing() { this.quadSorter.putSortedQuadIndices(this, indexType); sequentialIndexing = false; -// this.nextElementByte += indexBufferSize; -// size = vertexBufferSize + indexBufferSize; } else { sequentialIndexing = true; -// size = vertexBufferSize; } -// this.indexBuffer.limit(this.indexCount * indexType.bytes); - -// int ptr = this.renderedBufferPointer; -// this.renderedBufferPointer += size; -// ++this.renderedBufferCount; - return new DrawState(this.format.getVertexSize(), indexCount, indexType, this.indexOnly, sequentialIndexing); -// return new RenderedBuffer(ptr, drawState); } // TODO hardcoded index type size public ByteBuffer getIndexBuffer() { - TerrainBufferBuilder bufferBuilder = this.bufferBuilders[QuadFacing.NONE.ordinal()]; -// int indexCount = bufferBuilder.getVertices() * 6 / 4; int indexCount = this.quadSorter.getVertexCount() * 6 / 4; return MemoryUtil.memByteBuffer(this.indexBufferPtr, indexCount * 2); @@ -162,7 +148,6 @@ private void ensureDrawing() { public void reset() { this.building = false; -// this.quadSorter.reset(); this.indexOnly = false; this.needsSorting = false; @@ -176,23 +161,9 @@ public void clear() { } } -// public void vertex(float x, float y, float z, int color, float u, float v, int light, int packedNormal) { -// final long ptr = this.bufferPtr + this.nextElementByte; -// this.vertexBuilder.vertex(ptr, x, y, z, color, u, v, light, packedNormal); -// this.endVertex(); -// } - public void setBlockAttributes(BlockState blockState) { } -// public long getPtr() { -// return this.bufferPtr + this.nextElementByte; -// } -// -// public int getVertexCount() { -// return vertexCount; -// } - public record DrawState(int vertexSize, int indexCount, VertexFormat.IndexType indexType, boolean indexOnly, boolean sequentialIndex) { diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java index bd42c07528..2eb1a14d00 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java @@ -1,10 +1,12 @@ package net.vulkanmod.render.vertex; import net.minecraft.client.renderer.RenderType; +import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ExtendedRenderType; import net.vulkanmod.vulkan.VRenderSystem; import java.util.EnumSet; +import java.util.function.Function; public enum TerrainRenderType { SOLID(0.0f), @@ -18,6 +20,8 @@ public enum TerrainRenderType { public static final EnumSet COMPACT_RENDER_TYPES = EnumSet.of(CUTOUT_MIPPED, TRANSLUCENT); public static final EnumSet SEMI_COMPACT_RENDER_TYPES = EnumSet.of(CUTOUT_MIPPED, CUTOUT, TRANSLUCENT); + private static Function remapper; + static { SEMI_COMPACT_RENDER_TYPES.add(CUTOUT); SEMI_COMPACT_RENDER_TYPES.add(CUTOUT_MIPPED); @@ -61,4 +65,23 @@ public static RenderType getRenderType(TerrainRenderType renderType) { case TRIPWIRE -> RenderType.tripwire(); }; } + + public static void updateMapping() { + if (Initializer.CONFIG.uniqueOpaqueLayer) { + remapper = (renderType) -> switch (renderType) { + case SOLID, CUTOUT, CUTOUT_MIPPED -> TerrainRenderType.CUTOUT_MIPPED; + case TRANSLUCENT, TRIPWIRE -> TerrainRenderType.TRANSLUCENT; + }; + } else { + remapper = (renderType) -> switch (renderType) { + case SOLID, CUTOUT_MIPPED -> TerrainRenderType.CUTOUT_MIPPED; + case CUTOUT -> TerrainRenderType.CUTOUT; + case TRANSLUCENT, TRIPWIRE -> TerrainRenderType.TRANSLUCENT; + }; + } + } + + public static TerrainRenderType getRemapped(TerrainRenderType renderType) { + return remapper.apply(renderType); + } } diff --git a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java index 511845515c..c26f580824 100644 --- a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java @@ -5,6 +5,16 @@ public interface VertexBuilder { void vertex(long ptr, float x, float y, float z, int color, float u, float v, int light, int packedNormal); + void position(long ptr, float x, float y, float z); + + void color(long ptr, int color); + + void uv(long ptr, float u, float v); + + void light(long ptr, int light); + + void normal(long ptr, int normal); + int getStride(); class DefaultVertexBuilder implements VertexBuilder { @@ -26,6 +36,32 @@ public void vertex(long ptr, float x, float y, float z, int color, float u, floa MemoryUtil.memPutInt(ptr + 28, packedNormal); } + // TODO + @Override + public void position(long ptr, float x, float y, float z) { + + } + + @Override + public void color(long ptr, int color) { + + } + + @Override + public void uv(long ptr, float u, float v) { + + } + + @Override + public void light(long ptr, int light) { + + } + + @Override + public void normal(long ptr, int normal) { + + } + @Override public int getStride() { return VERTEX_SIZE; @@ -59,6 +95,39 @@ public void vertex(long ptr, float x, float y, float z, int color, float u, floa MemoryUtil.memPutShort(ptr + 14, (short) (v * UV_CONV_MUL)); } + @Override + public void position(long ptr, float x, float y, float z) { + final short sX = (short) (x * POS_CONV_MUL + POS_OFFSET_CONV); + final short sY = (short) (y * POS_CONV_MUL + POS_OFFSET_CONV); + final short sZ = (short) (z * POS_CONV_MUL + POS_OFFSET_CONV); + + MemoryUtil.memPutShort(ptr + 0, sX); + MemoryUtil.memPutShort(ptr + 2, sY); + MemoryUtil.memPutShort(ptr + 4, sZ); + } + + @Override + public void color(long ptr, int color) { + MemoryUtil.memPutInt(ptr + 8, color); + } + + @Override + public void uv(long ptr, float u, float v) { + MemoryUtil.memPutShort(ptr + 12, (short) (u * UV_CONV_MUL)); + MemoryUtil.memPutShort(ptr + 14, (short) (v * UV_CONV_MUL)); + } + + @Override + public void light(long ptr, int light) { + final short l = (short) (((light >>> 8) & 0xFF00) | (light & 0xFF)); + MemoryUtil.memPutShort(ptr + 6, l); + } + + @Override + public void normal(long ptr, int normal) { + + } + @Override public int getStride() { return VERTEX_SIZE; diff --git a/src/main/java/net/vulkanmod/render/vertex/VertexUtil.java b/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java similarity index 73% rename from src/main/java/net/vulkanmod/render/vertex/VertexUtil.java rename to src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java index 00777f51cd..fb83669916 100644 --- a/src/main/java/net/vulkanmod/render/vertex/VertexUtil.java +++ b/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java @@ -1,7 +1,6 @@ -package net.vulkanmod.render.vertex; - -public class VertexUtil { +package net.vulkanmod.render.vertex.format; +public abstract class I32_SNorm { private static final float NORM_INV = 1.0f / 127.0f; public static int packNormal(float x, float y, float z) { @@ -16,16 +15,15 @@ public static int packNormal(int x, int y, int z) { return (x & 0xFF) | (y & 0xFF) << 8| (z & 0xFF) << 16; } - public static float unpackN1(int i) { + public static float unpackX(int i) { return (byte)(i & 0xFF) * NORM_INV; } - public static float unpackN2(int i) { + public static float unpackY(int i) { return (byte)((i >> 8) & 0xFF) * NORM_INV; } - public static float unpackN3(int i) { + public static float unpackZ(int i) { return (byte)((i >> 16) & 0xFF) * NORM_INV; } - } diff --git a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java index 7dc60c03cc..145935a85b 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java @@ -47,11 +47,14 @@ public static int multiplyAlpha(int color, float m) { int newA = floatToInt(unpackA(color) * m); return (color & 0x00FFFFFF) | newA << 24; } + + public static int toRGBA(int color) { + return (color & 0xFF00FF00) | ((color >> 16) & 0xFF) | ((color << 16) & 0xFF0000); + } } public static class RGBA { public static int pack(float r, float g, float b, float a) { -// int color = floatToInt(r) << 24 | floatToInt(g) << 16 | floatToInt(b) << 8 | floatToInt(a); int color = floatToInt(a) << 24 | floatToInt(b) << 16 | floatToInt(g) << 8 | floatToInt(r); return color; diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 37218f426a..595e357a3c 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,9 @@ "depends": { "fabricloader": ">=0.14.14", - "minecraft": ">=1.21", - "java": ">=17" + "minecraft": ">=1.21" + }, + "custom": { + "fabric-renderer-api-v1:contains_renderer": true } } diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index fafeb90adf..a08997be2d 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -47,11 +47,17 @@ "render.RenderSystemMixin", "render.RenderTypeM", "render.ShaderInstanceM", + "render.block.BakedQuadM", "render.clouds.LevelRendererM", "render.entity.EntityRendererM", "render.entity.LevelRendererM", "render.entity.model.ModelPartCubeM", "render.entity.model.ModelPartM", + "render.frapi.fluid.FluidRenderingImplMixin", + "render.frapi.BakedModelM", + "render.frapi.ItemRendererAccessor", + "render.frapi.ItemRendererMixin", + "render.frapi.ModelBlockRendererM", "render.particle.SingleQuadParticleM", "render.target.MainTargetMixin", "render.target.RenderTargetMixin", @@ -89,8 +95,6 @@ "compatibility.PostChainM", "compatibility.PostPassM", - "render.block.BakedQuadM", - "voxel.VoxelShapeMixin" ], "injectors": { From 5c1106458d1673531bf8a4cf7cd8486bd06e5e11 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:52:19 +0200 Subject: [PATCH 007/177] Update default config --- src/main/java/net/vulkanmod/config/Config.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index 0063415dce..4110c0815d 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -19,7 +19,7 @@ public class Config { public boolean windowedFullscreen = false; public int advCulling = 2; - public boolean indirectDraw = false; + public boolean indirectDraw = true; public boolean uniqueOpaqueLayer = true; public boolean entityCulling = true; From de2391675e073e4eca47a8182cc050f5fff21275 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 12 Oct 2024 19:18:25 +0200 Subject: [PATCH 008/177] Add RenderAttachedBlockView interface implementation --- build.gradle | 1 + .../java/net/vulkanmod/render/chunk/build/RenderRegion.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d7efdffb06..06ef0df55b 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,7 @@ dependencies { includeModule("fabric-rendering-v1") includeModule("fabric-renderer-api-v1") includeModule("fabric-rendering-fluids-v1") + includeModule("fabric-rendering-data-attachment-v1") } project.ext.lwjglVersion = "3.3.3" diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 4623a8abff..64ed4dfa80 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -1,5 +1,6 @@ package net.vulkanmod.render.chunk.build; +import net.fabricmc.fabric.api.rendering.data.v1.RenderAttachedBlockView; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -24,7 +25,7 @@ import java.util.Map; import java.util.function.Function; -public class RenderRegion implements BlockAndTintGetter { +public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView { public static final int WIDTH = 3; public static final int SIZE = WIDTH * WIDTH * WIDTH; From a2901697ca4863bd35d86c1a6aeaab910bf2688c Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 13 Oct 2024 14:09:47 +0200 Subject: [PATCH 009/177] Implement IndexBuffer resize --- .../java/net/vulkanmod/vulkan/Drawer.java | 5 +++-- .../vulkanmod/vulkan/memory/IndexBuffer.java | 20 +++++++++++-------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index 74461c3854..999bd0ee50 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -13,7 +13,8 @@ import static org.lwjgl.vulkan.VK10.*; public class Drawer { - private static final int INITIAL_VB_SIZE = 2000000; + private static final int INITIAL_VB_SIZE = 4000000; + private static final int INITIAL_IB_SIZE = 1000000; private static final int INITIAL_UB_SIZE = 200000; private static final LongBuffer buffers = MemoryUtil.memAllocLong(1); @@ -67,7 +68,7 @@ public void createResources(int framesNum) { ); } this.indexBuffers = new IndexBuffer[framesNum]; - Arrays.setAll(this.indexBuffers, i -> new IndexBuffer(INITIAL_UB_SIZE, MemoryTypes.HOST_MEM)); + Arrays.setAll(this.indexBuffers, i -> new IndexBuffer(INITIAL_IB_SIZE, MemoryTypes.HOST_MEM)); if (this.uniformBuffers != null) { Arrays.stream(this.uniformBuffers).iterator().forEachRemaining( diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java index 311f717209..8ec992eb11 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java @@ -19,17 +19,21 @@ public IndexBuffer(int size, MemoryType type, IndexType indexType) { this.createBuffer(size); } - public void copyBuffer(ByteBuffer buffer) { - int size = buffer.remaining(); + public void copyBuffer(ByteBuffer byteBuffer) { + int size = byteBuffer.remaining(); if(size > this.bufferSize - this.usedBytes) { - throw new RuntimeException("Trying to write buffer beyond max size."); - } - else { - this.type.copyToBuffer(this, size, buffer); - offset = usedBytes; - usedBytes += size; + resizeBuffer((this.bufferSize + size) * 2); } + + this.type.copyToBuffer(this, size, byteBuffer); + offset = usedBytes; + usedBytes += size; + } + + private void resizeBuffer(int newSize) { + MemoryManager.getInstance().addToFreeable(this); + this.createBuffer(newSize); } public enum IndexType { From ef9388ea9eecb0e9a4807eb4dfbf8fb0c8fa4b48 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 13 Oct 2024 14:10:34 +0200 Subject: [PATCH 010/177] Add missing FAPI module --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index 06ef0df55b..b933e3fd7c 100644 --- a/build.gradle +++ b/build.gradle @@ -35,6 +35,7 @@ dependencies { includeModule("fabric-renderer-api-v1") includeModule("fabric-rendering-fluids-v1") includeModule("fabric-rendering-data-attachment-v1") + includeModule("fabric-block-view-api-v2") } project.ext.lwjglVersion = "3.3.3" From a7ffe3dd920e854dd74468a739074f4a7b073e4a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 13 Oct 2024 14:13:06 +0200 Subject: [PATCH 011/177] Add backface culling setting's translatable components --- src/main/java/net/vulkanmod/config/option/Options.java | 5 +++-- src/main/resources/assets/vulkanmod/lang/en_us.json | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index af6b99e430..5fc3d97176 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -258,12 +258,13 @@ public static OptionBlock[] getOptimizationOpts() { }, () -> config.uniqueOpaqueLayer) .setTooltip(Component.translatable("vulkanmod.options.uniqueOpaqueLayer.tooltip")), - new SwitchOption(Component.translatable("Back face culling"), + new SwitchOption(Component.translatable("vulkanmod.options.backfaceCulling"), value -> { config.backFaceCulling = value; Minecraft.getInstance().levelRenderer.allChanged(); }, - () -> config.backFaceCulling), + () -> config.backFaceCulling) + .setTooltip(Component.translatable("vulkanmod.options.backfaceCulling.tooltip")), new SwitchOption(Component.translatable("vulkanmod.options.indirectDraw"), value -> config.indirectDraw = value, () -> config.indirectDraw) diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 28f7ba3dbc..2560649373 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -28,8 +28,11 @@ "vulkanmod.options.frameQueue": "Render queue size", "vulkanmod.options.frameQueue.tooltip": "Higher values might help stabilize frametime but will increase input lag.", + "vulkanmod.options.backfaceCulling": "Backface Culling", + "vulkanmod.options.backfaceCulling.tooltip": "Culls not visible block faces on the CPU improving GPU performance. To prevent increased CPU overhead enable Indirect Draw.", + "vulkanmod.options.indirectDraw": "Indirect Draw", - "vulkanmod.options.indirectDraw.tooltip": "Reduces CPU overhead but increases GPU overhead. Enabling it might help in CPU limited systems.", + "vulkanmod.options.indirectDraw.tooltip": "Reduces CPU overhead but might increases GPU overhead.", "vulkanmod.options.refreshRate": "Refresh Rate", From 0ef9f9a0d88333e4364cb6a20583ebd10a24a58d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 13 Oct 2024 14:14:57 +0200 Subject: [PATCH 012/177] Use normal to calculate quad facing --- .../net/vulkanmod/mixin/render/block/BakedQuadM.java | 11 +++-------- .../render/chunk/build/frapi/mesh/QuadViewImpl.java | 4 ++-- .../net/vulkanmod/render/chunk/cull/QuadFacing.java | 9 +++++++++ .../net/vulkanmod/render/model/quad/ModelQuad.java | 3 +++ 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java index 39a05b21c1..1f012d4721 100644 --- a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java +++ b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java @@ -31,14 +31,9 @@ public class BakedQuadM implements ModelQuadView { private void onInit(int[] vertices, int tintIndex, Direction face, TextureAtlasSprite textureAtlasSprite, boolean shade, CallbackInfo ci) { this.flags = ModelQuadFlags.getQuadFlags(this, face); - if (face != null) { - this.facing = QuadFacing.fromDirection(face); - this.normal = NormalHelper.packedNormalFromDirection(face); - } else { - int packedNormal = NormalHelper.computePackedNormal(this); - this.facing = QuadFacing.fromNormal(packedNormal); - this.normal = packedNormal; - } + int packedNormal = NormalHelper.computePackedNormal(this); + this.normal = packedNormal; + this.facing = QuadFacing.fromNormal(packedNormal); } @Override diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java index a6a3ac29a5..526e45b615 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java @@ -73,7 +73,7 @@ public void load() { isGeometryInvalid = false; nominalFace = lightFace(); NormalHelper.unpackNormal(packedFaceNormal(), faceNormal); - facing = QuadFacing.fromDirection(lightFace()); + facing = QuadFacing.fromNormal(faceNormal); } protected void computeGeometry() { @@ -90,7 +90,7 @@ protected void computeGeometry() { // depends on light face data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], ModelQuadFlags.getQuadFlags(this, lightFace)); - facing = QuadFacing.fromDirection(lightFace); + facing = QuadFacing.fromNormal(faceNormal); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java index 6423968e4d..642fd9bf46 100644 --- a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java +++ b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java @@ -3,6 +3,7 @@ import net.minecraft.core.Direction; import net.minecraft.util.Mth; import net.vulkanmod.render.vertex.format.I32_SNorm; +import org.joml.Vector3f; public enum QuadFacing { X_POS, @@ -32,6 +33,14 @@ public static QuadFacing fromNormal(int packedNormal) { final float y = I32_SNorm.unpackY(packedNormal); final float z = I32_SNorm.unpackZ(packedNormal); + return fromNormal(x, y, z); + } + + public static QuadFacing fromNormal(Vector3f normal) { + return fromNormal(normal.x(), normal.y(), normal.z()); + } + + public static QuadFacing fromNormal(float x, float y, float z) { final float absX = Math.abs(x); final float absY = Math.abs(y); final float absZ = Math.abs(z); diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java index e560006e9b..d87df233d1 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java @@ -4,6 +4,9 @@ import net.minecraft.core.Direction; import net.vulkanmod.render.chunk.cull.QuadFacing; +/** + * Only used by FluidRenderer + */ public class ModelQuad implements ModelQuadView { public static final int VERTEX_SIZE = 8; From ca9cf7b6166191ffecd202c0de78b7355c79dc31 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 13 Oct 2024 14:16:02 +0200 Subject: [PATCH 013/177] Add missing normal vector copy --- .../render/chunk/build/frapi/helper/NormalHelper.java | 4 ++++ .../render/chunk/build/frapi/mesh/MutableQuadViewImpl.java | 1 + 2 files changed, 5 insertions(+) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java index 280ac96b1e..bf6deebb70 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java @@ -188,4 +188,8 @@ public static int packedNormalFromDirection(Direction direction) { return I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); } + + public static void unpackNormalTo(int packedNormal, Vector3f normal) { + normal.set(I32_SNorm.unpackX(packedNormal), I32_SNorm.unpackY(packedNormal), I32_SNorm.unpackZ(packedNormal)); + } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 297d573aef..6c83814bdf 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -200,6 +200,7 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate ModelQuadView quadView = (ModelQuadView) quad; int normal = quadView.getNormal(); data[baseIndex + HEADER_FACE_NORMAL] = normal; + NormalHelper.unpackNormalTo(normal, faceNormal); Direction lightFace = quadView.lightFace(); data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); From 4ec5d6a10cb02de770a0ca39de3b313911d6aa10 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 21 Oct 2024 23:05:42 +0200 Subject: [PATCH 014/177] Improve glsl conversion --- .../vulkan/shader/parser/GlslConverter.java | 109 ++++++++++++------ 1 file changed, 74 insertions(+), 35 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java b/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java index f934a5def9..e15622f4e8 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java @@ -20,66 +20,105 @@ public void process(String vertShader, String fragShader) { this.uniformParser = new UniformParser(this); this.inOutParser = new InputOutputParser(this); - StringBuilder vshOut = new StringBuilder(); - StringBuilder fshOut = new StringBuilder(); + StringBuilder vshOut = this.processShaderFile(ShaderStage.Vertex, vertShader); + vshOut.insert(0, this.inOutParser.createInOutCode()); - this.setShaderStage(ShaderStage.Vertex); + StringBuilder fshOut = this.processShaderFile(ShaderStage.Fragment, fragShader); + fshOut.insert(0, this.inOutParser.createInOutCode()); - String[] lines = vertShader.split("\n"); + String uniformBlock = this.uniformParser.createUniformsCode(); + vshOut.insert(0, uniformBlock); + fshOut.insert(0, uniformBlock); + + String samplersVertCode = this.uniformParser.createSamplersCode(ShaderStage.Vertex); + String samplersFragCode = this.uniformParser.createSamplersCode(ShaderStage.Fragment); + + vshOut.insert(0, samplersVertCode); + fshOut.insert(0, samplersFragCode); + + vshOut.insert(0, "#version 450\n\n"); + fshOut.insert(0, "#version 450\n\n"); + + this.vshConverted = vshOut.toString(); + this.fshConverted = fshOut.toString(); + + } + + private StringBuilder processShaderFile(ShaderStage stage, String shader) { + this.setShaderStage(stage); + + String[] lines = shader.split("\n"); + var out = new StringBuilder(); var iterator = Arrays.stream(lines).iterator(); while (iterator.hasNext()) { String line = iterator.next(); - String parsedLine = this.parseLine(line); - if (parsedLine != null) { - vshOut.append(parsedLine); - vshOut.append("\n"); - } + int semicolons = charOccurences(line, ';'); - } + if (semicolons > 1) { + var lines2 = line.splitWithDelimiters(";", 0); - vshOut.insert(0, this.inOutParser.createInOutCode()); + int matchingFor = 0; + for (int i = 0; i < lines2.length;) { + StringBuilder line2 = new StringBuilder(lines2[i]); + i++; - this.setShaderStage(ShaderStage.Fragment); + matchingFor += charOccurences(line2.toString(), '('); + matchingFor -= charOccurences(line2.toString(), ')'); - lines = fragShader.split("\n"); + while (matchingFor > 0) { + String next = lines2[i]; + i++; - iterator = Arrays.stream(lines).iterator(); + matchingFor += charOccurences(next, '('); + matchingFor -= charOccurences(next, ')'); - while (iterator.hasNext()) { - String line = iterator.next(); + line2.append(next); + } - String parsedLine = this.parseLine(line); - if (parsedLine != null) { - fshOut.append(parsedLine); - fshOut.append("\n"); - } - } + if (i < lines2.length) { + line2.append(lines2[i]); + i++; + } - fshOut.insert(0, this.inOutParser.createInOutCode()); - String uniformBlock = this.uniformParser.createUniformsCode(); - vshOut.insert(0, uniformBlock); - fshOut.insert(0, uniformBlock); + if (matchingFor == 0) { + String parsedLine = this.parseLine(line2.toString()); + if (parsedLine != null) { + out.append(parsedLine); + out.append("\n"); + } + } - String samplersVertCode = this.uniformParser.createSamplersCode(ShaderStage.Vertex); - String samplersFragCode = this.uniformParser.createSamplersCode(ShaderStage.Fragment); + } + } + else { + String parsedLine = this.parseLine(line); + if (parsedLine != null) { + out.append(parsedLine); + out.append("\n"); + } + } - vshOut.insert(0, samplersVertCode); - fshOut.insert(0, samplersFragCode); + } - vshOut.insert(0, "#version 450\n\n"); - fshOut.insert(0, "#version 450\n\n"); + return out; + } - this.vshConverted = vshOut.toString(); - this.fshConverted = fshOut.toString(); + private int charOccurences(String s, char c) { + int count = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + count++; + } + } + return count; } private String parseLine(String line) { - StringTokenizer tokenizer = new StringTokenizer(line); // empty line From eedfa5404d84e6756102eff228b76a1e1ae7bd10 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 21 Oct 2024 23:07:24 +0200 Subject: [PATCH 015/177] Improve compatibility --- .../vulkanmod/mixin/render/clouds/LevelRendererM.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index feec45ac05..a3c0317516 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -23,17 +23,14 @@ public abstract class LevelRendererM { @Unique private CloudRenderer cloudRenderer; - /** - * @author - * @reason - */ - @Overwrite - public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float partialTicks, double camX, double camY, double camZ) { + @Inject(method = "renderClouds", at = @At("HEAD"), cancellable = true) + public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float partialTicks, double camX, double camY, double camZ, CallbackInfo ci) { if (this.cloudRenderer == null) { this.cloudRenderer = new CloudRenderer(CLOUDS_LOCATION); } this.cloudRenderer.renderClouds(this.level, poseStack, modelView, projection, this.ticks, partialTicks, camX, camY, camZ); + ci.cancel(); } @Inject(method = "allChanged", at = @At("RETURN")) From 5c8bbfe4cb112d2ff71ef50d2e41b10fd4a70ebb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 21 Oct 2024 23:09:21 +0200 Subject: [PATCH 016/177] Add image format info --- src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java index 395c3cdc1f..70e9347afb 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java @@ -47,6 +47,7 @@ public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, i image = new VulkanImage.Builder(width, height) .setMipLevels(mipLevels + 1) + .setFormat(internalGlFormat) .setLinearFiltering(false) .setClamp(false) .createVulkanImage(); From b56a22d86a0b2ebb3441f659472c020da8479ae2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 21 Oct 2024 23:15:00 +0200 Subject: [PATCH 017/177] Use custom color resolver if requested - Implement BlockColorRegistry for fast look up - Refactor --- .../interfaces/color/BlockColorsExtended.java | 13 ++ .../mixin/render/color/BlockColorsM.java | 29 +++++ .../chunk/build/color/BlockColorRegistry.java | 21 ++++ .../render/chunk/build/color/TintCache.java | 111 +++++++++++------- .../render/AbstractBlockRenderContext.java | 13 +- src/main/resources/vulkanmod.mixins.json | 1 + 6 files changed, 141 insertions(+), 47 deletions(-) create mode 100644 src/main/java/net/vulkanmod/interfaces/color/BlockColorsExtended.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java diff --git a/src/main/java/net/vulkanmod/interfaces/color/BlockColorsExtended.java b/src/main/java/net/vulkanmod/interfaces/color/BlockColorsExtended.java new file mode 100644 index 0000000000..69579509e8 --- /dev/null +++ b/src/main/java/net/vulkanmod/interfaces/color/BlockColorsExtended.java @@ -0,0 +1,13 @@ +package net.vulkanmod.interfaces.color; + +import net.minecraft.client.color.block.BlockColors; +import net.vulkanmod.render.chunk.build.color.BlockColorRegistry; + +public interface BlockColorsExtended { + + static BlockColorsExtended from(BlockColors blockColors) { + return (BlockColorsExtended) blockColors; + } + + BlockColorRegistry getColorResolverMap(); +} diff --git a/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java b/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java new file mode 100644 index 0000000000..b3480e5c96 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java @@ -0,0 +1,29 @@ +package net.vulkanmod.mixin.render.color; + +import net.minecraft.client.color.block.BlockColor; +import net.minecraft.client.color.block.BlockColors; +import net.minecraft.world.level.block.Block; +import net.vulkanmod.interfaces.color.BlockColorsExtended; +import net.vulkanmod.render.chunk.build.color.BlockColorRegistry; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(BlockColors.class) +public class BlockColorsM implements BlockColorsExtended { + + @Unique + private BlockColorRegistry colorResolvers = new BlockColorRegistry(); + + @Inject(method = "register", at = @At("RETURN")) + private void onRegister(BlockColor blockColor, Block[] blocks, CallbackInfo ci) { + this.colorResolvers.register(blockColor, blocks); + } + + @Override + public BlockColorRegistry getColorResolverMap() { + return this.colorResolvers; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java b/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java new file mode 100644 index 0000000000..b8ec0ca392 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java @@ -0,0 +1,21 @@ +package net.vulkanmod.render.chunk.build.color; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import net.minecraft.client.color.block.BlockColor; +import net.minecraft.world.level.block.Block; + +public class BlockColorRegistry { + + private final Reference2ReferenceOpenHashMap map = new Reference2ReferenceOpenHashMap<>(); + + public void register(BlockColor blockColor, Block... blocks) { + for (Block block : blocks) { + this.map.put(block, blockColor); + } + } + + public BlockColor getBlockColor(Block block) { + return this.map.get(block); + } + +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java index 357b23edb8..cc460fa21f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java @@ -1,5 +1,6 @@ package net.vulkanmod.render.chunk.build.color; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BiomeColors; import net.minecraft.core.BlockPos; @@ -13,7 +14,7 @@ public class TintCache { private static final int SECTION_WIDTH = 16; - private final Layer[] layers = new Layer[SECTION_WIDTH]; + private final Reference2ReferenceOpenHashMap layers; private int blendRadius, totalWidth; private int secX, secY, secZ; @@ -24,7 +25,12 @@ public class TintCache { private int[] temp; public TintCache() { - Arrays.fill(layers, new Layer()); + this.layers = new Reference2ReferenceOpenHashMap<>(); + + // Default resolvers + this.layers.put(BiomeColors.FOLIAGE_COLOR_RESOLVER, allocateLayers()); + this.layers.put(BiomeColors.GRASS_COLOR_RESOLVER, allocateLayers()); + this.layers.put(BiomeColors.WATER_COLOR_RESOLVER, allocateLayers()); } public void init(int blendRadius, int secX, int secY, int secZ) { @@ -35,62 +41,91 @@ public void init(int blendRadius, int secX, int secY, int secZ) { this.secY = secY; this.secZ = secZ; - minX = (secX << 4) - blendRadius; - minZ = (secZ << 4) - blendRadius; - maxX = (secX << 4) + 16 + blendRadius; - maxZ = (secZ << 4) + 16 + blendRadius; + this.minX = (secX << 4) - blendRadius; + this.minZ = (secZ << 4) - blendRadius; + this.maxX = (secX << 4) + 16 + blendRadius; + this.maxZ = (secZ << 4) + 16 + blendRadius; int size = totalWidth * totalWidth; - if(size != dataSize) { + if (size != this.dataSize) { this.dataSize = size; - for (Layer layer : layers) { - layer.allocate(size); + + for (Layer[] layers : layers.values()) { + for (Layer layer : layers) { + layer.allocate(size); + } } - temp = new int[size]; - } else { - for (Layer layer : layers) { - layer.invalidate(); + + this.temp = new int[size]; + } + else { + for (Layer[] layers : layers.values()) { + for (Layer layer : layers) { + layer.invalidate(); + } } } } public int getColor(BlockPos blockPos, ColorResolver colorResolver) { int relY = blockPos.getY() & 15; - Layer layer = layers[relY]; - if(layer.invalidated) - calculateLayer(relY); - int[] values = layer.getValues(colorResolver); + if (!this.layers.containsKey(colorResolver)) { + addResolver(colorResolver); + } + + Layer layer = this.layers.get(colorResolver)[relY]; + + if (layer.invalidated) { + calculateLayer(layer, colorResolver, relY); + } + + int[] values = layer.getValues(); + int relX = blockPos.getX() & 15; int relZ = blockPos.getZ() & 15; - int idx = totalWidth * (relZ + blendRadius) + (relX + blendRadius); + int idx = this.totalWidth * (relZ + this.blendRadius) + (relX + this.blendRadius); return values[idx]; } - public void calculateLayer(int y) { + private void addResolver(ColorResolver colorResolver) { + Layer[] layers1 = allocateLayers(); + + for (Layer layer : layers1) { + layer.allocate(this.dataSize); + } + + this.layers.put(colorResolver, layers1); + } + + private Layer[] allocateLayers() { + Layer[] layers = new Layer[SECTION_WIDTH]; + + Arrays.fill(layers, new Layer()); + return layers; + } + + private void calculateLayer(Layer layer, ColorResolver colorResolver, int y) { Level level = WorldRenderer.getLevel(); - Layer layer = layers[y]; BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(); int absY = (secY << 4) + y; - for (int absZ = minZ; absZ < maxZ ; absZ++) { - for (int absX = minX; absX < maxX ; absX++) { + int[] values = layer.values; + + for (int absZ = minZ; absZ < maxZ; absZ++) { + for (int absX = minX; absX < maxX; absX++) { blockPos.set(absX, absY, absZ); Biome biome = level.getBiome(blockPos).value(); final int idx = (absX - minX) + (absZ - minZ) * totalWidth; - layer.grass[idx] = biome.getGrassColor(absX, absZ); - layer.foliage[idx] = biome.getFoliageColor(); - layer.water[idx] = biome.getWaterColor(); + values[idx] = colorResolver.getColor(biome, absX, absZ); } } if (blendRadius > 0) { - this.applyBlur(layer.grass); - this.applyBlur(layer.foliage); - this.applyBlur(layer.water); + this.applyBlur(values); } layer.invalidated = false; @@ -112,15 +147,10 @@ private void applyBlur(int[] buffer) { static class Layer { private boolean invalidated = true; - - private int[] grass; - private int[] foliage; - private int[] water; + private int[] values; void allocate(int size) { - grass = new int[size]; - foliage = new int[size]; - water = new int[size]; + this.values = new int[size]; invalidate(); } @@ -128,15 +158,8 @@ void invalidate() { this.invalidated = true; } - public int[] getValues(ColorResolver colorResolver) { - if (colorResolver == BiomeColors.GRASS_COLOR_RESOLVER) - return grass; - else if (colorResolver == BiomeColors.FOLIAGE_COLOR_RESOLVER) - return foliage; - else if (colorResolver == BiomeColors.WATER_COLOR_RESOLVER) - return water; - - throw new IllegalArgumentException("Unexpected resolver: " + colorResolver.toString()); + public int[] getValues() { + return this.values; } } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index 6ac3fcf9a3..2d7f86520a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -6,6 +6,7 @@ import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; import net.minecraft.client.Minecraft; +import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.util.RandomSource; @@ -15,6 +16,8 @@ import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; +import net.vulkanmod.interfaces.color.BlockColorsExtended; +import net.vulkanmod.render.chunk.build.color.BlockColorRegistry; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import org.jetbrains.annotations.Nullable; @@ -40,7 +43,7 @@ public abstract class AbstractBlockRenderContext extends AbstractRenderContext { protected static final RenderMaterial STANDARD_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).find(); protected static final RenderMaterial NO_AO_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).ambientOcclusion(TriState.FALSE).find(); - protected final BlockColors blockColors; + protected final BlockColorRegistry blockColorRegistry; private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { { @@ -88,7 +91,8 @@ protected void rehash(int i) { protected AbstractBlockRenderContext() { this.occlusionCache.defaultReturnValue((byte) 127); - this.blockColors = Minecraft.getInstance().getBlockColors(); + BlockColors blockColors = Minecraft.getInstance().getBlockColors(); + this.blockColorRegistry = BlockColorsExtended.from(blockColors).getColorResolverMap(); } protected void setupLightPipelines(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { @@ -226,7 +230,10 @@ protected void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { } private int getBlockColor(BlockAndTintGetter region, int colorIndex) { - return 0xFF000000 | blockColors.getColor(blockState, region, blockPos, colorIndex); + BlockColor blockColor = this.blockColorRegistry.getBlockColor(this.blockState.getBlock()); + + int color = blockColor != null ? blockColor.getColor(blockState, region, blockPos, colorIndex) : -1; + return 0xFF000000 | color; } protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, boolean emissive, boolean vanillaShade) { diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index a08997be2d..37e87d915d 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -49,6 +49,7 @@ "render.ShaderInstanceM", "render.block.BakedQuadM", "render.clouds.LevelRendererM", + "render.color.BlockColorsM", "render.entity.EntityRendererM", "render.entity.LevelRendererM", "render.entity.model.ModelPartCubeM", From 6c4fe7d9f12eaee7c6e39d4d1a86a7795835149d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 9 Nov 2024 18:47:16 +0100 Subject: [PATCH 018/177] Refactor pipeline builder and creation - refactor shader loading --- .../net/vulkanmod/interfaces/ShaderMixed.java | 17 ++ .../mixin/compatibility/EffectInstanceM.java | 2 +- .../mixin/render/ShaderInstanceM.java | 83 ++++++--- .../net/vulkanmod/render/PipelineManager.java | 30 ++- .../render/chunk/buffer/DrawBuffers.java | 4 +- .../render/shader/ShaderLoadUtil.java | 175 ++++++++++++++++++ .../render/vertex/TerrainBuilder.java | 4 +- .../net/vulkanmod/vulkan/shader/Pipeline.java | 73 ++++---- .../vulkanmod/vulkan/shader/SPIRVUtils.java | 66 ++----- .../net/vulkanmod/vulkan/shader/Uniforms.java | 12 ++ .../vulkan/shader/layout/AlignedStruct.java | 32 ++-- .../vulkan/shader/layout/Uniform.java | 51 +++-- .../vulkanmod/vulkan/shader/layout/Vec1f.java | 10 +- .../vulkanmod/vulkan/shader/layout/Vec1i.java | 8 +- .../vulkan/shader/parser/GlslConverter.java | 4 +- .../vulkan/shader/parser/UniformParser.java | 49 ++--- .../shaders/basic/terrain/terrain.json | 20 +- .../shaders/basic/terrain/terrain.vsh | 51 +++-- .../terrain_earlyZ.fsh} | 3 +- .../basic/terrain_earlyZ/terrain_earlyZ.json | 22 +++ .../core/blit_screen/blit_screen.fsh | 4 +- .../shaders/core/blit_screen/blit_screen.json | 9 + .../shaders/core/blit_screen/blit_screen.vsh | 11 ++ .../particle.fsh => core/entity/entity.fsh} | 0 .../entity/entity.vsh} | 0 .../glint/glint.fsh} | 0 .../glint/glint.vsh} | 0 .../position_color.fsh => core/gui/gui.fsh} | 0 .../assets/vulkanmod/shaders/core/gui/gui.vsh | 16 ++ .../shaders/core/lightmap/lightmap.fsh | 70 +++++++ .../shaders/core/lightmap/lightmap.json | 30 +++ .../particle/particle.fsh} | 0 .../core/particle/particle.json | 17 -- .../core/particle/particle.vsh | 0 .../core/position/position.fsh | 0 .../core/position/position.json | 0 .../core/position/position.vsh | 0 .../core/position_color/position_color.fsh | 17 ++ .../core/position_color/position_color.json | 0 .../core/position_color/position_color.vsh | 0 .../position_color_lightmap.fsh | 0 .../position_color_lightmap.json | 0 .../position_color_lightmap.vsh | 0 .../position_color_normal.fsh | 0 .../position_color_normal.json | 0 .../position_color_normal.vsh | 0 .../position_color_tex/position_color_tex.fsh | 0 .../position_color_tex.json | 0 .../position_color_tex/position_color_tex.vsh | 0 .../position_color_tex_lightmap.fsh | 0 .../position_color_tex_lightmap.json | 0 .../position_color_tex_lightmap.vsh | 0 .../core/position_tex/position_tex.fsh | 0 .../core/position_tex/position_tex.json | 0 .../core/position_tex/position_tex.vsh | 0 .../position_tex_color/position_tex_color.fsh | 0 .../position_tex_color.json | 20 ++ .../position_tex_color/position_tex_color.vsh | 0 .../position_tex_color_normal.fsh | 0 .../position_tex_color_normal.json | 0 .../position_tex_color_normal.vsh | 0 .../rendertype_armor_cutout_no_cull.fsh} | 0 .../rendertype_armor_cutout_no_cull.json | 0 .../rendertype_armor_cutout_no_cull.vsh} | 0 .../rendertype_armor_entity_glint.fsh} | 0 .../rendertype_armor_entity_glint.json | 0 .../rendertype_armor_entity_glint.vsh} | 0 .../rendertype_armor_glint.json | 19 +- .../rendertype_armor_translucent.json | 29 +++ .../rendertype_beacon_beam.fsh | 0 .../rendertype_beacon_beam.json | 0 .../rendertype_beacon_beam.vsh | 0 .../rendertype_breeze_wind.fsh | 0 .../rendertype_breeze_wind.json | 19 -- .../rendertype_breeze_wind.vsh | 3 +- .../rendertype_clouds/rendertype_clouds.fsh | 12 +- .../rendertype_clouds/rendertype_clouds.json | 12 +- .../rendertype_clouds/rendertype_clouds.vsh | 26 --- .../rendertype_crumbling.fsh | 0 .../rendertype_crumbling.json | 0 .../rendertype_crumbling.vsh | 0 .../rendertype_cutout/rendertype_cutout.fsh | 0 .../rendertype_cutout/rendertype_cutout.json | 0 .../rendertype_cutout/rendertype_cutout.vsh | 0 .../rendertype_cutout_mipped.fsh | 0 .../rendertype_cutout_mipped.json | 0 .../rendertype_cutout_mipped.vsh | 0 .../rendertype_end_gateway.json | 17 ++ .../rendertype_end_portal.fsh | 0 .../rendertype_end_portal.json | 10 - .../rendertype_end_portal.vsh | 0 .../rendertype_energy_swirl.fsh | 0 .../rendertype_energy_swirl.json | 0 .../rendertype_energy_swirl.vsh | 0 .../rendertype_entity_alpha.fsh | 0 .../rendertype_entity_alpha.json | 12 -- .../rendertype_entity_alpha.vsh | 0 .../rendertype_entity_cutout.json | 28 +-- .../rendertype_entity_cutout_no_cull.json | 27 +++ ...ertype_entity_cutout_no_cull_z_offset.json | 27 +++ .../rendertype_entity_decal.fsh | 0 .../rendertype_entity_decal.json | 0 .../rendertype_entity_decal.vsh | 0 .../rendertype_entity_glint.fsh | 0 .../rendertype_entity_glint.json | 0 .../rendertype_entity_glint.vsh | 0 .../rendertype_entity_glint_direct.fsh | 0 .../rendertype_entity_glint_direct.json | 0 .../rendertype_entity_glint_direct.vsh | 0 .../rendertype_entity_no_outline.fsh | 0 .../rendertype_entity_no_outline.json | 0 .../rendertype_entity_no_outline.vsh} | 0 .../rendertype_entity_shadow.fsh | 0 .../rendertype_entity_shadow.json | 0 .../rendertype_entity_shadow.vsh | 0 .../rendertype_entity_smooth_cutout.json | 27 +++ .../rendertype_entity_solid.fsh | 0 .../rendertype_entity_solid.json | 21 --- .../rendertype_entity_solid.vsh | 0 .../rendertype_entity_translucent.json | 28 +-- .../rendertype_entity_translucent_cull.fsh | 0 .../rendertype_entity_translucent_cull.json | 5 - .../rendertype_entity_translucent_cull.vsh | 0 ...rendertype_entity_translucent_emissive.fsh | 0 ...endertype_entity_translucent_emissive.json | 0 ...rendertype_entity_translucent_emissive.vsh | 0 .../core/rendertype_eyes/rendertype_eyes.fsh | 0 .../core/rendertype_eyes/rendertype_eyes.json | 0 .../core/rendertype_eyes/rendertype_eyes.vsh | 0 .../rendertype_glint/rendertype_glint.json | 19 +- .../rendertype_glint_direct.json | 21 +-- .../rendertype_glint_translucent.json | 21 +-- .../rendertype_gui/rendertype_gui.json} | 17 +- .../rendertype_gui_ghost_recipe_overlay.json | 19 ++ .../rendertype_gui_overlay.json | 19 ++ .../core/rendertype_gui_text_highlight.json | 19 ++ ...endertype_item_entity_translucent_cull.fsh | 0 ...ndertype_item_entity_translucent_cull.json | 0 ...ndertype_item_entity_translucent_cull.vsh} | 14 +- .../rendertype_leash/rendertype_leash.fsh | 0 .../rendertype_leash/rendertype_leash.json | 0 .../rendertype_leash/rendertype_leash.vsh | 0 .../rendertype_lightning.fsh | 0 .../rendertype_lightning.json | 0 .../rendertype_lightning.vsh | 0 .../rendertype_lines/rendertype_lines.fsh | 0 .../rendertype_lines/rendertype_lines.json | 0 .../rendertype_lines/rendertype_lines.vsh | 0 .../rendertype_outline/rendertype_outline.fsh | 0 .../rendertype_outline.json | 0 .../rendertype_outline/rendertype_outline.vsh | 0 .../rendertype_solid/rendertype_solid.fsh | 0 .../rendertype_solid/rendertype_solid.json | 0 .../rendertype_solid/rendertype_solid.vsh | 0 .../core/rendertype_text/rendertype_text.fsh | 0 .../core/rendertype_text/rendertype_text.json | 0 .../core/rendertype_text/rendertype_text.vsh | 0 .../rendertype_text_background.fsh | 0 .../rendertype_text_background.json | 0 .../rendertype_text_background.vsh | 0 ...rendertype_text_background_see_through.fsh | 0 ...endertype_text_background_see_through.json | 0 ...rendertype_text_background_see_through.vsh | 0 .../rendertype_text_intensity.fsh | 0 .../rendertype_text_intensity.json | 0 .../rendertype_text_intensity.vsh | 0 .../rendertype_text_intensity_see_through.fsh | 0 ...rendertype_text_intensity_see_through.json | 0 .../rendertype_text_intensity_see_through.vsh | 0 .../rendertype_text_see_through.fsh | 0 .../rendertype_text_see_through.json | 0 .../rendertype_text_see_through.vsh | 0 .../rendertype_translucent.fsh | 0 .../rendertype_translucent.json | 0 .../rendertype_translucent.vsh | 0 .../rendertype_translucent_moving_block.fsh | 0 .../rendertype_translucent_moving_block.json | 0 .../rendertype_translucent_moving_block.vsh | 0 .../rendertype_translucent_no_crumbling.fsh | 0 .../rendertype_translucent_no_crumbling.json | 0 .../rendertype_translucent_no_crumbling.vsh | 0 .../rendertype_tripwire.fsh} | 11 +- .../rendertype_tripwire.json | 0 .../rendertype_tripwire.vsh | 0 .../rendertype_water_mask.fsh | 0 .../rendertype_water_mask.json | 0 .../rendertype_water_mask.vsh | 0 .../core/blit_screen/blit_screen.json | 17 -- .../core/blit_screen/blit_screen.vsh | 12 -- .../rendertype_entity_cutout.fsh | 30 --- .../rendertype_entity_cutout.vsh | 36 ---- .../rendertype_entity_cutout_no_cull.fsh | 30 --- .../rendertype_entity_cutout_no_cull.json | 43 ----- .../rendertype_entity_cutout_no_cull.vsh | 36 ---- ...dertype_entity_cutout_no_cull_z_offset.fsh | 30 --- ...ertype_entity_cutout_no_cull_z_offset.json | 43 ----- ...dertype_entity_cutout_no_cull_z_offset.vsh | 36 ---- .../rendertype_entity_smooth_cutout.fsh | 30 --- .../rendertype_entity_smooth_cutout.json | 43 ----- .../rendertype_entity_smooth_cutout.vsh | 36 ---- .../rendertype_glint/rendertype_glint.fsh | 25 --- .../rendertype_glint/rendertype_glint.vsh | 21 --- .../rendertype_glint_direct.fsh | 25 --- .../rendertype_glint_direct.vsh | 21 --- .../rendertype_glint_translucent.fsh | 25 --- .../rendertype_glint_translucent.vsh | 21 --- 206 files changed, 880 insertions(+), 1072 deletions(-) create mode 100644 src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java rename src/main/resources/assets/vulkanmod/shaders/basic/{terrain/terrain_Z.fsh => terrain_earlyZ/terrain_earlyZ.fsh} (99%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/blit_screen/blit_screen.fsh (60%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/particle/particle.fsh => core/entity/entity.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh => core/entity/entity.vsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh => core/glint/glint.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh => core/glint/glint.vsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/position_color/position_color.fsh => core/gui/gui.fsh} (100%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh => core/particle/particle.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/particle/particle.json (58%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/particle/particle.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position/position.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position/position.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position/position.vsh (100%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color/position_color.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color/position_color.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_lightmap/position_color_lightmap.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_lightmap/position_color_lightmap.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_lightmap/position_color_lightmap.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_normal/position_color_normal.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_normal/position_color_normal.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_normal/position_color_normal.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex/position_color_tex.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex/position_color_tex.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex/position_color_tex.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex_lightmap/position_color_tex_lightmap.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex/position_tex.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex/position_tex.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex/position_tex.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex_color/position_tex_color.fsh (100%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex_color/position_tex_color.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex_color_normal/position_tex_color_normal.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex_color_normal/position_tex_color_normal.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/position_tex_color_normal/position_tex_color_normal.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_tripwire/rendertype_tripwire.fsh => core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh => core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_glint/rendertype_armor_glint.fsh => core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_armor_glint/rendertype_armor_glint.vsh => core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_armor_glint/rendertype_armor_glint.json (56%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_beacon_beam/rendertype_beacon_beam.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_breeze_wind/rendertype_breeze_wind.json (57%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh (88%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_clouds/rendertype_clouds.fsh (67%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_clouds/rendertype_clouds.json (84%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_clouds/rendertype_clouds.vsh (57%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_crumbling/rendertype_crumbling.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_crumbling/rendertype_crumbling.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_crumbling/rendertype_crumbling.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout/rendertype_cutout.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout/rendertype_cutout.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout/rendertype_cutout.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh (100%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_end_portal/rendertype_end_portal.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_end_portal/rendertype_end_portal.json (67%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_end_portal/rendertype_end_portal.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_energy_swirl/rendertype_energy_swirl.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_alpha/rendertype_entity_alpha.json (64%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_cutout/rendertype_entity_cutout.json (53%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_decal/rendertype_entity_decal.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_decal/rendertype_entity_decal.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_decal/rendertype_entity_decal.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint/rendertype_entity_glint.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint/rendertype_entity_glint.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint/rendertype_entity_glint.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh => core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_shadow/rendertype_entity_shadow.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh (100%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_solid/rendertype_entity_solid.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_solid/rendertype_entity_solid.json (57%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_solid/rendertype_entity_solid.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent/rendertype_entity_translucent.json (53%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json (94%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_eyes/rendertype_eyes.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_eyes/rendertype_eyes.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_eyes/rendertype_eyes.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_glint/rendertype_glint.json (56%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_glint_direct/rendertype_glint_direct.json (55%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_glint_translucent/rendertype_glint_translucent.json (55%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/position_tex_color/position_tex_color.json => core/rendertype_gui/rendertype_gui.json} (59%) create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.vsh => core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh} (57%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_leash/rendertype_leash.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_leash/rendertype_leash.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_leash/rendertype_leash.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lightning/rendertype_lightning.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lightning/rendertype_lightning.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lightning/rendertype_lightning.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lines/rendertype_lines.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lines/rendertype_lines.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_lines/rendertype_lines.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_outline/rendertype_outline.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_outline/rendertype_outline.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_outline/rendertype_outline.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_solid/rendertype_solid.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_solid/rendertype_solid.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_solid/rendertype_solid.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text/rendertype_text.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text/rendertype_text.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text/rendertype_text.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background/rendertype_text_background.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background/rendertype_text_background.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background/rendertype_text_background.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity/rendertype_text_intensity.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity/rendertype_text_intensity.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity/rendertype_text_intensity.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_see_through/rendertype_text_see_through.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_see_through/rendertype_text_see_through.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_text_see_through/rendertype_text_see_through.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent/rendertype_translucent.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent/rendertype_translucent.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent/rendertype_translucent.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.fsh => core/rendertype_tripwire/rendertype_tripwire.fsh} (59%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_tripwire/rendertype_tripwire.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_tripwire/rendertype_tripwire.vsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_water_mask/rendertype_water_mask.fsh (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_water_mask/rendertype_water_mask.json (100%) rename src/main/resources/assets/vulkanmod/shaders/{minecraft => }/core/rendertype_water_mask/rendertype_water_mask.vsh (100%) delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.vsh diff --git a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java b/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java index e1676144f1..e05a698d41 100644 --- a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java +++ b/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java @@ -1,8 +1,25 @@ package net.vulkanmod.interfaces; +import net.minecraft.client.renderer.ShaderInstance; import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.util.MappedBuffer; + +import java.util.function.Supplier; public interface ShaderMixed { + static ShaderMixed of(ShaderInstance compiledShaderProgram) { + return (ShaderMixed) compiledShaderProgram; + } + + void setPipeline(GraphicsPipeline graphicsPipeline); + GraphicsPipeline getPipeline(); + + void setupUniformSuppliers(UBO ubo); + + Supplier getUniformSupplier(String name); + + void setDoUniformsUpdate(); } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index 1e3d2827bd..622c23a710 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -114,7 +114,7 @@ private void createShaders(ResourceProvider resourceManager, String vertexShader GlslConverter converter = new GlslConverter(); converter.process(vshSrc, fshSrc); - UBO ubo = converter.getUBO(); + UBO ubo = converter.createUBO(); this.setUniformSuppliers(ubo); Pipeline.Builder builder = new Pipeline.Builder(DefaultVertexFormat.POSITION); diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java index ec2fa3f1e4..de8e9b01ab 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.render; +import com.google.gson.JsonObject; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.systems.RenderSystem; @@ -11,6 +12,7 @@ import net.minecraft.server.packs.resources.ResourceProvider; import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ShaderMixed; +import net.vulkanmod.render.shader.ShaderLoadUtil; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; @@ -46,7 +48,6 @@ public class ShaderInstanceM implements ShaderMixed { @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform PROJECTION_MATRIX; @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform COLOR_MODULATOR; @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform LINE_WIDTH; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GLINT_ALPHA; @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_START; @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_END; @@ -60,8 +61,7 @@ public class ShaderInstanceM implements ShaderMixed { private String fsName; private GraphicsPipeline pipeline; - boolean isLegacy = false; - + boolean doUniformUpdate = false; public GraphicsPipeline getPipeline() { return pipeline; @@ -69,23 +69,23 @@ public GraphicsPipeline getPipeline() { @Inject(method = "", at = @At("RETURN")) private void create(ResourceProvider resourceProvider, String name, VertexFormat format, CallbackInfo ci) { + String configName = name; + JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); - try { - if (Pipeline.class.getResourceAsStream(String.format("/assets/vulkanmod/shaders/minecraft/core/%s/%s.json", name, name)) == null) { - createLegacyShader(resourceProvider, format); - return; - } - - String path = String.format("minecraft/core/%s/%s", name, name); - Pipeline.Builder pipelineBuilder = new Pipeline.Builder(format, path); - pipelineBuilder.parseBindingsJSON(); - pipelineBuilder.compileShaders(); - this.pipeline = pipelineBuilder.createGraphicsPipeline(); - } catch (Exception e) { - System.out.printf("Error on shader %s creation\n", name); - e.printStackTrace(); - throw e; + if (config == null) { + createLegacyShader(resourceProvider, format); + return; } + + Pipeline.Builder builder = new Pipeline.Builder(format, configName); + builder.setUniformSupplierGetter(info -> this.getUniformSupplier(info.name)); + + builder.parseBindings(config); + + ShaderLoadUtil.loadShaders(builder, config, configName, "core"); + + GraphicsPipeline pipeline = builder.createGraphicsPipeline(); + this.pipeline = pipeline; } @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;")) @@ -123,7 +123,7 @@ public void close() { */ @Overwrite public void apply() { - if (!this.isLegacy) + if (!this.doUniformUpdate) return; if (this.MODEL_VIEW_MATRIX != null) { @@ -182,8 +182,7 @@ public void apply() { @Overwrite public void clear() {} - private void setUniformSuppliers(UBO ubo) { - + public void setupUniformSuppliers(UBO ubo) { for (Uniform vUniform : ubo.getUniforms()) { com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(vUniform.getName()); @@ -212,6 +211,41 @@ private void setUniformSuppliers(UBO ubo) { } + public Supplier getUniformSupplier(String name) { + com.mojang.blaze3d.shaders.Uniform uniform1 = this.uniformMap.get(name); + + if (uniform1 == null) { + Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", name)); + return null; + } + + Supplier supplier; + ByteBuffer byteBuffer; + + if (uniform1.getType() <= 3) { + byteBuffer = MemoryUtil.memByteBuffer(uniform1.getIntBuffer()); + } else if (uniform1.getType() <= 10) { + byteBuffer = MemoryUtil.memByteBuffer(uniform1.getFloatBuffer()); + } else { + throw new RuntimeException("out of bounds value for uniform " + uniform1); + } + + MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); + supplier = () -> mappedBuffer; + + return supplier; + } + + @Override + public void setDoUniformsUpdate() { + this.doUniformUpdate = true; + } + + @Override + public void setPipeline(GraphicsPipeline graphicsPipeline) { + this.pipeline = graphicsPipeline; + } + private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat format) { try { String vertPath = this.vsPath + ".vsh"; @@ -228,15 +262,14 @@ private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat Pipeline.Builder builder = new Pipeline.Builder(format, this.name); converter.process(vshSrc, fshSrc); - UBO ubo = converter.getUBO(); - this.setUniformSuppliers(ubo); + UBO ubo = converter.createUBO(); + this.setupUniformSuppliers(ubo); builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); this.pipeline = builder.createGraphicsPipeline(); - this.isLegacy = true; - + this.doUniformUpdate = true; } catch (Exception e) { Initializer.LOGGER.error("Error on shader {} conversion/compilation", this.name); e.printStackTrace(); diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 52b037fdb5..4a3ad56d7e 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -1,24 +1,22 @@ package net.vulkanmod.render; +import com.google.gson.JsonObject; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.RenderType; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; +import net.vulkanmod.render.shader.ShaderLoadUtil; import net.vulkanmod.render.vertex.CustomVertexFormat; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.SPIRVUtils; import java.util.function.Function; -import static net.vulkanmod.vulkan.shader.SPIRVUtils.compileShaderAbsoluteFile; - public abstract class PipelineManager { - private static final String shaderPath = SPIRVUtils.class.getResource("/assets/vulkanmod/shaders/").toExternalForm(); - public static VertexFormat TERRAIN_VERTEX_FORMAT; + public static VertexFormat terrainVertexFormat; public static void setTerrainVertexFormat(VertexFormat format) { - TERRAIN_VERTEX_FORMAT = format; + terrainVertexFormat = format; } static GraphicsPipeline terrainShaderEarlyZ, terrainShader, fastBlitPipeline; @@ -37,22 +35,18 @@ public static void setDefaultShader() { } private static void createBasicPipelines() { - terrainShaderEarlyZ = createPipeline("terrain","terrain", "terrain_Z", TERRAIN_VERTEX_FORMAT); - terrainShader = createPipeline("terrain", "terrain", "terrain", TERRAIN_VERTEX_FORMAT); - fastBlitPipeline = createPipeline("blit", "blit", "blit", CustomVertexFormat.NONE); + terrainShaderEarlyZ = createPipeline("terrain_earlyZ", terrainVertexFormat); + terrainShader = createPipeline("terrain", terrainVertexFormat); + fastBlitPipeline = createPipeline("blit", CustomVertexFormat.NONE); } - private static GraphicsPipeline createPipeline(String baseName, String vertName, String fragName,VertexFormat vertexFormat) { - String pathB = String.format("basic/%s/%s", baseName, baseName); - String pathV = String.format("basic/%s/%s", baseName, vertName); - String pathF = String.format("basic/%s/%s", baseName, fragName); + private static GraphicsPipeline createPipeline(String configName, VertexFormat vertexFormat) { + Pipeline.Builder pipelineBuilder = new Pipeline.Builder(vertexFormat, configName); - Pipeline.Builder pipelineBuilder = new Pipeline.Builder(vertexFormat, pathB); - pipelineBuilder.parseBindingsJSON(); + JsonObject config = ShaderLoadUtil.getJsonConfig("basic", configName); + pipelineBuilder.parseBindings(config); - SPIRVUtils.SPIRV vertShaderSPIRV = compileShaderAbsoluteFile(String.format("%s%s.vsh", shaderPath, pathV), SPIRVUtils.ShaderKind.VERTEX_SHADER); - SPIRVUtils.SPIRV fragShaderSPIRV = compileShaderAbsoluteFile(String.format("%s%s.fsh", shaderPath, pathF), SPIRVUtils.ShaderKind.FRAGMENT_SHADER); - pipelineBuilder.setSPIRVs(vertShaderSPIRV, fragShaderSPIRV); + ShaderLoadUtil.loadShaders(pipelineBuilder, config, configName, "basic"); return pipelineBuilder.createGraphicsPipeline(); } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 10b3b79b3b..636ea132ba 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -24,7 +24,7 @@ import static org.lwjgl.vulkan.VK10.*; public class DrawBuffers { - private static final int VERTEX_SIZE = PipelineManager.TERRAIN_VERTEX_FORMAT.getVertexSize(); + private static final int VERTEX_SIZE = PipelineManager.terrainVertexFormat.getVertexSize(); private static final int INDEX_SIZE = Short.BYTES; private static final int CMD_STRIDE = 32; @@ -121,7 +121,7 @@ private int encodeSectionOffset(int xOffset, int yOffset, int zOffset) { } // TODO: refactor - public static final float POS_OFFSET = PipelineManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN ? 4.0f : 0.0f; + public static final float POS_OFFSET = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN ? 4.0f : 0.0f; private void updateChunkAreaOrigin(VkCommandBuffer commandBuffer, Pipeline pipeline, double camX, double camY, double camZ, MemoryStack stack) { float xOffset = (float) ((this.origin.x) + POS_OFFSET - camX); diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java new file mode 100644 index 0000000000..a45ca73769 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -0,0 +1,175 @@ +package net.vulkanmod.render.shader; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.SPIRVUtils; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public abstract class ShaderLoadUtil { + + private static final String RESOURCES_PATH = SPIRVUtils.class.getResource("/assets/vulkanmod").toExternalForm(); + + public static void loadShaders(Pipeline.Builder pipelineBuilder, JsonObject config, String configName, String path) { + String vertexShader = config.has("vertex") ? config.get("vertex").getAsString() : configName; + String fragmentShader = config.has("fragment") ? config.get("fragment").getAsString() : configName; + + vertexShader = removeNameSpace(vertexShader); + fragmentShader = removeNameSpace(fragmentShader); + + vertexShader = getFileName(vertexShader); + fragmentShader = getFileName(fragmentShader); + + loadShader(pipelineBuilder, configName, path, vertexShader, SPIRVUtils.ShaderKind.VERTEX_SHADER); + loadShader(pipelineBuilder, configName, path, fragmentShader, SPIRVUtils.ShaderKind.FRAGMENT_SHADER); + } + + public static void loadShader(Pipeline.Builder pipelineBuilder, String configName, String path, SPIRVUtils.ShaderKind type) { + String[] splitPath = splitPath(path); + String shaderName = splitPath[1]; + String subPath = splitPath[0]; + + loadShader(pipelineBuilder, configName, subPath, shaderName, type); + } + + public static void loadShader(Pipeline.Builder pipelineBuilder, String configName, String path, String shaderName, SPIRVUtils.ShaderKind type) { + String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); + + String source = getShaderSource(basePath, configName, shaderName, type); + + SPIRVUtils.SPIRV spirv = SPIRVUtils.compileShader(shaderName, source, type); + + switch (type) { + case VERTEX_SHADER -> pipelineBuilder.setVertShaderSPIRV(spirv); + case FRAGMENT_SHADER -> pipelineBuilder.setFragShaderSPIRV(spirv); + } + } + + public static String getConfigFilePath(String path, String rendertype) { + String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); + String configPath = "%s/%s/%s.json".formatted(basePath, rendertype, rendertype); + + Path filePath; + try { + filePath = FileSystems.getDefault().getPath(configPath); + + if (!Files.exists(filePath)) { + configPath = "%s/%s.json".formatted(basePath, rendertype); + filePath = FileSystems.getDefault().getPath(configPath); + } + + if (!Files.exists(filePath)) { + return null; + } + } catch (Throwable e) { + throw new RuntimeException(e); + } + + return filePath.toString(); + } + + public static JsonObject getJsonConfig(String path, String rendertype) { + String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); + String configPath = "%s/%s/%s.json".formatted(basePath, rendertype, rendertype); + + InputStream stream; + try { + stream = getInputStream(configPath); + + if (stream == null) { + configPath = "%s/%s.json".formatted(basePath, rendertype); + stream = getInputStream(configPath); + } + + if (stream == null) { + return null; + } + + JsonElement jsonElement = JsonParser.parseReader(new BufferedReader(new InputStreamReader(stream))); + stream.close(); + + return (JsonObject) jsonElement; + } catch (Throwable e) { + throw new RuntimeException(e); + } + + } + + public static String getShaderSource(String basePath, String rendertype, String shaderName, SPIRVUtils.ShaderKind type) { + String shaderExtension = switch (type) { + case VERTEX_SHADER -> ".vsh"; + case FRAGMENT_SHADER -> ".fsh"; + default -> throw new UnsupportedOperationException("shader type %s unsupported"); + }; + + String shaderPath = "/%s/%s".formatted(rendertype, rendertype); + String shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); + + InputStream stream; + try { + stream = getInputStream(shaderFile); + + if (stream == null) { + shaderPath = "/%s/%s".formatted(rendertype, shaderName); + shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); + stream = getInputStream(shaderFile); + } + + if (stream == null) { + shaderPath = "/%s/%s".formatted(shaderName, shaderName); + shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); + stream = getInputStream(shaderFile); + } + + if (stream == null) { + return null; + } + + String source = IOUtils.toString(new BufferedReader(new InputStreamReader(stream))); + stream.close(); + + return source; + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static String getFileName(String path) { + int idx = path.lastIndexOf('/'); + return idx > -1 ? path.substring(idx + 1) : path; + } + + public static String removeNameSpace(String path) { + int idx = path.indexOf(':'); + return idx > -1 ? path.substring(idx + 1) : path; + } + + public static String[] splitPath(String path) { + int idx = path.lastIndexOf('/'); + + return new String[] {path.substring(0, idx), path.substring(idx + 1)}; + } + + public static InputStream getInputStream(String path) { + try { + var path1 = Paths.get(new URI(path)); + + if (!Files.exists(path1)) + return null; + + return Files.newInputStream(path1); + } catch (URISyntaxException | IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index e09264a682..f12c69a175 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -37,8 +37,8 @@ public TerrainBuilder(int size) { this.indexBufferPtr = ALLOCATOR.malloc(size); this.indexBufferCapacity = size; - this.format = PipelineManager.TERRAIN_VERTEX_FORMAT; - this.vertexBuilder = PipelineManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN + this.format = PipelineManager.terrainVertexFormat; + this.vertexBuilder = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); var bufferBuilders = new TerrainBufferBuilder[QuadFacing.COUNT]; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index f3f8bf326a..0045fc3f7b 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -18,26 +18,25 @@ import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.layout.PushConstants; +import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.texture.VulkanImage; +import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.lang3.Validate; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.*; -import java.io.InputStream; -import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; -import static net.vulkanmod.vulkan.shader.SPIRVUtils.compileShader; -import static net.vulkanmod.vulkan.shader.SPIRVUtils.compileShaderAbsoluteFile; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.VK10.*; @@ -481,14 +480,6 @@ private void cleanUp() { } public static class Builder { - - public static GraphicsPipeline createGraphicsPipeline(VertexFormat format, String path) { - Pipeline.Builder pipelineBuilder = new Pipeline.Builder(format, path); - pipelineBuilder.parseBindingsJSON(); - pipelineBuilder.compileShaders(); - return pipelineBuilder.createGraphicsPipeline(); - } - final VertexFormat vertexFormat; final String shaderPath; List UBOs; @@ -502,6 +493,8 @@ public static GraphicsPipeline createGraphicsPipeline(VertexFormat format, Strin RenderPass renderPass; + Function> uniformSupplierGetter; + public Builder(VertexFormat vertexFormat, String path) { this.vertexFormat = vertexFormat; this.shaderPath = path; @@ -511,6 +504,10 @@ public Builder(VertexFormat vertexFormat) { this(vertexFormat, null); } + public Builder() { + this(null, null); + } + public GraphicsPipeline createGraphicsPipeline() { Validate.isTrue(this.imageDescriptors != null && this.UBOs != null && this.vertShaderSPIRV != null && this.fragShaderSPIRV != null, @@ -532,34 +529,23 @@ public void setSPIRVs(SPIRV vertShaderSPIRV, SPIRV fragShaderSPIRV) { this.fragShaderSPIRV = fragShaderSPIRV; } - public void compileShaders() { - String resourcePath = SPIRVUtils.class.getResource("/assets/vulkanmod/shaders/").toExternalForm(); - - this.vertShaderSPIRV = compileShaderAbsoluteFile(String.format("%s%s.vsh", resourcePath, this.shaderPath), ShaderKind.VERTEX_SHADER); - this.fragShaderSPIRV = compileShaderAbsoluteFile(String.format("%s%s.fsh", resourcePath, this.shaderPath), ShaderKind.FRAGMENT_SHADER); + public void compileShaders(String name, String vsh, String fsh) { + this.vertShaderSPIRV = SPIRVUtils.compileShader(String.format("%s.vsh", name), vsh, ShaderKind.VERTEX_SHADER); + this.fragShaderSPIRV = SPIRVUtils.compileShader(String.format("%s.fsh", name), fsh, ShaderKind.FRAGMENT_SHADER); } - public void compileShaders(String name, String vsh, String fsh) { - this.vertShaderSPIRV = compileShader(String.format("%s.vsh", name), vsh, ShaderKind.VERTEX_SHADER); - this.fragShaderSPIRV = compileShader(String.format("%s.fsh", name), fsh, ShaderKind.FRAGMENT_SHADER); + public void setVertShaderSPIRV(SPIRV vertShaderSPIRV) { + this.vertShaderSPIRV = vertShaderSPIRV; } - public void parseBindingsJSON() { - Validate.notNull(this.shaderPath, "Cannot parse bindings: shaderPath is null"); + public void setFragShaderSPIRV(SPIRV fragShaderSPIRV) { + this.fragShaderSPIRV = fragShaderSPIRV; + } + public void parseBindings(JsonObject jsonObject) { this.UBOs = new ArrayList<>(); this.imageDescriptors = new ArrayList<>(); - JsonObject jsonObject; - - String resourcePath = String.format("/assets/vulkanmod/shaders/%s.json", this.shaderPath); - InputStream stream = Pipeline.class.getResourceAsStream(resourcePath); - - if (stream == null) - throw new NullPointerException(String.format("Failed to load: %s", resourcePath)); - - jsonObject = GsonHelper.parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - JsonArray jsonUbos = GsonHelper.getAsJsonArray(jsonObject, "UBOs", null); JsonArray jsonManualUbos = GsonHelper.getAsJsonArray(jsonObject, "ManualUBOs", null); JsonArray jsonSamplers = GsonHelper.getAsJsonArray(jsonObject, "samplers", null); @@ -586,6 +572,10 @@ public void parseBindingsJSON() { } } + public void setUniformSupplierGetter(Function> uniformSupplierGetter) { + this.uniformSupplierGetter = uniformSupplierGetter; + } + private void parseUboNode(JsonElement jsonelement) { JsonObject jsonobject = GsonHelper.convertToJsonObject(jsonelement, "UBO"); int binding = GsonHelper.getAsInt(jsonobject, "binding"); @@ -599,11 +589,24 @@ private void parseUboNode(JsonElement jsonelement) { //need to store some infos String name = GsonHelper.getAsString(jsonobject2, "name"); String type2 = GsonHelper.getAsString(jsonobject2, "type"); - int j = GsonHelper.getAsInt(jsonobject2, "count"); + int count = GsonHelper.getAsInt(jsonobject2, "count"); - builder.addUniformInfo(type2, name, j); + Uniform.Info uniformInfo = Uniform.createUniformInfo(type2, name, count); + uniformInfo.setupSupplier(); + + if (!uniformInfo.hasSupplier()) { + var uniformSupplier = this.uniformSupplierGetter.apply(uniformInfo); + + if (uniformSupplier == null) { + throw new IllegalStateException("No uniform supplier found for uniform: (%s:%s)".formatted(type2, name)); + } + uniformInfo.setBufferSupplier(this.uniformSupplierGetter.apply(uniformInfo)); + } + + builder.addUniformInfo(uniformInfo); } + UBO ubo = builder.buildUBO(binding, type); if (binding >= this.nextBinding) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index f1d8001e6c..5de582389f 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeResource; import org.lwjgl.util.shaderc.ShadercIncludeResolveI; import org.lwjgl.util.shaderc.ShadercIncludeResult; @@ -10,7 +9,6 @@ import org.lwjgl.vulkan.VK12; import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -24,7 +22,7 @@ import static org.lwjgl.util.shaderc.Shaderc.*; public class SPIRVUtils { - private static final boolean DEBUG = false; + private static final boolean DEBUG = true; private static final boolean OPTIMIZATIONS = true; private static long compiler; @@ -37,8 +35,6 @@ public class SPIRVUtils { private static ObjectArrayList includePaths; - private static float time = 0.0f; - static { initCompiler(); } @@ -46,20 +42,20 @@ public class SPIRVUtils { private static void initCompiler() { compiler = shaderc_compiler_initialize(); - if(compiler == NULL) { + if (compiler == NULL) { throw new RuntimeException("Failed to create shader compiler"); } options = shaderc_compile_options_initialize(); - if(options == NULL) { + if (options == NULL) { throw new RuntimeException("Failed to create compiler options"); } - if(OPTIMIZATIONS) + if (OPTIMIZATIONS) shaderc_compile_options_set_optimization_level(options, shaderc_optimization_level_performance); - if(DEBUG) + if (DEBUG) shaderc_compile_options_set_generate_debug_info(options); shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_2, VK12.VK_API_VERSION_1_2); @@ -72,52 +68,30 @@ private static void initCompiler() { public static void addIncludePath(String path) { URL url = SPIRVUtils.class.getResource(path); - if(url != null) + if (url != null) includePaths.add(url.toExternalForm()); } - public static SPIRV compileShaderAbsoluteFile(String shaderFile, ShaderKind shaderKind) { - try { - String source = new String(Files.readAllBytes(Paths.get(new URI(shaderFile)))); - return compileShader(shaderFile, source, shaderKind); - } catch (IOException | URISyntaxException e) { - e.printStackTrace(); - } - return null; - } - public static SPIRV compileShader(String filename, String source, ShaderKind shaderKind) { - long startTime = System.nanoTime(); + if (source == null) { + throw new NullPointerException("source for %s.%s is null".formatted(filename, shaderKind)); + } long result = shaderc_compile_into_spv(compiler, source, shaderKind.kind, filename, "main", options); - if(result == NULL) { + if (result == NULL) { throw new RuntimeException("Failed to compile shader " + filename + " into SPIR-V"); } - if(shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) { - throw new RuntimeException("Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message(result)); + if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) { + throw new RuntimeException( + "Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message( + result)); } - time += (System.nanoTime() - startTime) / 1000000.0f; - return new SPIRV(result, shaderc_result_get_bytes(result)); } - private static SPIRV readFromStream(InputStream inputStream) { - try { - byte[] bytes = inputStream.readAllBytes(); - ByteBuffer buffer = MemoryUtil.memAlloc(bytes.length); - buffer.put(bytes); - buffer.position(0); - - return new SPIRV(MemoryUtil.memAddress(buffer), buffer); - } catch (Exception e) { - e.printStackTrace(); - } - throw new RuntimeException("unable to read inputStream"); - } - public enum ShaderKind { VERTEX_SHADER(shaderc_glsl_vertex_shader), GEOMETRY_SHADER(shaderc_glsl_geometry_shader), @@ -140,19 +114,19 @@ public long invoke(long user_data, long requested_source, int type, long request var requesting = memASCII(requesting_source); var requested = memASCII(requested_source); - try(MemoryStack stack = MemoryStack.stackPush()) { + try (MemoryStack stack = MemoryStack.stackPush()) { Path path; - for(String includePath : includePaths) { + for (String includePath : includePaths) { path = Paths.get(new URI(String.format("%s%s", includePath, requested))); - if(Files.exists(path)) { + if (Files.exists(path)) { byte[] bytes = Files.readAllBytes(path); return ShadercIncludeResult.malloc(stack) - .source_name(stack.ASCII(requested)) - .content(stack.bytes(bytes)) - .user_data(user_data).address(); + .source_name(stack.ASCII(requested)) + .content(stack.bytes(bytes)) + .user_data(user_data).address(); } } } catch (IOException | URISyntaxException e) { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java index e233046d77..3098e0a7c2 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.util.MappedBuffer; import java.util.function.Supplier; @@ -51,4 +52,15 @@ public static void setupDefaultUniforms() { vec4f_uniformMap.put("FogColor", VRenderSystem::getShaderFogColor); } + + public static Supplier getUniformSupplier(String type, String name) { + return switch (type) { + case "mat4" -> Uniforms.mat4f_uniformMap.get(name); + case "vec4" -> Uniforms.vec4f_uniformMap.get(name); + case "vec3" -> Uniforms.vec3f_uniformMap.get(name); + case "vec2" -> Uniforms.vec2f_uniformMap.get(name); + + default -> null; + }; + } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java index 89c015da58..11560c621c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java @@ -13,18 +13,17 @@ public abstract class AlignedStruct { protected AlignedStruct(List infoList, int size) { this.size = size; - if(infoList == null) + if (infoList == null) return; - for(Uniform.Info info : infoList) { - + for (Uniform.Info info : infoList) { Uniform uniform = Uniform.createField(info); this.uniforms.add(uniform); } } public void update(long ptr) { - for(Uniform uniform : this.uniforms) { + for (Uniform uniform : this.uniforms) { uniform.update(ptr); } } @@ -39,33 +38,36 @@ public int getSize() { public static class Builder { - final List uniformsInfo = new ArrayList<>(); + final List uniforms = new ArrayList<>(); protected int currentOffset = 0; public void addUniformInfo(String type, String name, int count) { Uniform.Info info = Uniform.createUniformInfo(type, name, count); - - this.currentOffset = info.computeAlignmentOffset(this.currentOffset); - this.currentOffset += info.size; - this.uniformsInfo.add(info); + addUniformInfo(info); } public void addUniformInfo(String type, String name) { Uniform.Info info = Uniform.createUniformInfo(type, name); + addUniformInfo(info); + } - this.currentOffset = info.computeAlignmentOffset(this.currentOffset); - this.currentOffset += info.size; - this.uniformsInfo.add(info); + public void addUniformInfo(Uniform.Info uniformInfo) { + this.currentOffset = uniformInfo.computeAlignmentOffset(this.currentOffset); + this.currentOffset += uniformInfo.size; + this.uniforms.add(uniformInfo); } public UBO buildUBO(int binding, int stages) { //offset is expressed in floats/ints - return new UBO(binding, stages, this.currentOffset * 4, this.uniformsInfo); + return new UBO(binding, stages, this.currentOffset * 4, this.uniforms); } public PushConstants buildPushConstant() { - if(this.uniformsInfo.isEmpty()) return null; - return new PushConstants(this.uniformsInfo, this.currentOffset * 4); + if (this.uniforms.isEmpty()) { + return null; + } + + return new PushConstants(this.uniforms, this.currentOffset * 4); } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java index c0f07797c4..8c1509df14 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java @@ -17,18 +17,12 @@ public class Uniform { this.info = info; this.offset = info.offset * 4L; this.size = info.size * 4; - this.setSupplier(); - } - void setSupplier() { - this.values = switch (info.type) { - case "mat4" -> Uniforms.mat4f_uniformMap.get(info.name); - case "vec4" -> Uniforms.vec4f_uniformMap.get(info.name); - case "vec3" -> Uniforms.vec3f_uniformMap.get(info.name); - case "vec2" -> Uniforms.vec2f_uniformMap.get(info.name); + this.setupSupplier(); + } - default -> null; - }; + protected void setupSupplier() { + this.values = this.info.bufferSupplier; } public void setSupplier(Supplier supplier) { @@ -61,6 +55,10 @@ public int getOffset() { public int getSize() { return info.size; } + public Info getInfo() { + return info; + } + public String toString() { return String.format("%s: %s offset: %d", info.type, info.name, info.offset); } @@ -98,12 +96,16 @@ public static Info createUniformInfo(String type, String name) { } public static class Info { - final String type; - final String name; - final int align; - final int size; + public final String type; + public final String name; + public final int align; + public final int size; int offset; + Supplier bufferSupplier; + Supplier intSupplier; + Supplier floatSupplier; + Info(String type, String name, int align, int size) { this.type = type; this.name = name; @@ -116,5 +118,26 @@ public static class Info { int computeAlignmentOffset(int builderOffset) { return this.offset = builderOffset + ((align - (builderOffset % align)) % align); } + + public void setupSupplier() { + switch (this.type) { + case "float" -> this.floatSupplier = Uniforms.vec1f_uniformMap.get(this.name); + case "int" -> this.intSupplier = Uniforms.vec1i_uniformMap.get(this.name); + default -> this.bufferSupplier = Uniforms.getUniformSupplier(this.type, this.name); + } + } + + public boolean hasSupplier() { + return switch (this.type) { + case "float" -> this.floatSupplier != null || this.bufferSupplier != null; + case "int" -> this.intSupplier != null || this.bufferSupplier != null; + default -> this.bufferSupplier != null; + }; + } + + public void setBufferSupplier(Supplier supplier) { + this.bufferSupplier = supplier; + } + } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java index 4e9a2084ce..484861490a 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java @@ -1,8 +1,6 @@ package net.vulkanmod.vulkan.shader.layout; -import net.vulkanmod.vulkan.shader.Uniforms; import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.lang3.Validate; import org.lwjgl.system.MemoryUtil; import java.util.function.Supplier; @@ -14,8 +12,12 @@ public Vec1f(Info info) { super(info); } - void setSupplier() { - this.floatSupplier = Uniforms.vec1f_uniformMap.get(this.info.name); + protected void setupSupplier() { + if (this.info.floatSupplier != null) { + this.floatSupplier = this.info.floatSupplier; + } else { + this.setSupplier(this.info.bufferSupplier); + } } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java index 995076cb27..700fd00bf7 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java @@ -14,8 +14,12 @@ public Vec1i(Info info) { super(info); } - void setSupplier() { - this.intSupplier = Uniforms.vec1i_uniformMap.get(this.info.name); + protected void setupSupplier() { + if (this.info.intSupplier != null) { + this.intSupplier = this.info.intSupplier; + } else { + this.setSupplier(this.info.bufferSupplier); + } } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java b/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java index e15622f4e8..1687ea6e8f 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java @@ -174,8 +174,8 @@ private void setShaderStage(ShaderStage shaderStage) { this.inOutParser.setShaderStage(this.shaderStage); } - public UBO getUBO() { - return this.uniformParser.getUbo(); + public UBO createUBO() { + return this.uniformParser.createUBO(); } public List getSamplerList() { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java b/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java index cc5087ce09..34fe6df0d9 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java @@ -1,10 +1,10 @@ package net.vulkanmod.vulkan.shader.parser; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; -import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.shader.layout.AlignedStruct; +import org.lwjgl.vulkan.VK11; import java.util.ArrayList; import java.util.List; @@ -19,19 +19,18 @@ public class UniformParser { private String type; private String name; - private UBO ubo; private List imageDescriptors; public UniformParser(GlslConverter converterInstance) { this.converterInstance = converterInstance; - for(int i = 0; i < this.stageUniforms.length; ++i) { + for (int i = 0; i < this.stageUniforms.length; ++i) { this.stageUniforms[i] = new StageUniforms(); } } public boolean parseToken(String token) { - if(token.matches("uniform")) return false; + if (token.matches("uniform")) return false; if (this.type == null) { this.type = token; @@ -47,7 +46,8 @@ else if (this.name == null) { if ("sampler2D".equals(this.type)) { if (!this.currentUniforms.samplers.contains(uniform)) this.currentUniforms.samplers.add(uniform); - } else { + } + else { if (!this.globalUniforms.contains(uniform)) this.globalUniforms.add(uniform); } @@ -72,11 +72,9 @@ private void resetSate() { public String createUniformsCode() { StringBuilder builder = new StringBuilder(); - this.ubo = this.createUBO(); - //hardcoded 0 binding as it should always be 0 in this case builder.append(String.format("layout(binding = %d) uniform UniformBufferObject {\n", 0)); - for(Uniform uniform : this.globalUniforms) { + for (Uniform uniform : this.globalUniforms) { builder.append(String.format("%s %s;\n", uniform.type, uniform.name)); } builder.append("};\n\n"); @@ -89,23 +87,29 @@ public String createSamplersCode(GlslConverter.ShaderStage shaderStage) { this.imageDescriptors = createSamplerList(); - for(ImageDescriptor imageDescriptor : this.imageDescriptors) { - builder.append(String.format("layout(binding = %d) uniform %s %s;\n", imageDescriptor.getBinding(), imageDescriptor.qualifier, imageDescriptor.name)); + for (ImageDescriptor imageDescriptor : this.imageDescriptors) { + builder.append(String.format("layout(binding = %d) uniform %s %s;\n", imageDescriptor.getBinding(), + imageDescriptor.qualifier, imageDescriptor.name)); } builder.append("\n"); return builder.toString(); } - private UBO createUBO() { + public UBO createUBO() { AlignedStruct.Builder builder = new AlignedStruct.Builder(); - for(Uniform uniform : this.globalUniforms) { - builder.addUniformInfo(uniform.type, uniform.name); + for (UniformParser.Uniform uniform : this.globalUniforms) { + String name = uniform.name(); + String type = uniform.type(); + + net.vulkanmod.vulkan.shader.layout.Uniform.Info uniformInfo = net.vulkanmod.vulkan.shader.layout.Uniform.createUniformInfo(type, name); + + builder.addUniformInfo(uniformInfo); } - //hardcoded 0 binding as it should always be 0 in this case - return builder.buildUBO(0, Pipeline.Builder.getStageFromString("all")); + // Use binding 0 for global uniforms + return builder.buildUBO(0, VK11.VK_SHADER_STAGE_ALL); } private List createSamplerList() { @@ -113,8 +117,8 @@ private List createSamplerList() { List imageDescriptors = new ObjectArrayList<>(); - for(StageUniforms stageUniforms : this.stageUniforms) { - for(Uniform uniform : stageUniforms.samplers) { + for (StageUniforms stageUniforms : this.stageUniforms) { + for (Uniform uniform : stageUniforms.samplers) { int imageIdx = currentLocation - 1; imageDescriptors.add(new ImageDescriptor(currentLocation, uniform.type, uniform.name, imageIdx)); currentLocation++; @@ -126,20 +130,21 @@ private List createSamplerList() { public static String removeSemicolon(String s) { int last = s.length() - 1; - if((s.charAt(last)) != ';' ) + if ((s.charAt(last)) != ';') throw new IllegalArgumentException("last char is not ;"); return s.substring(0, last); } - public UBO getUbo() { - return this.ubo; + public List getGlobalUniforms() { + return globalUniforms; } public List getSamplers() { return this.imageDescriptors; } - public record Uniform(String type, String name) {} + public record Uniform(String type, String name) { + } private static class StageUniforms { List samplers = new ArrayList<>(); diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json index bf010c54bb..2233161b78 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json @@ -1,26 +1,10 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_solid", - "fragment": "rendertype_solid", - "attributes": [ - "Position", - "Color", - "UV0" - ], + "vertex": "terrain", + "fragment": "terrain", "samplers": [ { "name": "Sampler0" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh index 87a3531d52..e3493d561d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh @@ -18,40 +18,39 @@ layout (location = 0) out float vertexDistance; layout (location = 1) out vec4 vertexColor; layout (location = 2) out vec2 texCoord0; -//Compressed Vertex -layout (location = 0) in ivec4 Position; -layout (location = 1) in vec4 Color; -layout (location = 2) in uvec2 UV0; +#define COMPRESSED_VERTEX + +#ifdef COMPRESSED_VERTEX + layout (location = 0) in ivec4 Position; + layout (location = 1) in vec4 Color; + layout (location = 2) in uvec2 UV0; +#else + layout (location = 0) in vec3 Position; + layout (location = 1) in vec4 Color; + layout (location = 2) in vec2 UV0; + layout (location = 3) in ivec2 UV2; + layout (location = 4) in vec3 Normal; +#endif const float UV_INV = 1.0 / 32768.0; -//const vec3 POSITION_INV = vec3(1.0 / 1024.0); const vec3 POSITION_INV = vec3(1.0 / 2048.0); const vec3 POSITION_OFFSET = vec3(4.0); -void main() { +vec4 getVertexPosition() { const vec3 baseOffset = bitfieldExtract(ivec3(gl_InstanceIndex) >> ivec3(0, 16, 8), 0, 8); - const vec4 pos = vec4(fma(Position.xyz, POSITION_INV, ChunkOffset + baseOffset), 1.0); + + #ifdef COMPRESSED_VERTEX + return vec4(fma(Position.xyz, POSITION_INV, ChunkOffset + baseOffset), 1.0); + #else + return vec4(Position.xyz + baseOffset, 1.0); + #endif +} + +void main() { + const vec4 pos = getVertexPosition(); gl_Position = MVP * pos; vertexDistance = fog_distance(pos.xyz, 0); vertexColor = Color * sample_lightmap2(Sampler2, Position.a); texCoord0 = UV0 * UV_INV; -} - -////Default Vertex -//layout(location = 0) in vec3 Position; -//layout(location = 1) in vec4 Color; -//layout(location = 2) in vec2 UV0; -//layout(location = 3) in ivec2 UV2; -//layout(location = 4) in vec3 Normal; -// -//void main() { -// const vec3 baseOffset = bitfieldExtract(ivec3(gl_InstanceIndex) >> ivec3(0, 16, 8), 0, 8); -// const vec4 pos = vec4(Position.xyz + baseOffset, 1.0); -// gl_Position = MVP * pos; -// -// vertexDistance = length((ModelViewMat * pos).xyz); -// vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); -// texCoord0 = UV0; -// // normal = MVP * vec4(Normal, 0.0); -//} \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain_Z.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh similarity index 99% rename from src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain_Z.fsh rename to src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh index b3d4faf584..5386a55329 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain_Z.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh @@ -1,5 +1,7 @@ #version 450 + layout(early_fragment_tests) in; + #include "light.glsl" #include "fog.glsl" @@ -11,7 +13,6 @@ layout(binding = 1) uniform UBO { float FogEnd; }; - layout(location = 0) in float vertexDistance; layout(location = 1) in vec4 vertexColor; layout(location = 2) in vec2 texCoord0; diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json new file mode 100644 index 0000000000..9c00f2e058 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json @@ -0,0 +1,22 @@ +{ + "vertex": "terrain", + "fragment": "terrain_earlyZ", + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler2" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "AlphaCutout", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ], + "PushConstants": [ + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.fsh b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh similarity index 60% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh index be1711e592..471982cdde 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh @@ -1,6 +1,6 @@ #version 450 -layout(binding = 1) uniform sampler2D DiffuseSampler; +layout(binding = 0) uniform sampler2D DiffuseSampler; layout(location = 0) in vec2 texCoord; @@ -8,7 +8,5 @@ layout(location = 0) out vec4 fragColor; void main() { vec4 color = texture(DiffuseSampler, texCoord); - - // blit final output of compositor into displayed back buffer fragColor = color; } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json new file mode 100644 index 0000000000..6405ec09d9 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json @@ -0,0 +1,9 @@ +{ + "vertex": "blit_screen", + "fragment": "blit_screen", + "samplers": [ + { "name": "Sampler0" } + ], + "uniforms": [ + ] +} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh new file mode 100644 index 0000000000..8cedf72511 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh @@ -0,0 +1,11 @@ +#version 450 + +layout(location = 0) in vec3 Position; + +layout(location = 0) out vec2 texCoord; + +void main() { + vec2 screenPos = Position.xy * 2.0 - 1.0; + gl_Position = vec4(screenPos.x, screenPos.y, 1.0, 1.0); + texCoord = Position.xy; +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.fsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.fsh b/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh b/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh new file mode 100644 index 0000000000..5fd8ccf2b3 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh @@ -0,0 +1,16 @@ +#version 450 + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec4 Color; + +layout(binding = 0) uniform UniformBufferObject { + mat4 MVP; +}; + +layout(location = 0) out vec4 vertexColor; + +void main() { + gl_Position = MVP * vec4(Position, 1.0); + + vertexColor = Color; +} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh new file mode 100644 index 0000000000..8465e60343 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh @@ -0,0 +1,70 @@ +#version 450 + +layout(binding = 0) uniform UniformBufferObject { + float AmbientLightFactor; + float SkyFactor; + float BlockFactor; + int UseBrightLightmap; + vec3 SkyLightColor; + float NightVisionFactor; + float DarknessScale; + float DarkenWorldFactor; + float BrightnessFactor; +}; + +layout(location = 0) in vec2 texCoord; + +layout(location = 0) out vec4 fragColor; + +float get_brightness(float level) { + float curved_level = level / (4.0 - 3.0 * level); + return mix(curved_level, 1.0, AmbientLightFactor); +} + +vec3 notGamma(vec3 x) { + vec3 nx = 1.0 - x; + return 1.0 - nx * nx * nx * nx; +} + +void main() { + float block_brightness = get_brightness(floor(texCoord.x * 16) / 15) * BlockFactor; + float sky_brightness = get_brightness(floor(texCoord.y * 16) / 15) * SkyFactor; + + // cubic nonsense, dips to yellowish in the middle, white when fully saturated + vec3 color = vec3( + block_brightness, + block_brightness * ((block_brightness * 0.6 + 0.4) * 0.6 + 0.4), + block_brightness * (block_brightness * block_brightness * 0.6 + 0.4) + ); + + if (UseBrightLightmap != 0) { + color = mix(color, vec3(0.99, 1.12, 1.0), 0.25); + color = clamp(color, 0.0, 1.0); + } else { + color += SkyLightColor * sky_brightness; + color = mix(color, vec3(0.75), 0.04); + + vec3 darkened_color = color * vec3(0.7, 0.6, 0.6); + color = mix(color, darkened_color, DarkenWorldFactor); + } + + if (NightVisionFactor > 0.0) { + // scale up uniformly until 1.0 is hit by one of the colors + float max_component = max(color.r, max(color.g, color.b)); + if (max_component < 1.0) { + vec3 bright_color = color / max_component; + color = mix(color, bright_color, NightVisionFactor); + } + } + + if (UseBrightLightmap == 0) { + color = clamp(color - vec3(DarknessScale), 0.0, 1.0); + } + + vec3 notGamma = notGamma(color); + color = mix(color, notGamma, BrightnessFactor); + color = mix(color, vec3(0.75), 0.04); + color = clamp(color, 0.0, 1.0); + + fragColor = vec4(color, 1.0); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json new file mode 100644 index 0000000000..5efc51dacc --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json @@ -0,0 +1,30 @@ +{ + "vertex": "blit_screen", + "fragment": "lightmap", + "samplers": [ + ], + "uniforms": [ + { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, + { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, + { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, + { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, + { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, + { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } + ], + "UBOs": [ + { "type": "fragment", "binding": 0, "fields": [ + { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, + { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, + { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, + { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, + { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, + { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, + { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.json b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json similarity index 58% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.json rename to src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json index 6dddf404d3..f43398ce06 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json @@ -1,27 +1,10 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "particle", "fragment": "particle", - "attributes": [ - "Position", - "UV0", - "Color", - "UV2" - ], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.vsh b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/particle/particle.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.json b/src/main/resources/assets/vulkanmod/shaders/core/position/position.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.json rename to src/main/resources/assets/vulkanmod/shaders/core/position/position.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position/position.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh new file mode 100644 index 0000000000..fce9fa7c61 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh @@ -0,0 +1,17 @@ +#version 450 + +layout(location = 0) in vec4 vertexColor; + +layout(binding = 1) uniform UBO{ + vec4 ColorModulator; +}; + +layout(location = 0) out vec4 fragColor; + +void main() { + vec4 color = vertexColor; + if (color.a == 0.0) { + discard; + } + fragColor = color * ColorModulator; +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color/position_color.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_lightmap/position_color_lightmap.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_normal/position_color_normal.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex/position_color_tex.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex/position_tex.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json new file mode 100644 index 0000000000..c3bbf9faf0 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json @@ -0,0 +1,20 @@ +{ + "vertex": "minecraft:core/position_tex_color", + "fragment": "minecraft:core/position_tex_color", + "samplers": [ + { "name": "Sampler0" } + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.json rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color_normal/position_tex_color_normal.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json similarity index 56% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json index 33c472d393..04bbe696c4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_armor_glint/rendertype_armor_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json @@ -1,24 +1,9 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_armor_glint", - "fragment": "rendertype_armor_glint", - "attributes": [ - "Position", - "UV0" - ], + "vertex": "glint", + "fragment": "glint", "samplers": [ { "name": "Sampler0" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json new file mode 100644 index 0000000000..f393b88b00 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json @@ -0,0 +1,29 @@ +{ + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + }, + "flags": [ + "NO_OVERLAY" + ] + }, + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler2" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json similarity index 57% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json index 17a3bd328b..5f2a6453e2 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json @@ -1,29 +1,10 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "rendertype_breeze_wind", "fragment": "rendertype_breeze_wind", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2" - ], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh similarity index 88% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh index 714c6e1a7c..6c5a9f1cb8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh @@ -24,8 +24,7 @@ layout(location = 3) out vec2 texCoord0; void main() { gl_Position = MVP * vec4(Position, 1.0); - vec4 pos = ModelViewMat * (Position, 1.0); - vertexDistance = fog_distance(pos.xyz, FogShape); + vertexDistance = fog_distance(Position, FogShape); lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); vertexColor = Color * lightMapColor; diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh similarity index 67% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh index db89144f5d..2a3e1b3699 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh @@ -2,27 +2,19 @@ #include "fog.glsl" -layout(binding = 2) uniform sampler2D Sampler0; - layout(binding = 1) uniform UBO{ - vec4 ColorModulator; vec4 FogColor; float FogStart; float FogEnd; }; layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; +layout(location = 1) in float vertexDistance; layout(location = 0) out vec4 fragColor; void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = linear_fog(vertexColor, vertexDistance, FogStart, FogEnd, FogColor); } //#version 150 diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json similarity index 84% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json index 7798d39afb..d36098bcfb 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json @@ -1,17 +1,12 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_clouds", - "fragment": "rendertype_clouds", + "vertex": "minecraft:core/rendertype_clouds", + "fragment": "minecraft:core/rendertype_clouds", "samplers": [ - { "name": "Sampler0" } ], "uniforms": [ { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, @@ -25,7 +20,6 @@ { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh similarity index 57% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh index 289748aef4..7b65d90584 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_clouds/rendertype_clouds.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh @@ -26,29 +26,3 @@ void main() { vertexDistance = fog_distance(pos.xyz, FogShape); vertexColor = Color; } - -//#version 150 -// -//#moj_import -// -//in vec3 Position; -//in vec2 UV0; -//in vec4 Color; -//in vec3 Normal; -// -//uniform mat4 ModelViewMat; -//uniform mat4 ProjMat; -//uniform int FogShape; -// -//out vec2 texCoord0; -//out float vertexDistance; -//out vec4 vertexColor; -// -//void main() { -// vec4 pos = ModelViewMat * vec4(Position, 1.0); -// gl_Position = ProjMat * pos; -// -// texCoord0 = UV0; -// vertexDistance = fog_distance(pos.xyz, FogShape); -// vertexColor = Color; -//} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_crumbling/rendertype_crumbling.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout/rendertype_cutout.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json new file mode 100644 index 0000000000..8e6cb7d0b7 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json @@ -0,0 +1,17 @@ +{ + "vertex": "rendertype_end_portal", + "fragment": "rendertype_end_portal", + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json similarity index 67% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json index 8854d96e4c..8e6cb7d0b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json @@ -1,20 +1,10 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "rendertype_end_portal", "fragment": "rendertype_end_portal", - "attributes": [], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler1" } ], - "uniforms": [ - { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_end_portal/rendertype_end_portal.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json similarity index 64% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json index 4caff80794..edbd117d59 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json @@ -1,21 +1,9 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "rendertype_entity_alpha", "fragment": "rendertype_entity_alpha", - "attributes": [ - "Position", - "Color", - "UV0", - "Normal" - ], "samplers": [ { "name": "Sampler0" } ], - "uniforms": [], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json similarity index 53% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json index 51ae16d559..ea44c9e1e4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json @@ -1,32 +1,16 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } }, - "vertex": "rendertype_entity_cutout", - "fragment": "rendertype_entity_cutout", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler1" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json new file mode 100644 index 0000000000..ea44c9e1e4 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json @@ -0,0 +1,27 @@ +{ + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" }, + { "name": "Sampler2" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json new file mode 100644 index 0000000000..ea44c9e1e4 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json @@ -0,0 +1,27 @@ +{ + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" }, + { "name": "Sampler2" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_decal/rendertype_entity_decal.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint/rendertype_entity_glint.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json new file mode 100644 index 0000000000..ea44c9e1e4 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json @@ -0,0 +1,27 @@ +{ + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" }, + { "name": "Sampler2" } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json similarity index 57% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json index e3d0c8b9d7..0e4e0177ba 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json @@ -1,32 +1,11 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "rendertype_entity_solid", "fragment": "rendertype_entity_solid", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler1" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_solid/rendertype_entity_solid.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json similarity index 53% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json index a3f7071073..ea44c9e1e4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json @@ -1,32 +1,16 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } }, - "vertex": "rendertype_entity_translucent", - "fragment": "rendertype_entity_translucent", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], "samplers": [ { "name": "Sampler0" }, { "name": "Sampler1" }, { "name": "Sampler2" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json similarity index 94% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json index 3f5cf9af4b..3586e725a8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json @@ -1,9 +1,4 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, "vertex": "rendertype_entity_translucent_cull", "fragment": "rendertype_entity_translucent_cull", "attributes": [ diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_eyes/rendertype_eyes.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json similarity index 56% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json index 83e0056a28..04bbe696c4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json @@ -1,24 +1,9 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_glint", - "fragment": "rendertype_glint", - "attributes": [ - "Position", - "UV0" - ], + "vertex": "glint", + "fragment": "glint", "samplers": [ { "name": "Sampler0" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json similarity index 55% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json index d016ddf123..aadaa01d4f 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json @@ -1,29 +1,14 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_glint_direct", - "fragment": "rendertype_glint_direct", - "attributes": [ - "Position", - "UV0" - ], + "vertex": "glint", + "fragment": "glint", "samplers": [ { "name": "Sampler0" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, + ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json similarity index 55% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json index 4fbd62b864..aadaa01d4f 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json @@ -1,29 +1,14 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_glint_translucent", - "fragment": "rendertype_glint_translucent", - "attributes": [ - "Position", - "UV0" - ], + "vertex": "glint", + "fragment": "glint", "samplers": [ { "name": "Sampler0" } ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, + ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json similarity index 59% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json index e65c24526c..904c1badf1 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/position_tex_color/position_tex_color.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json @@ -1,20 +1,11 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_tex_color", - "fragment": "position_tex_color", - "attributes": [ - "Position", - "UV0", - "Color" - ], + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", "samplers": [ - { "name": "Sampler0" } ], "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } ], "UBOs": [ diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json new file mode 100644 index 0000000000..904c1badf1 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json @@ -0,0 +1,19 @@ +{ + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json new file mode 100644 index 0000000000..904c1badf1 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json @@ -0,0 +1,19 @@ +{ + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json new file mode 100644 index 0000000000..904c1badf1 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json @@ -0,0 +1,19 @@ +{ + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh similarity index 57% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh index 46038952cf..ea9fb38c1d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh @@ -6,7 +6,6 @@ layout(location = 0) in vec3 Position; layout(location = 1) in vec4 Color; layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; layout(location = 4) in ivec2 UV2; layout(location = 5) in vec3 Normal; @@ -16,21 +15,16 @@ layout(binding = 0) uniform UniformBufferObject { vec3 Light1_Direction; }; -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; +layout(binding = 3) uniform sampler2D Sampler2; layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; +layout(location = 1) out vec2 texCoord0; +layout(location = 2) out float vertexDistance; void main() { gl_Position = MVP * vec4(Position, 1.0); vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); texCoord0 = UV0; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_leash/rendertype_leash.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lightning/rendertype_lightning.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_lines/rendertype_lines.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_outline/rendertype_outline.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_solid/rendertype_solid.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text/rendertype_text.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background/rendertype_text_background.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity/rendertype_text_intensity.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_text_see_through/rendertype_text_see_through.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent/rendertype_translucent.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh similarity index 59% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh index 29fd0268fc..7659168a5b 100644 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_translucent/rendertype_entity_translucent.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh @@ -11,20 +11,15 @@ layout(binding = 1) uniform UBO{ }; layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; +layout(location = 1) in vec2 texCoord0; +layout(location = 2) in float vertexDistance; layout(location = 0) out vec4 fragColor; void main() { - vec4 color = texture(Sampler0, texCoord0); + vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; if (color.a < 0.1) { discard; } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_tripwire/rendertype_tripwire.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.fsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.json rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_water_mask/rendertype_water_mask.vsh rename to src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.json b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.json deleted file mode 100644 index bd9707c0e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "blit_screen", - "fragment": "blit_screen", - "attributes": [ - "Position", - "UV", - "Color" - ], - "samplers": [], - "uniforms": [], - "UBOs": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.vsh deleted file mode 100644 index e3dd01d3c4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/blit_screen/blit_screen.vsh +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV; - -layout(location = 0) out vec2 texCoord; - -void main() { - gl_Position = vec4(Position, 1.0); - - texCoord = UV; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.fsh deleted file mode 100644 index 29fd0268fc..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.fsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.vsh deleted file mode 100644 index 46038952cf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout/rendertype_entity_cutout.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.fsh deleted file mode 100644 index fe257648a7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.fsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json deleted file mode 100644 index d04943b44a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_cutout_no_cull", - "fragment": "rendertype_entity_cutout_no_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.vsh deleted file mode 100644 index 46038952cf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.fsh deleted file mode 100644 index fe257648a7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.fsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json deleted file mode 100644 index 45caf5fb9f..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_cutout_no_cull_z_offset", - "fragment": "rendertype_entity_cutout_no_cull_z_offset", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.vsh deleted file mode 100644 index 76e60cbae9..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.fsh deleted file mode 100644 index fe257648a7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.fsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json deleted file mode 100644 index c3f9d7219d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_smooth_cutout", - "fragment": "rendertype_entity_smooth_cutout", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.vsh deleted file mode 100644 index 46038952cf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint/rendertype_glint.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_direct/rendertype_glint_direct.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.fsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.vsh b/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/minecraft/core/rendertype_glint_translucent/rendertype_glint_translucent.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file From 48dbc22b5fbdcedf068f17002d25de0e725aac1a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 9 Nov 2024 19:35:09 +0100 Subject: [PATCH 019/177] Refactor: remove unused interface --- .../vulkanmod/interfaces/ExtendedRenderTarget.java | 10 ---------- .../mixin/render/target/RenderTargetMixin.java | 14 +------------- 2 files changed, 1 insertion(+), 23 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/interfaces/ExtendedRenderTarget.java diff --git a/src/main/java/net/vulkanmod/interfaces/ExtendedRenderTarget.java b/src/main/java/net/vulkanmod/interfaces/ExtendedRenderTarget.java deleted file mode 100644 index f5da47f6d2..0000000000 --- a/src/main/java/net/vulkanmod/interfaces/ExtendedRenderTarget.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.vulkanmod.interfaces; - -import net.vulkanmod.vulkan.framebuffer.RenderPass; - -public interface ExtendedRenderTarget { - - boolean isBound(); - - RenderPass getRenderPass(); -} diff --git a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java index 9dd3134b40..7c1ebabd9a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java @@ -5,10 +5,8 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.vulkanmod.gl.GlFramebuffer; import net.vulkanmod.gl.GlTexture; -import net.vulkanmod.interfaces.ExtendedRenderTarget; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.framebuffer.Framebuffer; -import net.vulkanmod.vulkan.framebuffer.RenderPass; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.util.DrawUtil; import org.lwjgl.opengl.GL30; @@ -20,7 +18,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(RenderTarget.class) -public abstract class RenderTargetMixin implements ExtendedRenderTarget { +public abstract class RenderTargetMixin { @Shadow public int viewWidth; @Shadow public int viewHeight; @@ -142,16 +140,6 @@ private void injClear(CallbackInfoReturnable cir) { applyClear(); } - @Override - public boolean isBound() { - return bound; - } - - @Override - public RenderPass getRenderPass() { - return GlFramebuffer.getFramebuffer(this.frameBufferId).getRenderPass(); - } - @Unique private void applyClear() { if (this.needClear) { From 51fa204bea2994a270dba8f8123c02621a42bd73 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Wed, 13 Nov 2024 16:52:03 +0100 Subject: [PATCH 020/177] Fix profiler result missing entries --- .../net/vulkanmod/mixin/render/clouds/LevelRendererM.java | 2 ++ .../java/net/vulkanmod/render/profiling/Profiler.java | 8 ++++++-- .../net/vulkanmod/render/profiling/ProfilerOverlay.java | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index a3c0317516..0eb2f68d09 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -5,6 +5,7 @@ import net.minecraft.client.renderer.*; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; +import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.sky.CloudRenderer; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; @@ -30,6 +31,7 @@ public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f proje } this.cloudRenderer.renderClouds(this.level, poseStack, modelView, projection, this.ticks, partialTicks, camX, camY, camZ); + Profiler.getMainProfiler().pop(); ci.cancel(); } diff --git a/src/main/java/net/vulkanmod/render/profiling/Profiler.java b/src/main/java/net/vulkanmod/render/profiling/Profiler.java index a5a34318cd..ccfe5cb595 100644 --- a/src/main/java/net/vulkanmod/render/profiling/Profiler.java +++ b/src/main/java/net/vulkanmod/render/profiling/Profiler.java @@ -37,6 +37,7 @@ public static void setActive(boolean b) { ObjectArrayList nodeStack = new ObjectArrayList<>(); ObjectArrayList nodes = new ObjectArrayList<>(); + ObjectArrayList currentFrameNodes = new ObjectArrayList<>(); Object2ReferenceOpenHashMap nodeMap = new Object2ReferenceOpenHashMap<>(); Node mainNode; @@ -67,7 +68,7 @@ public void push(String s) { node.children.clear(); if (node.parent == selectedNode) - nodes.add(node); + currentFrameNodes.add(node); currentNode = node; @@ -118,7 +119,10 @@ public void start() { pushNodeStack(mainNode); - nodes.clear(); + var t = nodes; + nodes = currentFrameNodes; + currentFrameNodes = t; + currentFrameNodes.clear(); } public void end() { diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index 3a1a22b0db..b5f21bc7bd 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -137,7 +137,7 @@ private void updateResults() { return; Profiler.ProfilerResults results = Profiler.getMainProfiler().getProfilerResults(); - if (results == null) + if (results == null || results.partialResults.size() < 2) return; frametime = results.getResult().value; From aebc01d80bab23d80daf35f7bb4d09f92cd0ad0e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:13:02 +0100 Subject: [PATCH 021/177] Add clouds shader --- .../mixin/render/clouds/LevelRendererM.java | 5 +- .../net/vulkanmod/render/PipelineManager.java | 17 ++++- .../vulkanmod/render/sky/CloudRenderer.java | 70 +++++++++++-------- .../vulkanmod/shaders/basic/clouds/clouds.fsh | 20 ++++++ .../shaders/basic/clouds/clouds.json | 17 +++++ .../vulkanmod/shaders/basic/clouds/clouds.vsh | 20 ++++++ 6 files changed, 115 insertions(+), 34 deletions(-) create mode 100644 src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json create mode 100644 src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index 0eb2f68d09..a885536d1d 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -19,7 +19,6 @@ public abstract class LevelRendererM { @Shadow private int ticks; @Shadow private @Nullable ClientLevel level; - @Shadow @Final protected static ResourceLocation CLOUDS_LOCATION; @Unique private CloudRenderer cloudRenderer; @@ -27,7 +26,7 @@ public abstract class LevelRendererM { @Inject(method = "renderClouds", at = @At("HEAD"), cancellable = true) public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float partialTicks, double camX, double camY, double camZ, CallbackInfo ci) { if (this.cloudRenderer == null) { - this.cloudRenderer = new CloudRenderer(CLOUDS_LOCATION); + this.cloudRenderer = new CloudRenderer(); } this.cloudRenderer.renderClouds(this.level, poseStack, modelView, projection, this.ticks, partialTicks, camX, camY, camZ); @@ -45,7 +44,7 @@ private void onAllChanged(CallbackInfo ci) { @Inject(method = "onResourceManagerReload", at = @At("RETURN")) private void onReload(ResourceManager resourceManager, CallbackInfo ci) { if (this.cloudRenderer != null) { - this.cloudRenderer.loadTexture(CLOUDS_LOCATION); + this.cloudRenderer.loadTexture(); } } diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 4a3ad56d7e..710c32ec01 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -1,6 +1,7 @@ package net.vulkanmod.render; import com.google.gson.JsonObject; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.RenderType; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; @@ -19,7 +20,9 @@ public static void setTerrainVertexFormat(VertexFormat format) { terrainVertexFormat = format; } - static GraphicsPipeline terrainShaderEarlyZ, terrainShader, fastBlitPipeline; + static GraphicsPipeline + terrainShader, terrainShaderEarlyZ, + fastBlitPipeline, cloudsPipeline; private static Function shaderGetter; @@ -31,13 +34,15 @@ public static void init() { } public static void setDefaultShader() { - setShaderGetter(renderType -> renderType == TerrainRenderType.TRANSLUCENT ? terrainShaderEarlyZ : terrainShader); + setShaderGetter( + renderType -> renderType == TerrainRenderType.TRANSLUCENT ? terrainShaderEarlyZ : terrainShader); } private static void createBasicPipelines() { terrainShaderEarlyZ = createPipeline("terrain_earlyZ", terrainVertexFormat); terrainShader = createPipeline("terrain", terrainVertexFormat); fastBlitPipeline = createPipeline("blit", CustomVertexFormat.NONE); + cloudsPipeline = createPipeline("clouds", DefaultVertexFormat.POSITION_COLOR); } private static GraphicsPipeline createPipeline(String configName, VertexFormat vertexFormat) { @@ -67,7 +72,13 @@ public static GraphicsPipeline getTerrainIndirectShader(RenderType renderType) { return terrainShaderEarlyZ; } - public static GraphicsPipeline getFastBlitPipeline() { return fastBlitPipeline; } + public static GraphicsPipeline getFastBlitPipeline() { + return fastBlitPipeline; + } + + public static GraphicsPipeline getCloudsPipeline() { + return cloudsPipeline; + } public static void destroyPipelines() { terrainShaderEarlyZ.cleanUp(); diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index d430bc744c..4e6360bb09 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -7,13 +7,14 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.FogRenderer; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.Mth; import net.minecraft.world.phys.Vec3; +import net.vulkanmod.render.PipelineManager; +import net.vulkanmod.render.VBO; +import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.util.ColorUtil; import org.apache.commons.lang3.Validate; import org.joml.Matrix4f; @@ -21,7 +22,8 @@ import java.io.IOException; public class CloudRenderer { - // TODO move to util + private static final ResourceLocation TEXTURE_LOCATION = ResourceLocation.withDefaultNamespace("textures/environment/clouds.png"); + private static final int DIR_NEG_Y_BIT = 1 << 0; private static final int DIR_POS_Y_BIT = 1 << 1; private static final int DIR_NEG_X_BIT = 1 << 2; @@ -29,27 +31,31 @@ public class CloudRenderer { private static final int DIR_NEG_Z_BIT = 1 << 4; private static final int DIR_POS_Z_BIT = 1 << 5; + private static final byte Y_BELOW_CLOUDS = 0; + private static final byte Y_ABOVE_CLOUDS = 1; + private static final byte Y_INSIDE_CLOUDS = 2; + private static final int CELL_WIDTH = 12; private static final int CELL_HEIGHT = 4; private CloudGrid cloudGrid; private int prevCloudX; - private int prevCloudY; private int prevCloudZ; + private byte prevCloudY; private CloudStatus prevCloudsType; private boolean prevInsideClouds; private boolean generateClouds; - private VertexBuffer cloudBuffer; + private VBO cloudBuffer; - public CloudRenderer(ResourceLocation textureLocation) { - loadTexture(textureLocation); + public CloudRenderer() { + loadTexture(); } - public void loadTexture(ResourceLocation location) { - this.cloudGrid = createCloudGrid(location); + public void loadTexture() { + this.cloudGrid = createCloudGrid(TEXTURE_LOCATION); } public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { @@ -69,16 +75,25 @@ public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelV int centerCellX = (int) Math.floor(centerX / CELL_WIDTH); int centerCellZ = (int) Math.floor(centerZ / CELL_WIDTH); - boolean insideClouds = (centerY >= -4.0f && centerY <= 0.0f); + byte yState; + if (centerY < -4.0f) { + yState = Y_BELOW_CLOUDS; + } + else if (centerY > 0.0f) { + yState = Y_ABOVE_CLOUDS; + } + else { + yState = Y_INSIDE_CLOUDS; + } if (centerCellX != this.prevCloudX || centerCellZ != this.prevCloudZ || (minecraft.options.getCloudsType() != this.prevCloudsType) - || (this.prevInsideClouds != insideClouds) + || (this.prevCloudY != yState) || this.cloudBuffer == null) { this.prevCloudX = centerCellX; this.prevCloudZ = centerCellZ; this.prevCloudsType = minecraft.options.getCloudsType(); - this.prevInsideClouds = insideClouds; + this.prevCloudY = yState; this.generateClouds = true; } @@ -88,34 +103,33 @@ public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelV this.cloudBuffer.close(); } - this.cloudBuffer = new VertexBuffer(VertexBuffer.Usage.STATIC); - this.cloudBuffer.bind(); + this.cloudBuffer = new VBO(VertexBuffer.Usage.STATIC); MeshData cloudsMesh = this.buildClouds(Tesselator.getInstance(), centerCellX, centerCellZ, centerY); this.cloudBuffer.upload(cloudsMesh); - VertexBuffer.unbind(); } FogRenderer.levelFogColor(); - float xTranslation = (float)(centerX - (centerCellX * CELL_WIDTH)); - float yTranslation = (float) centerY; - float zTranslation = (float)(centerZ - (centerCellZ * CELL_WIDTH)); + float xTranslation = (float) (centerX - (centerCellX * CELL_WIDTH)); + float yTranslation = (float) (centerY); + float zTranslation = (float) (centerZ - (centerCellZ * CELL_WIDTH)); poseStack.pushPose(); poseStack.mulPose(modelView); poseStack.translate(-xTranslation, yTranslation, -zTranslation); + VRenderSystem.setModelOffset(-xTranslation, 0, -zTranslation); + Vec3 cloudColor = level.getCloudColor(partialTicks); RenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); - this.cloudBuffer.bind(); - - ShaderInstance shaderInstance = GameRenderer.getPositionColorShader(); + GraphicsPipeline pipeline = PipelineManager.getCloudsPipeline(); RenderSystem.enableBlend(); RenderSystem.enableDepthTest(); boolean fastClouds = this.prevCloudsType == CloudStatus.FAST; + boolean insideClouds = yState == Y_INSIDE_CLOUDS; boolean disableCull = insideClouds || (fastClouds && centerY <= 0.0f); if (disableCull) { @@ -124,17 +138,16 @@ public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelV if (!fastClouds) { RenderSystem.colorMask(false, false, false, false); - this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, shaderInstance); + this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); RenderSystem.colorMask(true, true, true, true); } - this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, shaderInstance); + this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); RenderSystem.enableCull(); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - - VertexBuffer.unbind(); + VRenderSystem.setModelOffset(0.0f, 0.0f, 0.0f); poseStack.popPose(); } @@ -155,7 +168,7 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - int renderDistance = 32; + int renderDistance = 45; boolean insideClouds = this.prevInsideClouds; if (this.prevCloudsType == CloudStatus.FANCY) { @@ -212,7 +225,8 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC } } - } else { + } + else { for (int cellX = -renderDistance; cellX < renderDistance; ++cellX) { for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh new file mode 100644 index 0000000000..738d242d16 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh @@ -0,0 +1,20 @@ +#version 450 + +layout(binding = 1) uniform UBO{ + vec4 ColorModulator; + vec4 FogColor; + float FogStart; + float FogEnd; +}; + +layout(location = 0) in vec4 vertexColor; +layout(location = 1) in float vertexDistance; + +layout(location = 0) out vec4 fragColor; + +void main() { + vec4 color = vertexColor * ColorModulator; + + float alpha = smoothstep(FogEnd, FogStart, vertexDistance); + fragColor = vec4(color.rgb, color.a * alpha); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json new file mode 100644 index 0000000000..ccfee165ad --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json @@ -0,0 +1,17 @@ +{ + "vertex": "clouds", + "fragment": "clouds", + "samplers": [], + "UBOs": [ + { "type": "vertex", "binding": 0, "fields": [ + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } + ] }, + { "type": "fragment", "binding": 1, "fields": [ + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + ] } + ] +} diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh new file mode 100644 index 0000000000..203842a4ec --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh @@ -0,0 +1,20 @@ +#version 450 + +layout(binding = 0) uniform UniformBufferObject { + mat4 MVP; + vec3 ModelOffset; +}; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec4 Color; + +layout(location = 0) out vec4 vertexColor; +layout(location = 1) out float vertexDistance; + +void main() { + gl_Position = MVP * vec4(Position, 1.0); + vec3 viewPos = Position + ModelOffset; + vertexDistance = length(viewPos.xyz); + + vertexColor = Color; +} From 39a53cc6f168bd5e4018c9f3c41b264aa6e93b14 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:15:21 +0100 Subject: [PATCH 022/177] Refactor terrain shader's uniform name --- .../net/vulkanmod/vulkan/VRenderSystem.java | 18 +++++++-------- .../net/vulkanmod/vulkan/shader/Pipeline.java | 22 +++++++++++++------ .../vulkanmod/vulkan/shader/SPIRVUtils.java | 2 +- .../net/vulkanmod/vulkan/shader/Uniforms.java | 3 +-- .../shaders/basic/terrain/terrain.fsh | 6 ++--- .../shaders/basic/terrain/terrain.json | 2 +- .../shaders/basic/terrain/terrain.vsh | 10 ++++----- .../basic/terrain_earlyZ/terrain_earlyZ.fsh | 6 ++--- .../basic/terrain_earlyZ/terrain_earlyZ.json | 2 +- 9 files changed, 38 insertions(+), 33 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index 08bd5bdc62..7f647f9d59 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -3,7 +3,6 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.shader.PipelineState; @@ -46,7 +45,7 @@ public abstract class VRenderSystem { public static MappedBuffer TextureMatrix = new MappedBuffer(16 * 4); public static MappedBuffer MVP = new MappedBuffer(16 * 4); - public static MappedBuffer ChunkOffset = new MappedBuffer(3 * 4); + public static MappedBuffer modelOffset = new MappedBuffer(3 * 4); public static MappedBuffer lightDirection0 = new MappedBuffer(3 * 4); public static MappedBuffer lightDirection1 = new MappedBuffer(3 * 4); @@ -79,8 +78,8 @@ public static void setWindow(long window) { VRenderSystem.window = window; } - public static ByteBuffer getChunkOffset() { - return ChunkOffset.buffer; + public static ByteBuffer getModelOffset() { + return modelOffset.buffer; } public static int maxSupportedTextureSize() { @@ -95,7 +94,6 @@ public static void applyMVP(Matrix4f MV, Matrix4f P) { public static void applyModelViewMatrix(Matrix4f mat) { mat.get(modelViewMatrix.buffer.asFloatBuffer()); - //MemoryUtil.memPutFloat(MemoryUtil.memAddress(modelViewMatrix), 1); } public static void applyProjectionMatrix(Matrix4f mat) { @@ -129,11 +127,11 @@ public static MappedBuffer getMVP() { return MVP; } - public static void setChunkOffset(float f1, float f2, float f3) { - long ptr = ChunkOffset.ptr; - VUtil.UNSAFE.putFloat(ptr, f1); - VUtil.UNSAFE.putFloat(ptr + 4, f2); - VUtil.UNSAFE.putFloat(ptr + 8, f3); + public static void setModelOffset(float x, float y, float z) { + long ptr = modelOffset.ptr; + VUtil.UNSAFE.putFloat(ptr, x); + VUtil.UNSAFE.putFloat(ptr + 4, y); + VUtil.UNSAFE.putFloat(ptr + 8, z); } public static void setShaderColor(float f1, float f2, float f3, float f4) { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 0045fc3f7b..10208d948e 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -595,13 +595,18 @@ private void parseUboNode(JsonElement jsonelement) { uniformInfo.setupSupplier(); if (!uniformInfo.hasSupplier()) { - var uniformSupplier = this.uniformSupplierGetter.apply(uniformInfo); + if (this.uniformSupplierGetter != null) { + var uniformSupplier = this.uniformSupplierGetter.apply(uniformInfo); - if (uniformSupplier == null) { + if (uniformSupplier == null) { + throw new IllegalStateException("No uniform supplier found for uniform: (%s:%s)".formatted(type2, name)); + } + + uniformInfo.setBufferSupplier(uniformSupplier); + } + else { throw new IllegalStateException("No uniform supplier found for uniform: (%s:%s)".formatted(type2, name)); } - - uniformInfo.setBufferSupplier(this.uniformSupplierGetter.apply(uniformInfo)); } builder.addUniformInfo(uniformInfo); @@ -640,13 +645,16 @@ private void parsePushConstantNode(JsonArray jsonArray) { AlignedStruct.Builder builder = new AlignedStruct.Builder(); for (JsonElement jsonelement : jsonArray) { - JsonObject jsonobject2 = GsonHelper.convertToJsonObject(jsonelement, "PC"); + JsonObject jsonobject2 = GsonHelper.convertToJsonObject(jsonelement, "PushConstants"); String name = GsonHelper.getAsString(jsonobject2, "name"); String type2 = GsonHelper.getAsString(jsonobject2, "type"); - int j = GsonHelper.getAsInt(jsonobject2, "count"); + int count = GsonHelper.getAsInt(jsonobject2, "count"); - builder.addUniformInfo(type2, name, j); + Uniform.Info uniformInfo = Uniform.createUniformInfo(type2, name, count); + uniformInfo.setupSupplier(); + + builder.addUniformInfo(uniformInfo); } this.pushConstants = builder.buildPushConstant(); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index 5de582389f..05c95e547c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -22,7 +22,7 @@ import static org.lwjgl.util.shaderc.Shaderc.*; public class SPIRVUtils { - private static final boolean DEBUG = true; + private static final boolean DEBUG = false; private static final boolean OPTIMIZATIONS = true; private static long compiler; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java index 3098e0a7c2..7ca193a650 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java @@ -3,7 +3,6 @@ import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.util.MappedBuffer; import java.util.function.Supplier; @@ -45,7 +44,7 @@ public static void setupDefaultUniforms() { //Vec3 vec3f_uniformMap.put("Light0_Direction", () -> VRenderSystem.lightDirection0); vec3f_uniformMap.put("Light1_Direction", () -> VRenderSystem.lightDirection1); - vec3f_uniformMap.put("ChunkOffset", () -> VRenderSystem.ChunkOffset); + vec3f_uniformMap.put("ModelOffset", () -> VRenderSystem.modelOffset); //Vec4 vec4f_uniformMap.put("ColorModulator", VRenderSystem::getShaderColor); diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh index 84146fa240..9da3f09ffd 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh @@ -12,9 +12,9 @@ layout(binding = 1) uniform UBO { float AlphaCutout; }; -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; +layout(location = 0) in vec4 vertexColor; +layout(location = 1) in vec2 texCoord0; +layout(location = 2) in float vertexDistance; layout(location = 0) out vec4 fragColor; diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json index 2233161b78..b527c51692 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json @@ -17,6 +17,6 @@ ] } ], "PushConstants": [ - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } + { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh index e3493d561d..ea99bd0f14 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh @@ -8,15 +8,15 @@ layout (binding = 0) uniform UniformBufferObject { }; layout (push_constant) uniform pushConstant { - vec3 ChunkOffset; + vec3 ModelOffset; }; layout (binding = 3) uniform sampler2D Sampler2; -layout (location = 0) out float vertexDistance; -layout (location = 1) out vec4 vertexColor; -layout (location = 2) out vec2 texCoord0; +layout (location = 0) out vec4 vertexColor; +layout (location = 1) out vec2 texCoord0; +layout (location = 2) out float vertexDistance; #define COMPRESSED_VERTEX @@ -40,7 +40,7 @@ vec4 getVertexPosition() { const vec3 baseOffset = bitfieldExtract(ivec3(gl_InstanceIndex) >> ivec3(0, 16, 8), 0, 8); #ifdef COMPRESSED_VERTEX - return vec4(fma(Position.xyz, POSITION_INV, ChunkOffset + baseOffset), 1.0); + return vec4(fma(Position.xyz, POSITION_INV, ModelOffset + baseOffset), 1.0); #else return vec4(Position.xyz + baseOffset, 1.0); #endif diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh index 5386a55329..6ee8d3e746 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh @@ -13,9 +13,9 @@ layout(binding = 1) uniform UBO { float FogEnd; }; -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; +layout(location = 0) in vec4 vertexColor; +layout(location = 1) in vec2 texCoord0; +layout(location = 2) in float vertexDistance; layout(location = 0) out vec4 fragColor; diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json index 9c00f2e058..13062973c5 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json @@ -17,6 +17,6 @@ ] } ], "PushConstants": [ - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } + { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] } From 31ef3de1ec2ef3f833ff331835de195973d13402 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:20:49 +0100 Subject: [PATCH 023/177] Minimize upload and layout transition command buffers used per frame - Refactor CommandPool class --- .../mixin/render/MinecraftMixin.java | 27 +-- .../mixin/texture/update/GameRendererM.java | 27 +++ .../mixin/texture/update/MLightTexture.java | 210 ++++++++++++++++++ .../texture/{ => update}/MSpriteContents.java | 12 +- .../texture/{ => update}/MTextureManager.java | 13 +- .../render/texture/ImageUploadHelper.java | 41 ++++ ...{SpriteUtil.java => SpriteUpdateUtil.java} | 16 +- .../java/net/vulkanmod/vulkan/Renderer.java | 50 ++--- .../vulkanmod/vulkan/memory/MemoryTypes.java | 7 +- .../vulkanmod/vulkan/queue/CommandPool.java | 139 +++++++----- .../net/vulkanmod/vulkan/queue/Queue.java | 16 +- .../vulkanmod/vulkan/texture/ImageUtil.java | 100 ++++----- .../vulkanmod/vulkan/texture/VulkanImage.java | 36 +-- src/main/resources/vulkanmod.mixins.json | 6 +- 14 files changed, 494 insertions(+), 206 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java create mode 100644 src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java rename src/main/java/net/vulkanmod/mixin/texture/{ => update}/MSpriteContents.java (70%) rename src/main/java/net/vulkanmod/mixin/texture/{ => update}/MTextureManager.java (61%) create mode 100644 src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java rename src/main/java/net/vulkanmod/render/texture/{SpriteUtil.java => SpriteUpdateUtil.java} (62%) diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 85c22cfeff..5cbb3d1509 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -3,13 +3,12 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.TimerQuery; -import net.minecraft.Util; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; import net.minecraft.client.main.GameConfig; import net.vulkanmod.Initializer; -import net.vulkanmod.render.texture.SpriteUtil; +import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; import org.objectweb.asm.Opcodes; @@ -35,18 +34,18 @@ public class MinecraftMixin { private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { var graphicsModeOption = this.options.graphicsMode(); - if(graphicsModeOption.get() == GraphicsStatus.FABULOUS) { + if (graphicsModeOption.get() == GraphicsStatus.FABULOUS) { Initializer.LOGGER.error("Fabulous graphics mode not supported, forcing Fancy"); graphicsModeOption.set(GraphicsStatus.FANCY); } } @Inject(method = "runTick", at = @At(value = "HEAD")) - private void resetBuffers(boolean bl, CallbackInfo ci) { + private void preFrameOps(boolean bl, CallbackInfo ci) { Renderer.getInstance().preInitFrame(); } - //Main target (framebuffer) ops + // Main target (framebuffer) ops @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V")) private void beginRender(int i, boolean bl) { RenderSystem.clear(i, bl); @@ -79,7 +78,8 @@ private void removeThreadYield() { @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) private void limitWhenMinimized(CallbackInfoReturnable cir) { - if(this.noRender) cir.setReturnValue(10); + if (this.noRender) + cir.setReturnValue(10); } @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) @@ -88,10 +88,11 @@ private Optional removeTimer() { } @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;tick()V"), - locals = LocalCapture.CAPTURE_FAILHARD) + locals = LocalCapture.CAPTURE_FAILHARD) private void redirectResourceTick(boolean bl, CallbackInfo ci, Runnable runnable, int i, int j) { int n = Math.min(10, i) - 1; - SpriteUtil.setDoUpload(j == n); + boolean doUpload = j == n; + SpriteUpdateUtil.setDoUpload(doUpload); } @Inject(method = "close", at = @At(value = "HEAD")) @@ -103,12 +104,6 @@ public void close(CallbackInfo ci) { @Inject(method = "close", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/VirtualScreen;close()V")) public void close2(CallbackInfo ci) { Vulkan.cleanUp(); - Util.shutdownExecutors(); - } - - @Redirect(method = "run", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;emergencySave()V")) - private void skipEmergencySave(Minecraft instance) { - } @Inject(method = "resizeDisplay", at = @At("HEAD")) @@ -116,8 +111,8 @@ public void onResolutionChanged(CallbackInfo ci) { Renderer.scheduleSwapChainUpdate(); } - //Fixes crash when minimizing window before setScreen is called + // Fixes crash when minimizing window before setScreen is called @Redirect(method = "setScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;noRender:Z", opcode = Opcodes.PUTFIELD)) - private void keepVar(Minecraft instance, boolean value) { } + private void keepVar(Minecraft instance, boolean value) {} } diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java b/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java new file mode 100644 index 0000000000..bb0ce2b696 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java @@ -0,0 +1,27 @@ +package net.vulkanmod.mixin.texture.update; + +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.vulkanmod.render.texture.ImageUploadHelper; +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; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(GameRenderer.class) +public abstract class GameRendererM { + + @Shadow + @Final + Minecraft minecraft; + + @Inject(method = "render", at = @At("HEAD")) + private void onRender(DeltaTracker deltaTracker, boolean bl, CallbackInfo ci) { + if (this.minecraft.noRender || !(bl && this.minecraft.level != null && this.minecraft.isGameLoadFinished())) { + ImageUploadHelper.INSTANCE.submitCommands(); + } + } +} diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java new file mode 100644 index 0000000000..81e47a432e --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java @@ -0,0 +1,210 @@ +package net.vulkanmod.mixin.texture.update; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.util.Mth; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.LivingEntity; +import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.mixin.texture.image.NativeImageAccessor; +import net.vulkanmod.render.texture.ImageUploadHelper; +import net.vulkanmod.vulkan.queue.CommandPool; +import org.joml.Vector3f; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LightTexture.class) +public class MLightTexture { + @Shadow @Final private Minecraft minecraft; + @Shadow @Final private GameRenderer renderer; + + @Shadow private boolean updateLightTexture; + @Shadow private float blockLightRedFlicker; + + @Shadow @Final private DynamicTexture lightTexture; + @Shadow @Final private NativeImage lightPixels; + + + private Vector3f[] tempVecs; + + @Inject(method = "", at = @At("RETURN")) + private void onInit(GameRenderer gameRenderer, Minecraft minecraft, CallbackInfo ci) { + this.tempVecs = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; + } + + /** + * @author + * @reason + */ + @Overwrite + public void turnOnLightLayer() { + RenderSystem.setShaderTexture(2, this.lightTexture.getId()); + } + + /** + * @author + * @reason + */ + @SuppressWarnings("UnreachableCode") + @Overwrite + public void updateLightTexture(float partialTicks) { + if (this.updateLightTexture) { + this.updateLightTexture = false; + + this.minecraft.getProfiler().push("lightTex"); + + ClientLevel clientLevel = this.minecraft.level; + if (clientLevel != null) { + float skyDarken = clientLevel.getSkyDarken(1.0F); + float skyFlashTime; + if (clientLevel.getSkyFlashTime() > 0) { + skyFlashTime = 1.0F; + } else { + skyFlashTime = skyDarken * 0.95F + 0.05F; + } + + float darknessEffectScale = this.minecraft.options.darknessEffectScale().get().floatValue(); + float darknessGamma = this.getDarknessGamma(partialTicks) * darknessEffectScale; + float darknessScale = this.calculateDarknessScale(this.minecraft.player, darknessGamma, partialTicks) * darknessEffectScale; + float waterVision = this.minecraft.player.getWaterVision(); + float nightVisionFactor; + if (this.minecraft.player.hasEffect(MobEffects.NIGHT_VISION)) { + nightVisionFactor = GameRenderer.getNightVisionScale(this.minecraft.player, partialTicks); + } else if (waterVision > 0.0F && this.minecraft.player.hasEffect(MobEffects.CONDUIT_POWER)) { + nightVisionFactor = waterVision; + } else { + nightVisionFactor = 0.0F; + } + +// Vector3f skyLightColor = new Vector3f(skyDarken, skyDarken, 1.0F).lerp(new Vector3f(1.0F, 1.0F, 1.0F), 0.35F); + skyDarken = lerp(skyDarken, 1.0f, 0.35f); + Vector3f skyLightColor = this.tempVecs[0].set(skyDarken, skyDarken, 1.0F); + float redFlicker = this.blockLightRedFlicker + 1.5F; + Vector3f lightColor = this.tempVecs[1]; + + float gamma = this.minecraft.options.gamma().get().floatValue(); + float darkenWorldAmount = this.renderer.getDarkenWorldAmount(partialTicks); + boolean forceBrightLightmap = clientLevel.effects().forceBrightLightmap(); + float ambientLight = clientLevel.dimensionType().ambientLight(); + + long ptr = ((NativeImageAccessor)(Object)this.lightPixels).getPixels(); + int width = this.lightPixels.getWidth(); + + Vector3f tVec3f = this.tempVecs[2]; + + for(int y = 0; y < 16; ++y) { + float brY = getBrightness(ambientLight, y) * skyFlashTime; + + for(int x = 0; x < 16; ++x) { + float brX = getBrightness(ambientLight, x) * redFlicker; + float t = brX * ((brX * 0.6F + 0.4F) * 0.6F + 0.4F); + float u = brX * (brX * brX * 0.6F + 0.4F); + lightColor.set(brX, t, u); + + if (forceBrightLightmap) { + lightColor.lerp(tVec3f.set(0.99F, 1.12F, 1.0F), 0.25F); + clampColor(lightColor); + } else { + tVec3f.set(skyLightColor).mul(brY); + lightColor.add(tVec3f); + + tVec3f.set(0.75F, 0.75F, 0.75F); + lightColor.lerp(tVec3f, 0.04F); + + if (darkenWorldAmount > 0.0F) { + tVec3f.set(lightColor).mul(0.7F, 0.6F, 0.6F); + lightColor.lerp(tVec3f, darkenWorldAmount); + } + } + + if (nightVisionFactor > 0.0F) { + // scale up uniformly until 1.0 is hit by one of the colors + float maxComponent = Math.max(lightColor.x(), Math.max(lightColor.y(), lightColor.z())); + if (maxComponent < 1.0F) { + float brightColor = 1.0F / maxComponent; + tVec3f.set(lightColor).mul(brightColor); + lightColor.lerp(tVec3f, nightVisionFactor); + } + } + + if (!forceBrightLightmap) { + lightColor.add(-darknessScale, -darknessScale, -darknessScale); + clampColor(lightColor); + } + + tVec3f.set(this.notGamma(lightColor.x), this.notGamma(lightColor.y), this.notGamma(lightColor.z)); + lightColor.lerp(tVec3f, Math.max(0.0F, gamma - darknessGamma)); + + lightColor.lerp(tVec3f.set(0.75F, 0.75F, 0.75F), 0.04F); + clampColor(lightColor); + + lightColor.mul(255.0F); + int r = (int)lightColor.x(); + int g = (int)lightColor.y(); + int b = (int)lightColor.z(); + + MemoryUtil.memPutInt(ptr + (((long) y * width + x) * 4L), 0xFF000000 | b << 16 | g << 8 | r); + } + } + + CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); + this.lightTexture.upload(); + + try (MemoryStack stack = MemoryStack.stackPush()) { + GlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); + } + + ImageUploadHelper.INSTANCE.submitCommands(); + + this.minecraft.getProfiler().pop(); + } + } + } + + @Unique + private float getDarknessGamma(float f) { + MobEffectInstance mobEffectInstance = this.minecraft.player.getEffect(MobEffects.DARKNESS); + return mobEffectInstance != null ? mobEffectInstance.getBlendFactor(this.minecraft.player, f) : 0.0F; + } + + @Unique + private float calculateDarknessScale(LivingEntity livingEntity, float f, float g) { + float h = 0.45F * f; + return Math.max(0.0F, Mth.cos(((float)livingEntity.tickCount - g) * (float) Math.PI * 0.025F) * h); + } + + @Unique + private static float lerp(float a, float x, float t) { + return (x - a) * t + a; + } + + @Unique + private static void clampColor(Vector3f vector3f) { + vector3f.set(Mth.clamp(vector3f.x, 0.0F, 1.0F), Mth.clamp(vector3f.y, 0.0F, 1.0F), Mth.clamp(vector3f.z, 0.0F, 1.0F)); + } + + @Unique + private float notGamma(float f) { + float g = 1.0F - f; + g = g * g; + return 1.0F - g * g; + } + + @Unique + private static float getBrightness(float ambientLight, int i) { + float f = (float)i / 15.0F; + float g = f / (4.0F - 3.0F * f); + return Mth.lerp(ambientLight, g, 1.0F); + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/texture/MSpriteContents.java b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java similarity index 70% rename from src/main/java/net/vulkanmod/mixin/texture/MSpriteContents.java rename to src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java index 8148c95f6c..8313ca9245 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MSpriteContents.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java @@ -1,8 +1,8 @@ -package net.vulkanmod.mixin.texture; +package net.vulkanmod.mixin.texture.update; import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.client.renderer.texture.SpriteContents; -import net.vulkanmod.render.texture.SpriteUtil; +import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -14,9 +14,11 @@ public class MSpriteContents { @Inject(method = "upload", at = @At("HEAD"), cancellable = true) private void checkUpload(int i, int j, int k, int l, NativeImage[] nativeImages, CallbackInfo ci) { - if(!SpriteUtil.shouldUpload()) + if (!SpriteUpdateUtil.shouldUpload()) { ci.cancel(); - - SpriteUtil.addTransitionedLayout(VTextureSelector.getBoundTexture(0)); + } + else { + SpriteUpdateUtil.addTransitionedLayout(VTextureSelector.getBoundTexture(0)); + } } } diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java similarity index 61% rename from src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java rename to src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java index f0baa1c9ea..551f797eea 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java @@ -1,10 +1,9 @@ -package net.vulkanmod.mixin.texture; +package net.vulkanmod.mixin.texture.update; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.Tickable; -import net.vulkanmod.render.texture.SpriteUtil; +import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.device.DeviceManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -26,14 +25,10 @@ public void tick() { return; //Debug D - if (SpriteUtil.shouldUpload()) - DeviceManager.getGraphicsQueue().startRecording(); for (Tickable tickable : this.tickableTextures) { tickable.tick(); } - if (SpriteUtil.shouldUpload()) { - SpriteUtil.transitionLayouts(DeviceManager.getGraphicsQueue().getCommandBuffer().getHandle()); - DeviceManager.getGraphicsQueue().endRecordingAndSubmit(); - } + + SpriteUpdateUtil.transitionLayouts(); } } diff --git a/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java new file mode 100644 index 0000000000..9e5f80493f --- /dev/null +++ b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java @@ -0,0 +1,41 @@ +package net.vulkanmod.render.texture; + +import net.vulkanmod.vulkan.Synchronization; +import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.queue.CommandPool; +import net.vulkanmod.vulkan.queue.Queue; + +public class ImageUploadHelper { + + public static final ImageUploadHelper INSTANCE = new ImageUploadHelper(); + + final Queue queue; + private CommandPool.CommandBuffer currentCmdBuffer; + + public ImageUploadHelper() { + queue = DeviceManager.getGraphicsQueue(); + } + + public void submitCommands() { + if (this.currentCmdBuffer == null) { + return; + } + + long fence = queue.submitCommands(this.currentCmdBuffer); + Synchronization.INSTANCE.addCommandBuffer(this.currentCmdBuffer); + + this.currentCmdBuffer = null; + } + + public CommandPool.CommandBuffer getOrStartCommandBuffer() { + if (this.currentCmdBuffer == null) { + this.currentCmdBuffer = this.queue.beginCommands(); + } + + return this.currentCmdBuffer; + } + + public CommandPool.CommandBuffer getCommandBuffer() { + return this.currentCmdBuffer; + } +} diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java similarity index 62% rename from src/main/java/net/vulkanmod/render/texture/SpriteUtil.java rename to src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index 6b5df13ff2..a749582880 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -7,11 +7,10 @@ import java.util.HashSet; import java.util.Set; -public abstract class SpriteUtil { +public abstract class SpriteUpdateUtil { private static boolean doUpload = false; - - private static Set transitionedLayouts = new HashSet<>(); + private static final Set transitionedLayouts = new HashSet<>(); public static void setDoUpload(boolean b) { doUpload = b; @@ -25,10 +24,15 @@ public static void addTransitionedLayout(VulkanImage image) { transitionedLayouts.add(image); } - public static void transitionLayouts(VkCommandBuffer commandBuffer) { - try(MemoryStack stack = MemoryStack.stackPush()) { - transitionedLayouts.forEach(image -> image.readOnlyLayout(stack, commandBuffer)); + public static void transitionLayouts() { + if (!doUpload || transitionedLayouts.isEmpty()) { + return; + } + VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getCommandBuffer().handle; + + try (MemoryStack stack = MemoryStack.stackPush()) { + transitionedLayouts.forEach(image -> image.readOnlyLayout(stack, commandBuffer)); transitionedLayouts.clear(); } } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index d068313749..d09618c725 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -10,6 +10,7 @@ import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.buffer.UploadManager; import net.vulkanmod.render.profiling.Profiler; +import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; @@ -191,6 +192,25 @@ private void createSyncObjects() { } } + public void preInitFrame() { + Profiler p = Profiler.getMainProfiler(); + p.pop(); + p.round(); + p.push("Frame_ops"); + + // runTick might be called recursively, + // this check forces sync to avoid upload corruption + if (lastReset == currentFrame) { + Synchronization.INSTANCE.waitFences(); + } + lastReset = currentFrame; + + drawer.resetBuffers(currentFrame); + + WorldRenderer.getInstance().uploadSections(); + UploadManager.INSTANCE.submitUploads(); + } + public void beginFrame() { Profiler p = Profiler.getMainProfiler(); p.pop(); @@ -278,6 +298,11 @@ public void endFrame() { mainPass.end(currentCmdBuffer); + // Make sure there are no uploads/transitions scheduled + ImageUploadHelper.INSTANCE.submitCommands(); + Synchronization.INSTANCE.waitFences(); + Vulkan.getStagingBuffer().reset(); + submitFrame(); recordingCmds = false; @@ -298,15 +323,11 @@ private void submitFrame() { submitInfo.waitSemaphoreCount(1); submitInfo.pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))); submitInfo.pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)); - submitInfo.pSignalSemaphores(stack.longs(renderFinishedSemaphores.get(currentFrame))); - submitInfo.pCommandBuffers(stack.pointers(currentCmdBuffer)); vkResetFences(device, inFlightFences.get(currentFrame)); - Synchronization.INSTANCE.waitFences(); - if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult))); @@ -403,27 +424,6 @@ public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) { return true; } - public void preInitFrame() { - Profiler p = Profiler.getMainProfiler(); - p.pop(); - p.round(); - p.push("Frame_ops"); - - // runTick might be called recursively, - // this check forces sync to avoid upload corruption - if (lastReset == currentFrame) { - Synchronization.INSTANCE.waitFences(); - } - lastReset = currentFrame; - - drawer.resetBuffers(currentFrame); - - Vulkan.getStagingBuffer().reset(); - - WorldRenderer.getInstance().uploadSections(); - UploadManager.INSTANCE.submitUploads(); - } - public void addUsedPipeline(Pipeline pipeline) { usedPipelines.add(pipeline); } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 300a813b51..c8fa7f475e 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -19,14 +19,13 @@ public static void createMemoryTypes() { for (int i = 0; i < DeviceManager.memoryProperties.memoryTypeCount(); ++i) { VkMemoryType memoryType = DeviceManager.memoryProperties.memoryTypes(i); VkMemoryHeap heap = DeviceManager.memoryProperties.memoryHeaps(memoryType.heapIndex()); + int propertyFlags = memoryType.propertyFlags(); - //GPU only Memory - if (memoryType.propertyFlags() == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + if (propertyFlags == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { GPU_MEM = new DeviceLocalMemory(memoryType, heap); - } - if (memoryType.propertyFlags() == (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT)) { + if (propertyFlags == (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { HOST_MEM = new HostLocalCachedMemory(memoryType, heap); } } diff --git a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java index eff323b7f2..0558a012fd 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java @@ -23,13 +23,12 @@ public class CommandPool { this.createCommandPool(queueFamilyIndex); } - public void createCommandPool(int familyIndex) { - + public void createCommandPool(int queueFamily) { try (MemoryStack stack = stackPush()) { VkCommandPoolCreateInfo poolInfo = VkCommandPoolCreateInfo.calloc(stack); poolInfo.sType(VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO); - poolInfo.queueFamilyIndex(familyIndex); + poolInfo.queueFamilyIndex(queueFamily); poolInfo.flags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); LongBuffer pCommandPool = stack.mallocLong(1); @@ -42,68 +41,45 @@ public void createCommandPool(int familyIndex) { } } - public CommandBuffer beginCommands() { - - try (MemoryStack stack = stackPush()) { - final int size = 10; - - if (availableCmdBuffers.isEmpty()) { - - VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); - allocInfo.sType$Default(); - allocInfo.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY); - allocInfo.commandPool(id); - allocInfo.commandBufferCount(size); - - PointerBuffer pCommandBuffer = stack.mallocPointer(size); - vkAllocateCommandBuffers(Vulkan.getVkDevice(), allocInfo, pCommandBuffer); - - VkFenceCreateInfo fenceInfo = VkFenceCreateInfo.calloc(stack); - fenceInfo.sType$Default(); - fenceInfo.flags(VK_FENCE_CREATE_SIGNALED_BIT); - - for (int i = 0; i < size; ++i) { - LongBuffer pFence = stack.mallocLong(size); - vkCreateFence(Vulkan.getVkDevice(), fenceInfo, null, pFence); - - CommandBuffer commandBuffer = new CommandBuffer(new VkCommandBuffer(pCommandBuffer.get(i), Vulkan.getVkDevice()), pFence.get(0)); - commandBuffer.handle = new VkCommandBuffer(pCommandBuffer.get(i), Vulkan.getVkDevice()); - commandBuffers.add(commandBuffer); - availableCmdBuffers.add(commandBuffer); - } - - } - - CommandBuffer commandBuffer = availableCmdBuffers.poll(); - - VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack); - beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); - beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - - vkBeginCommandBuffer(commandBuffer.handle, beginInfo); - -// current++; - - return commandBuffer; + public CommandBuffer getCommandBuffer(MemoryStack stack) { + if (availableCmdBuffers.isEmpty()) { + allocateCommandBuffers(stack); } + + CommandBuffer commandBuffer = availableCmdBuffers.poll(); + return commandBuffer; } - public long submitCommands(CommandBuffer commandBuffer, VkQueue queue) { + private void allocateCommandBuffers(MemoryStack stack) { + final int size = 10; - try (MemoryStack stack = stackPush()) { - long fence = commandBuffer.fence; + VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); + allocInfo.sType$Default(); + allocInfo.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY); + allocInfo.commandPool(id); + allocInfo.commandBufferCount(size); - vkEndCommandBuffer(commandBuffer.handle); + PointerBuffer pCommandBuffer = stack.mallocPointer(size); + vkAllocateCommandBuffers(Vulkan.getVkDevice(), allocInfo, pCommandBuffer); - vkResetFences(Vulkan.getVkDevice(), commandBuffer.fence); + VkFenceCreateInfo fenceInfo = VkFenceCreateInfo.calloc(stack); + fenceInfo.sType$Default(); + fenceInfo.flags(VK_FENCE_CREATE_SIGNALED_BIT); - VkSubmitInfo submitInfo = VkSubmitInfo.calloc(stack); - submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO); - submitInfo.pCommandBuffers(stack.pointers(commandBuffer.handle)); + VkSemaphoreCreateInfo semaphoreCreateInfo = VkSemaphoreCreateInfo.calloc(stack); + semaphoreCreateInfo.sType$Default(); - vkQueueSubmit(queue, submitInfo, fence); + for (int i = 0; i < size; ++i) { + LongBuffer pFence = stack.mallocLong(1); + vkCreateFence(Vulkan.getVkDevice(), fenceInfo, null, pFence); - return fence; + LongBuffer pSemaphore = stack.mallocLong(1); + vkCreateSemaphore(Vulkan.getVkDevice(), semaphoreCreateInfo, null, pSemaphore); + + VkCommandBuffer vkCommandBuffer = new VkCommandBuffer(pCommandBuffer.get(i), Vulkan.getVkDevice()); + CommandBuffer commandBuffer = new CommandBuffer(this, vkCommandBuffer, pFence.get(0), pSemaphore.get(0)); + commandBuffers.add(commandBuffer); + availableCmdBuffers.add(commandBuffer); } } @@ -119,15 +95,24 @@ public void cleanUp() { vkDestroyCommandPool(Vulkan.getVkDevice(), id, null); } - public class CommandBuffer { - VkCommandBuffer handle; - long fence; + public long getId() { + return id; + } + + public static class CommandBuffer { + public final CommandPool commandPool; + public final VkCommandBuffer handle; + public final long fence; + public final long semaphore; + boolean submitted; boolean recording; - public CommandBuffer(VkCommandBuffer handle, long fence) { + public CommandBuffer(CommandPool commandPool, VkCommandBuffer handle, long fence, long semaphore) { + this.commandPool = commandPool; this.handle = handle; this.fence = fence; + this.semaphore = semaphore; } public VkCommandBuffer getHandle() { @@ -146,10 +131,42 @@ public boolean isRecording() { return recording; } + public void begin(MemoryStack stack) { + VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack); + beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); + beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + + vkBeginCommandBuffer(this.handle, beginInfo); + + this.recording = true; + } + + public long submitCommands(MemoryStack stack, VkQueue queue, boolean useSemaphore) { + long fence = this.fence; + + vkEndCommandBuffer(this.handle); + + vkResetFences(Vulkan.getVkDevice(), this.fence); + + VkSubmitInfo submitInfo = VkSubmitInfo.calloc(stack); + submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO); + submitInfo.pCommandBuffers(stack.pointers(this.handle)); + + if (useSemaphore) { + submitInfo.pSignalSemaphores(stack.longs(this.semaphore)); + } + + vkQueueSubmit(queue, submitInfo, fence); + + this.recording = false; + this.submitted = true; + return fence; + } + public void reset() { this.submitted = false; this.recording = false; - addToAvailable(this); + this.commandPool.addToAvailable(this); } } } diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index 4f68e0778f..0d0b30c2c4 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -26,7 +26,12 @@ public abstract class Queue { private final VkQueue queue; public synchronized CommandPool.CommandBuffer beginCommands() { - return this.commandPool.beginCommands(); + try (MemoryStack stack = stackPush()) { + CommandPool.CommandBuffer commandBuffer = this.commandPool.getCommandBuffer(stack); + commandBuffer.begin(stack); + + return commandBuffer; + } } Queue(MemoryStack stack, int familyIndex) { @@ -43,7 +48,9 @@ public synchronized CommandPool.CommandBuffer beginCommands() { } public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { - return this.commandPool.submitCommands(commandBuffer, queue); + try (MemoryStack stack = stackPush()) { + return commandBuffer.submitCommands(stack, queue, false); + } } public VkQueue queue() { @@ -59,6 +66,10 @@ public void waitIdle() { vkQueueWaitIdle(queue); } + public CommandPool getCommandPool() { + return commandPool; + } + public enum Family { Graphics, Transfer, @@ -76,7 +87,6 @@ public static QueueFamilyIndices getQueueFamilies() { } public static QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { - QueueFamilyIndices indices = new QueueFamilyIndices(); try (MemoryStack stack = stackPush()) { diff --git a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java index 151969d06d..c9aa78d114 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java @@ -15,23 +15,21 @@ public abstract class ImageUtil { - public static void copyBufferToImageCmd(VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLenght, int bufferImageHeight) { - - try (MemoryStack stack = stackPush()) { - - VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); - region.bufferOffset(bufferOffset); - region.bufferRowLength(bufferRowLenght); // Tightly packed - region.bufferImageHeight(bufferImageHeight); // Tightly packed - region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); - region.imageSubresource().mipLevel(mipLevel); - region.imageSubresource().baseArrayLayer(0); - region.imageSubresource().layerCount(1); - region.imageOffset().set(xOffset, yOffset, 0); - region.imageExtent(VkExtent3D.calloc(stack).set(width, height, 1)); - - vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, region); - } + public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, + int mipLevel, int width, int height, int xOffset, int yOffset, + int bufferOffset, int bufferRowLenght, int bufferImageHeight) { + VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); + region.bufferOffset(bufferOffset); + region.bufferRowLength(bufferRowLenght); // Tightly packed + region.bufferImageHeight(bufferImageHeight); // Tightly packed + region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); + region.imageSubresource().mipLevel(mipLevel); + region.imageSubresource().baseArrayLayer(0); + region.imageSubresource().layerCount(1); + region.imageOffset().set(xOffset, yOffset, 0); + region.imageExtent(VkExtent3D.calloc(stack).set(width, height, 1)); + + vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, region); } public static void downloadTexture(VulkanImage image, long ptr) { @@ -44,27 +42,27 @@ public static void downloadTexture(VulkanImage image, long ptr) { LongBuffer pStagingBuffer = stack.mallocLong(1); PointerBuffer pStagingAllocation = stack.pointers(0L); - MemoryManager.getInstance().createBuffer(imageSize, - VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - pStagingBuffer, - pStagingAllocation); + MemoryManager.getInstance().createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + pStagingBuffer, pStagingAllocation); - copyImageToBuffer(commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, image.height, 0, 0, 0, 0, 0); + copyImageToBuffer(commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, + image.height, 0, 0, 0, 0, 0); image.transitionImageLayout(stack, commandBuffer.getHandle(), prevLayout); long fence = DeviceManager.getGraphicsQueue().submitCommands(commandBuffer); vkWaitForFences(DeviceManager.vkDevice, fence, true, VUtil.UINT64_MAX); MemoryManager.MapAndCopy(pStagingAllocation.get(0), - (data) -> VUtil.memcpy(data.getByteBuffer(0, (int) imageSize), ptr) - ); + (data) -> VUtil.memcpy(data.getByteBuffer(0, (int) imageSize), ptr)); MemoryManager.freeBuffer(pStagingBuffer.get(0), pStagingAllocation.get(0)); } } - public static void copyImageToBuffer(VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLenght, int bufferImageHeight) { + public static void copyImageToBuffer(VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, + int width, int height, int xOffset, int yOffset, int bufferOffset, + int bufferRowLenght, int bufferImageHeight) { try (MemoryStack stack = stackPush()) { VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); @@ -112,12 +110,8 @@ public static void generateMipmaps(VulkanImage image) { barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT); barrier.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT); - vkCmdPipelineBarrier(commandBuffer.getHandle(), - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, - null, - null, - barrier); + vkCmdPipelineBarrier(commandBuffer.getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, null, null, barrier); prevLevel = level - 1; @@ -125,24 +119,18 @@ public static void generateMipmaps(VulkanImage image) { blit.srcOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.srcOffsets(1, VkOffset3D.calloc(stack).set(image.width >> prevLevel, image.height >> prevLevel, 1)); blit.srcSubresource() - .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) - .mipLevel(prevLevel) - .baseArrayLayer(0) - .layerCount(1); + .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) + .mipLevel(prevLevel) + .baseArrayLayer(0) + .layerCount(1); blit.dstOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.dstOffsets(1, VkOffset3D.calloc(stack).set(image.width >> level, image.height >> level, 1)); - blit.dstSubresource() - .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) - .mipLevel(level) - .baseArrayLayer(0) - .layerCount(1); - - vkCmdBlitImage(commandBuffer.getHandle(), - image.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - image.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - blit, - VK_FILTER_LINEAR); + blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(level).baseArrayLayer(0) + .layerCount(1); + + vkCmdBlitImage(commandBuffer.getHandle(), image.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + image.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); } @@ -165,22 +153,20 @@ public static void generateMipmaps(VulkanImage image) { barrier.dstAccessMask(VK_ACCESS_SHADER_READ_BIT); vkCmdPipelineBarrier(commandBuffer.getHandle(), - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - null, - null, - barrier); + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, + null, null, + barrier); barrier.oldLayout(VK_IMAGE_USAGE_TRANSFER_DST_BIT); barrier.subresourceRange().baseMipLevel(image.mipLevels - 1); barrier.subresourceRange().levelCount(1); vkCmdPipelineBarrier(commandBuffer.getHandle(), - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - null, - null, - barrier); + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, + null, null, + barrier); image.setCurrentLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index 440f1ec56d..c3daa8b908 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -1,9 +1,9 @@ package net.vulkanmod.vulkan.texture; import com.mojang.blaze3d.platform.NativeImage; -import net.vulkanmod.vulkan.Synchronization; +import net.vulkanmod.render.texture.ImageUploadHelper; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.StagingBuffer; import net.vulkanmod.vulkan.queue.CommandPool; @@ -194,23 +194,18 @@ public static long createImageView(long image, int format, int aspectFlags, int public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { long imageSize = buffer.limit(); - CommandPool.CommandBuffer commandBuffer = DeviceManager.getGraphicsQueue().getCommandBuffer(); + CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); try (MemoryStack stack = stackPush()) { transferDstLayout(stack, commandBuffer.getHandle()); - } - - StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - stagingBuffer.align(this.formatSize); - stagingBuffer.copyBuffer((int) imageSize, buffer); + StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); + stagingBuffer.align(this.formatSize); - ImageUtil.copyBufferToImageCmd(commandBuffer.getHandle(), stagingBuffer.getId(), id, mipLevel, width, height, xOffset, yOffset, - (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize), unpackRowLength, height); + stagingBuffer.copyBuffer((int) imageSize, buffer); - long fence = DeviceManager.getGraphicsQueue().endIfNeeded(commandBuffer); - if (fence != VK_NULL_HANDLE) -// Synchronization.INSTANCE.addFence(fence); - Synchronization.INSTANCE.addCommandBuffer(commandBuffer); + ImageUtil.copyBufferToImageCmd(stack, commandBuffer.getHandle(), stagingBuffer.getId(), id, mipLevel, width, height, xOffset, yOffset, + (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize), unpackRowLength, height); + } } private void transferDstLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { @@ -221,12 +216,17 @@ public void readOnlyLayout() { if (this.currentLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) return; - CommandPool.CommandBuffer commandBuffer = DeviceManager.getGraphicsQueue().getCommandBuffer(); try (MemoryStack stack = MemoryStack.stackPush()) { - readOnlyLayout(stack, commandBuffer.getHandle()); + if (Renderer.getInstance().getBoundRenderPass() != null) { + CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); + VkCommandBuffer vkCommandBuffer = commandBuffer.getHandle(); + + readOnlyLayout(stack, vkCommandBuffer); + } + else { + readOnlyLayout(stack, Renderer.getCommandBuffer()); + } } - DeviceManager.getGraphicsQueue().submitCommands(commandBuffer); - Synchronization.INSTANCE.addCommandBuffer(commandBuffer); } public void readOnlyLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 37e87d915d..f37e232b18 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -75,9 +75,11 @@ "texture.mip.MipmapGeneratorM", "texture.image.MNativeImage", "texture.image.NativeImageAccessor", + "texture.update.GameRendererM", + "texture.update.MLightTexture", + "texture.update.MSpriteContents", + "texture.update.MTextureManager", "texture.MAbstractTexture", - "texture.MSpriteContents", - "texture.MTextureManager", "texture.MTextureUtil", "util.ScreenshotRecorderM", From 0a9168f84756d665d22e4f016532a2dfb58db0b8 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:32:47 +0100 Subject: [PATCH 024/177] Use raw memory for section draw parameters --- .../net/vulkanmod/render/chunk/ChunkArea.java | 10 +- .../render/chunk/ChunkAreaManager.java | 37 ++- .../vulkanmod/render/chunk/RenderSection.java | 42 +-- .../vulkanmod/render/chunk/SectionGrid.java | 65 +++-- .../vulkanmod/render/chunk/WorldRenderer.java | 6 +- .../render/chunk/buffer/AreaBuffer.java | 14 +- .../render/chunk/buffer/DrawBuffers.java | 259 +++++++++++++----- .../chunk/buffer/DrawParametersBuffer.java | 77 ++++++ 8 files changed, 368 insertions(+), 142 deletions(-) create mode 100644 src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java b/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java index 26e6bb1e84..85400a8f1b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java @@ -11,11 +11,11 @@ public class ChunkArea { public final int index; + final DrawBuffers drawBuffers; final Vector3i position; final byte[] frustumBuffer = new byte[64]; - int sectionsContained = 0; - DrawBuffers drawBuffers; + int sectionsContained = 0; //Help JIT optimisations by hardcoding the queue size to the max possible ChunkArea limit public final StaticQueue sectionQueue = new StaticQueue<>(512); @@ -142,11 +142,15 @@ public void removeSection() { this.sectionsContained--; if (this.sectionsContained == 0) { - this.releaseBuffers(); + this.drawBuffers.releaseBuffers(); } } public void releaseBuffers() { this.drawBuffers.releaseBuffers(); } + + public void free() { + this.drawBuffers.free(); + } } diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java index 0541706363..1cdfa99f29 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java @@ -123,12 +123,7 @@ public void repositionAreas(int secX, int secZ) { int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { - int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); - ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; - - chunkArea.setPosition(x1, y1, z1); - chunkArea.releaseBuffers(); - + this.moveArea(xRelativeIndex, yRel, zRelativeIndex, x1, z1); } } } @@ -146,12 +141,7 @@ public void repositionAreas(int secX, int secZ) { int z1 = (zAbsChunkIndex << (AREA_SH_XZ + SEC_SH)); for (int yRel = 0; yRel < this.ySize; ++yRel) { - int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); - ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; - - chunkArea.setPosition(x1, y1, z1); - chunkArea.releaseBuffers(); - + this.moveArea(xRelativeIndex, yRel, zRelativeIndex, x1, z1); } } } @@ -160,6 +150,14 @@ public void repositionAreas(int secX, int secZ) { this.prevZ = zS; } + private void moveArea(int xRelativeIndex, int yRel, int zRelativeIndex, int x1, int z1) { + int y1 = this.minHeight + (yRel << (AREA_SH_Y + SEC_SH)); + ChunkArea chunkArea = this.chunkAreasArr[this.getAreaIndex(xRelativeIndex, yRel, zRelativeIndex)]; + + chunkArea.setPosition(x1, y1, z1); + chunkArea.releaseBuffers(); + } + public ChunkArea getChunkArea(RenderSection section, int x, int y, int z) { ChunkArea chunkArea; @@ -197,9 +195,9 @@ private int getAreaIndex(int x, int y, int z) { return (z * this.ySize + y) * this.xzSize + x; } - public void releaseAllBuffers() { + public void freeAllBuffers() { for (ChunkArea chunkArea : this.chunkAreasArr) { - chunkArea.releaseBuffers(); + chunkArea.free(); } } @@ -231,11 +229,12 @@ public String[] getStats() { } } - vbSize /= 1024 * 1024; - vbUsed /= 1024 * 1024; - ibSize /= 1024 * 1024; - ibUsed /= 1024 * 1024; - frag /= 1024 * 1024; + final int div = 1024 * 1024; + vbSize /= div; + vbUsed /= div; + ibSize /= div; + ibUsed /= div; + frag /= div; return new String[]{ String.format("Vertex Buffers: %d/%d MB", vbUsed, vbSize), diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index f6f13d0524..81dca75d92 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -6,7 +6,9 @@ import net.minecraft.client.Minecraft; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; +import net.vulkanmod.render.chunk.buffer.AreaBuffer; import net.vulkanmod.render.chunk.buffer.DrawBuffers; +import net.vulkanmod.render.chunk.buffer.DrawParametersBuffer; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; import net.vulkanmod.render.chunk.build.task.TaskDispatcher; @@ -30,6 +32,7 @@ public class RenderSection { public byte frustumIndex; public short lastFrame = -1; private short lastFrame2 = -1; + public short inAreaIndex; public byte adjDirs; public RenderSection @@ -48,8 +51,6 @@ public class RenderSection { public int xOffset, yOffset, zOffset; - private final DrawBuffers.DrawParameters[] drawParametersArray; - // Graph-info public byte mainDir; public byte directions; @@ -61,12 +62,6 @@ public RenderSection(int index, int x, int y, int z) { this.xOffset = x; this.yOffset = y; this.zOffset = z; - - final int size = TerrainRenderType.VALUES.length * QuadFacing.VALUES.length; - this.drawParametersArray = new DrawBuffers.DrawParameters[size]; - for (int i = 0; i < size; ++i) { - this.drawParametersArray[i] = new DrawBuffers.DrawParameters(); - } } public void setOrigin(int x, int y, int z) { @@ -301,12 +296,18 @@ public int zOffset() { public void resetDrawParameters(TerrainRenderType renderType) { for (int i = 0; i < QuadFacing.COUNT; ++i) { - drawParametersArray[renderType.ordinal() * QuadFacing.COUNT + i].reset(this.chunkArea, renderType); - } - } + DrawBuffers drawBuffers = this.chunkArea.getDrawBuffers(); + long ptr = DrawParametersBuffer.getParamsPtr(drawBuffers.getDrawParamsPtr(), this.inAreaIndex, renderType.ordinal(), i); + + AreaBuffer areaBuffer = drawBuffers.getAreaBuffer(renderType); + int vertexOffset = DrawParametersBuffer.getVertexOffset(ptr); + if (areaBuffer != null && vertexOffset != -1) { + int segmentOffset = vertexOffset * DrawBuffers.VERTEX_SIZE; + areaBuffer.setSegmentFree(segmentOffset); + } - public DrawBuffers.DrawParameters getDrawParameters(TerrainRenderType renderType, int facing) { - return drawParametersArray[renderType.ordinal() * QuadFacing.COUNT + facing]; + DrawParametersBuffer.resetParameters(ptr); + } } public void setChunkArea(ChunkArea chunkArea) { @@ -347,6 +348,10 @@ public byte getVisibilityDirs() { return (byte) (this.visibility >> (Util.getOppositeDirIdx(this.mainDir) << 3)); } + public long getVisibility() { + return visibility; + } + public boolean isCompletelyEmpty() { return this.completelyEmpty; } @@ -363,8 +368,7 @@ public void updateGlobalBlockEntities(Collection fullSet) { Set set1; Set sectionSet; synchronized (globalBlockEntitiesMap) { - sectionSet = globalBlockEntitiesMap.computeIfAbsent(this, - (section) -> new ObjectOpenHashSet<>()); + sectionSet = globalBlockEntitiesMap.computeIfAbsent(this, (section) -> new ObjectOpenHashSet<>()); } if (sectionSet.size() != fullSet.size() || !sectionSet.containsAll(fullSet)) { @@ -393,9 +397,11 @@ private void resetDrawParameters() { if (this.chunkArea == null) return; + long basePtr = this.chunkArea.getDrawBuffers().getDrawParamsPtr(); for (TerrainRenderType renderType : TerrainRenderType.VALUES) { for (QuadFacing facing : QuadFacing.VALUES) { - this.getDrawParameters(renderType, facing.ordinal()).reset(this.chunkArea, renderType); + long ptr = DrawParametersBuffer.getParamsPtr(basePtr, this.inAreaIndex, renderType.ordinal(), facing.ordinal()); + DrawParametersBuffer.resetParameters(ptr); } } } @@ -428,6 +434,10 @@ public short getLastFrame() { return this.lastFrame; } + public short getLastFrame2() { + return this.lastFrame2; + } + static class CompileStatus { CompiledSection compiledSection = CompiledSection.UNCOMPILED; BuildTask buildTask; diff --git a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java index 54ee8d3ed2..3a94d37f3c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java +++ b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java @@ -53,8 +53,8 @@ protected void createChunks() { } } - public void releaseAllBuffers() { - this.chunkAreaManager.releaseAllBuffers(); + public void freeAllBuffers() { + this.chunkAreaManager.freeAllBuffers(); } private int getChunkIndex(int x, int y, int z) { @@ -133,19 +133,9 @@ public void repositionCamera(double x, double z) { zRelativeIndex = zIterator.next(); int z1 = (zAbsChunkIndex << 4); - for (int yRel = 0; - yRel < this.gridHeight; ++yRel) { - int y1 = this.level.getMinBuildHeight() + (yRel << 4); - RenderSection renderSection = this.sections[this.getChunkIndex(xRelativeIndex, yRel, zRelativeIndex)]; - - renderSection.setOrigin(x1, y1, z1); - - this.unsetNeighbours(renderSection); - - this.setNeighbours(renderSection, xList, zList, xRangeIterator.getCurrentIndex(), zIterator.getCurrentIndex(), - xRelativeIndex, yRel, zRelativeIndex); - - this.setChunkArea(renderSection, x1, y1, z1); + for (int yRel = 0; yRel < this.gridHeight; ++yRel) { + moveSection(xRelativeIndex, yRel, zRelativeIndex, x1, z1, + xList, zList, xRangeIterator.getCurrentIndex(), zIterator.getCurrentIndex()); } } } @@ -162,26 +152,45 @@ public void repositionCamera(double x, double z) { zRelativeIndex = zRangeIterator.next(); int z1 = (zAbsChunkIndex << 4); - for (int yRel = 0; - yRel < this.gridHeight; ++yRel) { - int y1 = this.level.getMinBuildHeight() + (yRel << 4); - RenderSection renderSection = this.sections[this.getChunkIndex(xRelativeIndex, yRel, zRelativeIndex)]; + for (int yRel = 0; yRel < this.gridHeight; ++yRel) { + moveSection(xRelativeIndex, yRel, zRelativeIndex, x1, z1, + xList, zList, xComplIterator.getCurrentIndex(), zRangeIterator.getCurrentIndex()); + } + } + } - renderSection.setOrigin(x1, y1, z1); + this.prevSecX = secX; + this.prevSecZ = secZ; + } - this.unsetNeighbours(renderSection); + private void moveSection(int xRelativeIndex, int yRel, int zRelativeIndex, + int x1, int z1, + CircularIntList xList, CircularIntList zList, + int xCurrentIdx, int zCurrentIdx) { - this.setNeighbours(renderSection, xList, zList, xComplIterator.getCurrentIndex(), zRangeIterator.getCurrentIndex(), - xRelativeIndex, yRel, zRelativeIndex); + int y1 = this.level.getMinBuildHeight() + (yRel << 4); + RenderSection renderSection = this.sections[this.getChunkIndex(xRelativeIndex, yRel, zRelativeIndex)]; - this.setChunkArea(renderSection, x1, y1, z1); + this.unsetNeighbours(renderSection); - } - } + renderSection.setOrigin(x1, y1, z1); + + this.setNeighbours(renderSection, xList, zList, xCurrentIdx, zCurrentIdx, + xRelativeIndex, yRel, zRelativeIndex); + + ChunkArea oldArea = renderSection.getChunkArea(); + + if (oldArea != null) { + oldArea.removeSection(); } - this.prevSecX = secX; - this.prevSecZ = secZ; + ChunkArea chunkArea = this.chunkAreaManager.getChunkArea(renderSection, x1, y1, z1); + chunkArea.addSection(); + renderSection.setChunkArea(chunkArea); + + renderSection.inAreaIndex = (short) (((x1 - chunkArea.position.x()) >> 4) + + (((z1 - chunkArea.position.z()) >> 4) * 8 + ((y1 - chunkArea.position.y()) >> 4)) * 8); + } private void setNeighbours(RenderSection section, CircularIntList xList, CircularIntList zList, diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 7385f7db8c..821282f3fb 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -240,7 +240,7 @@ public void allChanged() { this.renderDistance = this.minecraft.options.getEffectiveRenderDistance(); if (this.sectionGrid != null) { - this.sectionGrid.releaseAllBuffers(); + this.sectionGrid.freeAllBuffers(); } this.taskDispatcher.clearBatchQueue(); @@ -276,7 +276,7 @@ public void setLevel(@Nullable ClientLevel level) { this.allChanged(); } else { if (this.sectionGrid != null) { - this.sectionGrid.releaseAllBuffers(); + this.sectionGrid.freeAllBuffers(); this.sectionGrid = null; } @@ -350,7 +350,7 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, //Need to reset push constants in case the pipeline will still be used for rendering if (!indirectDraw) { - VRenderSystem.setChunkOffset(0, 0, 0); + VRenderSystem.setModelOffset(0, 0, 0); renderer.pushConstants(pipeline); } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java index b19f3a1125..4eb65a7809 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java @@ -49,7 +49,7 @@ private Buffer allocateBuffer() { return buffer; } - public Segment upload(ByteBuffer byteBuffer, int oldOffset, DrawBuffers.DrawParameters drawParameters) { + public Segment upload(ByteBuffer byteBuffer, int oldOffset, long paramsPtr) { // Free old segment if (oldOffset != -1) { // Need to delay segment freeing since it might be still used by prev frames in flight @@ -81,7 +81,7 @@ public Segment upload(ByteBuffer byteBuffer, int oldOffset, DrawBuffers.DrawPara segment.free = false; this.usedSegments.put(segment.offset, segment); - segment.drawParameters = drawParameters; + segment.paramsPtr = paramsPtr; Buffer dst = this.buffer; UploadManager.INSTANCE.recordUpload(dst, segment.offset, size, byteBuffer); @@ -227,7 +227,7 @@ public void setSegmentFree(int offset) { this.used -= segment.size; segment.free = true; - segment.drawParameters = null; + segment.paramsPtr = -1; Segment next = segment.next; if (next != null && next.isFree()) { @@ -254,13 +254,11 @@ private void mergeSegments(Segment segment, Segment next) { } private void updateDrawParams(Segment segment) { - DrawBuffers.DrawParameters params = segment.drawParameters; - int elementOffset = segment.offset / elementSize; if (this.usage == Usage.VERTEX.usage) { - params.vertexOffset = elementOffset; + DrawParametersBuffer.setVertexOffset(segment.paramsPtr, elementOffset); } else { - params.firstIndex = elementOffset; + DrawParametersBuffer.setFirstIndex(segment.paramsPtr, elementOffset); } } @@ -351,7 +349,7 @@ public int getUsed() { public static class Segment { int offset, size; boolean free = true; - DrawBuffers.DrawParameters drawParameters; + long paramsPtr; Segment next, prev; diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 636ea132ba..16c4b64b63 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -1,8 +1,8 @@ package net.vulkanmod.render.chunk.buffer; import net.minecraft.world.phys.Vec3; +import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; -import net.vulkanmod.render.chunk.ChunkArea; import net.vulkanmod.render.chunk.ChunkAreaManager; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.build.UploadBuffer; @@ -24,8 +24,8 @@ import static org.lwjgl.vulkan.VK10.*; public class DrawBuffers { - private static final int VERTEX_SIZE = PipelineManager.terrainVertexFormat.getVertexSize(); - private static final int INDEX_SIZE = Short.BYTES; + public static final int VERTEX_SIZE = PipelineManager.terrainVertexFormat.getVertexSize(); + public static final int INDEX_SIZE = Short.BYTES; private static final int CMD_STRIDE = 32; @@ -39,54 +39,70 @@ public class DrawBuffers { AreaBuffer indexBuffer; private final EnumMap vertexBuffers = new EnumMap<>(TerrainRenderType.class); + long drawParamsPtr; + final int[] sectionIndices = new int[512]; + final int[] masks = new int[512]; + //Need ugly minHeight Parameter to fix custom world heights (exceeding 384 Blocks in total) public DrawBuffers(int index, Vector3i origin, int minHeight) { this.index = index; this.origin = origin; this.minHeight = minHeight; + + this.drawParamsPtr = DrawParametersBuffer.allocateBuffer(); } public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType renderType) { var vertexBuffers = buffer.getVertexBuffers(); if (buffer.indexOnly) { - DrawParameters drawParameters = section.getDrawParameters(renderType, QuadFacing.UNDEFINED.ordinal()); + long paramsPtr = DrawParametersBuffer.getParamsPtr(this.drawParamsPtr, section.inAreaIndex, renderType.ordinal(), QuadFacing.UNDEFINED.ordinal()); + + int firstIndex = DrawParametersBuffer.getFirstIndex(paramsPtr); + int indexCount = DrawParametersBuffer.getIndexCount(paramsPtr); + + int oldOffset = indexCount > 0 ? firstIndex : -1; + AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), oldOffset, paramsPtr); + firstIndex = segment.offset / INDEX_SIZE; - AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); - drawParameters.firstIndex = segment.offset / INDEX_SIZE; + DrawParametersBuffer.setFirstIndex(paramsPtr, firstIndex); buffer.release(); return; } for (int i = 0; i < QuadFacing.COUNT; i++) { - DrawParameters drawParameters = section.getDrawParameters(renderType, i); - int vertexOffset = drawParameters.vertexOffset; - int firstIndex = -1; + long paramPtr = DrawParametersBuffer.getParamsPtr(this.drawParamsPtr, section.inAreaIndex, renderType.ordinal(), i); + + int vertexOffset = DrawParametersBuffer.getVertexOffset(paramPtr); + int firstIndex = 0; int indexCount = 0; var vertexBuffer = vertexBuffers[i]; if (vertexBuffer != null) { - AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(vertexBuffer, vertexOffset, drawParameters); + AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(vertexBuffer, vertexOffset, paramPtr); vertexOffset = segment.offset / VERTEX_SIZE; - drawParameters.baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); + int baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); + DrawParametersBuffer.setBaseInstance(paramPtr, baseInstance); + indexCount = vertexBuffer.limit() / VERTEX_SIZE * 6 / 4; } - if (i == QuadFacing.UNDEFINED.ordinal() && !buffer.autoIndices) { - if (this.indexBuffer == null) { - this.indexBuffer = new AreaBuffer(AreaBuffer.Usage.INDEX, 60000, INDEX_SIZE); - } + if (i == QuadFacing.UNDEFINED.ordinal() && !buffer.autoIndices) { + if (this.indexBuffer == null) { + this.indexBuffer = new AreaBuffer(AreaBuffer.Usage.INDEX, 60000, INDEX_SIZE); + } - AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), drawParameters.firstIndex, drawParameters); + int oldOffset = DrawParametersBuffer.getIndexCount(paramPtr) > 0 ? DrawParametersBuffer.getFirstIndex(paramPtr) : -1; + AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), oldOffset, paramPtr); firstIndex = segment.offset / INDEX_SIZE; } - drawParameters.firstIndex = firstIndex; - drawParameters.vertexOffset = vertexOffset; - drawParameters.indexCount = indexCount; + DrawParametersBuffer.setIndexCount(paramPtr, indexCount); + DrawParametersBuffer.setFirstIndex(paramPtr, firstIndex); + DrawParametersBuffer.setVertexOffset(paramPtr, vertexOffset); } buffer.release(); @@ -141,37 +157,105 @@ public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuff long bufferPtr = cmdBufferPtr; boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; + boolean backFaceCulling = Initializer.CONFIG.backFaceCulling && !isTranslucent; int drawCount = 0; - for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { - final RenderSection section = iterator.next(); + long drawParamsBasePtr = this.drawParamsPtr + (terrainRenderType.ordinal() * DrawParametersBuffer.SECTIONS * DrawParametersBuffer.FACINGS) * DrawParametersBuffer.STRIDE; + final long facingsStride = DrawParametersBuffer.FACINGS * DrawParametersBuffer.STRIDE; - int mask = getMask(cameraPos, section); + int count = 0; + if (backFaceCulling) { + for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { + final RenderSection section = iterator.next(); - for (int i = 0; i < QuadFacing.COUNT; i++) { + sectionIndices[count] = section.inAreaIndex; + masks[count] = getMask(cameraPos, section); + count++; + } - if ((mask & 1 << i) == 0) - continue; + long ptr = bufferPtr; + + for (int j = 0; j < count; ++j) { + final int sectionIdx = sectionIndices[j]; + + int mask = masks[j]; + + long drawParamsBasePtr2 = drawParamsBasePtr + (sectionIdx * facingsStride); + + for (int i = 0; i < QuadFacing.COUNT; i++) { + + if ((mask & 1 << i) == 0) { + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + continue; + } + + long drawParamsPtr = drawParamsBasePtr2; - final DrawParameters drawParameters = section.getDrawParameters(terrainRenderType, i); + final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); - if (drawParameters.indexCount <= 0) + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + + if (indexCount <= 0) { + continue; + } + + MemoryUtil.memPutInt(ptr, indexCount); + MemoryUtil.memPutInt(ptr + 4, 1); + MemoryUtil.memPutInt(ptr + 8, firstIndex); + MemoryUtil.memPutInt(ptr + 12, vertexOffset); + MemoryUtil.memPutInt(ptr + 16, baseInstance); + + ptr += CMD_STRIDE; + drawCount++; + } + } + + } + else { + for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { + final RenderSection section = iterator.next(); + + sectionIndices[count] = section.inAreaIndex; + count++; + } + + final int facing = 6; + final long facingOffset = facing * DrawParametersBuffer.STRIDE; + drawParamsBasePtr += facingOffset; + + long ptr = bufferPtr; + for (int i = 0; i < count; ++i) { + int sectionIdx = sectionIndices[i]; + + long drawParamsPtr = drawParamsBasePtr + (sectionIdx * facingsStride); + + final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); + + if (indexCount <= 0) { continue; + } - long ptr = bufferPtr + ((long) drawCount * CMD_STRIDE); - MemoryUtil.memPutInt(ptr, drawParameters.indexCount); + MemoryUtil.memPutInt(ptr, indexCount); MemoryUtil.memPutInt(ptr + 4, 1); - MemoryUtil.memPutInt(ptr + 8, drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex); - MemoryUtil.memPutInt(ptr + 12, drawParameters.vertexOffset); - MemoryUtil.memPutInt(ptr + 16, drawParameters.baseInstance); + MemoryUtil.memPutInt(ptr + 8, firstIndex); + MemoryUtil.memPutInt(ptr + 12, vertexOffset); + MemoryUtil.memPutInt(ptr + 16, baseInstance); + ptr += CMD_STRIDE; drawCount++; } } - if (drawCount == 0) + if (drawCount == 0) { return; + } ByteBuffer byteBuffer = MemoryUtil.memByteBuffer(cmdBufferPtr, queue.size() * QuadFacing.COUNT * CMD_STRIDE); indirectBuffer.recordCopyCmd(byteBuffer.position(0)); @@ -179,30 +263,86 @@ public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuff vkCmdDrawIndexedIndirect(Renderer.getCommandBuffer(), indirectBuffer.getId(), indirectBuffer.getOffset(), drawCount, CMD_STRIDE); } - public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue queue, TerrainRenderType renderType) { - boolean isTranslucent = renderType == TerrainRenderType.TRANSLUCENT; + public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue queue, TerrainRenderType terrainRenderType) { + boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; + boolean backFaceCulling = Initializer.CONFIG.backFaceCulling && !isTranslucent; + VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); - for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { - final RenderSection section = iterator.next(); + long drawParamsBasePtr = this.drawParamsPtr + (terrainRenderType.ordinal() * DrawParametersBuffer.SECTIONS * DrawParametersBuffer.FACINGS) * DrawParametersBuffer.STRIDE; + final long facingsStride = DrawParametersBuffer.FACINGS * DrawParametersBuffer.STRIDE; - int mask = getMask(cameraPos, section); + int count = 0; + if (backFaceCulling) { + for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { + final RenderSection section = iterator.next(); - for (int i = 0; i < QuadFacing.COUNT; i++) { + sectionIndices[count] = section.inAreaIndex; + masks[count] = getMask(cameraPos, section); + count++; + } - if((mask & 1 << i) == 0) - continue; + for (int j = 0; j < count; ++j) { + final int sectionIdx = sectionIndices[j]; - final DrawParameters drawParameters = section.getDrawParameters(renderType, i); + int mask = masks[j]; - if (drawParameters.indexCount <= 0) - continue; + long drawParamsBasePtr2 = drawParamsBasePtr + (sectionIdx * facingsStride); + + for (int i = 0; i < QuadFacing.COUNT; i++) { + + if ((mask & 1 << i) == 0) { + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + continue; + } + + long drawParamsPtr = drawParamsBasePtr2; + + final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); - final int firstIndex = drawParameters.firstIndex == -1 ? 0 : drawParameters.firstIndex; - vkCmdDrawIndexed(commandBuffer, drawParameters.indexCount, 1, firstIndex, drawParameters.vertexOffset, drawParameters.baseInstance); + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + + if (indexCount <= 0) { + continue; + } + + vkCmdDrawIndexed(commandBuffer, indexCount, 1, firstIndex, vertexOffset, baseInstance); + } } } + else { + final int facing = 6; + final long facingOffset = facing * DrawParametersBuffer.STRIDE; + drawParamsBasePtr += facingOffset; + + for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { + final RenderSection section = iterator.next(); + + sectionIndices[count] = section.inAreaIndex; + count++; + } + + for (int i = 0; i < count; ++i) { + int sectionIdx = sectionIndices[i]; + + long drawParamsPtr = drawParamsBasePtr + (sectionIdx * facingsStride); + + final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); + + if (indexCount <= 0) { + continue; + } + + vkCmdDrawIndexed(commandBuffer, indexCount, 1, firstIndex, vertexOffset, baseInstance); + } + } } private int getMask(Vec3 camera, RenderSection section) { @@ -248,6 +388,12 @@ public void releaseBuffers() { this.allocated = false; } + public void free() { + this.releaseBuffers(); + + DrawParametersBuffer.freeBuffer(this.drawParamsPtr); + } + public boolean isAllocated() { return !this.vertexBuffers.isEmpty(); } @@ -260,25 +406,8 @@ public AreaBuffer getIndexBuffer() { return indexBuffer; } - public static class DrawParameters { - int indexCount = 0; - int firstIndex = -1; - int vertexOffset = -1; - int baseInstance; - - public DrawParameters() {} - - public void reset(ChunkArea chunkArea, TerrainRenderType r) { - AreaBuffer areaBuffer = chunkArea.getDrawBuffers().getAreaBuffer(r); - if (areaBuffer != null && this.vertexOffset != -1) { - int segmentOffset = this.vertexOffset * VERTEX_SIZE; - areaBuffer.setSegmentFree(segmentOffset); - } - - this.indexCount = 0; - this.firstIndex = -1; - this.vertexOffset = -1; - } + public long getDrawParamsPtr() { + return drawParamsPtr; } } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java new file mode 100644 index 0000000000..f26c2420dd --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java @@ -0,0 +1,77 @@ +package net.vulkanmod.render.chunk.buffer; + +import net.vulkanmod.render.chunk.ChunkAreaManager; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.vertex.TerrainRenderType; +import org.lwjgl.system.MemoryUtil; + +public abstract class DrawParametersBuffer { + static final long INDEX_COUNT_OFFSET = 0; + static final long FIRST_INDEX_OFFSET = 4; + static final long VERTEX_OFFSET_OFFSET = 8; + static final long BASE_INSTANCE_OFFSET = 12; + + public static final long STRIDE = 16; + + static final int SECTIONS = ChunkAreaManager.AREA_SIZE; + static final int FACINGS = 7; + + public static long allocateBuffer() { + int size = (int) (ChunkAreaManager.AREA_SIZE * TerrainRenderType.VALUES.length * QuadFacing.COUNT * DrawParametersBuffer.STRIDE); + long drawParamsPtr = MemoryUtil.nmemAlignedAlloc(32, size); + + for (long ptr = drawParamsPtr; ptr < drawParamsPtr + size; ptr += DrawParametersBuffer.STRIDE) { + DrawParametersBuffer.resetParameters(ptr); + } + + return drawParamsPtr; + } + + public static void freeBuffer(long ptr) { + MemoryUtil.nmemAlignedFree(ptr); + } + + public static long getParamsPtr(long basePtr, int section, int renderType, int facing) { + return basePtr + (((renderType * SECTIONS + section) * FACINGS) + facing) * STRIDE; + } + + public static void resetParameters(long ptr) { + setIndexCount(ptr, 0); + setFirstIndex(ptr, 0); + setVertexOffset(ptr, -1); + setBaseInstance(ptr, 0); + } + + public static void setIndexCount(long ptr, int value) { + MemoryUtil.memPutInt(ptr + INDEX_COUNT_OFFSET, value); + } + + public static void setFirstIndex(long ptr, int value) { + MemoryUtil.memPutInt(ptr + FIRST_INDEX_OFFSET, value); + } + + public static void setVertexOffset(long ptr, int value) { + MemoryUtil.memPutInt(ptr + VERTEX_OFFSET_OFFSET, value); + } + + public static void setBaseInstance(long ptr, int value) { + MemoryUtil.memPutInt(ptr + BASE_INSTANCE_OFFSET, value); + } + + public static int getIndexCount(long ptr) { + return MemoryUtil.memGetInt(ptr + INDEX_COUNT_OFFSET); + } + + public static int getFirstIndex(long ptr) { + return MemoryUtil.memGetInt(ptr + FIRST_INDEX_OFFSET); + } + + public static int getVertexOffset(long ptr) { + return MemoryUtil.memGetInt(ptr + VERTEX_OFFSET_OFFSET); + } + + public static int getBaseInstance(long ptr) { + return MemoryUtil.memGetInt(ptr + BASE_INSTANCE_OFFSET); + } + +} From 34b8e0a1dad9f9216468e6d58696c8d443c02512 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:39:17 +0100 Subject: [PATCH 025/177] Use optimal swapchain image count --- .../net/vulkanmod/vulkan/framebuffer/SwapChain.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 44b8bf7e56..9b68ec2d7f 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -29,8 +29,6 @@ import static org.lwjgl.vulkan.VK10.*; public class SwapChain extends Framebuffer { - private static final int DEFAULT_IMAGE_COUNT = 3; - // Necessary until tearing-control-unstable-v1 is fully implemented on all GPU Drivers for Wayland // (As Immediate Mode (and by extension Screen tearing) doesn't exist on some Wayland installations currently) private static final int defUncappedMode = checkPresentMode(VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR); @@ -90,9 +88,10 @@ private void createSwapChain() { return; } - // minImageCount depends on driver: Mesa/RADV needs a min of 4, but most other drivers are at least 2 or 3 - // TODO using FIFO present mode with image num > 2 introduces (unnecessary) input lag - int requestedImages = Math.max(DEFAULT_IMAGE_COUNT, surfaceProperties.capabilities.minImageCount()); + int requestedImages = surfaceProperties.capabilities.minImageCount() + 1; + if (surfaceProperties.capabilities.maxImageCount() > 0 && requestedImages > surfaceProperties.capabilities.maxImageCount()) { + requestedImages = surfaceProperties.capabilities.maxImageCount(); + } IntBuffer imageCount = stack.ints(requestedImages); @@ -291,7 +290,7 @@ private int getPresentMode(IntBuffer availablePresentModes) { } } - Initializer.LOGGER.warn("Requested mode not supported: " + getDisplayModeString(requestedMode) + ": using VSync"); + Initializer.LOGGER.warn("Requested mode not supported: " + getDisplayModeString(requestedMode) + ": using FIFO present mode"); return VK_PRESENT_MODE_FIFO_KHR; } From 2302da6d4e32d2732e265b5c677bac37f0f75254 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 18 Nov 2024 16:52:16 +0100 Subject: [PATCH 026/177] Revert clouds render distance --- src/main/java/net/vulkanmod/render/sky/CloudRenderer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 4e6360bb09..805d39baae 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -168,7 +168,7 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - int renderDistance = 45; + int renderDistance = 32; boolean insideClouds = this.prevInsideClouds; if (this.prevCloudsType == CloudStatus.FANCY) { From abee6c88d315e2ff64661d97b088682250291ce1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 18 Nov 2024 16:52:46 +0100 Subject: [PATCH 027/177] Add shader namespace check --- .../java/net/vulkanmod/render/shader/ShaderLoadUtil.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index a45ca73769..b7b036307c 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -79,6 +79,11 @@ public static String getConfigFilePath(String path, String rendertype) { } public static JsonObject getJsonConfig(String path, String rendertype) { + // Check for external shader + if (rendertype.contains(String.valueOf(ResourceLocation.NAMESPACE_SEPARATOR))) { + return null; + } + String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); String configPath = "%s/%s/%s.json".formatted(basePath, rendertype, rendertype); From 52dd96fc614abb398d3513b3ae755850ef8ecb83 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 18 Nov 2024 16:53:14 +0100 Subject: [PATCH 028/177] Fix out of bounds error --- .../render/profiling/ProfilerOverlay.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index b5f21bc7bd..8fec0f5508 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -104,14 +104,20 @@ private List buildInfo() { this.updateResults(); - if (lastResults == null) + if (lastResults == null) { return list; + } + + var partialResults = lastResults.getPartialResults(); + if (partialResults.size() < 2) { + return list; + } int fps = Math.round(1000.0f / frametime); list.add(String.format("FPS: %d Frametime: %.3f", fps, frametime)); list.add(""); - list.add(String.format("CPU fence wait time: %.3f", lastResults.getPartialResults().get(1).value)); + list.add(String.format("CPU fence wait time: %.3f", partialResults.get(1).value)); list.add(""); for (Profiler.Result result : lastResults.getPartialResults()) { @@ -126,8 +132,9 @@ private List buildInfo() { list.add(""); list.add(String.format("Build time: %.0fms", BuildTimeProfiler.getDeltaTime())); - if (ChunkTask.BENCH) + if (ChunkTask.BENCH) { list.add(buildStats); + } return list; } @@ -137,7 +144,7 @@ private void updateResults() { return; Profiler.ProfilerResults results = Profiler.getMainProfiler().getProfilerResults(); - if (results == null || results.partialResults.size() < 2) + if (results == null) return; frametime = results.getResult().value; From 8da14709f7c4e4d483f04f64190015788ce1880a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 18 Nov 2024 16:54:41 +0100 Subject: [PATCH 029/177] Fix incorrect entity shaders --- .../vulkanmod/shaders/core/entity/entity.fsh | 11 +++++++--- .../vulkanmod/shaders/core/entity/entity.vsh | 20 ++++++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh index 7659168a5b..29fd0268fc 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh @@ -11,15 +11,20 @@ layout(binding = 1) uniform UBO{ }; layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; +layout(location = 1) in vec4 lightMapColor; +layout(location = 2) in vec4 overlayColor; +layout(location = 3) in vec2 texCoord0; +layout(location = 4) in float vertexDistance; layout(location = 0) out vec4 fragColor; void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; + vec4 color = texture(Sampler0, texCoord0); if (color.a < 0.1) { discard; } + color *= vertexColor * ColorModulator; + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + color *= lightMapColor; fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh index ea9fb38c1d..76e60cbae9 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh @@ -6,25 +6,31 @@ layout(location = 0) in vec3 Position; layout(location = 1) in vec4 Color; layout(location = 2) in vec2 UV0; +layout(location = 3) in ivec2 UV1; layout(location = 4) in ivec2 UV2; layout(location = 5) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; + mat4 MVP; + vec3 Light0_Direction; + vec3 Light1_Direction; }; -layout(binding = 3) uniform sampler2D Sampler2; +layout(binding = 3) uniform sampler2D Sampler1; +layout(binding = 4) uniform sampler2D Sampler2; layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; +layout(location = 1) out vec4 lightMapColor; +layout(location = 2) out vec4 overlayColor; +layout(location = 3) out vec2 texCoord0; +layout(location = 4) out float vertexDistance; void main() { gl_Position = MVP * vec4(Position, 1.0); vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); texCoord0 = UV0; } \ No newline at end of file From 3ac10f3981288a96998f76e703c49e5f8d27559f Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 23 Nov 2024 12:42:39 +0100 Subject: [PATCH 030/177] Use fixed size staging buffer - Refactor classes - Add missing resources' clean up - Track allocated image memory --- .../java/net/vulkanmod/gl/GlFramebuffer.java | 8 +- .../mixin/compatibility/EffectInstanceM.java | 17 ++-- .../mixin/render/GameRendererMixin.java | 9 ++- .../mixin/render/LevelRendererMixin.java | 56 ------------- .../mixin/texture/image/MNativeImage.java | 5 +- .../net/vulkanmod/render/PipelineManager.java | 1 + src/main/java/net/vulkanmod/render/VBO.java | 10 +-- .../vulkanmod/render/chunk/WorldRenderer.java | 8 +- .../render/chunk/buffer/AreaBuffer.java | 6 +- .../render/chunk/buffer/UploadManager.java | 9 +-- .../net/vulkanmod/render/chunk/util/Util.java | 8 +- .../vulkanmod/render/sky/CloudRenderer.java | 3 +- .../render/texture/SpriteUpdateUtil.java | 2 +- .../java/net/vulkanmod/vulkan/Drawer.java | 8 +- .../java/net/vulkanmod/vulkan/Renderer.java | 69 +++++++++------- .../java/net/vulkanmod/vulkan/Vulkan.java | 74 ++---------------- .../vulkan/framebuffer/Framebuffer.java | 15 +--- .../vulkan/framebuffer/RenderPass.java | 2 - .../vulkan/memory/AutoIndexBuffer.java | 4 +- .../net/vulkanmod/vulkan/memory/Buffer.java | 63 ++++++++++----- .../vulkanmod/vulkan/memory/IndexBuffer.java | 2 +- .../vulkan/memory/IndirectBuffer.java | 6 +- .../vulkan/memory/MemoryManager.java | 54 +++++++------ .../vulkanmod/vulkan/memory/MemoryType.java | 2 +- .../vulkanmod/vulkan/memory/MemoryTypes.java | 28 +++---- .../vulkan/memory/StagingBuffer.java | 48 +++++++----- .../vulkan/memory/UniformBuffer.java | 4 +- .../vulkanmod/vulkan/memory/VertexBuffer.java | 2 +- .../vulkan/pass/DefaultMainPass.java | 18 +++-- .../net/vulkanmod/vulkan/pass/MainPass.java | 2 + .../vulkanmod/vulkan/queue/CommandPool.java | 1 + .../net/vulkanmod/vulkan/queue/Queue.java | 12 +-- .../vulkan/shader/GraphicsPipeline.java | 18 +++-- .../vulkanmod/vulkan/texture/VulkanImage.java | 62 +++++++++------ .../java/net/vulkanmod/vulkan/util/VUtil.java | 78 +++++-------------- src/main/resources/vulkanmod.mixins.json | 1 - 36 files changed, 303 insertions(+), 412 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/mixin/render/LevelRendererMixin.java diff --git a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java index 0201441ecc..6b3ca17c1a 100644 --- a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java @@ -91,7 +91,7 @@ public static void deleteFramebuffer(int id) { if (boundFramebuffer == null) throw new NullPointerException("bound framebuffer is null"); - boundFramebuffer.cleanUp(); + boundFramebuffer.cleanUp(true); boundFramebuffer = null; } @@ -208,7 +208,7 @@ void createAndBind() { return; if (this.framebuffer != null) { - this.cleanUp(); + this.cleanUp(false); } boolean hasDepthImage = this.depthAttachment != null; @@ -237,8 +237,8 @@ public RenderPass getRenderPass() { return renderPass; } - void cleanUp() { - this.framebuffer.cleanUp(false); + void cleanUp(boolean freeAttachments) { + this.framebuffer.cleanUp(freeAttachments); this.renderPass.cleanUp(); this.framebuffer = null; diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index 622c23a710..3cc3bef002 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -22,10 +22,7 @@ import org.apache.commons.io.IOUtils; import org.lwjgl.opengl.GL30; import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -38,7 +35,6 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.IntSupplier; @@ -60,9 +56,9 @@ public class EffectInstanceM { @Shadow @Final private Map samplerMap; @Shadow @Final private String name; - private static GraphicsPipeline lastPipeline; - private GraphicsPipeline pipeline; + @Unique private static GraphicsPipeline lastPipeline; + @Unique private GraphicsPipeline pipeline; @Inject(method = "", at = @At(value = "INVOKE", @@ -86,13 +82,11 @@ private EffectProgram redirectShader(ResourceProvider resourceProvider, Program. */ @Overwrite public void close() { - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { uniform.close(); } - //TODO -// ProgramManager.releaseProgram(this); + this.pipeline.scheduleCleanUp(); } private void createShaders(ResourceProvider resourceManager, String vertexShader, String fragShader) { @@ -110,14 +104,13 @@ private void createShaders(ResourceProvider resourceManager, String vertexShader inputStream = resource.open(); String fshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - //TODO GlslConverter converter = new GlslConverter(); converter.process(vshSrc, fshSrc); UBO ubo = converter.createUBO(); this.setUniformSuppliers(ubo); - Pipeline.Builder builder = new Pipeline.Builder(DefaultVertexFormat.POSITION); + Pipeline.Builder builder = new Pipeline.Builder(DefaultVertexFormat.POSITION, this.name); builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); diff --git a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java index 63cc0fa944..640fa34f2e 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java @@ -204,9 +204,13 @@ public void reloadShaders(ResourceProvider provider, CallbackInfo ci) { pairs.add( Pair.of(new ShaderInstance(provider, "rendertype_eyes", DefaultVertexFormat.NEW_ENTITY), (shaderInstance) -> rendertypeEyesShader = shaderInstance)); + var energySwirlShader = new ShaderInstance(provider, "rendertype_energy_swirl", DefaultVertexFormat.NEW_ENTITY); pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_energy_swirl", DefaultVertexFormat.NEW_ENTITY), + Pair.of(energySwirlShader, (shaderInstance) -> rendertypeEnergySwirlShader = shaderInstance)); + pairs.add( + Pair.of(energySwirlShader, + (shaderInstance) -> rendertypeBreezeWindShader = shaderInstance)); pairs.add( Pair.of(new ShaderInstance(provider, "rendertype_leash", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP), (shaderInstance) -> rendertypeLeashShader = shaderInstance)); @@ -293,9 +297,6 @@ public void reloadShaders(ResourceProvider provider, CallbackInfo ci) { pairs.add( Pair.of(positionColor, (shaderInstance) -> rendertypeGuiGhostRecipeOverlayShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_energy_swirl", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeBreezeWindShader = shaderInstance)); // FRAPI shader loading CoreShaderRegistrationCallback.RegistrationContext context = (id, vertexFormat, loadCallback) -> { diff --git a/src/main/java/net/vulkanmod/mixin/render/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/LevelRendererMixin.java deleted file mode 100644 index f397ee81f5..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/LevelRendererMixin.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.google.gson.JsonSyntaxException; -import com.mojang.blaze3d.pipeline.RenderTarget; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.PostChain; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.io.IOException; - -@Mixin(LevelRenderer.class) -public abstract class LevelRendererMixin { - - @Shadow private @Nullable PostChain entityEffect; - - @Shadow @Final private Minecraft minecraft; - - @Shadow @Nullable private RenderTarget entityTarget; - - @Shadow @Final private static Logger LOGGER; - -// /** -// * @author -// */ -// @Overwrite -// public void initOutline() { -// if (this.entityEffect != null) { -// this.entityEffect.close(); -// } -// -//// ResourceLocation resourceLocation = new ResourceLocation("shaders/post/entity_outline.json"); -//// -//// try { -//// this.entityEffect = new PostChain(this.minecraft.getTextureManager(), this.minecraft.getResourceManager(), this.minecraft.getMainRenderTarget(), resourceLocation); -//// this.entityEffect.resize(this.minecraft.getWindow().getWidth(), this.minecraft.getWindow().getHeight()); -//// this.entityTarget = this.entityEffect.getTempTarget("final"); -//// } catch (IOException var3) { -//// LOGGER.warn("Failed to load shader: {}", resourceLocation, var3); -//// this.entityEffect = null; -//// this.entityTarget = null; -//// } catch (JsonSyntaxException var4) { -//// LOGGER.warn("Failed to parse shader: {}", resourceLocation, var4); -//// this.entityEffect = null; -//// this.entityTarget = null; -//// } -// } - -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java index cc4537bcdb..31a01f58f9 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java @@ -2,10 +2,9 @@ import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.vulkan.Vulkan; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.texture.ImageUtil; import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.texture.VulkanImage; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Final; @@ -91,7 +90,7 @@ public void downloadTexture(int level, boolean removeAlpha) { int v = MemoryUtil.memGetInt(this.pixels + l); //TODO - if(Vulkan.getSwapChain().isBGRAformat) + if(Renderer.getInstance().getSwapChain().isBGRAformat) v = ColorUtil.BGRAtoRGBA(v); v = v | 255 << this.format.alphaOffset(); diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 710c32ec01..97bca6f339 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -84,5 +84,6 @@ public static void destroyPipelines() { terrainShaderEarlyZ.cleanUp(); terrainShader.cleanUp(); fastBlitPipeline.cleanUp(); + cloudsPipeline.cleanUp(); } } diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 59fb23ba09..afc9f26bc1 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -49,7 +49,7 @@ public void upload(MeshData meshData) { private void uploadVertexBuffer(MeshData.DrawState parameters, ByteBuffer data) { if (data != null) { if (this.vertexBuffer != null) - this.vertexBuffer.freeBuffer(); + this.vertexBuffer.scheduleFree(); this.vertexBuffer = new VertexBuffer(data.remaining(), this.memoryType); this.vertexBuffer.copyToVertexBuffer(parameters.format().getVertexSize(), parameters.vertexCount(), data); @@ -85,7 +85,7 @@ public void uploadIndexBuffer(ByteBuffer data) { } if (this.indexBuffer != null && !this.autoIndexed) - this.indexBuffer.freeBuffer(); + this.indexBuffer.scheduleFree(); if (autoIndexBuffer != null) { autoIndexBuffer.checkCapacity(this.vertexCount); @@ -96,7 +96,7 @@ public void uploadIndexBuffer(ByteBuffer data) { } else { if (this.indexBuffer != null) - this.indexBuffer.freeBuffer(); + this.indexBuffer.scheduleFree(); this.indexBuffer = new IndexBuffer(data.remaining(), MemoryTypes.GPU_MEM); this.indexBuffer.copyBuffer(data); @@ -154,11 +154,11 @@ public void close() { if (this.vertexCount <= 0) return; - this.vertexBuffer.freeBuffer(); + this.vertexBuffer.scheduleFree(); this.vertexBuffer = null; if (!this.autoIndexed) { - this.indexBuffer.freeBuffer(); + this.indexBuffer.scheduleFree(); this.indexBuffer = null; } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 821282f3fb..907c0ca84b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -101,16 +101,13 @@ private WorldRenderer(RenderBuffers renderBuffers) { private void allocateIndirectBuffers() { if (this.indirectBuffers != null) - Arrays.stream(this.indirectBuffers).forEach(Buffer::freeBuffer); + Arrays.stream(this.indirectBuffers).forEach(Buffer::scheduleFree); this.indirectBuffers = new IndirectBuffer[Renderer.getFramesNum()]; for (int i = 0; i < this.indirectBuffers.length; ++i) { this.indirectBuffers[i] = new IndirectBuffer(1000000, MemoryTypes.HOST_MEM); -// this.indirectBuffers[i] = new IndirectBuffer(1000000, MemoryTypes.GPU_MEM); } - -// uniformBuffers = new UniformBuffers(100000, MemoryTypes.GPU_MEM); } public static WorldRenderer init(RenderBuffers renderBuffers) { @@ -197,7 +194,6 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus } this.indirectBuffers[Renderer.getCurrentFrame()].reset(); -// this.uniformBuffers.reset(); this.minecraft.getProfiler().pop(); profiler.pop(); @@ -466,7 +462,7 @@ public String getChunkStatistics() { public void cleanUp() { if (indirectBuffers != null) - Arrays.stream(indirectBuffers).forEach(Buffer::freeBuffer); + Arrays.stream(indirectBuffers).forEach(Buffer::scheduleFree); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java index 4eb65a7809..b7894b4244 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java @@ -115,7 +115,7 @@ public Segment reallocate(int uploadSize) { int oldSize = this.size; int minIncrement = this.size >> 3; - minIncrement = Util.align(minIncrement, this.elementSize); + minIncrement = (int) Util.align(minIncrement, this.elementSize); int increment = Math.max(minIncrement, uploadSize << 1); @@ -132,7 +132,7 @@ public Segment reallocate(int uploadSize) { // TODO: moving only used segments causes corruption // moveUsedSegments(dst); - this.buffer.freeBuffer(); + this.buffer.scheduleFree(); this.buffer = dst; if (last.isFree()) { @@ -267,7 +267,7 @@ public long getId() { } public void freeBuffer() { - this.buffer.freeBuffer(); + this.buffer.scheduleFree(); } public int fragmentation() { diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java index 9f14e3ccd7..ef9ab1e953 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java @@ -43,13 +43,12 @@ public void submitUploads() { } public void recordUpload(Buffer buffer, long dstOffset, long bufferSize, ByteBuffer src) { - beginCommands(); - - VkCommandBuffer commandBuffer = this.commandBuffer.getHandle(); - StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); stagingBuffer.copyBuffer((int) bufferSize, src); + beginCommands(); + VkCommandBuffer commandBuffer = this.commandBuffer.getHandle(); + if (!this.dstBuffers.add(buffer.getId())) { try (MemoryStack stack = MemoryStack.stackPush()) { VkMemoryBarrier.Buffer barrier = VkMemoryBarrier.calloc(1, stack); @@ -75,7 +74,7 @@ public void copyBuffer(Buffer src, Buffer dst) { copyBuffer(src, 0, dst, 0, src.getBufferSize()); } - public void copyBuffer(Buffer src, int srcOffset, Buffer dst, int dstOffset, int size) { + public void copyBuffer(Buffer src, long srcOffset, Buffer dst, long dstOffset, long size) { beginCommands(); VkCommandBuffer commandBuffer = this.commandBuffer.getHandle(); diff --git a/src/main/java/net/vulkanmod/render/chunk/util/Util.java b/src/main/java/net/vulkanmod/render/chunk/util/Util.java index c37ddd0ffb..caa063410a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/Util.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/Util.java @@ -44,11 +44,11 @@ public static int flooredLog(int v) { return log; } - public static int align(int i, int alignment) { + public static long align(long l, int alignment) { if (alignment == 0) - return i; + return l; - int r = i % alignment; - return r != 0 ? i + alignment - r : i; + long r = l % alignment; + return r != 0 ? l + alignment - r : l; } } diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 805d39baae..23f41b43a8 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -45,7 +45,6 @@ public class CloudRenderer { private byte prevCloudY; private CloudStatus prevCloudsType; - private boolean prevInsideClouds; private boolean generateClouds; private VBO cloudBuffer; @@ -169,7 +168,7 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); int renderDistance = 32; - boolean insideClouds = this.prevInsideClouds; + boolean insideClouds = this.prevCloudY == Y_INSIDE_CLOUDS; if (this.prevCloudsType == CloudStatus.FANCY) { diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index a749582880..add740f8c7 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -29,7 +29,7 @@ public static void transitionLayouts() { return; } - VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getCommandBuffer().handle; + VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer().handle; try (MemoryStack stack = MemoryStack.stackPush()) { transitionedLayouts.forEach(image -> image.readOnlyLayout(stack, commandBuffer)); diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index 999bd0ee50..e0fbea59f0 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -56,7 +56,7 @@ public void createResources(int framesNum) { if (this.vertexBuffers != null) { Arrays.stream(this.vertexBuffers).iterator().forEachRemaining( - Buffer::freeBuffer + Buffer::scheduleFree ); } this.vertexBuffers = new VertexBuffer[framesNum]; @@ -64,7 +64,7 @@ public void createResources(int framesNum) { if (this.indexBuffers != null) { Arrays.stream(this.indexBuffers).iterator().forEachRemaining( - Buffer::freeBuffer + Buffer::scheduleFree ); } this.indexBuffers = new IndexBuffer[framesNum]; @@ -72,7 +72,7 @@ public void createResources(int framesNum) { if (this.uniformBuffers != null) { Arrays.stream(this.uniformBuffers).iterator().forEachRemaining( - Buffer::freeBuffer + Buffer::scheduleFree ); } this.uniformBuffers = new UniformBuffer[framesNum]; @@ -154,8 +154,10 @@ public void cleanUpResources() { } this.quadsIndexBuffer.freeBuffer(); + this.quadsIntIndexBuffer.freeBuffer(); this.linesIndexBuffer.freeBuffer(); this.triangleFanIndexBuffer.freeBuffer(); + this.triangleStripIndexBuffer.freeBuffer(); this.debugLineStripIndexBuffer.freeBuffer(); } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index d09618c725..a58561db8a 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -14,6 +14,7 @@ import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; +import net.vulkanmod.vulkan.framebuffer.SwapChain; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.pass.DefaultMainPass; import net.vulkanmod.vulkan.pass.MainPass; @@ -80,8 +81,9 @@ public static int getCurrentImage() { private Drawer drawer; + private SwapChain swapChain; + private int framesNum; - private int imagesNum; private List commandBuffers; private ArrayList imageAvailableSemaphores; private ArrayList renderFinishedSemaphores; @@ -96,14 +98,13 @@ public static int getCurrentImage() { private VkCommandBuffer currentCmdBuffer; private boolean recordingCmds = false; - MainPass mainPass = DefaultMainPass.create(); + MainPass mainPass; private final List onResizeCallbacks = new ObjectArrayList<>(); public Renderer() { device = Vulkan.getVkDevice(); framesNum = Initializer.CONFIG.frameQueueSize; - imagesNum = getSwapChain().getImagesNum(); } public static void setLineWidth(float width) { @@ -117,6 +118,9 @@ private void init() { MemoryManager.createInstance(Renderer.getFramesNum()); Vulkan.createStagingBuffers(); + swapChain = new SwapChain(); + mainPass = DefaultMainPass.create(); + drawer = new Drawer(); drawer.createResources(framesNum); @@ -250,7 +254,7 @@ public void beginFrame() { IntBuffer pImageIndex = stack.mallocInt(1); - int vkResult = vkAcquireNextImageKHR(device, Vulkan.getSwapChain().getId(), VUtil.UINT64_MAX, + int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex); if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) { @@ -339,7 +343,7 @@ private void submitFrame() { presentInfo.pWaitSemaphores(stack.longs(renderFinishedSemaphores.get(currentFrame))); presentInfo.swapchainCount(1); - presentInfo.pSwapchains(stack.longs(Vulkan.getSwapChain().getId())); + presentInfo.pSwapchains(stack.longs(swapChain.getId())); presentInfo.pImageIndices(stack.ints(imageIndex)); @@ -465,18 +469,18 @@ private void recreateSwapChain() { commandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0)); - Vulkan.getSwapChain().recreate(); + swapChain.recreate(); //Semaphores need to be recreated in order to make them unsignaled destroySyncObjects(); int newFramesNum = Initializer.CONFIG.frameQueueSize; - imagesNum = getSwapChain().getImagesNum(); if (framesNum != newFramesNum) { UploadManager.INSTANCE.submitUploads(); framesNum = newFramesNum; + MemoryManager.getInstance().freeAllBuffers(); MemoryManager.createInstance(newFramesNum); createStagingBuffers(); allocateCommandBuffers(); @@ -495,9 +499,12 @@ private void recreateSwapChain() { } public void cleanUpResources() { + WorldRenderer.getInstance().cleanUp(); destroySyncObjects(); drawer.cleanUpResources(); + mainPass.cleanUp(); + swapChain.cleanUp(); PipelineManager.destroyPipelines(); VTextureSelector.getWhiteTexture().free(); @@ -511,26 +518,6 @@ private void destroySyncObjects() { } } - public void setBoundFramebuffer(Framebuffer framebuffer) { - this.boundFramebuffer = framebuffer; - } - - public void setBoundRenderPass(RenderPass boundRenderPass) { - this.boundRenderPass = boundRenderPass; - } - - public RenderPass getBoundRenderPass() { - return boundRenderPass; - } - - public void setMainPass(MainPass mainPass) { - this.mainPass = mainPass; - } - - public MainPass getMainPass() { - return this.mainPass; - } - public void addOnResizeCallback(Runnable runnable) { this.onResizeCallbacks.add(runnable); } @@ -575,6 +562,30 @@ public Pipeline getBoundPipeline() { return boundPipeline; } + public void setBoundFramebuffer(Framebuffer framebuffer) { + this.boundFramebuffer = framebuffer; + } + + public void setBoundRenderPass(RenderPass boundRenderPass) { + this.boundRenderPass = boundRenderPass; + } + + public RenderPass getBoundRenderPass() { + return boundRenderPass; + } + + public void setMainPass(MainPass mainPass) { + this.mainPass = mainPass; + } + + public MainPass getMainPass() { + return this.mainPass; + } + + public SwapChain getSwapChain() { + return swapChain; + } + private static void resetDynamicState(VkCommandBuffer commandBuffer) { vkCmdSetDepthBias(commandBuffer, 0.0F, 0.0F, 0.0F); @@ -681,8 +692,8 @@ public static void setViewport(int x, int y, int width, int height, MemoryStack public static void resetViewport() { try (MemoryStack stack = stackPush()) { - int width = getSwapChain().getWidth(); - int height = getSwapChain().getHeight(); + int width = INSTANCE.getSwapChain().getWidth(); + int height = INSTANCE.getSwapChain().getHeight(); VkViewport.Buffer viewport = VkViewport.malloc(1, stack); viewport.x(0.0f); diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 33c75fceab..ba60a3f984 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -9,7 +9,7 @@ import net.vulkanmod.vulkan.memory.StagingBuffer; import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.util.VUtil; +import net.vulkanmod.vulkan.texture.SamplerManager; import net.vulkanmod.vulkan.util.VkResult; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; @@ -125,8 +125,6 @@ public static long getAllocator() { private static long debugMessenger; private static long surface; - private static SwapChain swapChain; - private static long commandPool; private static VkCommandBuffer immediateCmdBuffer; private static long immediateFence; @@ -149,12 +147,9 @@ public static void initVulkan(long window) { MemoryTypes.createMemoryTypes(); createCommandPool(); - allocateImmediateCmdBuffer(); setupDepthFormat(); - createSwapChain(); Renderer.initRenderer(); - } static void createStagingBuffers() { @@ -165,7 +160,7 @@ static void createStagingBuffers() { stagingBuffers = new StagingBuffer[Renderer.getFramesNum()]; for (int i = 0; i < stagingBuffers.length; ++i) { - stagingBuffers[i] = new StagingBuffer(30 * 1024 * 1024); + stagingBuffers[i] = new StagingBuffer(); } } @@ -173,10 +168,6 @@ static void setupDepthFormat() { DEFAULT_DEPTH_FORMAT = DeviceManager.findDepthFormat(use24BitsDepthFormat); } - private static void createSwapChain() { - swapChain = new SwapChain(); - } - public static void waitIdle() { vkDeviceWaitIdle(DeviceManager.vkDevice); } @@ -189,7 +180,6 @@ public static void cleanUp() { Pipeline.destroyPipelineCache(); Renderer.getInstance().cleanUpResources(); - swapChain.cleanUp(); freeStagingBuffers(); @@ -201,6 +191,7 @@ public static void cleanUp() { vmaDestroyAllocator(allocator); + SamplerManager.cleanUp(); DeviceManager.destroy(); destroyDebugUtilsMessengerEXT(instance, debugMessenger, null); KHRSurface.vkDestroySurfaceKHR(instance, surface, null); @@ -208,7 +199,7 @@ public static void cleanUp() { } private static void freeStagingBuffers() { - Arrays.stream(stagingBuffers).forEach(Buffer::freeBuffer); + Arrays.stream(stagingBuffers).forEach(Buffer::scheduleFree); } private static void createInstance() { @@ -361,58 +352,6 @@ private static void createCommandPool() { } } - private static void allocateImmediateCmdBuffer() { - try (MemoryStack stack = stackPush()) { - - VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); - allocInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO); - allocInfo.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY); - allocInfo.commandPool(commandPool); - allocInfo.commandBufferCount(1); - - PointerBuffer pCommandBuffer = stack.mallocPointer(1); - vkAllocateCommandBuffers(DeviceManager.vkDevice, allocInfo, pCommandBuffer); - immediateCmdBuffer = new VkCommandBuffer(pCommandBuffer.get(0), DeviceManager.vkDevice); - - VkFenceCreateInfo fenceInfo = VkFenceCreateInfo.calloc(stack); - fenceInfo.sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); - fenceInfo.flags(VK_FENCE_CREATE_SIGNALED_BIT); - - LongBuffer pFence = stack.mallocLong(1); - vkCreateFence(DeviceManager.vkDevice, fenceInfo, null, pFence); - vkResetFences(DeviceManager.vkDevice, pFence.get(0)); - - immediateFence = pFence.get(0); - } - } - - public static VkCommandBuffer beginImmediateCmd() { - try (MemoryStack stack = stackPush()) { - VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack); - beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); - - vkBeginCommandBuffer(immediateCmdBuffer, beginInfo); - } - return immediateCmdBuffer; - } - - public static void endImmediateCmd() { - try (MemoryStack stack = stackPush()) { - vkEndCommandBuffer(immediateCmdBuffer); - - VkSubmitInfo submitInfo = VkSubmitInfo.calloc(stack); - submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO); - submitInfo.pCommandBuffers(stack.pointers(immediateCmdBuffer)); - - vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, immediateFence); - - vkWaitForFences(DeviceManager.vkDevice, immediateFence, true, VUtil.UINT64_MAX); - vkResetFences(DeviceManager.vkDevice, immediateFence); - vkResetCommandBuffer(immediateCmdBuffer, 0); - } - - } - private static PointerBuffer getRequiredInstanceExtensions() { PointerBuffer glfwExtensions = glfwGetRequiredInstanceExtensions(); @@ -440,6 +379,7 @@ public static void checkResult(int result, String errorMessage) { } public static void setVsync(boolean b) { + SwapChain swapChain = Renderer.getInstance().getSwapChain(); if (swapChain.isVsync() != b) { Renderer.scheduleSwapChainUpdate(); swapChain.setVsync(b); @@ -454,10 +394,6 @@ public static long getSurface() { return surface; } - public static SwapChain getSwapChain() { - return swapChain; - } - public static long getCommandPool() { return commandPool; } diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java index b5eb00b10b..116f419bfc 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java @@ -1,6 +1,5 @@ package net.vulkanmod.vulkan.framebuffer; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.Reference2LongArrayMap; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; @@ -34,9 +33,7 @@ public class Framebuffer { private VulkanImage colorAttachment; protected VulkanImage depthAttachment; - private final ObjectArrayList renderPasses = new ObjectArrayList<>(); - - private final Reference2LongArrayMap framebufferIds = new Reference2LongArrayMap<>(); + private final Reference2LongArrayMap renderpassToFramebufferMap = new Reference2LongArrayMap<>(); //SwapChain protected Framebuffer() {} @@ -59,10 +56,6 @@ public Framebuffer(Builder builder) { } } - public void addRenderPass(RenderPass renderPass) { - this.renderPasses.add(renderPass); - } - public void createImages() { if (this.hasColorAttachment) { this.colorAttachment = VulkanImage.builder(this.width, this.height) @@ -138,7 +131,7 @@ public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass } protected long getFramebufferId(RenderPass renderPass) { - return this.framebufferIds.computeIfAbsent(renderPass, renderPass1 -> createFramebuffer(renderPass)); + return this.renderpassToFramebufferMap.computeIfAbsent(renderPass, renderPass1 -> createFramebuffer(renderPass)); } public VkViewport.Buffer viewport(MemoryStack stack) { @@ -175,7 +168,7 @@ public void cleanUp(boolean cleanImages) { } final VkDevice device = Vulkan.getVkDevice(); - final var ids = framebufferIds.values().toLongArray(); + final var ids = renderpassToFramebufferMap.values().toLongArray(); MemoryManager.getInstance().addFrameOp( () -> Arrays.stream(ids).forEach(id -> @@ -183,7 +176,7 @@ public void cleanUp(boolean cleanImages) { ); - framebufferIds.clear(); + renderpassToFramebufferMap.clear(); } public long getDepthImageView() { diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java index 24cc8c0316..589f00c218 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java @@ -34,8 +34,6 @@ public RenderPass(Framebuffer framebuffer, AttachmentInfo colorAttachmentInfo, A this.attachmentCount = count; if (!Vulkan.DYNAMIC_RENDERING) { - framebuffer.addRenderPass(this); - createRenderPass(); } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java index 7ac57e683f..4ed088fecb 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java @@ -70,7 +70,7 @@ public void checkCapacity(int vertexCount) { int newVertexCount = this.vertexCount * 2; Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); - this.indexBuffer.freeBuffer(); + this.indexBuffer.scheduleFree(); createIndexBuffer(newVertexCount); } } @@ -200,7 +200,7 @@ public static int roundUpToDivisible(int n, int d) { public IndexBuffer getIndexBuffer() { return this.indexBuffer; } public void freeBuffer() { - this.indexBuffer.freeBuffer(); + this.indexBuffer.scheduleFree(); } public enum DrawType { diff --git a/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java b/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java index b0a558f41b..910592171c 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java @@ -1,18 +1,17 @@ package net.vulkanmod.vulkan.memory; -import org.lwjgl.PointerBuffer; - public abstract class Buffer { protected long id; protected long allocation; - protected int bufferSize; - protected int usedBytes; - protected int offset; + protected long bufferSize; + protected long usedBytes; + protected long offset; protected MemoryType type; protected int usage; - protected PointerBuffer data; + + protected long dataPtr; protected Buffer(int usage, MemoryType type) { //TODO: check usage @@ -21,37 +20,61 @@ protected Buffer(int usage, MemoryType type) { } - protected void createBuffer(int bufferSize) { + protected void createBuffer(long bufferSize) { this.type.createBuffer(this, bufferSize); - if(this.type.mappable()) { - this.data = MemoryManager.getInstance().Map(this.allocation); + if (this.type.mappable()) { + this.dataPtr = MemoryManager.getInstance().Map(this.allocation).get(0); } } - public void freeBuffer() { + public void scheduleFree() { MemoryManager.getInstance().addToFreeable(this); } - public void reset() { usedBytes = 0; } + public void reset() { + usedBytes = 0; + } - public long getAllocation() { return allocation; } + public long getAllocation() { + return allocation; + } - public long getUsedBytes() { return usedBytes; } + public long getUsedBytes() { + return usedBytes; + } + + public long getOffset() { + return offset; + } - public long getOffset() { return offset; } + public long getId() { + return id; + } - public long getId() { return id; } + public long getBufferSize() { + return bufferSize; + } - public int getBufferSize() { return bufferSize; } + public long getDataPtr() { + return dataPtr; + } - protected void setBufferSize(int size) { this.bufferSize = size; } + protected void setBufferSize(long size) { + this.bufferSize = size; + } - protected void setId(long id) { this.id = id; } + protected void setId(long id) { + this.id = id; + } - protected void setAllocation(long allocation) {this.allocation = allocation; } + protected void setAllocation(long allocation) { + this.allocation = allocation; + } - public BufferInfo getBufferInfo() { return new BufferInfo(this.id, this.allocation, this.bufferSize, this.type.getType()); } + public BufferInfo getBufferInfo() { + return new BufferInfo(this.id, this.allocation, this.bufferSize, this.type.getType()); + } public record BufferInfo(long id, long allocation, long bufferSize, MemoryType.Type type) { diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java index 8ec992eb11..7a96097b80 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java @@ -31,7 +31,7 @@ public void copyBuffer(ByteBuffer byteBuffer) { usedBytes += size; } - private void resizeBuffer(int newSize) { + private void resizeBuffer(long newSize) { MemoryManager.getInstance().addToFreeable(this); this.createBuffer(newSize); } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java index 811bddfb15..b39cb60689 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java @@ -43,7 +43,7 @@ public void recordCopyCmd(ByteBuffer byteBuffer) { private void resizeBuffer() { MemoryManager.getInstance().addToFreeable(this); - int newSize = this.bufferSize + (this.bufferSize >> 1); + long newSize = this.bufferSize + (this.bufferSize >> 1); this.createBuffer(newSize); this.usedBytes = 0; } @@ -57,8 +57,4 @@ public void submitUploads() { commandBuffer = null; } - //debug - public ByteBuffer getByteBuffer() { - return this.data.getByteBuffer(0, this.bufferSize); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java index a007bb1898..ba10692aa9 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java @@ -6,6 +6,7 @@ import net.vulkanmod.render.chunk.buffer.AreaBuffer; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.texture.VulkanImage; import net.vulkanmod.vulkan.util.Pair; import net.vulkanmod.vulkan.util.VkResult; @@ -43,11 +44,11 @@ public class MemoryManager { private int currentFrame = 0; - private ObjectArrayList[] freeableBuffers = new ObjectArrayList[Frames]; - private ObjectArrayList[] freeableImages = new ObjectArrayList[Frames]; + private final ObjectArrayList[] freeableBuffers = new ObjectArrayList[Frames]; + private final ObjectArrayList[] freeableImages = new ObjectArrayList[Frames]; - private ObjectArrayList[] frameOps = new ObjectArrayList[Frames]; - private ObjectArrayList>[] segmentsToFree = new ObjectArrayList[Frames]; + private final ObjectArrayList[] frameOps = new ObjectArrayList[Frames]; + private final ObjectArrayList>[] segmentsToFree = new ObjectArrayList[Frames]; //debug private ObjectArrayList[] stackTraces; @@ -82,6 +83,7 @@ public static void createInstance(int frames) { public synchronized void initFrame(int frame) { this.setCurrentFrame(frame); this.freeBuffers(frame); + this.freeImages(frame); this.doFrameOps(frame); this.freeSegments(frame); } @@ -94,6 +96,7 @@ public void setCurrentFrame(int frame) { public void freeAllBuffers() { for (int frame = 0; frame < Frames; ++frame) { this.freeBuffers(frame); + this.freeImages(frame); this.doFrameOps(frame); } @@ -124,8 +127,7 @@ public void createBuffer(long size, int usage, int properties, LongBuffer pBuffe } } - public synchronized void createBuffer(Buffer buffer, int size, int usage, int properties) { - + public synchronized void createBuffer(Buffer buffer, long size, int usage, int properties) { try (MemoryStack stack = stackPush()) { buffer.setBufferSize(size); @@ -137,9 +139,10 @@ public synchronized void createBuffer(Buffer buffer, int size, int usage, int pr buffer.setId(pBuffer.get(0)); buffer.setAllocation(pAllocation.get(0)); - if ((properties & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) > 0) { + if ((properties & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { deviceMemory += size; - } else { + } + else { nativeMemory += size; } @@ -147,11 +150,11 @@ public synchronized void createBuffer(Buffer buffer, int size, int usage, int pr } } - public static synchronized void createImage(int width, int height, int mipLevels, int format, int tiling, int usage, int memProperties, - LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { + public void createImage(int width, int height, int mipLevels, int format, int tiling, int usage, + int memProperties, + LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { try (MemoryStack stack = stackPush()) { - VkImageCreateInfo imageInfo = VkImageCreateInfo.calloc(stack); imageInfo.sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO); imageInfo.imageType(VK_IMAGE_TYPE_2D); @@ -166,19 +169,26 @@ public static synchronized void createImage(int width, int height, int mipLevels imageInfo.usage(usage); imageInfo.samples(VK_SAMPLE_COUNT_1_BIT); // imageInfo.sharingMode(VK_SHARING_MODE_CONCURRENT); - // TODO hardcoded queue family indices - imageInfo.pQueueFamilyIndices(stack.ints(0, 1)); + imageInfo.pQueueFamilyIndices( + stack.ints(Queue.getQueueFamilies().graphicsFamily, Queue.getQueueFamilies().computeFamily)); VmaAllocationCreateInfo allocationInfo = VmaAllocationCreateInfo.calloc(stack); allocationInfo.requiredFlags(memProperties); - vmaCreateImage(ALLOCATOR, imageInfo, allocationInfo, pTextureImage, pTextureImageMemory, null); + int result = vmaCreateImage(ALLOCATOR, imageInfo, allocationInfo, pTextureImage, pTextureImageMemory, null); + if (result != VK_SUCCESS) { + Initializer.LOGGER.info(String.format("Failed to create image with size: %dx%d", width, height)); + + throw new RuntimeException("Failed to create image: %s".formatted(VkResult.decode(result))); + } } } public static void addImage(VulkanImage image) { images.putIfAbsent(image.getId(), image); + + deviceMemory += image.size; } public static void MapAndCopy(long allocation, Consumer consumer) { @@ -210,17 +220,19 @@ private static void freeBuffer(Buffer.BufferInfo bufferInfo) { if (bufferInfo.type() == MemoryType.Type.DEVICE_LOCAL) { deviceMemory -= bufferInfo.bufferSize(); - } else { + } + else { nativeMemory -= bufferInfo.bufferSize(); } buffers.remove(bufferInfo.id()); } - public static void freeImage(long image, long allocation) { - vmaDestroyImage(ALLOCATOR, image, allocation); + public static void freeImage(long imageId, long allocation) { + vmaDestroyImage(ALLOCATOR, imageId, allocation); - images.remove(image); + VulkanImage image = images.remove(imageId); + deviceMemory -= image.size; } public synchronized void addToFreeable(Buffer buffer) { @@ -261,12 +273,10 @@ private void freeBuffers(int frame) { if (DEBUG) stackTraces[frame].clear(); - - this.freeImages(); } - private void freeImages() { - List bufferList = freeableImages[currentFrame]; + private void freeImages(int frame) { + List bufferList = freeableImages[frame]; for (VulkanImage image : bufferList) { image.doFree(); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java index 91380c0d65..68ab635f2c 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java @@ -16,7 +16,7 @@ public abstract class MemoryType { this.vkMemoryHeap = vkMemoryHeap; } - abstract void createBuffer(Buffer buffer, int size); + abstract void createBuffer(Buffer buffer, long size); abstract void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index c8fa7f475e..98f77d14ab 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -3,6 +3,7 @@ import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.util.VUtil; +import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkMemoryHeap; import org.lwjgl.vulkan.VkMemoryType; @@ -62,7 +63,7 @@ public static class DeviceLocalMemory extends MemoryType { } @Override - void createBuffer(Buffer buffer, int size) { + void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT); @@ -102,13 +103,14 @@ static abstract class MappableMemory extends MemoryType { } @Override - void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { - VUtil.memcpy(byteBuffer, buffer.data.getByteBuffer(0, (int) buffer.bufferSize), (int) bufferSize, buffer.getUsedBytes()); + void copyToBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { + VUtil.memcpy(byteBuffer, buffer, size); } @Override - void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { - VUtil.memcpy(buffer.data.getByteBuffer(0, (int) buffer.bufferSize), byteBuffer, 0); + void copyFromBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { + MemoryUtil.memCopy(buffer.getDataPtr(), MemoryUtil.memAddress(byteBuffer), size); + VUtil.memcpy(buffer, byteBuffer, size); } @Override @@ -124,23 +126,13 @@ static class HostLocalCachedMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, int size) { + void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); } - void copyToBuffer(Buffer buffer, long dstOffset, long bufferSize, ByteBuffer byteBuffer) { - VUtil.memcpy(byteBuffer, buffer.data.getByteBuffer((int) 0, (int) buffer.bufferSize), (int) bufferSize, dstOffset); - } - - void copyBuffer(Buffer src, Buffer dst) { - VUtil.memcpy(src.data.getByteBuffer(0, src.bufferSize), - dst.data.getByteBuffer(0, dst.bufferSize), src.bufferSize, 0); - -// copyBufferCmd(src.getId(), 0, dst.getId(), 0, src.bufferSize); - } } static class HostLocalFallbackMemory extends MappableMemory { @@ -150,7 +142,7 @@ static class HostLocalFallbackMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, int size) { + void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); @@ -164,7 +156,7 @@ static class DeviceMappableMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, int size) { + void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java index f903310874..6cb35d35fc 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java @@ -1,7 +1,9 @@ package net.vulkanmod.vulkan.memory; +import net.vulkanmod.render.chunk.buffer.UploadManager; import net.vulkanmod.render.chunk.util.Util; -import net.vulkanmod.vulkan.util.VUtil; +import net.vulkanmod.render.texture.ImageUploadHelper; +import net.vulkanmod.vulkan.Synchronization; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -10,44 +12,52 @@ import static org.lwjgl.vulkan.VK10.*; public class StagingBuffer extends Buffer { + private static final long DEFAULT_SIZE = 64 * 1024 * 1024; - public StagingBuffer(int bufferSize) { + public StagingBuffer() { + this(DEFAULT_SIZE); + } + + public StagingBuffer(long size) { super(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, MemoryTypes.HOST_MEM); this.usedBytes = 0; this.offset = 0; - this.createBuffer(bufferSize); + this.createBuffer(size); } public void copyBuffer(int size, ByteBuffer byteBuffer) { - - if(size > this.bufferSize - this.usedBytes) { - resizeBuffer((this.bufferSize + size) * 2); + if (size > this.bufferSize) { + throw new IllegalArgumentException("Upload size is greater than staging buffer size."); } -// VUtil.memcpy(byteBuffer, this.data.getByteBuffer(0, this.bufferSize), this.usedBytes); - nmemcpy(this.data.get(0) + this.usedBytes, MemoryUtil.memAddress(byteBuffer), size); + if (size > this.bufferSize - this.usedBytes) { + submitUploads(); + } - offset = usedBytes; - usedBytes += size; + nmemcpy(this.dataPtr + this.usedBytes, MemoryUtil.memAddress(byteBuffer), size); - //createVertexBuffer(vertexSize, vertexCount, byteBuffer); + this.offset = this.usedBytes; + this.usedBytes += size; } public void align(int alignment) { - int alignedValue = Util.align(usedBytes, alignment); + long alignedOffset = Util.align(usedBytes, alignment); - if(alignedValue > this.bufferSize) { - resizeBuffer((this.bufferSize) * 2); + if (alignedOffset > this.bufferSize) { + submitUploads(); + alignedOffset = 0; } - usedBytes = alignedValue; + this.usedBytes = alignedOffset; } - private void resizeBuffer(int newSize) { - MemoryManager.getInstance().addToFreeable(this); - this.createBuffer(newSize); + private void submitUploads() { + // Submit and wait all recorded uploads before resetting the buffer + UploadManager.INSTANCE.submitUploads(); + ImageUploadHelper.INSTANCE.submitCommands(); + Synchronization.INSTANCE.waitFences(); - System.out.println("resized staging buffer to: " + newSize); + this.reset(); } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java index fd6f80fe3b..d7c7368d45 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java @@ -28,12 +28,12 @@ public void updateOffset(int alignedSize) { usedBytes += alignedSize; } - private void resizeBuffer(int newSize) { + private void resizeBuffer(long newSize) { MemoryManager.getInstance().addToFreeable(this); createBuffer(newSize); } public long getPointer() { - return this.data.get(0) + usedBytes; + return this.dataPtr + usedBytes; } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java index 37f3ffc7f1..c1e66f8dc8 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java @@ -30,7 +30,7 @@ public void copyToVertexBuffer(long vertexSize, long vertexCount, ByteBuffer byt } - private void resizeBuffer(int newSize) { + private void resizeBuffer(long newSize) { MemoryManager.getInstance().addToFreeable(this); this.createBuffer(newSize); diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index 59b1c2afe6..f6c2e07a49 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -31,7 +31,7 @@ public static DefaultMainPass create() { DefaultMainPass() { this.mainTarget = Minecraft.getInstance().getMainRenderTarget(); - this.mainFramebuffer = Vulkan.getSwapChain(); + this.mainFramebuffer = Renderer.getInstance().getSwapChain(); createRenderPasses(); } @@ -55,7 +55,7 @@ private void createRenderPasses() { @Override public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { - SwapChain framebuffer = Vulkan.getSwapChain(); + SwapChain framebuffer = Renderer.getInstance().getSwapChain(); VulkanImage colorAttachment = framebuffer.getColorAttachment(); colorAttachment.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); @@ -74,7 +74,7 @@ public void end(VkCommandBuffer commandBuffer) { Renderer.getInstance().endRenderPass(commandBuffer); try(MemoryStack stack = MemoryStack.stackPush()) { - SwapChain framebuffer = Vulkan.getSwapChain(); + SwapChain framebuffer = Renderer.getInstance().getSwapChain(); framebuffer.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); } @@ -84,8 +84,14 @@ public void end(VkCommandBuffer commandBuffer) { } } + @Override + public void cleanUp() { + this.mainRenderPass.cleanUp(); + this.auxRenderPass.cleanUp(); + } + public void rebindMainTarget() { - SwapChain swapChain = Vulkan.getSwapChain(); + SwapChain swapChain = Renderer.getInstance().getSwapChain(); VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); // Do not rebind if the framebuffer is already bound @@ -103,7 +109,7 @@ public void rebindMainTarget() { @Override public void bindAsTexture() { - SwapChain swapChain = Vulkan.getSwapChain(); + SwapChain swapChain = Renderer.getInstance().getSwapChain(); VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); // Check if render pass is using the framebuffer @@ -119,7 +125,7 @@ public void bindAsTexture() { } public int getColorAttachmentGlId() { - SwapChain swapChain = Vulkan.getSwapChain(); + SwapChain swapChain = Renderer.getInstance().getSwapChain(); return swapChain.getColorAttachmentGlId(); } } diff --git a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java index d62476f0b8..f84b52daf2 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java @@ -11,6 +11,8 @@ public interface MainPass { void end(VkCommandBuffer commandBuffer); + void cleanUp(); + default void mainTargetBindWrite() {} default void mainTargetUnbindWrite() {} diff --git a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java index 0558a012fd..d6de2982e8 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java @@ -90,6 +90,7 @@ public void addToAvailable(CommandBuffer commandBuffer) { public void cleanUp() { for (CommandBuffer commandBuffer : commandBuffers) { vkDestroyFence(Vulkan.getVkDevice(), commandBuffer.fence, null); + vkDestroySemaphore(Vulkan.getVkDevice(), commandBuffer.semaphore, null); } vkResetCommandPool(Vulkan.getVkDevice(), id, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT); vkDestroyCommandPool(Vulkan.getVkDevice(), id, null); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index 0d0b30c2c4..c2775d05ea 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -18,13 +18,13 @@ import static org.lwjgl.vulkan.VK10.*; public abstract class Queue { - private static VkDevice DEVICE; - + private static VkDevice device; private static QueueFamilyIndices queueFamilyIndices; - protected CommandPool commandPool; private final VkQueue queue; + protected CommandPool commandPool; + public synchronized CommandPool.CommandBuffer beginCommands() { try (MemoryStack stack = stackPush()) { CommandPool.CommandBuffer commandBuffer = this.commandPool.getCommandBuffer(stack); @@ -77,11 +77,11 @@ public enum Family { } public static QueueFamilyIndices getQueueFamilies() { - if (DEVICE == null) - DEVICE = Vulkan.getVkDevice(); + if (device == null) + device = Vulkan.getVkDevice(); if (queueFamilyIndices == null) { - queueFamilyIndices = findQueueFamilies(DEVICE.getPhysicalDevice()); + queueFamilyIndices = findQueueFamilies(device.getPhysicalDevice()); } return queueFamilyIndices; } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java index 179ce47b31..e4e74043a5 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -164,10 +164,15 @@ private long createGraphicsPipeline(PipelineState state) { VkPipelineDynamicStateCreateInfo dynamicStates = VkPipelineDynamicStateCreateInfo.calloc(stack); dynamicStates.sType(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); - if (topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || polygonMode == VK_POLYGON_MODE_LINE) - dynamicStates.pDynamicStates(stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH)); - else - dynamicStates.pDynamicStates(stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR)); + if (topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || polygonMode == VK_POLYGON_MODE_LINE) { + dynamicStates.pDynamicStates( + stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_LINE_WIDTH)); + } + else { + dynamicStates.pDynamicStates( + stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR)); + } VkGraphicsPipelineCreateInfo.Buffer pipelineInfo = VkGraphicsPipelineCreateInfo.calloc(1, stack); pipelineInfo.sType(VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO); @@ -199,9 +204,8 @@ private long createGraphicsPipeline(PipelineState state) { LongBuffer pGraphicsPipeline = stack.mallocLong(1); - if (vkCreateGraphicsPipelines(DeviceManager.vkDevice, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline) != VK_SUCCESS) { - throw new RuntimeException("Failed to create graphics pipeline"); - } + Vulkan.checkResult(vkCreateGraphicsPipelines(DeviceManager.vkDevice, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline), + "Failed to create graphics pipeline " + this.name); return pGraphicsPipeline.get(0); } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index c3daa8b908..f0b681e747 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -28,6 +28,15 @@ public class VulkanImage { private static final VkDevice DEVICE = Vulkan.getVkDevice(); + public final int format; + public final int aspect; + public final int mipLevels; + public final int width; + public final int height; + public final int formatSize; + public final int usage; + public final int size; + private long id; private long allocation; private long mainImageView; @@ -36,14 +45,6 @@ public class VulkanImage { private long sampler; - public final int format; - public final int aspect; - public final int mipLevels; - public final int width; - public final int height; - public final int formatSize; - private final int usage; - private int currentLayout; //Used for swap chain images @@ -59,6 +60,8 @@ public VulkanImage(long id, int format, int mipLevels, int width, int height, in this.usage = usage; this.aspect = getAspect(this.format); + this.size = width * height * formatSize; + this.sampler = SamplerManager.getTextureSampler((byte) this.mipLevels, (byte) 0); } @@ -70,12 +73,14 @@ private VulkanImage(Builder builder) { this.format = builder.format; this.usage = builder.usage; this.aspect = getAspect(this.format); + + this.size = width * height * formatSize; } public static VulkanImage createTextureImage(Builder builder) { VulkanImage image = new VulkanImage(builder); - image.createImage(builder.mipLevels, builder.width, builder.height, builder.format, builder.usage); + image.createImage(); image.mainImageView = createImageView(image.id, builder.format, image.aspect, builder.mipLevels); image.sampler = SamplerManager.getTextureSampler(builder.mipLevels, builder.samplerFlags); @@ -120,14 +125,12 @@ public static VulkanImage createWhiteTexture() { } } - private void createImage(int mipLevels, int width, int height, int format, int usage) { - + private void createImage() { try (MemoryStack stack = stackPush()) { - LongBuffer pTextureImage = stack.mallocLong(1); PointerBuffer pAllocation = stack.pointers(0L); - MemoryManager.createImage(width, height, mipLevels, + MemoryManager.getInstance().createImage(width, height, mipLevels, format, VK_IMAGE_TILING_OPTIMAL, usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, @@ -192,19 +195,30 @@ public static long createImageView(long image, int format, int aspectFlags, int } public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { - long imageSize = buffer.limit(); + long uploadSize = buffer.limit(); - CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); - try (MemoryStack stack = stackPush()) { - transferDstLayout(stack, commandBuffer.getHandle()); + StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - stagingBuffer.align(this.formatSize); + // Use a temporary staging buffer if the upload size is greater than + // the default staging buffer + if (uploadSize > stagingBuffer.getBufferSize()) { + stagingBuffer = new StagingBuffer(uploadSize); + stagingBuffer.scheduleFree(); + } + + stagingBuffer.align(this.formatSize); + stagingBuffer.copyBuffer((int) uploadSize, buffer); + + long bufferId = stagingBuffer.getId(); - stagingBuffer.copyBuffer((int) imageSize, buffer); + VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer().getHandle(); + try (MemoryStack stack = stackPush()) { + transferDstLayout(stack, commandBuffer); + + final int srcOffset = (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize); - ImageUtil.copyBufferToImageCmd(stack, commandBuffer.getHandle(), stagingBuffer.getId(), id, mipLevel, width, height, xOffset, yOffset, - (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize), unpackRowLength, height); + ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, + srcOffset, unpackRowLength, height); } } @@ -504,8 +518,8 @@ private static int formatSize(int format) { VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT -> 4; case VK_FORMAT_R8_UNORM -> 1; -// default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); - default -> 0; + default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); +// default -> 0; }; } } diff --git a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java index 46ffadeb39..9b31ee3a54 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java @@ -1,5 +1,6 @@ package net.vulkanmod.vulkan.util; +import net.vulkanmod.vulkan.memory.Buffer; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; @@ -7,12 +8,13 @@ import java.lang.reflect.Field; import java.nio.ByteBuffer; -import java.nio.FloatBuffer; import java.util.Collection; import static org.lwjgl.system.MemoryStack.stackGet; public class VUtil { + public static final boolean CHECKS = true; + public static final int UINT32_MAX = 0xFFFFFFFF; public static final long UINT64_MAX = 0xFFFFFFFFFFFFFFFFL; @@ -43,74 +45,34 @@ public static PointerBuffer asPointerBuffer(Collection collection) { return buffer.rewind(); } - public static void memcpy(ByteBuffer buffer, short[] indices) { - - for(short index : indices) { - buffer.putShort(index); - } - - buffer.rewind(); - } - - public static void memcpy(ByteBuffer buffer, short[] indices, long offset) { - buffer.position((int) offset); - - for(short index : indices) { - buffer.putShort(index); - } - - buffer.rewind(); - } - - public static void memcpy(ByteBuffer src, ByteBuffer dst) { - MemoryUtil.memCopy(src, dst); - src.limit(src.capacity()).rewind(); - } - public static void memcpy(ByteBuffer src, long dstPtr) { MemoryUtil.memCopy(MemoryUtil.memAddress0(src), dstPtr, src.capacity()); } - public static void memcpy(ByteBuffer src, ByteBuffer dst, long offset) { - dst.position((int)offset); - - MemoryUtil.memCopy(src, dst); - src.limit(src.capacity()).rewind(); - } + public static void memcpy(ByteBuffer src, Buffer dst, long size) { + if (CHECKS) { + if (size > dst.getBufferSize() - dst.getUsedBytes()) { + throw new IllegalArgumentException("Upload size is greater than available dst buffer size"); + } + } - public static void memcpy(ByteBuffer src, ByteBuffer dst, int size, long offset) { - dst.position((int)offset); - src.limit(size); + final long srcPtr = MemoryUtil.memAddress(src); + final long dstPtr = dst.getDataPtr() + dst.getUsedBytes(); - MemoryUtil.memCopy(src, dst); - src.limit(src.capacity()).rewind(); + MemoryUtil.memCopy(srcPtr, dstPtr, size); } - public static void memcpyImage(ByteBuffer dst, ByteBuffer src, int width, int height, int channels, int unpackSkipRows, int unpackSkipPixels, int unpackRowLenght) { - int offset = (unpackSkipRows * unpackRowLenght + unpackSkipPixels) * channels; - for (int i = 0; i < height; ++i) { - src.limit(offset + width * channels); - src.position(offset); - dst.put(src); - offset += unpackRowLenght * channels; + public static void memcpy(Buffer src, ByteBuffer dst, long size) { + if (CHECKS) { + if (size > dst.remaining()) { + throw new IllegalArgumentException("Upload size is greater than available dst buffer size"); + } } - } - public static void memcpy(ByteBuffer buffer, FloatBuffer floatBuffer) { - while(floatBuffer.hasRemaining()) { - float f = floatBuffer.get(); - buffer.putFloat(f); - } - floatBuffer.position(0); - } + final long srcPtr = src.getDataPtr(); + final long dstPtr = MemoryUtil.memAddress(dst); - public static void memcpy(ByteBuffer buffer, FloatBuffer floatBuffer, long offset) { - buffer.position((int) offset); - while(floatBuffer.hasRemaining()) { - float f = floatBuffer.get(); - buffer.putFloat(f); - } - floatBuffer.position(0); + MemoryUtil.memCopy(srcPtr, dstPtr, size); } public static int align(int x, int align) { diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index f37e232b18..ebbf80f7d7 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -42,7 +42,6 @@ "render.GameRendererMixin", "render.GlProgramManagerMixin", "render.GlStateManagerM", - "render.LevelRendererMixin", "render.MinecraftMixin", "render.RenderSystemMixin", "render.RenderTypeM", From 3cfe47849f63077f6027140fdae3cc41baedbeb0 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 24 Nov 2024 12:32:15 +0100 Subject: [PATCH 031/177] Fix crash when clouds mesh is empty --- .../mixin/render/clouds/LevelRendererM.java | 3 +-- .../net/vulkanmod/render/sky/CloudRenderer.java | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index a885536d1d..a5680870ac 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -3,7 +3,6 @@ import com.mojang.blaze3d.vertex.*; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.*; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.sky.CloudRenderer; @@ -37,7 +36,7 @@ public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f proje @Inject(method = "allChanged", at = @At("RETURN")) private void onAllChanged(CallbackInfo ci) { if (this.cloudRenderer != null) { - this.cloudRenderer.reset(); + this.cloudRenderer.resetBuffer(); } } diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 23f41b43a8..80e14fdef5 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -102,12 +102,22 @@ else if (centerY > 0.0f) { this.cloudBuffer.close(); } - this.cloudBuffer = new VBO(VertexBuffer.Usage.STATIC); + this.resetBuffer(); MeshData cloudsMesh = this.buildClouds(Tesselator.getInstance(), centerCellX, centerCellZ, centerY); + + if (cloudsMesh == null) { + return; + } + + this.cloudBuffer = new VBO(VertexBuffer.Usage.STATIC); this.cloudBuffer.upload(cloudsMesh); } + if (this.cloudBuffer == null) { + return; + } + FogRenderer.levelFogColor(); float xTranslation = (float) (centerX - (centerCellX * CELL_WIDTH)); @@ -151,7 +161,7 @@ else if (centerY > 0.0f) { poseStack.popPose(); } - public void reset() { + public void resetBuffer() { if (this.cloudBuffer != null) { this.cloudBuffer.close(); this.cloudBuffer = null; @@ -159,7 +169,6 @@ public void reset() { } private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerCellZ, double cloudY) { - final int upFaceColor = ColorUtil.RGBA.pack(1.0f, 1.0f, 1.0f, 1.0f); final int xDirColor = ColorUtil.RGBA.pack(0.9f, 0.9f, 0.9f, 1.0f); final int downFaceColor = ColorUtil.RGBA.pack(0.7f, 0.7f, 0.7f, 1.0f); @@ -246,7 +255,7 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC } } - return bufferBuilder.buildOrThrow(); + return bufferBuilder.build(); } private static void putVertex(BufferBuilder bufferBuilder, float x, float y, float z, int color) { From 100fde1fcf13e838ee48e84f8a571929dd6556d0 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 24 Nov 2024 12:32:44 +0100 Subject: [PATCH 032/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index d0a493533a..459f2a8bbd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version=0.16.5 fabric_version=0.102.0+1.21 # Mod Properties -mod_version = 0.5.0_dev +mod_version = 0.5.1-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21 From 1bbd0accbe882b9189c40ed4869e945aff4d44d1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 24 Nov 2024 16:40:30 +0100 Subject: [PATCH 033/177] Use non cached memory type --- .../java/net/vulkanmod/vulkan/memory/MemoryTypes.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 98f77d14ab..72fc7546e4 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -27,7 +27,7 @@ public static void createMemoryTypes() { } if (propertyFlags == (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { - HOST_MEM = new HostLocalCachedMemory(memoryType, heap); + HOST_MEM = new HostCoherentMemory(memoryType, heap); } } @@ -119,18 +119,17 @@ boolean mappable() { } } - static class HostLocalCachedMemory extends MappableMemory { + static class HostCoherentMemory extends MappableMemory { - HostLocalCachedMemory(VkMemoryType vkMemoryType, VkMemoryHeap vkMemoryHeap) { + HostCoherentMemory(VkMemoryType vkMemoryType, VkMemoryHeap vkMemoryHeap) { super(Type.HOST_LOCAL, vkMemoryType, vkMemoryHeap); } @Override void createBuffer(Buffer buffer, long size) { - MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } } From 349de864a7feaab88fa0fb35737c27e17d92b5ce Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:39:19 +0100 Subject: [PATCH 034/177] Use level renderer light values to improve compatibility --- .../build/light/data/ArrayLightDataCache.java | 4 +- .../build/light/data/LightDataAccess.java | 64 +++++++++++-------- .../build/light/flat/FlatLightPipeline.java | 2 +- .../light/smooth/NewSmoothLightPipeline.java | 2 +- .../light/smooth/SmoothLightPipeline.java | 2 +- 5 files changed, 41 insertions(+), 33 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java index 74e9a2b9ca..3e23dcc5cb 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/ArrayLightDataCache.java @@ -25,7 +25,7 @@ public ArrayLightDataCache() { } public void reset(BlockAndTintGetter blockAndTintGetter, int x, int y, int z) { - this.world = blockAndTintGetter; + this.region = blockAndTintGetter; this.xOffset = x - NEIGHBOR_BLOCK_RADIUS; this.yOffset = y - NEIGHBOR_BLOCK_RADIUS; @@ -35,7 +35,7 @@ public void reset(BlockAndTintGetter blockAndTintGetter, int x, int y, int z) { } public void reset(BlockAndTintGetter blockAndTintGetter, BlockPos origin) { - this.world = blockAndTintGetter; + this.region = blockAndTintGetter; this.xOffset = origin.getX() - NEIGHBOR_BLOCK_RADIUS; this.yOffset = origin.getY() - NEIGHBOR_BLOCK_RADIUS; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java index ff0ad86d4d..1312b46715 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java @@ -5,7 +5,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.LightLayer; -import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.VoxelShape; import net.vulkanmod.Initializer; @@ -16,10 +15,10 @@ /** * The light data cache is used to make accessing the light data and occlusion properties of blocks cheaper. The data * for each block is stored as an integer with packed fields in order to work around the lack of value types in Java. - * + *

* This code is not very pretty, but it does perform significantly faster than the vanilla implementation and has * good cache locality. - * + *

* Each integer contains the following fields: * - BL: World block light, encoded as a 4-bit unsigned integer * - SL: World sky light, encoded as a 4-bit unsigned integer @@ -29,7 +28,7 @@ * - OP: Block opacity test, true if opaque * - FO: Full cube opacity test, true if opaque full cube * - FC: Full cube test, true if full cube - * + *

* You can use the various static pack/unpack methods to extract these values in a usable format. */ public abstract class LightDataAccess { @@ -45,7 +44,7 @@ public abstract class LightDataAccess { private static final float AO_INV = 1.0f / 2048.0f; private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); - protected BlockAndTintGetter world; + protected BlockAndTintGetter region; final boolean subBlockLighting; @@ -55,14 +54,14 @@ protected LightDataAccess() { public int get(int x, int y, int z, SimpleDirection d1, SimpleDirection d2) { return this.get(x + d1.getStepX() + d2.getStepX(), - y + d1.getStepY() + d2.getStepY(), - z + d1.getStepZ() + d2.getStepZ()); + y + d1.getStepY() + d2.getStepY(), + z + d1.getStepZ() + d2.getStepZ()); } public int get(int x, int y, int z, SimpleDirection dir) { return this.get(x + dir.getStepX(), - y + dir.getStepY(), - z + dir.getStepZ()); + y + dir.getStepY(), + z + dir.getStepZ()); } public int get(BlockPos pos, SimpleDirection dir) { @@ -81,19 +80,18 @@ public int get(BlockPos pos) { protected int compute(int x, int y, int z) { BlockPos pos = this.pos.set(x, y, z); + BlockState state = region.getBlockState(pos); - BlockState state = world.getBlockState(pos); - - boolean em = state.emissiveRendering(world, pos); + boolean em = state.emissiveRendering(region, pos); boolean op; - if(this.subBlockLighting) + if (this.subBlockLighting) op = state.canOcclude(); else - op = state.isViewBlocking(world, pos) && state.getLightBlock(world, pos) != 0; + op = state.isViewBlocking(region, pos) && state.getLightBlock(region, pos) != 0; - boolean fo = state.isSolidRender(world, pos); - boolean fc = state.isCollisionShapeFullBlock(world, pos); + boolean fo = state.isSolidRender(region, pos); + boolean fc = state.isCollisionShapeFullBlock(region, pos); int lu = state.getLightEmission(); @@ -103,16 +101,25 @@ protected int compute(int x, int y, int z) { if (fo && lu == 0) { bl = 0; sl = 0; - } else { - bl = world.getBrightness(LightLayer.BLOCK, pos); - sl = world.getBrightness(LightLayer.SKY, pos); + } + else { + if (em) { + bl = region.getBrightness(LightLayer.BLOCK, pos); + sl = region.getBrightness(LightLayer.SKY, pos); + } + else { + int light = LevelRenderer.getLightColor(region, state, pos); + bl = LightTexture.block(light); + sl = LightTexture.sky(light); + } } // FIX: Do not apply AO from blocks that emit light float ao; if (lu == 0) { - ao = state.getShadeBrightness(world, pos); - } else { + ao = state.getShadeBrightness(region, pos); + } + else { ao = 1.0f; } @@ -121,12 +128,12 @@ protected int compute(int x, int y, int z) { bl = Math.max(bl, lu); int crs = (fo || fc) && lu == 0 && useAo ? 0xFF : 0; - if(!fo && op) { - VoxelShape shape = state.getShape(world, pos); - crs = ((VoxelShapeExtended)(shape)).getCornerOcclusion(); + if (!fo && op) { + VoxelShape shape = state.getShape(region, pos); + crs = ((VoxelShapeExtended) (shape)).getCornerOcclusion(); } - return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packCO(crs) | packAO(ao) | packSL(sl) | packBL(bl); + return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packCO(crs) | packAO(ao) | packSL(sl) | packBL(bl); } public static int packBL(int blockLight) { @@ -210,12 +217,13 @@ public static int getLightmap(int word) { public static int getEmissiveLightmap(int word) { if (unpackEM(word)) { return LightTexture.FULL_BRIGHT; - } else { + } + else { return getLightmap(word); } } - public BlockAndTintGetter getWorld() { - return this.world; + public BlockAndTintGetter getRegion() { + return this.region; } } \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java index ac350f6933..b11f4e3522 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java @@ -47,7 +47,7 @@ public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direc } Arrays.fill(out.lm, lightmap); - Arrays.fill(out.br, this.lightCache.getWorld().getShade(lightFace, shade)); + Arrays.fill(out.br, this.lightCache.getRegion().getShade(lightFace, shade)); } private int getLightmap(BlockPos pos, Direction face) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java index 45ff919c5d..503d27ff97 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java @@ -229,7 +229,7 @@ private void applyInsetPartialFaceVertexSO(BlockPos pos, SimpleDirection dir, fl } private void applySidedBrightness(QuadLightData out, Direction face, boolean shade) { - float brightness = this.lightCache.getWorld().getShade(face, shade); + float brightness = this.lightCache.getRegion().getShade(face, shade); float[] br = out.br; for (int i = 0; i < br.length; i++) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java index b33d6cf3ae..154eb0518a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java @@ -220,7 +220,7 @@ private void applyInsetPartialFaceVertex(BlockPos pos, SimpleDirection dir, floa } private void applySidedBrightness(QuadLightData out, Direction face, boolean shade) { - float brightness = this.lightCache.getWorld().getShade(face, shade); + float brightness = this.lightCache.getRegion().getShade(face, shade); float[] br = out.br; for (int i = 0; i < br.length; i++) { From 1139f7d5b59e7cebf6bb98a6998d259a38b14767 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:40:47 +0100 Subject: [PATCH 035/177] Set bound framebuffer on begin rendering - Fixes null pointer exception --- src/main/java/net/vulkanmod/gl/GlFramebuffer.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java index 6b3ca17c1a..457a94e58e 100644 --- a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java @@ -39,6 +39,7 @@ public static void beginRendering(GlFramebuffer glFramebuffer) { VRenderSystem.disableCull(); boundId = glFramebuffer.id; + boundFramebuffer = glFramebuffer; } public static int genFramebufferId() { @@ -106,6 +107,9 @@ public static void framebufferTexture2D(int target, int attachment, int texTarge throw new UnsupportedOperationException(); } + if (boundFramebuffer == null) + System.nanoTime(); + boundFramebuffer.setAttachmentTexture(attachment, texture); } From 4c47fb6dc5d4406e3a7e18e8ef64e14d0bfab7a1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:41:53 +0100 Subject: [PATCH 036/177] Improve mixin compatibility --- .../mixin/texture/update/MLightTexture.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java index 81e47a432e..5cfadf94b7 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java @@ -51,18 +51,16 @@ public void turnOnLightLayer() { RenderSystem.setShaderTexture(2, this.lightTexture.getId()); } - /** - * @author - * @reason - */ @SuppressWarnings("UnreachableCode") - @Overwrite - public void updateLightTexture(float partialTicks) { + @Inject(method = "updateLightTexture", at = @At("HEAD"), cancellable = true) + public void updateLightTexture(float partialTicks, CallbackInfo ci) { if (this.updateLightTexture) { this.updateLightTexture = false; this.minecraft.getProfiler().push("lightTex"); + // TODO: Other mods might be changing lightmap behaviour, we can't be aware of that here + ClientLevel clientLevel = this.minecraft.level; if (clientLevel != null) { float skyDarken = clientLevel.getSkyDarken(1.0F); @@ -169,6 +167,8 @@ public void updateLightTexture(float partialTicks) { this.minecraft.getProfiler().pop(); } } + + ci.cancel(); } @Unique From 868bbf1d64d4062beaad42452f74caedb4ad124e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:42:56 +0100 Subject: [PATCH 037/177] Reset blend function before drawing --- src/main/java/net/vulkanmod/render/sky/CloudRenderer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 80e14fdef5..c7e3d3b4db 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -135,6 +135,7 @@ else if (centerY > 0.0f) { GraphicsPipeline pipeline = PipelineManager.getCloudsPipeline(); RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); RenderSystem.enableDepthTest(); boolean fastClouds = this.prevCloudsType == CloudStatus.FAST; From 3f37e93f01b9c5aa367ed25c4cd4969757e2a883 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 16:42:13 +0100 Subject: [PATCH 038/177] Improve framebuffer compatibility - Implement blit method --- .../java/net/vulkanmod/gl/GlFramebuffer.java | 88 +++++++++---------- .../mixin/compatibility/gl/GL30M.java | 10 +++ .../mixin/render/target/MainTargetMixin.java | 2 + .../vulkanmod/vulkan/texture/ImageUtil.java | 39 ++++++++ 4 files changed, 91 insertions(+), 48 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java index 457a94e58e..b61995a00d 100644 --- a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/GlFramebuffer.java @@ -7,6 +7,7 @@ import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; +import net.vulkanmod.vulkan.texture.ImageUtil; import net.vulkanmod.vulkan.texture.VulkanImage; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -15,47 +16,42 @@ import static org.lwjgl.vulkan.VK11.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; public class GlFramebuffer { - private static int ID_COUNTER = 1; + private static int idCounter = 1; + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); - private static int boundId = 0; private static GlFramebuffer boundFramebuffer; + private static GlFramebuffer readFramebuffer; public static void resetBoundFramebuffer() { boundFramebuffer = null; - boundId = 0; } public static void beginRendering(GlFramebuffer glFramebuffer) { - Renderer.getInstance().beginRendering(glFramebuffer.renderPass, glFramebuffer.framebuffer); + boolean begunRendering = glFramebuffer.beginRendering(); - Framebuffer framebuffer = glFramebuffer.framebuffer; - int viewWidth = framebuffer.getWidth(); - int viewHeight = framebuffer.getHeight(); + if (begunRendering) { + Framebuffer framebuffer = glFramebuffer.framebuffer; + int viewWidth = framebuffer.getWidth(); + int viewHeight = framebuffer.getHeight(); - Renderer.setInvertedViewport(0, 0, viewWidth, viewHeight); - Renderer.setScissor(0, 0, viewWidth, viewHeight); + Renderer.setInvertedViewport(0, 0, viewWidth, viewHeight); + Renderer.setScissor(0, 0, viewWidth, viewHeight); - // TODO: invert cull instead of disabling - VRenderSystem.disableCull(); + // TODO: invert cull instead of disabling + VRenderSystem.disableCull(); + } - boundId = glFramebuffer.id; boundFramebuffer = glFramebuffer; } public static int genFramebufferId() { - int id = ID_COUNTER; + int id = idCounter; map.put(id, new GlFramebuffer(id)); - ID_COUNTER++; + idCounter++; return id; } public static void bindFramebuffer(int target, int id) { - // target - // 36160 GL_FRAMEBUFFER - // 36161 GL_RENDERBUFFER - - if (boundId == id) - return; if (id == 0) { Renderer.getInstance().endRenderPass(); @@ -66,7 +62,6 @@ public static void bindFramebuffer(int target, int id) { } boundFramebuffer = null; - boundId = 0; return; } @@ -75,11 +70,19 @@ public static void bindFramebuffer(int target, int id) { if (glFramebuffer == null) throw new NullPointerException("No Framebuffer with ID: %d ".formatted(id)); - if (glFramebuffer.framebuffer != null) { - beginRendering(glFramebuffer); + switch (target) { + case GL30.GL_DRAW_FRAMEBUFFER , GL30.GL_FRAMEBUFFER -> { + if (glFramebuffer.framebuffer != null) { + beginRendering(glFramebuffer); + } + + boundFramebuffer = glFramebuffer; + } + case GL30.GL_READ_FRAMEBUFFER -> { + readFramebuffer = glFramebuffer; + } } - boundFramebuffer = glFramebuffer; } public static void deleteFramebuffer(int id) { @@ -107,9 +110,6 @@ public static void framebufferTexture2D(int target, int attachment, int texTarge throw new UnsupportedOperationException(); } - if (boundFramebuffer == null) - System.nanoTime(); - boundFramebuffer.setAttachmentTexture(attachment, texture); } @@ -120,6 +120,11 @@ public static void framebufferRenderbuffer(int target, int attachment, int rende boundFramebuffer.setAttachmentRenderbuffer(attachment, renderbuffer); } + public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + // TODO: add missing parameters + ImageUtil.blitFramebuffer(boundFramebuffer.colorAttachment, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1); + } + public static int glCheckFramebufferStatus(int target) { //TODO return GL30.GL_FRAMEBUFFER_COMPLETE; @@ -158,9 +163,8 @@ void setAttachmentTexture(int attachment, int texture) { return; switch (attachment) { - case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(glTexture); - - case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(glTexture); + case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(glTexture.getVulkanImage()); + case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(glTexture.getVulkanImage()); default -> throw new IllegalStateException("Unexpected value: " + attachment); } @@ -176,33 +180,21 @@ void setAttachmentRenderbuffer(int attachment, int texture) { return; switch (attachment) { - case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(renderbuffer); - - case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(renderbuffer); + case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(renderbuffer.getVulkanImage()); + case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(renderbuffer.getVulkanImage()); default -> throw new IllegalStateException("Unexpected value: " + attachment); } } - void setColorAttachment(GlTexture texture) { - this.colorAttachment = texture.vulkanImage; - createAndBind(); - } - - void setDepthAttachment(GlTexture texture) { - //TODO check if texture is in depth format - this.depthAttachment = texture.vulkanImage; - createAndBind(); - } - - void setColorAttachment(GlRenderbuffer texture) { - this.colorAttachment = texture.vulkanImage; + void setColorAttachment(VulkanImage image) { + this.colorAttachment = image; createAndBind(); } - void setDepthAttachment(GlRenderbuffer texture) { + void setDepthAttachment(VulkanImage image) { //TODO check if texture is in depth format - this.depthAttachment = texture.vulkanImage; + this.depthAttachment = image; createAndBind(); } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java index 1a34e6bb99..fc4a2ce07a 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java @@ -4,6 +4,7 @@ import net.vulkanmod.gl.GlRenderbuffer; import net.vulkanmod.gl.GlTexture; import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL30C; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -76,6 +77,15 @@ public static int glCheckFramebufferStatus(@NativeType("GLenum") int target) { return GlFramebuffer.glCheckFramebufferStatus(target); } + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glBlitFramebuffer(@NativeType("GLint") int srcX0, @NativeType("GLint") int srcY0, @NativeType("GLint") int srcX1, @NativeType("GLint") int srcY1, @NativeType("GLint") int dstX0, @NativeType("GLint") int dstY0, @NativeType("GLint") int dstX1, @NativeType("GLint") int dstY1, @NativeType("GLbitfield") int mask, @NativeType("GLenum") int filter) { + GlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + } + //RENDER BUFFER /** diff --git a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java index ff10c3d45f..5d5dbf1fd5 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java @@ -21,6 +21,8 @@ public MainTargetMixin(boolean useDepth) { */ @Overwrite private void createFrameBuffer(int width, int height) { + this.frameBufferId = 0; + this.viewWidth = width; this.viewHeight = height; this.width = width; diff --git a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java index c9aa78d114..6ec57980f3 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java @@ -1,5 +1,6 @@ package net.vulkanmod.vulkan.texture; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.queue.CommandPool; @@ -80,6 +81,44 @@ public static void copyImageToBuffer(VkCommandBuffer commandBuffer, long buffer, } } + public static void blitFramebuffer(VulkanImage dstImage, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1) { + try (MemoryStack stack = stackPush()) { + + VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); + + Renderer.getInstance().endRenderPass(commandBuffer); + + dstImage.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + // TODO: hardcoded srcImage + VulkanImage srcImage = Renderer.getInstance().getSwapChain().getColorAttachment(); + + srcImage.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + VkImageBlit.Buffer blit = VkImageBlit.calloc(1, stack); + blit.srcOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); + blit.srcOffsets(1, VkOffset3D.calloc(stack).set(srcImage.width, srcImage.height, 1)); + blit.srcSubresource() + .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) + .mipLevel(0) + .baseArrayLayer(0) + .layerCount(1); + + blit.dstOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); + blit.dstOffsets(1, VkOffset3D.calloc(stack).set(dstImage.width, dstImage.height, 1)); + blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(0).baseArrayLayer(0) + .layerCount(1); + + vkCmdBlitImage(commandBuffer, srcImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + dstImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); + + dstImage.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + + Renderer.getInstance().getMainPass().rebindMainTarget(); + + } + } + public static void generateMipmaps(VulkanImage image) { try (MemoryStack stack = stackPush()) { From 8b413984ac4629e33eab8d605734532e6838dd62 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 16:43:51 +0100 Subject: [PATCH 039/177] Fix crash on setting texture parameter --- src/main/java/net/vulkanmod/gl/GlTexture.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/net/vulkanmod/gl/GlTexture.java b/src/main/java/net/vulkanmod/gl/GlTexture.java index 4658fbc701..8d2a0969c3 100644 --- a/src/main/java/net/vulkanmod/gl/GlTexture.java +++ b/src/main/java/net/vulkanmod/gl/GlTexture.java @@ -164,6 +164,9 @@ public static void texParameteri(int target, int pName, int param) { if (target != GL11.GL_TEXTURE_2D) throw new UnsupportedOperationException("target != GL_TEXTURE_2D not supported"); + if (boundTexture == null) + return; + switch (pName) { case GL30.GL_TEXTURE_MAX_LEVEL -> boundTexture.setMaxLevel(param); case GL30.GL_TEXTURE_MAX_LOD -> boundTexture.setMaxLod(param); From 20dcc219a4baad838775fc2f22277121cb873ae5 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 16:45:02 +0100 Subject: [PATCH 040/177] Implement missing methods --- .../java/net/vulkanmod/mixin/compatibility/gl/GL11M.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index 3328002fc6..f595e65c2d 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -1,15 +1,13 @@ package net.vulkanmod.mixin.compatibility.gl; import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; @@ -24,6 +22,7 @@ public class GL11M { */ @Overwrite(remap = false) public static void glScissor(@NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) { + Renderer.setScissor(x, y, width, height); } /** @@ -61,7 +60,7 @@ public static int glGenTextures() { @NativeType("GLboolean") @Overwrite(remap = false) public static boolean glIsEnabled(@NativeType("GLenum") int cap) { - return false; + return true; } /** From 1ad99e08a9bc4c1518a2b03509d874b1ccab22ff Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 17:19:26 +0100 Subject: [PATCH 041/177] Improve set viewport compatibility --- .../mixin/compatibility/gl/GL11M.java | 10 ++++++ .../mixin/render/GlStateManagerM.java | 7 ++-- .../mixin/render/RenderSystemMixin.java | 8 ----- .../java/net/vulkanmod/vulkan/Renderer.java | 34 ++++++++----------- .../vulkan/framebuffer/Framebuffer.java | 2 +- 5 files changed, 30 insertions(+), 31 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index f595e65c2d..170604a42d 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -4,6 +4,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; @@ -25,6 +26,15 @@ public static void glScissor(@NativeType("GLint") int x, @NativeType("GLint") in Renderer.setScissor(x, y, width, height); } + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glViewport(@NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int w, @NativeType("GLsizei") int h) { + Renderer.setViewport(x, y, w, h); + } + /** * @author * @reason diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 59fcef1d32..8794d62595 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -9,10 +9,11 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL20; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; import java.nio.ByteBuffer; import java.nio.IntBuffer; @@ -99,8 +100,8 @@ public static void _disableCull() { /** * @author */ - @Overwrite(remap = false) - public static void _viewport(int x, int y, int width, int height) { + @Redirect(method = "_viewport", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glViewport(IIII)V"), remap = false) + private static void _viewport(int x, int y, int width, int height) { Renderer.setViewport(x, y, width, height); } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 03fcbd0f07..4ce202ca21 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -143,14 +143,6 @@ public static void clearDepth(double d) { private static void removeSwapBuffers(long window) { } - /** - * @author - */ - @Overwrite(remap = false) - public static void viewport(int x, int y, int width, int height) { - Renderer.setViewport(x, y, width, height); - } - /** * @author */ diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index a58561db8a..b67bc63d61 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -1,5 +1,6 @@ package net.vulkanmod.vulkan; +import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.client.Minecraft; @@ -398,7 +399,7 @@ public void endRenderPass() { } public void endRenderPass(VkCommandBuffer commandBuffer) { - if (skipRendering || this.boundFramebuffer == null) + if (skipRendering || !recordingCmds || this.boundFramebuffer == null) return; if (!DYNAMIC_RENDERING) @@ -468,6 +469,7 @@ private void recreateSwapChain() { Vulkan.waitIdle(); commandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0)); + recordingCmds = false; swapChain.recreate(); @@ -666,7 +668,18 @@ public static void clearAttachments(int v, int width, int height) { } public static void setInvertedViewport(int x, int y, int width, int height) { - setViewport(x, y + height, width, -height); + setViewportState(x, y + height, width, -height); + } + + public static void resetViewport() { + int width = INSTANCE.getSwapChain().getWidth(); + int height = INSTANCE.getSwapChain().getHeight(); + + setViewportState(0, 0, width, height); + } + + public static void setViewportState(int x, int y, int width, int height) { + GlStateManager._viewport(x, y, width, height); } public static void setViewport(int x, int y, int width, int height) { @@ -690,23 +703,6 @@ public static void setViewport(int x, int y, int width, int height, MemoryStack vkCmdSetViewport(INSTANCE.currentCmdBuffer, 0, viewport); } - public static void resetViewport() { - try (MemoryStack stack = stackPush()) { - int width = INSTANCE.getSwapChain().getWidth(); - int height = INSTANCE.getSwapChain().getHeight(); - - VkViewport.Buffer viewport = VkViewport.malloc(1, stack); - viewport.x(0.0f); - viewport.y(height); - viewport.width(width); - viewport.height(-height); - viewport.minDepth(0.0f); - viewport.maxDepth(1.0f); - - vkCmdSetViewport(INSTANCE.currentCmdBuffer, 0, viewport); - } - } - public static void setScissor(int x, int y, int width, int height) { if (INSTANCE.boundFramebuffer == null) return; diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java index 116f419bfc..8a2d5ad09b 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java @@ -126,7 +126,7 @@ public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass Renderer.getInstance().setBoundRenderPass(renderPass); Renderer.getInstance().setBoundFramebuffer(this); - Renderer.setViewport(0, 0, this.width, this.height); + Renderer.setViewportState(0, 0, this.width, this.height); Renderer.setScissor(0, 0, this.width, this.height); } From ac508a75d1ff6be5a33e14ab144d534e6c114d2d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 17:29:29 +0100 Subject: [PATCH 042/177] Improve shader compatibility - shader uniforms and samplers --- .../mixin/compatibility/EffectInstanceM.java | 2 +- .../mixin/render/ShaderInstanceM.java | 56 ++++++++++++++----- .../{parser => converter}/CodeParser.java | 2 +- .../{parser => converter}/GlslConverter.java | 3 +- .../InputOutputParser.java | 4 +- .../{parser => converter}/UniformParser.java | 2 +- 6 files changed, 48 insertions(+), 21 deletions(-) rename src/main/java/net/vulkanmod/vulkan/shader/{parser => converter}/CodeParser.java (97%) rename src/main/java/net/vulkanmod/vulkan/shader/{parser => converter}/GlslConverter.java (98%) rename src/main/java/net/vulkanmod/vulkan/shader/{parser => converter}/InputOutputParser.java (96%) rename src/main/java/net/vulkanmod/vulkan/shader/{parser => converter}/UniformParser.java (99%) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index 3cc3bef002..a38d9d62f2 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -17,7 +17,7 @@ import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.parser.GlslConverter; +import net.vulkanmod.vulkan.shader.converter.GlslConverter; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.io.IOUtils; import org.lwjgl.opengl.GL30; diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java index de8e9b01ab..375647f74a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -1,12 +1,14 @@ package net.vulkanmod.mixin.render; import com.google.gson.JsonObject; +import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; @@ -17,15 +19,12 @@ import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.layout.Uniform; -import net.vulkanmod.vulkan.shader.parser.GlslConverter; +import net.vulkanmod.vulkan.shader.converter.GlslConverter; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.Nullable; import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -35,6 +34,7 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.function.Supplier; @@ -57,11 +57,15 @@ public class ShaderInstanceM implements ShaderMixed { @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GAME_TIME; @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform SCREEN_SIZE; - private String vsPath; - private String fsName; + @Shadow @Final private Map samplerMap; + @Shadow @Final private List samplerLocations; + @Shadow @Final private List samplerNames; - private GraphicsPipeline pipeline; - boolean doUniformUpdate = false; + @Unique private String vsPath; + @Unique private String fsName; + + @Unique private GraphicsPipeline pipeline; + @Unique boolean doUniformUpdate = false; public GraphicsPipeline getPipeline() { return pipeline; @@ -126,6 +130,27 @@ public void apply() { if (!this.doUniformUpdate) return; + for(int j = 0; j < this.samplerLocations.size(); ++j) { + String string = this.samplerNames.get(j); + if (this.samplerMap.get(string) != null) { + RenderSystem.activeTexture(33984 + j); + Object object = this.samplerMap.get(string); + int texId = -1; + if (object instanceof RenderTarget) { + texId = ((RenderTarget)object).getColorTextureId(); + } else if (object instanceof AbstractTexture) { + texId = ((AbstractTexture)object).getId(); + } else if (object instanceof Integer) { + texId = (Integer)object; + } + + if (texId != -1) { + RenderSystem.bindTexture(texId); + RenderSystem.setShaderTexture(j, texId); + } + } + } + if (this.MODEL_VIEW_MATRIX != null) { this.MODEL_VIEW_MATRIX.set(RenderSystem.getModelViewMatrix()); } @@ -186,15 +211,16 @@ public void setupUniformSuppliers(UBO ubo) { for (Uniform vUniform : ubo.getUniforms()) { com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(vUniform.getName()); - if (uniform == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); - continue; - } - Supplier supplier; ByteBuffer byteBuffer; - if (uniform.getType() <= 3) { + if (uniform == null) { + Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); + + int size = vUniform.getSize(); + byteBuffer = MemoryUtil.memAlloc(size * 4); + } + else if (uniform.getType() <= 3) { byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); } else if (uniform.getType() <= 10) { byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/CodeParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java similarity index 97% rename from src/main/java/net/vulkanmod/vulkan/shader/parser/CodeParser.java rename to src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java index b6f95f7529..7ed82e3fbe 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/CodeParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java @@ -1,4 +1,4 @@ -package net.vulkanmod.vulkan.shader.parser; +package net.vulkanmod.vulkan.shader.converter; import it.unimi.dsi.fastutil.objects.ObjectArrayList; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java similarity index 98% rename from src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java rename to src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java index 1687ea6e8f..50d2302a71 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java @@ -1,4 +1,4 @@ -package net.vulkanmod.vulkan.shader.parser; +package net.vulkanmod.vulkan.shader.converter; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; import net.vulkanmod.vulkan.shader.descriptor.UBO; @@ -37,6 +37,7 @@ public void process(String vertShader, String fragShader) { fshOut.insert(0, samplersFragCode); vshOut.insert(0, "#version 450\n\n"); + fshOut.insert(0, "#define sample sample1\n"); fshOut.insert(0, "#version 450\n\n"); this.vshConverted = vshOut.toString(); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/InputOutputParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java similarity index 96% rename from src/main/java/net/vulkanmod/vulkan/shader/parser/InputOutputParser.java rename to src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java index aa8c5c0fee..cde9e5eff2 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/InputOutputParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java @@ -1,4 +1,4 @@ -package net.vulkanmod.vulkan.shader.parser; +package net.vulkanmod.vulkan.shader.converter; import com.mojang.blaze3d.vertex.VertexFormat; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -6,7 +6,7 @@ import java.util.List; import java.util.Objects; -import static net.vulkanmod.vulkan.shader.parser.UniformParser.removeSemicolon; +import static net.vulkanmod.vulkan.shader.converter.UniformParser.removeSemicolon; public class InputOutputParser { private final GlslConverter converterInstance; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java similarity index 99% rename from src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java rename to src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java index 34fe6df0d9..0fe03111e1 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java @@ -1,4 +1,4 @@ -package net.vulkanmod.vulkan.shader.parser; +package net.vulkanmod.vulkan.shader.converter; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; From 66bd4a42d6abd4cddd8ef6bc930719fdf6193f1a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 17:39:36 +0100 Subject: [PATCH 043/177] Restart render pass if terminated early --- src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 5cbb3d1509..2217745c14 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -57,6 +57,11 @@ private void submitRender(boolean tick, CallbackInfo ci) { Renderer.getInstance().endFrame(); } + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) + private void beginRender2(CallbackInfo ci) { + Renderer.getInstance().beginFrame(); + } + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) private void redirectMainTarget1(RenderTarget instance, boolean bl) { Renderer.getInstance().getMainPass().mainTargetBindWrite(); From ab6c7d1f3235d241a865b546962e9c4ef4841074 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 18:12:00 +0100 Subject: [PATCH 044/177] Remove reloadShaders injection --- .../mixin/render/GameRendererMixin.java | 285 ------------------ 1 file changed, 285 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java index 640fa34f2e..d516895d6a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java @@ -1,14 +1,9 @@ package net.vulkanmod.mixin.render; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.datafixers.util.Pair; -import net.fabricmc.fabric.api.client.rendering.v1.CoreShaderRegistrationCallback; -import net.fabricmc.fabric.impl.client.rendering.FabricShaderProgram; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.server.packs.resources.ResourceProvider; @@ -18,14 +13,9 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.io.IOException; -import java.util.List; import java.util.Map; -import java.util.function.Consumer; @Mixin(GameRenderer.class) public abstract class GameRendererMixin { @@ -36,61 +26,9 @@ public abstract class GameRendererMixin { @Shadow private @Nullable static ShaderInstance positionColorShader; @Shadow private @Nullable static ShaderInstance positionTexShader; @Shadow private @Nullable static ShaderInstance positionTexColorShader; - @Shadow private @Nullable static ShaderInstance particleShader; - @Shadow private @Nullable static ShaderInstance rendertypeSolidShader; - @Shadow private @Nullable static ShaderInstance rendertypeCutoutMippedShader; - @Shadow private @Nullable static ShaderInstance rendertypeCutoutShader; - @Shadow private @Nullable static ShaderInstance rendertypeTranslucentShader; - @Shadow private @Nullable static ShaderInstance rendertypeTranslucentMovingBlockShader; - @Shadow private @Nullable static ShaderInstance rendertypeArmorCutoutNoCullShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntitySolidShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityCutoutShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityCutoutNoCullShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityCutoutNoCullZOffsetShader; - @Shadow private @Nullable static ShaderInstance rendertypeItemEntityTranslucentCullShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityTranslucentCullShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityTranslucentShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityTranslucentEmissiveShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntitySmoothCutoutShader; - @Shadow private @Nullable static ShaderInstance rendertypeBeaconBeamShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityDecalShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityNoOutlineShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityShadowShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityAlphaShader; - @Shadow private @Nullable static ShaderInstance rendertypeEyesShader; - @Shadow private @Nullable static ShaderInstance rendertypeEnergySwirlShader; - @Shadow private @Nullable static ShaderInstance rendertypeLeashShader; - @Shadow private @Nullable static ShaderInstance rendertypeWaterMaskShader; - @Shadow private @Nullable static ShaderInstance rendertypeOutlineShader; - @Shadow private @Nullable static ShaderInstance rendertypeArmorGlintShader; - @Shadow private @Nullable static ShaderInstance rendertypeArmorEntityGlintShader; - @Shadow private @Nullable static ShaderInstance rendertypeGlintTranslucentShader; - @Shadow private @Nullable static ShaderInstance rendertypeGlintShader; - @Shadow private @Nullable static ShaderInstance rendertypeGlintDirectShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityGlintShader; - @Shadow private @Nullable static ShaderInstance rendertypeEntityGlintDirectShader; @Shadow private @Nullable static ShaderInstance rendertypeTextShader; - @Shadow private @Nullable static ShaderInstance rendertypeTextIntensityShader; - @Shadow private @Nullable static ShaderInstance rendertypeTextSeeThroughShader; - @Shadow private @Nullable static ShaderInstance rendertypeTextIntensitySeeThroughShader; - @Shadow private @Nullable static ShaderInstance rendertypeLightningShader; - @Shadow private @Nullable static ShaderInstance rendertypeTripwireShader; - @Shadow private @Nullable static ShaderInstance rendertypeEndPortalShader; - @Shadow private @Nullable static ShaderInstance rendertypeEndGatewayShader; - @Shadow private @Nullable static ShaderInstance rendertypeLinesShader; - @Shadow private @Nullable static ShaderInstance rendertypeCrumblingShader; - @Shadow private static @Nullable ShaderInstance rendertypeBreezeWindShader; - @Shadow private static @Nullable ShaderInstance rendertypeCloudsShader; - - @Shadow private static @Nullable ShaderInstance rendertypeTextBackgroundShader; - @Shadow private static @Nullable ShaderInstance rendertypeTextBackgroundSeeThroughShader; @Shadow private static @Nullable ShaderInstance rendertypeGuiShader; @Shadow private static @Nullable ShaderInstance rendertypeGuiOverlayShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiTextHighlightShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiGhostRecipeOverlayShader; - - @Shadow private @Nullable static ShaderInstance positionColorLightmapShader; - @Shadow private @Nullable static ShaderInstance positionColorTexLightmapShader; @Shadow public ShaderInstance blitShader; @@ -98,229 +36,6 @@ public abstract class GameRendererMixin { @Shadow public abstract float getRenderDistance(); - @Shadow protected abstract void loadBlurEffect(ResourceProvider resourceProvider); - - @Inject(method = "reloadShaders", at = @At("HEAD"), cancellable = true) - public void reloadShaders(ResourceProvider provider, CallbackInfo ci) { - RenderSystem.assertOnRenderThread(); - - List>> pairs = Lists.newArrayListWithCapacity(this.shaders.size()); - - try { - pairs.add( - Pair.of(new ShaderInstance(provider, "particle", DefaultVertexFormat.PARTICLE), - (shaderInstance) -> particleShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "position", DefaultVertexFormat.POSITION), - (shaderInstance) -> positionShader = shaderInstance)); - - ShaderInstance positionColor = new ShaderInstance(provider, "position_color", DefaultVertexFormat.POSITION_COLOR); - pairs.add( - Pair.of( - positionColor, - (shaderInstance) -> positionColorShader = shaderInstance)); - - // These aren't used -// pairs.add( -// Pair.of(new ShaderInstance(provider, "position_color_lightmap", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP), -// (shaderInstance) -> positionColorLightmapShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "position_color_tex_lightmap", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP), - (shaderInstance) -> positionColorTexLightmapShader = shaderInstance)); - - pairs.add( - Pair.of(new ShaderInstance(provider, "position_tex", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> positionTexShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "position_tex_color", DefaultVertexFormat.POSITION_TEX_COLOR), - (shaderInstance) -> positionTexColorShader = shaderInstance)); -// pairs.add( -// Pair.of(new ShaderInstance(provider, "position_tex_lightmap_color", DefaultVertexFormat.POSITION_TEX_LIGHTMAP_COLOR), -// (shaderInstance) -> positionTexLightmapColorShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_solid", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeSolidShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_cutout_mipped", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeCutoutMippedShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_cutout", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeCutoutShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_translucent", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeTranslucentShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_translucent_moving_block", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeTranslucentMovingBlockShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_armor_cutout_no_cull", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeArmorCutoutNoCullShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_solid", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntitySolidShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_cutout", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityCutoutShader = shaderInstance)); - - // No diff in these shaders - ShaderInstance entity_no_cull = new ShaderInstance(provider, "rendertype_entity_cutout_no_cull", DefaultVertexFormat.NEW_ENTITY); - pairs.add( - Pair.of(entity_no_cull, - (shaderInstance) -> rendertypeEntityCutoutNoCullShader = shaderInstance)); - pairs.add( - Pair.of(entity_no_cull, - (shaderInstance) -> rendertypeEntityCutoutNoCullZOffsetShader = shaderInstance)); - - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_item_entity_translucent_cull", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeItemEntityTranslucentCullShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_translucent_cull", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityTranslucentCullShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_translucent", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityTranslucentShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_translucent_emissive", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityTranslucentEmissiveShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_smooth_cutout", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntitySmoothCutoutShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_beacon_beam", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeBeaconBeamShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_decal", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityDecalShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_no_outline", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityNoOutlineShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_shadow", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityShadowShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_alpha", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEntityAlphaShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_eyes", DefaultVertexFormat.NEW_ENTITY), - (shaderInstance) -> rendertypeEyesShader = shaderInstance)); - var energySwirlShader = new ShaderInstance(provider, "rendertype_energy_swirl", DefaultVertexFormat.NEW_ENTITY); - pairs.add( - Pair.of(energySwirlShader, - (shaderInstance) -> rendertypeEnergySwirlShader = shaderInstance)); - pairs.add( - Pair.of(energySwirlShader, - (shaderInstance) -> rendertypeBreezeWindShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_leash", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP), - (shaderInstance) -> rendertypeLeashShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_water_mask", DefaultVertexFormat.POSITION), - (shaderInstance) -> rendertypeWaterMaskShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_outline", DefaultVertexFormat.POSITION_TEX_COLOR), - (shaderInstance) -> rendertypeOutlineShader = shaderInstance)); -// pairs.add(Pair.of(new ShaderInstance(provider, "rendertype_armor_glint", DefaultVertexFormat.POSITION_TEX), (shaderInstance) -> { -// rendertypeArmorGlintShader = shaderInstance; -// })); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_armor_entity_glint", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> rendertypeArmorEntityGlintShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_glint_translucent", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> rendertypeGlintTranslucentShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_glint", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> rendertypeGlintShader = shaderInstance)); -// pairs.add(Pair.of(new ShaderInstance(provider, "rendertype_glint_direct", DefaultVertexFormat.POSITION_TEX), (shaderInstance) -> { -// rendertypeGlintDirectShader = shaderInstance; -// })); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_glint", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> rendertypeEntityGlintShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_entity_glint_direct", DefaultVertexFormat.POSITION_TEX), - (shaderInstance) -> rendertypeEntityGlintDirectShader = shaderInstance)); - - //Text - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP), - (shaderInstance) -> rendertypeTextShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text_background", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP), - (shaderInstance) -> rendertypeTextBackgroundShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text_intensity", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP), - (shaderInstance) -> rendertypeTextIntensityShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text_see_through", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP), - (shaderInstance) -> rendertypeTextSeeThroughShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text_background_see_through", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP), - (shaderInstance) -> rendertypeTextBackgroundSeeThroughShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_text_intensity_see_through", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP), - (shaderInstance) -> rendertypeTextIntensitySeeThroughShader = shaderInstance)); - - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_lightning", DefaultVertexFormat.POSITION_COLOR), - (shaderInstance) -> rendertypeLightningShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_tripwire", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeTripwireShader = shaderInstance)); - ShaderInstance endPortalShader = new ShaderInstance(provider, "rendertype_end_portal", DefaultVertexFormat.POSITION); - pairs.add( - Pair.of(endPortalShader, - (shaderInstance) -> rendertypeEndPortalShader = shaderInstance)); - pairs.add( - Pair.of(endPortalShader, - (shaderInstance) -> rendertypeEndGatewayShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_clouds", DefaultVertexFormat.POSITION_TEX_COLOR_NORMAL), - (shaderInstance) -> rendertypeCloudsShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_lines", DefaultVertexFormat.POSITION_COLOR_NORMAL), - (shaderInstance) -> rendertypeLinesShader = shaderInstance)); - pairs.add( - Pair.of(new ShaderInstance(provider, "rendertype_crumbling", DefaultVertexFormat.BLOCK), - (shaderInstance) -> rendertypeCrumblingShader = shaderInstance)); - - pairs.add( - Pair.of(positionColor, - (shaderInstance) -> rendertypeGuiShader = shaderInstance)); - pairs.add( - Pair.of(positionColor, - (shaderInstance) -> rendertypeGuiOverlayShader = shaderInstance)); - pairs.add( - Pair.of(positionColor, - (shaderInstance) -> rendertypeGuiTextHighlightShader = shaderInstance)); - pairs.add( - Pair.of(positionColor, - (shaderInstance) -> rendertypeGuiGhostRecipeOverlayShader = shaderInstance)); - - // FRAPI shader loading - CoreShaderRegistrationCallback.RegistrationContext context = (id, vertexFormat, loadCallback) -> { - ShaderInstance program = new FabricShaderProgram(provider, id, vertexFormat); - pairs.add(Pair.of(program, loadCallback)); - }; - CoreShaderRegistrationCallback.EVENT.invoker().registerShaders(context); - - this.loadBlurEffect(provider); - } catch (IOException ioexception) { - pairs.forEach((pair) -> pair.getFirst().close()); - throw new RuntimeException("could not reload shaders", ioexception); - } - - this.shutdownShaders(); - pairs.forEach((pair) -> { - ShaderInstance shaderinstance = pair.getFirst(); - this.shaders.put(shaderinstance.getName(), shaderinstance); - pair.getSecond().accept(shaderinstance); - }); - - ci.cancel(); - } - /** * @author * @reason From 1c189cf8c29fda26a85766ff6c4bdfa4b5f70db4 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 18:31:34 +0100 Subject: [PATCH 045/177] Implement data cache for biome data --- .../biome/BiomeManagerExtended.java | 13 ++ .../mixin/render/biome/BiomeManagerM.java | 18 +++ .../render/chunk/build/RenderRegion.java | 20 ++- .../chunk/build/RenderRegionBuilder.java | 11 +- .../render/chunk/build/biome/BiomeData.java | 153 ++++++++++++++++++ .../render/chunk/build/color/TintCache.java | 13 +- src/main/resources/vulkanmod.mixins.json | 1 + 7 files changed, 211 insertions(+), 18 deletions(-) create mode 100644 src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java diff --git a/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java b/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java new file mode 100644 index 0000000000..6cb365021e --- /dev/null +++ b/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java @@ -0,0 +1,13 @@ +package net.vulkanmod.interfaces.biome; + +import net.minecraft.world.level.biome.BiomeManager; + +public interface BiomeManagerExtended { + + static BiomeManagerExtended of(BiomeManager biomeManager) { + return (BiomeManagerExtended) biomeManager; + } + + long getBiomeZoomSeed(); + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java b/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java new file mode 100644 index 0000000000..7ec047b323 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java @@ -0,0 +1,18 @@ +package net.vulkanmod.mixin.render.biome; + +import net.minecraft.world.level.biome.BiomeManager; +import net.vulkanmod.interfaces.biome.BiomeManagerExtended; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(BiomeManager.class) +public class BiomeManagerM implements BiomeManagerExtended { + + @Shadow @Final private long biomeZoomSeed; + + @Override + public long getBiomeZoomSeed() { + return this.biomeZoomSeed; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 64ed4dfa80..94a19358b1 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -17,6 +17,7 @@ import net.minecraft.world.level.levelgen.DebugLevelSource; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.material.FluidState; +import net.vulkanmod.render.chunk.build.biome.BiomeData; import net.vulkanmod.render.chunk.build.color.TintCache; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,13 +46,15 @@ public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView private final BlockState[] blockData; private final DataLayer[][] lightData; + private BiomeData biomeData; private TintCache tintCache; private final Map blockEntityMap; private final Function blockStateGetter; - RenderRegion(Level level, int x, int y, int z, PalettedContainer[] blockData, DataLayer[][] lightData, Map blockEntityMap) { + RenderRegion(Level level, int x, int y, int z, PalettedContainer[] blockData, DataLayer[][] lightData, + BiomeData biomeData, Map blockEntityMap) { this.level = level; this.minSecX = x - 1; @@ -66,6 +69,7 @@ public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView this.blockDataContainers = blockData; this.lightData = lightData; + this.biomeData = biomeData; this.blockEntityMap = blockEntityMap; this.blockData = new BlockState[BLOCK_COUNT]; @@ -78,14 +82,14 @@ public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView public void loadBlockStates() { Arrays.fill(blockData, Blocks.AIR.defaultBlockState()); - for(int x = 0; x <= 2; ++x) { - for(int z = 0; z <= 2; ++z) { - for(int y = 0; y <= 2; ++y) { + for (int x = 0; x <= 2; ++x) { + for (int z = 0; z <= 2; ++z) { + for (int y = 0; y <= 2; ++y) { final int idx = getSectionIdx(x, y, z); PalettedContainer container = blockDataContainers[idx]; - if(container == null) + if (container == null) continue; int absBlockX = (x + minSecX) << 4; @@ -101,8 +105,8 @@ public void loadBlockStates() { int tMaxZ = Math.min(maxZ, absBlockZ + 16); loadSectionBlockStates(container, blockData, - tMinX, tMinY, tMinZ, tMaxX, tMaxY, tMaxZ); - + tMinX, tMinY, tMinZ, tMaxX, tMaxY, tMaxZ); + } } } @@ -126,7 +130,7 @@ void loadSectionBlockStates(PalettedContainer container, BlockState[ public void initTintCache(TintCache tintCache) { this.tintCache = tintCache; - this.tintCache.init(blendRadius, minSecX + 1, minSecY + 1, minSecZ + 1); + this.tintCache.init(biomeData, blendRadius, minSecX + 1, minSecY + 1, minSecZ + 1); } public BlockState getBlockState(BlockPos blockPos) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java index adf6db694a..dc33176367 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java @@ -10,6 +10,8 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.PalettedContainer; +import net.vulkanmod.interfaces.biome.BiomeManagerExtended; +import net.vulkanmod.render.chunk.build.biome.BiomeData; public class RenderRegionBuilder { private static final DataLayer DEFAULT_SKY_LIGHT_DATA_LAYER = new DataLayer(15); @@ -26,7 +28,7 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { if (section == null || section.hasOnlyAir()) return null; - var entityMap = levelChunk.getBlockEntities(); + var blockEntityMap = levelChunk.getBlockEntities(); int minSecX = secX - 1; int minSecZ = secZ - 1; @@ -39,6 +41,9 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { DataLayer[][] lightData = new DataLayer[RenderRegion.SIZE][2 /* Light types */]; + long biomeZoomSeed = BiomeManagerExtended.of(level.getBiomeManager()).getBiomeZoomSeed(); + BiomeData biomeData = new BiomeData(biomeZoomSeed, minSecX, minSecY, minSecZ); + final int minHeightSec = level.getMinBuildHeight() >> 4; for (int x = minSecX; x <= maxSecX; ++x) { for (int z = minSecZ; z <= maxSecZ; ++z) { @@ -60,11 +65,13 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { DataLayer[] dataLayers = getSectionDataLayers(level, pos); lightData[idx] = dataLayers; + + biomeData.getBiomeData(level, section, relX, relY, relZ); } } } - return new RenderRegion(level, secX, secY, secZ, blockData, lightData, entityMap); + return new RenderRegion(level, secX, secY, secZ, blockData, lightData, biomeData, blockEntityMap); } private DataLayer[] getSectionDataLayers(Level level, SectionPos pos) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java new file mode 100644 index 0000000000..166f4b3a8a --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java @@ -0,0 +1,153 @@ +package net.vulkanmod.render.chunk.build.biome; + +import net.minecraft.core.registries.Registries; +import net.minecraft.util.LinearCongruentialGenerator; +import net.minecraft.util.Mth; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.vulkanmod.render.chunk.build.RenderRegion; +import org.joml.Vector3f; + +public class BiomeData { + private static final int ZOOM_LENGTH = 4; + private static final int BIOMES_PER_SECTION = 4 * 4 * 4; + private static final int SIZE = RenderRegion.SIZE * BIOMES_PER_SECTION; + + Biome[] biomes = new Biome[SIZE]; + private final long biomeZoomSeed; + + int secX, secY, secZ; + + // Cached cell offsets + Vector3f[] offsets = new Vector3f[SIZE]; + + public BiomeData(long biomeZoomSeed, int secX, int secY, int secZ) { + this.biomeZoomSeed = biomeZoomSeed; + this.secX = secX; + this.secY = secY; + this.secZ = secZ; + } + + public void getBiomeData(Level level, LevelChunkSection chunkSection, int secX, int secY, int secZ) { + Biome defaultValue = level.registryAccess() + .registryOrThrow(Registries.BIOME) + .getHolderOrThrow(Biomes.PLAINS) + .value(); + + int baseIdx = getRelativeSectionIdx(secX, secY, secZ); + + for (int x = 0; x < 4; x++) { + for (int y = 0; y < 4; y++) { + for (int z = 0; z < 4; z++) { + int relIdx = getRelativeIdx(x, y, z); + int idx = baseIdx + relIdx; + + if (chunkSection != null) { + biomes[idx] = chunkSection.getNoiseBiome(x, y, z) + .value(); + } + else { + biomes[idx] = defaultValue; + } + + } + } + } + + } + + public Biome getBiome(int blockX, int blockY, int blockZ) { + int x = blockX - 2; + int y = blockY - 2; + int z = blockZ - 2; + + int zoomX = x >> 2; + int zoomY = y >> 2; + int zoomZ = z >> 2; + + float fracZoomX = (x & 3) * 0.25f; + float fracZoomY = (y & 3) * 0.25f; + float fracZoomZ = (z & 3) * 0.25f; + + int closestCellIdx = 0; + double closestDistance = Double.POSITIVE_INFINITY; + + for (int i = 0; i < 8; ++i) { + boolean dirX = (i & 4) != 0; + boolean dirY = (i & 2) != 0; + boolean dirZ = (i & 1) != 0; + + int cellX = dirX ? zoomX + 1 : zoomX; + int cellY = dirY ? zoomY + 1 : zoomY; + int cellZ = dirZ ? zoomZ + 1 : zoomZ; + + float fCellX = dirX ? fracZoomX - 1.0f : fracZoomX; + float fCellY = dirY ? fracZoomY - 1.0f : fracZoomY; + float fCellZ = dirZ ? fracZoomZ - 1.0f : fracZoomZ; + + int baseSectionIdx = getSectionIdx(cellX >> 2, cellY >> 2, cellZ >> 2); + int cellIdx = baseSectionIdx + getRelativeIdx(cellX & 3, cellY & 3, cellZ & 3); + + Vector3f offset = getOffset(baseSectionIdx, cellX, cellY, cellZ); + float distance = Mth.square(fCellX + offset.x()) + Mth.square(fCellY + offset.y()) + Mth.square(fCellZ + offset.z()); + + if (closestDistance > distance) { + closestCellIdx = cellIdx; + closestDistance = distance; + } + } + + return this.biomes[closestCellIdx]; + } + + private int getSectionIdx(int secX, int secY, int secZ) { + return getRelativeSectionIdx(secX - this.secX, secY - this.secY, secZ - this.secZ); + } + + private Vector3f getOffset(int baseIndex, int cellX, int cellY, int cellZ) { + int relCellX = cellX & 3; + int relCellY = cellY & 3; + int relCellZ = cellZ & 3; + int idx = baseIndex + getRelativeIdx(relCellX, relCellY, relCellZ); + + if (this.offsets[idx] == null) { + this.offsets[idx] = computeCellOffset(this.biomeZoomSeed, cellX, cellY, cellZ); + } + + return this.offsets[idx]; + } + + private static Vector3f computeCellOffset(long l, int cellX, int cellY, int cellZ) { + long seed; + seed = LinearCongruentialGenerator.next(l, cellX); + seed = LinearCongruentialGenerator.next(seed, cellY); + seed = LinearCongruentialGenerator.next(seed, cellZ); + seed = LinearCongruentialGenerator.next(seed, cellX); + seed = LinearCongruentialGenerator.next(seed, cellY); + seed = LinearCongruentialGenerator.next(seed, cellZ); + + float xOffset = getFiddle(seed); + seed = LinearCongruentialGenerator.next(seed, l); + float yOffset = getFiddle(seed); + seed = LinearCongruentialGenerator.next(seed, l); + float zOffset = getFiddle(seed); + + return new Vector3f(xOffset, yOffset, zOffset); + } + + private static float getFiddle(long l) { + float d = Math.floorMod(l >> 24, 1024) * (1.0f / 1024.0f); + return (d - 0.5f) * 0.9f; + } + + private static int getRelativeSectionIdx(int x, int y, int z) { + return ((x * RenderRegion.WIDTH * RenderRegion.WIDTH) + (y * RenderRegion.WIDTH) + z) * BIOMES_PER_SECTION; + } + + private static int getRelativeIdx(int x, int y, int z) { + return (x * ZOOM_LENGTH * ZOOM_LENGTH) + (y * ZOOM_LENGTH) + z; + } + +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java index cc460fa21f..2a8828d447 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java @@ -5,9 +5,8 @@ import net.minecraft.client.renderer.BiomeColors; import net.minecraft.core.BlockPos; import net.minecraft.world.level.ColorResolver; -import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; -import net.vulkanmod.render.chunk.WorldRenderer; +import net.vulkanmod.render.chunk.build.biome.BiomeData; import java.util.Arrays; @@ -16,6 +15,7 @@ public class TintCache { private final Reference2ReferenceOpenHashMap layers; + private BiomeData biomeData; private int blendRadius, totalWidth; private int secX, secY, secZ; private int minX, minZ; @@ -33,7 +33,8 @@ public TintCache() { this.layers.put(BiomeColors.WATER_COLOR_RESOLVER, allocateLayers()); } - public void init(int blendRadius, int secX, int secY, int secZ) { + public void init(BiomeData biomeData, int blendRadius, int secX, int secY, int secZ) { + this.biomeData = biomeData; this.blendRadius = Minecraft.getInstance().options.biomeBlendRadius().get(); this.totalWidth = (blendRadius * 2) + 16; @@ -107,17 +108,13 @@ private Layer[] allocateLayers() { } private void calculateLayer(Layer layer, ColorResolver colorResolver, int y) { - Level level = WorldRenderer.getLevel(); - - BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos(); int absY = (secY << 4) + y; int[] values = layer.values; for (int absZ = minZ; absZ < maxZ; absZ++) { for (int absX = minX; absX < maxX; absX++) { - blockPos.set(absX, absY, absZ); - Biome biome = level.getBiome(blockPos).value(); + Biome biome = this.biomeData.getBiome(absX, absY, absZ); final int idx = (absX - minX) + (absZ - minZ) * totalWidth; values[idx] = colorResolver.getColor(biome, absX, absZ); diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index ebbf80f7d7..2a26be555b 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -46,6 +46,7 @@ "render.RenderSystemMixin", "render.RenderTypeM", "render.ShaderInstanceM", + "render.biome.BiomeManagerM", "render.block.BakedQuadM", "render.clouds.LevelRendererM", "render.color.BlockColorsM", From 70d5cdc6fc293e662aa7481d4292892f354e9e49 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 18:33:47 +0100 Subject: [PATCH 046/177] Bump fabric versions --- gradle.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 459f2a8bbd..ec11cbc3a0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,12 +6,12 @@ org.gradle.parallel=true # check these on https://fabricmc.net/develop minecraft_version=1.21 yarn_mappings=1.21+build.1 -loader_version=0.16.5 +loader_version=0.16.9 # Fabric API -fabric_version=0.102.0+1.21 +fabric_version=0.110.0+1.21.1 # Mod Properties mod_version = 0.5.1-dev maven_group = net.vulkanmod -archives_base_name = VulkanMod_1.21 +archives_base_name = VulkanMod_1.21.1 From d8f2073c4a659a30c16f9022b3c223ec73b61cb1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 13 Dec 2024 17:04:35 +0100 Subject: [PATCH 047/177] Refactor window mode option --- .../java/net/vulkanmod/config/Config.java | 2 +- .../net/vulkanmod/config/option/Options.java | 20 ++++++------ .../vulkanmod/config/video/WindowMode.java | 31 +++++++++++++++++++ .../vulkanmod/mixin/window/WindowMixin.java | 3 +- .../assets/vulkanmod/lang/en_us.json | 4 ++- 5 files changed, 47 insertions(+), 13 deletions(-) create mode 100644 src/main/java/net/vulkanmod/config/video/WindowMode.java diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index 4110c0815d..f59034624f 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -16,7 +16,7 @@ public class Config { public int frameQueueSize = 2; public VideoModeSet.VideoMode videoMode = VideoModeManager.getFirstAvailable().getVideoMode(); - public boolean windowedFullscreen = false; + public int windowMode = 0; public int advCulling = 2; public boolean indirectDraw = true; diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index 5fc3d97176..e211412374 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -8,6 +8,7 @@ import net.vulkanmod.config.gui.OptionBlock; import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.video.VideoModeSet; +import net.vulkanmod.config.video.WindowMode; import net.vulkanmod.render.chunk.build.light.LightMode; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; @@ -77,19 +78,18 @@ public static OptionBlock[] getVideoOpts() { new OptionBlock("", new Option[]{ resolutionOption, RefreshRate, - new SwitchOption(Component.translatable("options.fullscreen"), + new CyclingOption<>(Component.translatable("vulkanmod.options.windowMode"), + WindowMode.values(), value -> { - minecraftOptions.fullscreen().set(value); -// window.toggleFullScreen(); - fullscreenDirty = true; - }, - () -> minecraftOptions.fullscreen().get()), - new SwitchOption(Component.translatable("vulkanmod.options.windowedFullscreen"), - value -> { - config.windowedFullscreen = value; + boolean exclusiveFullscreen = value == WindowMode.EXCLUSIVE_FULLSCREEN; + minecraftOptions.fullscreen() + .set(exclusiveFullscreen); + + config.windowMode = value.mode; fullscreenDirty = true; }, - () -> config.windowedFullscreen), + () -> WindowMode.fromValue(config.windowMode)) + .setTranslator(value -> Component.translatable(WindowMode.getComponentName(value))), new RangeOption(Component.translatable("options.framerateLimit"), 10, 260, 10, value -> Component.nullToEmpty(value == 260 ? diff --git a/src/main/java/net/vulkanmod/config/video/WindowMode.java b/src/main/java/net/vulkanmod/config/video/WindowMode.java new file mode 100644 index 0000000000..621f06dea2 --- /dev/null +++ b/src/main/java/net/vulkanmod/config/video/WindowMode.java @@ -0,0 +1,31 @@ +package net.vulkanmod.config.video; + +public enum WindowMode { + WINDOWED(0), + WINDOWED_FULLSCREEN(1), + EXCLUSIVE_FULLSCREEN(2); + + public final int mode; + + WindowMode(int mode) { + this.mode = mode; + } + + public static WindowMode fromValue(int value) { + return switch (value) { + case 0 -> WINDOWED; + case 1 -> WINDOWED_FULLSCREEN; + case 2 -> EXCLUSIVE_FULLSCREEN; + + default -> throw new IllegalStateException("Unexpected value: " + value); + }; + } + + public static String getComponentName(WindowMode windowMode) { + return switch (windowMode) { + case WINDOWED -> "vulkanmod.options.windowMode.windowed"; + case WINDOWED_FULLSCREEN -> "vulkanmod.options.windowMode.windowedFullscreen"; + case EXCLUSIVE_FULLSCREEN -> "options.fullscreen"; + }; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java index 72ef9ae128..5f4c71ce83 100644 --- a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java +++ b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java @@ -8,6 +8,7 @@ import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.option.Options; import net.vulkanmod.config.video.VideoModeSet; +import net.vulkanmod.config.video.WindowMode; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.Vulkan; @@ -163,7 +164,7 @@ private void setMode() { this.wasOnFullscreen = true; } } - else if (config.windowedFullscreen) { + else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { VideoModeSet.VideoMode videoMode = VideoModeManager.getOsVideoMode(); if (!this.wasOnFullscreen) { diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 2560649373..5880f84fce 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -39,5 +39,7 @@ "vulkanmod.options.uniqueOpaqueLayer": "Unique opaque layer", "vulkanmod.options.uniqueOpaqueLayer.tooltip": "Use a unique render layer for opaque terrain to improve performance.", - "vulkanmod.options.windowedFullscreen": "Windowed Fullscreen" + "vulkanmod.options.windowMode": "Window Mode", + "vulkanmod.options.windowMode.windowed": "Windowed", + "vulkanmod.options.windowMode.windowedFullscreen": "Windowed Fullscreen" } \ No newline at end of file From 6ee4b3981c828bd282b73903e8986b4e60580ef1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:10:48 +0100 Subject: [PATCH 048/177] Refactor CircularIntList --- .../render/chunk/ChunkAreaManager.java | 22 +++-- .../vulkanmod/render/chunk/SectionGrid.java | 22 +++-- .../render/chunk/util/CircularIntList.java | 87 ++++++++----------- 3 files changed, 69 insertions(+), 62 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java index 1cdfa99f29..4b79212b6b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java @@ -31,6 +31,10 @@ public class ChunkAreaManager { int prevX; int prevZ; + private final CircularIntList xList; + private final CircularIntList zList; + private final CircularIntList.RangeIterator xComplIterator; + public ChunkAreaManager(int width, int height, int minHeight) { this.minHeight = minHeight; this.sectionGridWidth = width; @@ -61,6 +65,10 @@ public ChunkAreaManager(int width, int height, int minHeight) { this.prevX = Integer.MIN_VALUE; this.prevZ = Integer.MIN_VALUE; + + this.xList = new CircularIntList(this.xzSize); + this.zList = new CircularIntList(this.xzSize); + this.xComplIterator = this.xList.createRangeIterator(); } public void repositionAreas(int secX, int secZ) { @@ -75,8 +83,11 @@ public void repositionAreas(int secX, int secZ) { int zAbsChunkIndex = zS - this.xzSize / 2; int zStart = Math.floorMod(zAbsChunkIndex, this.xzSize); - CircularIntList xList = new CircularIntList(this.xzSize, xStart); - CircularIntList zList = new CircularIntList(this.xzSize, zStart); + CircularIntList xList = this.xList; + CircularIntList zList = this.zList; + xList.updateStartIdx(xStart); + zList.updateStartIdx(zStart); + CircularIntList.OwnIterator xIterator = xList.iterator(); CircularIntList.OwnIterator zIterator = zList.iterator(); @@ -106,9 +117,10 @@ public void repositionAreas(int secX, int secZ) { zRangeEnd = -deltaZ - 1; } - CircularIntList.RangeIterator xRangeIterator = xList.rangeIterator(xRangeStart, xRangeEnd); - CircularIntList.RangeIterator xComplIterator = xList.rangeIterator(xComplStart, xComplEnd); - CircularIntList.RangeIterator zRangeIterator = zList.rangeIterator(zRangeStart, zRangeEnd); + CircularIntList.RangeIterator xRangeIterator = xList.getRangeIterator(xRangeStart, xRangeEnd); + CircularIntList.RangeIterator zRangeIterator = zList.getRangeIterator(zRangeStart, zRangeEnd); + CircularIntList.RangeIterator xComplIterator = this.xComplIterator; + xComplIterator.update(xComplStart, xComplEnd); xAbsChunkIndex = xS - this.xzSize / 2 + xRangeStart; for (int xRelativeIndex; xRangeIterator.hasNext(); xAbsChunkIndex++) { diff --git a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java index 3a94d37f3c..b6d142b227 100644 --- a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java +++ b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java @@ -23,6 +23,10 @@ public class SectionGrid { private int prevSecX; private int prevSecZ; + private final CircularIntList xList; + private final CircularIntList zList; + private final CircularIntList.RangeIterator xComplIterator; + public SectionGrid(Level level, int viewDistance) { this.level = level; this.setViewDistance(viewDistance); @@ -31,6 +35,10 @@ public SectionGrid(Level level, int viewDistance) { this.prevSecX = Integer.MIN_VALUE; this.prevSecZ = Integer.MIN_VALUE; + + this.xList = new CircularIntList(this.gridWidth); + this.zList = new CircularIntList(this.gridWidth); + this.xComplIterator = this.xList.createRangeIterator(); } protected void createChunks() { @@ -86,8 +94,11 @@ public void repositionCamera(double x, double z) { int zAbsChunkIndex = secZ - this.gridWidth / 2; int zStart = Math.floorMod(zAbsChunkIndex, this.gridWidth); - CircularIntList xList = new CircularIntList(this.gridWidth, xStart); - CircularIntList zList = new CircularIntList(this.gridWidth, zStart); + CircularIntList xList = this.xList; + CircularIntList zList = this.zList; + xList.updateStartIdx(xStart); + zList.updateStartIdx(zStart); + CircularIntList.OwnIterator xIterator = xList.iterator(); CircularIntList.OwnIterator zIterator = zList.iterator(); @@ -117,9 +128,10 @@ public void repositionCamera(double x, double z) { zRangeEnd = -dz - 1; } - CircularIntList.RangeIterator xRangeIterator = xList.rangeIterator(xRangeStart, xRangeEnd); - CircularIntList.RangeIterator xComplIterator = xList.rangeIterator(xComplStart, xComplEnd); - CircularIntList.RangeIterator zRangeIterator = zList.rangeIterator(zRangeStart, zRangeEnd); + CircularIntList.RangeIterator xRangeIterator = xList.getRangeIterator(xRangeStart, xRangeEnd); + CircularIntList.RangeIterator zRangeIterator = zList.getRangeIterator(zRangeStart, zRangeEnd); + CircularIntList.RangeIterator xComplIterator = this.xComplIterator; + xComplIterator.update(xComplStart, xComplEnd); xAbsChunkIndex = secX - (this.gridWidth >> 1) + xRangeStart; for (int xRelativeIndex; xRangeIterator.hasNext(); xAbsChunkIndex++) { diff --git a/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java b/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java index e81145a911..d8964eaa90 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java @@ -1,78 +1,67 @@ package net.vulkanmod.render.chunk.util; import org.apache.commons.lang3.Validate; -import org.jetbrains.annotations.NotNull; import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Spliterator; -import java.util.function.Consumer; public class CircularIntList { - private int[] list; - private final int startIndex; + private final int size; + private final int[] list; + private int startIndex; - private int[] previous; - private int[] next; + private final OwnIterator iterator; + private final RangeIterator rangeIterator; - private OwnIterator iterator; + public CircularIntList(int size) { + this.size = size; + this.list = new int[size + 2]; - public CircularIntList(int size, int startIndex) { - this.startIndex = startIndex; - - this.generateList(size); + this.iterator = new OwnIterator(); + this.rangeIterator = new RangeIterator(); } - private void generateList(int size) { - int[] list = new int[size]; + public void updateStartIdx(int startIndex) { + int[] list = this.list; + this.startIndex = startIndex; - this.previous = new int[size]; - this.next = new int[size]; + list[0] = -1; + list[size + 1] = -1; - int k = 0; + int k = 1; for(int i = startIndex; i < size; ++i) { list[k] = i; - ++k; } for(int i = 0; i < startIndex; ++i) { list[k] = i; ++k; } - - this.previous[0] = -1; - System.arraycopy(list, 0, this.previous, 1, size - 1); - - this.next[size - 1] = -1; - System.arraycopy(list, 1, this.next, 0, size - 1); - - this.list = list; } public int getNext(int i) { - return this.next[i]; + return this.list[i + 1]; } public int getPrevious(int i) { - return this.previous[i]; + return this.list[i - 1]; } public OwnIterator iterator() { - return new OwnIterator(); + return this.iterator; } - public RangeIterator rangeIterator(int startIndex, int endIndex) { - return new RangeIterator(startIndex, endIndex); + public RangeIterator getRangeIterator(int startIndex, int endIndex) { + this.rangeIterator.update(startIndex, endIndex); + return this.rangeIterator; } - public void restartIterator() { - this.iterator.restart(); + public RangeIterator createRangeIterator() { + return new RangeIterator(); } public class OwnIterator implements Iterator { - private int currentIndex = -1; - private final int maxIndex = list.length - 1; + private int currentIndex = 0; + private final int maxIndex = size; @Override public boolean hasNext() { @@ -90,38 +79,32 @@ public int getCurrentIndex() { } public void restart() { - this.currentIndex = -1; + this.currentIndex = 0; } } public class RangeIterator implements Iterator { private int currentIndex; - private final int startIndex; - private final int maxIndex; + private int startIndex; + private int endIndex; - public RangeIterator(int startIndex, int endIndex) { - this.startIndex = startIndex; - this.maxIndex = endIndex; - Validate.isTrue(this.maxIndex < list.length, "Beyond max size"); + public void update(int startIndex, int endIndex) { + Validate.isTrue(endIndex < list.length, "Beyond max size"); + this.startIndex = startIndex + 1; + this.endIndex = endIndex + 1; this.restart(); } @Override public boolean hasNext() { - return currentIndex < maxIndex; + return currentIndex < endIndex; } @Override public Integer next() { currentIndex++; - try { - return list[currentIndex]; - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(); - } - + return list[currentIndex]; } public int getCurrentIndex() { From 1799d82c4d17d9f91fbd28a3278708e2f6c3b384 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:11:26 +0100 Subject: [PATCH 049/177] Fix wrong sampler binding --- .../core/rendertype_breeze_wind/rendertype_breeze_wind.vsh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh index 6c5a9f1cb8..94a186ffd3 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh @@ -14,7 +14,7 @@ layout(binding = 0) uniform UniformBufferObject { int FogShape; }; -layout(binding = 4) uniform sampler2D Sampler2; +layout(binding = 3) uniform sampler2D Sampler2; layout(location = 0) out float vertexDistance; layout(location = 1) out vec4 vertexColor; From 2350b4a3d582de5bd40881285fa6e08b84b8b5fb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:21:58 +0100 Subject: [PATCH 050/177] Update Minecraft version dependency --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 595e357a3c..b70e87d78a 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,7 @@ "depends": { "fabricloader": ">=0.14.14", - "minecraft": ">=1.21" + "minecraft": ["1.21", "1.21.1"] }, "custom": { "fabric-renderer-api-v1:contains_renderer": true From b96e46d590218b2ef86c539133011e0fbf25749b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:22:41 +0100 Subject: [PATCH 051/177] Move end frame injection - Refactor --- .../mixin/render/MinecraftMixin.java | 52 ---------------- .../mixin/render/RenderSystemMixin.java | 7 --- .../mixin/render/frame/MinecraftMixin.java | 61 +++++++++++++++++++ .../mixin/render/frame/RenderSystemMixin.java | 16 +++++ src/main/resources/vulkanmod.mixins.json | 2 + 5 files changed, 79 insertions(+), 59 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 2217745c14..2b42bbcdd1 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -1,7 +1,5 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.TimerQuery; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; @@ -19,7 +17,6 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Optional; @@ -27,7 +24,6 @@ @Mixin(Minecraft.class) public class MinecraftMixin { - @Shadow public boolean noRender; @Shadow @Final public Options options; @Inject(method = "", at = @At(value = "RETURN")) @@ -40,53 +36,6 @@ private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { } } - @Inject(method = "runTick", at = @At(value = "HEAD")) - private void preFrameOps(boolean bl, CallbackInfo ci) { - Renderer.getInstance().preInitFrame(); - } - - // Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V")) - private void beginRender(int i, boolean bl) { - RenderSystem.clear(i, bl); - Renderer.getInstance().beginFrame(); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;updateDisplay()V", shift = At.Shift.BEFORE)) - private void submitRender(boolean tick, CallbackInfo ci) { - Renderer.getInstance().endFrame(); - } - - @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) - private void beginRender2(CallbackInfo ci) { - Renderer.getInstance().beginFrame(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) - private void redirectMainTarget1(RenderTarget instance, boolean bl) { - Renderer.getInstance().getMainPass().mainTargetBindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) - private void redirectMainTarget2(RenderTarget instance) { - Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) - private void removeBlit(RenderTarget instance, int i, int j) { - } - - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Ljava/lang/Thread;yield()V")) - private void removeThreadYield() { - } - - @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) - private void limitWhenMinimized(CallbackInfoReturnable cir) { - if (this.noRender) - cir.setReturnValue(10); - } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) private Optional removeTimer() { return Optional.empty(); @@ -105,7 +54,6 @@ public void close(CallbackInfo ci) { Vulkan.waitIdle(); } - @Inject(method = "close", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/VirtualScreen;close()V")) public void close2(CallbackInfo ci) { Vulkan.cleanUp(); diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 4ce202ca21..240c202166 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -14,8 +14,6 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; import java.util.function.Consumer; @@ -30,7 +28,6 @@ public abstract class RenderSystemMixin { @Shadow private static Matrix4f modelViewMatrix; @Shadow private static Matrix4f textureMatrix; - @Shadow @Final private static int[] shaderTextures; @Shadow @Final private static float[] shaderColor; @Shadow @Final private static Vector3f[] shaderLightDirections; @Shadow @Final private static float[] shaderFogColor; @@ -139,10 +136,6 @@ public static void clearDepth(double d) { VRenderSystem.clearDepth(d); } - @Redirect(method = "flipFrame", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwSwapBuffers(J)V"), remap = false) - private static void removeSwapBuffers(long window) { - } - /** * @author */ diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java new file mode 100644 index 0000000000..6184f79028 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java @@ -0,0 +1,61 @@ +package net.vulkanmod.mixin.render.frame; + +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.vulkanmod.vulkan.Renderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(Minecraft.class) +public class MinecraftMixin { + + @Shadow public boolean noRender; + + @Inject(method = "runTick", at = @At(value = "HEAD")) + private void preFrameOps(boolean bl, CallbackInfo ci) { + Renderer.getInstance().preInitFrame(); + } + + // Main target (framebuffer) ops + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V")) + private void beginRender(int i, boolean bl) { + RenderSystem.clear(i, bl); + Renderer.getInstance().beginFrame(); + } + + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) + private void beginRender2(CallbackInfo ci) { + Renderer.getInstance().beginFrame(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) + private void redirectMainTarget1(RenderTarget instance, boolean bl) { + Renderer.getInstance().getMainPass().mainTargetBindWrite(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) + private void redirectMainTarget2(RenderTarget instance) { + Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) + private void removeBlit(RenderTarget instance, int i, int j) { + } + + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Ljava/lang/Thread;yield()V")) + private void removeThreadYield() { + } + + @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) + private void limitWhenMinimized(CallbackInfoReturnable cir) { + if (this.noRender) + cir.setReturnValue(10); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java new file mode 100644 index 0000000000..f4ca167b94 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java @@ -0,0 +1,16 @@ +package net.vulkanmod.mixin.render.frame; + +import com.mojang.blaze3d.systems.RenderSystem; +import net.vulkanmod.vulkan.Renderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(RenderSystem.class) +public class RenderSystemMixin { + + @Redirect(method = "flipFrame", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwSwapBuffers(J)V"), remap = false) + private static void endFrame(long window) { + Renderer.getInstance().endFrame(); + } +} diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 2a26be555b..69d941237f 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -54,6 +54,8 @@ "render.entity.LevelRendererM", "render.entity.model.ModelPartCubeM", "render.entity.model.ModelPartM", + "render.frame.MinecraftMixin", + "render.frame.RenderSystemMixin", "render.frapi.fluid.FluidRenderingImplMixin", "render.frapi.BakedModelM", "render.frapi.ItemRendererAccessor", From cd876d3997bb6fac3f6213d1391eb2cfbb37e13c Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:23:30 +0100 Subject: [PATCH 052/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ec11cbc3a0..8f55f61cb9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version=0.16.9 fabric_version=0.110.0+1.21.1 # Mod Properties -mod_version = 0.5.1-dev +mod_version = 0.5.2-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.1 From 4319366c3c9969472122fb13855d9d660e46646c Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 22 Dec 2024 16:32:49 +0100 Subject: [PATCH 053/177] Improve gl texture compatibility - Add gl method overwrites --- src/main/java/net/vulkanmod/gl/GlTexture.java | 72 +++++++++++++------ .../mixin/compatibility/gl/GL11M.java | 18 +++++ .../mixin/render/GlStateManagerM.java | 4 +- 3 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/GlTexture.java b/src/main/java/net/vulkanmod/gl/GlTexture.java index 8d2a0969c3..085705d038 100644 --- a/src/main/java/net/vulkanmod/gl/GlTexture.java +++ b/src/main/java/net/vulkanmod/gl/GlTexture.java @@ -23,6 +23,10 @@ public class GlTexture { private static GlTexture boundTexture; private static int activeTexture = 0; + private static int unpackRowLength; + private static int unpackSkipRows; + private static int unpackSkipPixels; + public static void bindIdToImage(int id, VulkanImage vulkanImage) { GlTexture texture = map.get(id); texture.vulkanImage = vulkanImage; @@ -79,7 +83,9 @@ public static void texImage2D(int target, int level, int internalFormat, int wid if (checkParams(level, width, height)) return; - boundTexture.allocateIfNeeded(width, height, internalFormat, type); + boundTexture.updateParams(level, width, height, internalFormat, type); + boundTexture.allocateIfNeeded(); + VTextureSelector.bindTexture(activeTexture, boundTexture.vulkanImage); texSubImage2D(target, level, 0, 0, width, height, format, type, pixels); @@ -89,7 +95,9 @@ public static void texImage2D(int target, int level, int internalFormat, int wid if (checkParams(level, width, height)) return; - boundTexture.allocateIfNeeded(width, height, internalFormat, type); + boundTexture.updateParams(level, width, height, internalFormat, type); + boundTexture.allocateIfNeeded(); + VTextureSelector.bindTexture(activeTexture, boundTexture.vulkanImage); texSubImage2D(target, level, 0, 0, width, height, format, type, pixels); @@ -99,11 +107,6 @@ private static boolean checkParams(int level, int width, int height) { if (width == 0 || height == 0) return true; - // TODO: levels - if (level != 0) { -// throw new UnsupportedOperationException(); - return true; - } return false; } @@ -127,7 +130,7 @@ public static void texSubImage2D(int target, int level, int xOffset, int yOffset } if (src != null) - boundTexture.uploadSubImage(xOffset, yOffset, width, height, format, src); + boundTexture.uploadSubImage(level, xOffset, yOffset, width, height, format, src); } private static ByteBuffer getByteBuffer(int width, int height, long pixels) { @@ -157,7 +160,7 @@ public static void texSubImage2D(int target, int level, int xOffset, int yOffset } if (src != null) - boundTexture.uploadSubImage(xOffset, yOffset, width, height, format, src); + boundTexture.uploadSubImage(level, xOffset, yOffset, width, height, format, src); } public static void texParameteri(int target, int pName, int param) { @@ -200,6 +203,14 @@ public static int getTexLevelParameter(int target, int level, int pName) { }; } + public static void pixelStoreI(int pName, int value) { + switch (pName) { + case GL11.GL_UNPACK_ROW_LENGTH -> unpackRowLength = value; + case GL11.GL_UNPACK_SKIP_ROWS -> unpackSkipRows = value; + case GL11.GL_UNPACK_SKIP_PIXELS -> unpackSkipPixels = value; + } + } + public static void generateMipmap(int target) { if (target != GL11.GL_TEXTURE_2D) throw new UnsupportedOperationException("target != GL_TEXTURE_2D not supported"); @@ -237,7 +248,9 @@ public static GlTexture getBoundTexture() { final int id; VulkanImage vulkanImage; - int internalFormat; + + int width, height; + int vkFormat; boolean needsUpdate = false; int maxLevel = 0; @@ -250,14 +263,27 @@ public GlTexture(int id) { this.id = id; } - void allocateIfNeeded(int width, int height, int internalFormat, int type) { - this.internalFormat = internalFormat; - int vkFormat = GlUtil.vulkanFormat(internalFormat, type); + void updateParams(int level, int width, int height, int internalFormat, int type) { + if (level > this.maxLevel) { + this.maxLevel = level; - needsUpdate |= vulkanImage == null || - vulkanImage.width != width || vulkanImage.height != height || - vkFormat != vulkanImage.format; + this.needsUpdate = true; + } + + if (level == 0) { + int vkFormat = GlUtil.vulkanFormat(internalFormat, type); + + if (this.vulkanImage == null || this.width != width || this.height != height || vkFormat != vulkanImage.format) { + this.width = width; + this.height = height; + this.vkFormat = vkFormat; + this.needsUpdate = true; + } + } + } + + void allocateIfNeeded() { if (needsUpdate) { allocateImage(width, height, vkFormat); updateSampler(); @@ -270,17 +296,19 @@ void allocateImage(int width, int height, int vkFormat) { if (this.vulkanImage != null) this.vulkanImage.free(); - if (VulkanImage.isDepthFormat(vkFormat)) - this.vulkanImage = VulkanImage.createDepthImage(vkFormat, - width, height, + if (VulkanImage.isDepthFormat(vkFormat)) { + this.vulkanImage = VulkanImage.createDepthImage( + vkFormat, width, height, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, false, true); - else + } + else { this.vulkanImage = new VulkanImage.Builder(width, height) .setMipLevels(maxLevel + 1) .setFormat(vkFormat) .addUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) .createVulkanImage(); + } } void updateSampler() { @@ -300,7 +328,7 @@ void updateSampler() { vulkanImage.updateTextureSampler(maxLod, samplerFlags); } - private void uploadSubImage(int xOffset, int yOffset, int width, int height, int format, ByteBuffer pixels) { + private void uploadSubImage(int level, int xOffset, int yOffset, int width, int height, int format, ByteBuffer pixels) { ByteBuffer src; if (format == GL11.GL_RGB && vulkanImage.format == VK_FORMAT_R8G8B8A8_UNORM) { src = GlUtil.RGBtoRGBA_buffer(pixels); @@ -310,7 +338,7 @@ private void uploadSubImage(int xOffset, int yOffset, int width, int height, int src = pixels; } - this.vulkanImage.uploadSubTextureAsync(0, width, height, xOffset, yOffset, 0, 0, 0, src); + this.vulkanImage.uploadSubTextureAsync(level, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, src); if (src != pixels) { MemoryUtil.memFree(src); diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index 170604a42d..369eba7c95 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -192,6 +192,15 @@ public static int glGetTexLevelParameteri(@NativeType("GLenum") int target, @Nat return GlTexture.getTexLevelParameter(target, level, pname); } + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glPixelStorei(@NativeType("GLenum") int pname, @NativeType("GLint") int param) { + GlTexture.pixelStoreI(pname, param); + } + /** * @author * @reason @@ -278,4 +287,13 @@ public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLi public static void glCopyTexSubImage2D(@NativeType("GLenum") int target, @NativeType("GLint") int level, @NativeType("GLint") int xoffset, @NativeType("GLint") int yoffset, @NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) { // TODO } + + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glBlendFunc(@NativeType("GLenum") int sfactor, @NativeType("GLenum") int dfactor) { + // TODO + } } diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 8794d62595..fb460b49c9 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -127,6 +127,7 @@ public static int _getError() { */ @Overwrite(remap = false) public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { + RenderSystem.assertOnRenderThreadOrInit(); GlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); } @@ -135,7 +136,8 @@ public static void _texImage2D(int target, int level, int internalFormat, int wi */ @Overwrite(remap = false) public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { - + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** From 211ada81ad2179ba070a290e97489c2a205bbdfa Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 22 Dec 2024 16:34:06 +0100 Subject: [PATCH 054/177] Fix image upload sync bugs --- .../mixin/texture/update/MSpriteContents.java | 25 +++++++++++---- .../render/texture/SpriteUpdateUtil.java | 4 +-- .../java/net/vulkanmod/vulkan/Renderer.java | 32 +++++++++++-------- .../vulkan/texture/VTextureSelector.java | 2 ++ src/main/resources/vulkanmod.accesswidener | 6 ++++ 5 files changed, 47 insertions(+), 22 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java index 8313ca9245..ea6603d66e 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java @@ -1,24 +1,37 @@ package net.vulkanmod.mixin.texture.update; -import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.client.renderer.texture.SpriteContents; import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.texture.VTextureSelector; +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; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(SpriteContents.class) +@Mixin(SpriteContents.Ticker.class) public class MSpriteContents { - @Inject(method = "upload", at = @At("HEAD"), cancellable = true) - private void checkUpload(int i, int j, int k, int l, NativeImage[] nativeImages, CallbackInfo ci) { - if (!SpriteUpdateUtil.shouldUpload()) { + @Shadow int subFrame; + @Shadow int frame; + @Shadow @Final SpriteContents.AnimatedTexture animationInfo; + + @Inject(method = "tickAndUpload", at = @At("HEAD"), cancellable = true) + private void checkUpload(int i, int j, CallbackInfo ci) { + if (!SpriteUpdateUtil.doUploadFrame()) { + // Update animations frames even if no upload is scheduled + ++this.subFrame; + SpriteContents.FrameInfo frameInfo = this.animationInfo.frames.get(this.frame); + if (this.subFrame >= frameInfo.time) { + this.frame = (this.frame + 1) % this.animationInfo.frames.size(); + this.subFrame = 0; + } + ci.cancel(); } else { - SpriteUpdateUtil.addTransitionedLayout(VTextureSelector.getBoundTexture(0)); + SpriteUpdateUtil.addTransitionedLayout(VTextureSelector.getBoundTexture()); } } } diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index add740f8c7..82f0ceab20 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -9,14 +9,14 @@ public abstract class SpriteUpdateUtil { - private static boolean doUpload = false; + private static boolean doUpload = true; private static final Set transitionedLayouts = new HashSet<>(); public static void setDoUpload(boolean b) { doUpload = b; } - public static boolean shouldUpload() { + public static boolean doUploadFrame() { return doUpload; } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index b67bc63d61..fc21d3a8e3 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -182,8 +182,8 @@ private void createSyncObjects() { for (int i = 0; i < framesNum; i++) { if (vkCreateSemaphore(device, semaphoreInfo, null, pImageAvailableSemaphore) != VK_SUCCESS - || vkCreateSemaphore(device, semaphoreInfo, null, pRenderFinishedSemaphore) != VK_SUCCESS - || vkCreateFence(device, fenceInfo, null, pFence) != VK_SUCCESS) { + || vkCreateSemaphore(device, semaphoreInfo, null, pRenderFinishedSemaphore) != VK_SUCCESS + || vkCreateFence(device, fenceInfo, null, pFence) != VK_SUCCESS) { throw new RuntimeException("Failed to create synchronization objects for the frame: " + i); } @@ -206,7 +206,7 @@ public void preInitFrame() { // runTick might be called recursively, // this check forces sync to avoid upload corruption if (lastReset == currentFrame) { - Synchronization.INSTANCE.waitFences(); + waitFences(); } lastReset = currentFrame; @@ -256,7 +256,7 @@ public void beginFrame() { IntBuffer pImageIndex = stack.mallocInt(1); int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, - imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex); + imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex); if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) { swapChainUpdate = true; @@ -303,10 +303,7 @@ public void endFrame() { mainPass.end(currentCmdBuffer); - // Make sure there are no uploads/transitions scheduled - ImageUploadHelper.INSTANCE.submitCommands(); - Synchronization.INSTANCE.waitFences(); - Vulkan.getStagingBuffer().reset(); + waitFences(); submitFrame(); recordingCmds = false; @@ -362,7 +359,7 @@ private void submitFrame() { } /** - * Called in case draw results are needed before the of the frame + * Called in case draw results are needed before the of the frame */ public void flushCmds() { if (!this.recordingCmds) @@ -381,7 +378,7 @@ public void flushCmds() { vkResetFences(device, inFlightFences.get(currentFrame)); - Synchronization.INSTANCE.waitFences(); + waitFences(); if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); @@ -437,6 +434,13 @@ public void removeUsedPipeline(Pipeline pipeline) { usedPipelines.remove(pipeline); } + private void waitFences() { + // Make sure there are no uploads/transitions scheduled + ImageUploadHelper.INSTANCE.submitCommands(); + Synchronization.INSTANCE.waitFences(); + Vulkan.getStagingBuffer().reset(); + } + private void resetDescriptors() { for (Pipeline pipeline : usedPipelines) { pipeline.resetDescriptorPool(currentFrame); @@ -454,9 +458,9 @@ void waitForSwapChain() { try (MemoryStack stack = MemoryStack.stackPush()) { //Empty Submit VkSubmitInfo info = VkSubmitInfo.calloc(stack) - .sType$Default() - .pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))) - .pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); + .sType$Default() + .pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))) + .pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), info, inFlightFences.get(currentFrame)); vkWaitForFences(device, inFlightFences.get(currentFrame), true, -1); @@ -465,7 +469,7 @@ void waitForSwapChain() { @SuppressWarnings("UnreachableCode") private void recreateSwapChain() { - Synchronization.INSTANCE.waitFences(); + waitFences(); Vulkan.waitIdle(); commandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0)); diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index 0b3903d7f3..b8b9fee587 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -105,6 +105,8 @@ public static void setActiveTexture(int activeTexture) { VTextureSelector.activeTexture = activeTexture; } + public static VulkanImage getBoundTexture() { return boundTextures[activeTexture]; } + public static VulkanImage getBoundTexture(int i) { return boundTextures[i]; } public static VulkanImage getWhiteTexture() { return whiteTexture; } diff --git a/src/main/resources/vulkanmod.accesswidener b/src/main/resources/vulkanmod.accesswidener index 459ba601dc..2dd84a08c2 100644 --- a/src/main/resources/vulkanmod.accesswidener +++ b/src/main/resources/vulkanmod.accesswidener @@ -6,6 +6,12 @@ accessible class net/minecraft/client/gui/Gui$HeartType accessible class net/minecraft/client/renderer/OutlineBufferSource$EntityOutlineGenerator +accessible class net/minecraft/client/renderer/texture/SpriteContents$Ticker +accessible class net/minecraft/client/renderer/texture/SpriteContents$FrameInfo +accessible class net/minecraft/client/renderer/texture/SpriteContents$AnimatedTexture +accessible field net/minecraft/client/renderer/texture/SpriteContents$AnimatedTexture frames Ljava/util/List; +accessible field net/minecraft/client/renderer/texture/SpriteContents$FrameInfo time I + #1.20 accessible field com/mojang/blaze3d/systems/RenderSystem vertexSorting Lcom/mojang/blaze3d/vertex/VertexSorting; accessible field net/minecraft/client/renderer/RenderStateShard name Ljava/lang/String; From 16e8cda996df0cde99cea3cb595b7c7397a9746e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 22 Dec 2024 16:39:13 +0100 Subject: [PATCH 055/177] Add method overwrite --- src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index fb460b49c9..594a3cfaf6 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -178,6 +178,8 @@ public static int _getTexLevelParameter(int i, int j, int k) { @Overwrite(remap = false) public static void _pixelStore(int pname, int param) { //Used during upload to set copy offsets + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.pixelStoreI(pname, param); } /** From 5231929b092a39072cc6366a0f3ed539e1f83c36 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 23 Dec 2024 00:29:38 +0100 Subject: [PATCH 056/177] Fix: buffer size --- src/main/java/net/vulkanmod/gl/GlTexture.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/GlTexture.java b/src/main/java/net/vulkanmod/gl/GlTexture.java index 085705d038..ae7f2be19b 100644 --- a/src/main/java/net/vulkanmod/gl/GlTexture.java +++ b/src/main/java/net/vulkanmod/gl/GlTexture.java @@ -137,7 +137,9 @@ private static ByteBuffer getByteBuffer(int width, int height, long pixels) { ByteBuffer src; // TODO: hardcoded format size int formatSize = 4; - src = MemoryUtil.memByteBuffer(pixels, width * height * formatSize); + int rowLength = unpackRowLength != 0 ? unpackRowLength : width; + int offset = (unpackSkipRows * rowLength + unpackSkipPixels) * formatSize; + src = MemoryUtil.memByteBuffer(pixels + offset, (rowLength * height - unpackSkipPixels) * formatSize); return src; } @@ -338,7 +340,7 @@ private void uploadSubImage(int level, int xOffset, int yOffset, int width, int src = pixels; } - this.vulkanImage.uploadSubTextureAsync(level, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, src); + this.vulkanImage.uploadSubTextureAsync(level, width, height, xOffset, yOffset, 0, 0, unpackRowLength, src); if (src != pixels) { MemoryUtil.memFree(src); From 93ef2a63700bbeddfaeabc8c16e6561855239b47 Mon Sep 17 00:00:00 2001 From: Fox2Code <42963271+Fox2Code@users.noreply.github.com> Date: Wed, 15 Jan 2025 16:55:56 +0100 Subject: [PATCH 057/177] Fix polygon mode mixin using face as mode (#516) --- .../java/net/vulkanmod/mixin/render/RenderSystemMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 240c202166..2fd1cfa7dd 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -276,9 +276,9 @@ public static void disableCull() { * @author */ @Overwrite(remap = false) - public static void polygonMode(final int i, final int j) { + public static void polygonMode(final int face, final int mode) { assertOnRenderThread(); - VRenderSystem.setPolygonModeGL(i); + VRenderSystem.setPolygonModeGL(mode); } /** From 6ce22778f7f03993191587aa6d4d35034a7a8617 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 16 Jan 2025 23:48:52 +0100 Subject: [PATCH 058/177] Update gradle and fabric-loom versions --- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.jar | Bin 43453 -> 43583 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 6 ++++-- gradlew.bat | 2 ++ 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index b933e3fd7c..3f9e6b94dc 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'fabric-loom' version '1.6.11' + id 'fabric-loom' version '1.9.2' id 'maven-publish' } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e6441136f3d4ba8a0da8d277868979cfbc8ad796..a4b76b9530d66f5e68d973ea569d8e19de379189 100644 GIT binary patch delta 12612 zcmY+pRa6|n(lttO3GVLh?(Xh3xVuAe26uONcL=V5;I6?T_zdn2`Oi5I_gl9gx~lft zRjVKRp?B~8Wyrx5$mS3|py!Njy{0Wt4i%@s8v88pK z6fPNA45)|*9+*w5kcg$o)}2g}%JfXe6l9ig4T8ia3Hlw#3f^fAKW63%<~GZJd-0YA z9YjleCs~#Y?V+`#nr+49hhsr$K$k!lg}AZDw@>2j=f7t~5IW6#K|lAX7|^N}lJ)I!km`nrwx> z))1Es16__aXGVzQM0EC8xH+O!nqTFBg9Ci{NwRK*CP<6s`Gq(~#lqb(zOlh6ZDBK* zr$|NDj^s6VanrKa+QC;5>twePaexqRI%RO~OY075y?NN90I|f^(P# zF=b>fZ73b5JzD`#GC3lTQ_B3lMeBWgQUGYnFw*HQC}^z{$6G4j(n4y-pRxPT(d2Wgb%vCH(?+t&Pj z)QM`zc`U`+<~D+9E{4Uj2kc#*6eZMU$4Oj6QMfA^K!rbl`iBix=2sPrs7j@aqIrE zTaZJ2M09>rp$mgyUZ!r2$UK{+DGqgl`n;*qFF~M(r#eh`T{MO?2&j?xgr8FU$u3-` zhRDc_I23LL4)K&xg$^&l-W=!Jp-P(_Ie07q>Je;QLxi8LaEc%;WIacJD_T69egF?7 z;I_Sg_!+qrur8$Hq4grigaiVF>U7uWJ@Hkd&%kmFnQN-P^fq0gB1|uRt!U#X;DnlV zo?yHWTw7g5B;#xxY`adhi4yZn@f(7-Xa(J6S=#d@&rlFw!qfvholE>MEb|VWn^g}G zMSrK&zQ^vDId&ojL!{%{o7?s{7;{+u%L{|tar(gp?Uxq3p?xAysB>0E$eG#$tvkk9 z2Q2gEP17{U6@UD*v({5MP-CTZfvWMItVjb4c;i~WLq&{?Q1(koX&vt7+$z}10{^Id z{KDjGi0JpD7@;~odF__0m|p;5rIrHidOP9^mwKe#-&JX-X@acc)06G{LO1Wu)#gvZ za~y9(fhA%UwkDOVU1LBJ`0ROE z4&)dJKK%mG@+CIm?+wt9f~@xIMr8}UH*K1j| z0pppo{7gv3v{URwxVMeg>Ps!L5IKxm zjac2egjgb0vH5i75$s|sY_RYec#>faqJk|AGgV;v=^%BM(^p{p;(^SVt-88G9f!q; z>p}9E4^f0=01S2pQBE4}9YqE%TV)*hlU^8k9{&=K76+*Ax^r=AkBb%OCP^P2nm0Ri z;D-|Zk?gGeU<12ti2CnPVNA(Pb)02+r|&yTWW-OJO7 zNLb0pps6aN?A~NJp5kj{{IOlf!5KWMleV@-hYLift)D>-7K+tgs=7Ake}oBnIy-y1 z(Hn@Hjw=_(x>dO5ysQsrnE%A*bk0K<-j{1Yqz@#n#jOL^AzCr#wR|WYzqk6i7v)Lf zkXdKxzuu20aP{Tbg$(+9&oh7cd(Uoqqf<#ujb$q4sZ~gxFbQfS zS)kNklyL*{2AELgjZ(LBu*>S(oH5AaJ;YiB@;l@=O%F6B?oanzoYRM^fQ9-<~^=3$H0g^JPMLQo@SZ@QuNvy)tyJ)LSj`+()#fy?{aV4Yg^7dlQ7AQM^3GLCR2dAFR zJjtfKiVqF`l-H_fz0HD|9g>)pOxn}k!vdZ=DO!7Sikm{Z%P6BrRkBS6W?ZB5W&7rT z@uYpf@M@a!z7H&o@-yrcCL^Ff3e7p3T`R9p?@o-acXmbTSa0>ZANzCSgovsd%;i$| zVus`not!oL#(W`L-!9w0jdaECaG4hk{V7IOs676ZquZH~0TX5hDq|)x z6T497l|E?f4)LA>j=S8}b$0LS=I4h|hUFJYJODT8Li@#6kF$k0)@*l{RnM1HQ%?VT ze-Pqlc!~t(oumVC*?5fwR;P6u{tHaZ~*LlD;B)4f? z?lpWfa2P@)g57flVl83Ej%P`2)gGyaPjhvD(%i~{`2b>#3!+y&` z!2nuwHMFA-zUY}f1^0B8<`N)Gr=A4TS@b1qykmd0Pq{?r)+1^^+D(=xasb^Tf!oK9 zBLL+*p6M_#ufgLzgq1zcSwZsZnQWFLC3`Yxdg-2=*tT`J9nrfYt)RF)YryBf8_gW{ zvKbB+oZLehfT)S#<|y1)E0hW^?+AnqPXq9Hu;v3dsMGdr{SVyF63;K<8VcgI#~}1i zLYSBL0K;RTT(;>2x=*!1Di9w0mwr;`CN}kM65|Ay{~z}_^JKOsRaN<~#9O^iiW<5P zYN7r~HV!#Nz~IZU`P>1Xe%4f~K}KcF#X&5kO*G}-)74S*tQ8CietdPcA1Yl;S=Mr# z`#MYY!{s^uo=jn7;k6O%(}fN+*0cWMpt~#n9DR<3NyU?+3D^AgI}S)Cu-Tljg`VY} zX1=fq$?8$DtOeGxE6f8lbS_6Q3C4+LDTO$}_IpM$Xv<|QSC%+Oll^q$y`7o@jD{dp zNDl|&X)r7wETa-#h*d`KXntxI(Y{vLha{$0i7@G8xx^m=c<{lJ9?p-i!^W{%j7-oo z0W^SzZ^(Wkyz*We{lEn%Yhu-ycUOHtrRiVJL4~&S91*D0MrLu}Q>v-Mc?GcWfpyz% zX|UvcN@krFO#@v|CtYM}g|=L3%aMo$E5<@CM%c*;?u>LOTz00@+dt1{yg1y=$h+{|D17U}$*^fE^H&8b431EUE z<9tv0V_#%#&1N#j7AKCj!tTK@J%oFW*ESW<(#Gl#Xs%v<@AitI?s92nLzm<)w3Wkkom1f$gcdUi%g_*jofy&}N#luL<$GVIe{iQkQ)sIHVy zBgItnPBFamrv6Kb{eE($Q(f`ZPeW!Hm%Y@F*OF1sKB{Yy|C>WEv_mfvv-N-jh)B-5 z4a!1WcT@9a+hGaBrc~sz=>G?Q!*Zp^JFRUvBMyNR1;`)j$RhH$6gEyVKhd$&K-CFT zXaWC-Y=fyOnqT84iMn9o5oLEOI(_3fk!W^8-74|q1QhQ|CmT0i=b;6Z3u?E{p7V{? z;f#Q-33!L+4&QQcZ~GAqu$NS{M;u%`+#9=7^Oa5PKvCCCWNG_~l(CidS!+xr-*gg{ z$UQ`_1tLT_9jB=Hckkwu>G{s0b0F4bnR7GibmHo?>TR&<3?D;5Fb#gd8*wYa$$~ar z7epl1qM)L{kwiNjQk}?)CFpNTd?0wAOUZ|gC{Ub|c-7h~+Rm(JbdoRe!RNVBQi!M8 z+~U6E2X&KSA*T6KJvsqwqZl#1&==Dm(#b^&VAKQ>7ygv*Fyr;)q9*^F@dCTg2g!w~ z%hg)UXAUyIpIbLXJv1nZX+a_C)BOH2hUim|>=JHCRf(!dtTidb&*~I!JrfRe+PO>w z@ox$G2a3i9d_N9J=|2$y2m-P&#PTNwe!oLBZFs;z|F5kXvBDn<)WwE0E3$ow=zg3R zK(9;sf0t;VEV3@gAg7jRtnj%-6O@!Hvg*;XcUAw}!=2*aErvB(eQIm(-UGmq^J=XN zTqJo$Y|WKo^HlBF3BXJrA#}7ZLg=r*w`I*~Ix`o&2k8^(0mt8Rp=A>F`&gehhp@Jy z^e^#B2!~$LvNCKugg)8)-G%&THdk~kfextilegP9?#C#()F59U$&eo(h|5>ceo*Em z{PEE79T$YP|Kr7K`WBHbtQwyxFkCl6xX&+oUf90B5xoi3_5KHHCyEE*oPbOQkfMz& z6^hT8_NXd2iWk{q9IKae1{_7hMPH8I7_BMtVOM4 z6jm?E0QJOn$qrgsJ`9w##GB9?G})-GXSQo6(tYS(Q0-Ct$co?Zzl0?NHsDRron?;_ zZZgQg)%XW>P?8_&zoGuF(>Och2kEJXsu1_X&~w87x!b z>~h!a>e7{`p@+#hXF88wI*JeWRZ;J4ev4<}HWf|Z;(7$E!S5l9wzBHFe>^I{2`a;a)QnAwa2xv1e(bq$<}!8o^ofGvYpk7dBR+`*%iE;hUY5 zaHF}OjGO9r*{%lmcK^uFiTHgoUD`^9Nx@~;Bg!V* zuuJ&ti{DQiq7RyJAR94wem{}cPK1J(Yxnn_{=>?USqz-~&QXRStS^s-7TksZ$AEI! z#og36s3JGtGU{CnDHRFtipFqvrE*gw7_K@NN0h+ItTq@4fqN!HeQU1y7*X?9+IfZT4Vxebpt z%#VzgdDK~-&+=Z*#>=n#XUhNvBZp3=Cr41jMqwJkHLf3L7Vm~V#GgJ(Jpii~PmJ#s zA7Ft!{xD@z>9DUb4JbiUBdNEcU4BO$651iN*mp*f)HbRRM`Cx5cR?5IfEcU{IZWwf zz(M6CDv)>xa3x}K6%tP^i15P1&&DOLK=k~+jNR$UK3frSl+|PjSC-dBItvD~LL! z>_g(YYdO4k(5EbPOw+v+;G7~jYm>F@Ai|o`gs%F)F8tDz$dl7Q%aCe|v|$UkAul_R zNlA-beBX^IJU?kgS`E$it7nF4DaI!SJAGq)2P&Few(-|tp z?K+%D3e4{pfkayrcbm0ftu6Ol2ZzdKM+4i!hNP3NRL`EvvZJ3yvNr2MV%igZ4kj``Qrdb_OI$7jWP z;l0DYf&0(-*QcP5zrP`HVznW+SbH63Qx$7_9~NjRNg7eKqI!UJ=XH`g^=t8GiFTu( z?2L{JKEu%jJx&XjNzU(*!ZNmL1@RlJA0G$2_LrAb_7lmjil(GSlSM zwTes`m+3R;3#N~Xg#9owh3ycXV8@ZlaY_16kpPFA={721b~URO4HD3sp%fmkZM}k) zZB0#)kP=RkNB~R-MCk8aljG_bagt4vIb~8)BV%(b8_;)&Kf9GX+%O_cNG|(D$!3&D zL(I8}*LqN5NntipFlN13=`D>6!{D@CFMBH0kW3=HccJV+xW~|$qeFR5i-2{X+iWMu zI2$gepQ)H_B%ip_BlWOQ*|pErXs|4ir{IHccgaIJ84irE{?+$KDABXr&f`jB^V-c% z$$u`uU1YB^{<+UN2cNg#7&0bz@yF?5>j|;)5&IV3wIQp58X#OE-M^$HdyvL|Um5t? zhZlAG!Mz%XkUe3t471JM*Yur}o30vzu6RN7gJyNcf!IItsDO730mcJ*O!~V``y5=3 zNJGp34DZ}wd1H6V`Uuy%es>BiO_aE-S8jzir#$& zyk)@2a5tP$@g%jW^b^JGdo)X@Q%sE`^lDQmY9m%uDFpPX`w9%=yQ+nneMm#OaXcD` z9}{tn5A2b2z9783vL2_jSao?uxJhWJoq%47*RafM4o0@gY(p)F>qT4^XM5GLzV#6j zC+HoGhAne7o_w{WUo(B++z7lU3Y0k1rYv9|TSv0vR-Du(5=VakbbelgZTeDn+a_Wv zq_j-^+Qz1WAl;Zg>ahX|CERbX1V%B!hTKN?M}fGoA07M(WU&NfT&TmN`P@56U2 z^)vLDs|Ln~0iTtn-?KTeQl@T&bskJFuTUS!m+$CS9vnd}8(UMO|Kv6TCfGN9NUu&4 zL{)GTxPq>fwsJ~aU=4Qhuq8*RzDsP(LZh$BHezq&9gK$IS<|DYbm})$QTGCS6T;Dr zEkLct!b+#<1r9OKG@P!f1wm8>=Nz!7OzJm!g<+`?N3;YaA3(P@EL=(sTaRMDD!c8=-XN^4BXp(eVkj$NmEMYPP>YJ4bJ3yUud z<3BeJAJ$6z^TuywnfH5lv#$lgwraNw{IV=tIznPH1DT`v-5yS=!)J<}xxl}uZf9azA2A97Haf!;<3y01hlw?dWNEv@TLi1s-mO4vmIT%O_42nS z$VRWrs9NngqRRkWAnWkn%`Rw@?wH|)7XL`EL5EZu$qyJW31&CB^T_)qwIv!{;E_6 zo-9XAryQRlk-O0>o#-SZO>|6OYq;}<*>Wu1AsVRiXY4f8qb;+sItv3AyS!4Ry+q}) zA!pAB|BmC;=RIOk^^vlsEH(!Q!7_1FK~ZB2err*o!+b(r=m1b?$6d!%zmN+69LXnT z&gRmM+n_R-F@sT*IYv0_mGPvur!u`iWbQO7SqiGFLeY&yga zf`lM&B74FA2C?N@8_z652fjhBEoDUKbP8hL{0{HAF%qDo7)o3=3rg#6)T7%%5^wl% z9R0*S*<~>nzYOdQk2l`9h#t+gJy_xujw6xjV(8S<_DbVg61&pT%Hi42l%D73G?adn znB%UdNM0p}lEF-P2%TAMam2zpQev71e>a$$%i+r~b+D9G9pF|oY_*(-u*89oKsXLY+UIbqq)MQ%(GYS{(*n_S_*RN$*~`zUtab%0aKwhx znc)Yo?{xq1sJCgQD)TeTci1ucvbez9q=A72H(-SB18Kl&6^vHV8^i!p@>iF!DIw17 z+8Q)TNisB7>pwyww4y)yJx*wX6SJO78eLBC-ar1+k$Z9fy;wBD|3kzI{<+l*>PSY^ z_?nLOZaeWbU@C3hfK?X;Di*8CHCPkx2qco6(ZyJdqSzp^TJ_5Lpa0UP{Gy+!b0Lr% z@xYxSjUKoY6L#>$qx~KD$-0=|OF7zhVP~ntMgEALYPIfhj@+ z!;JJ7te>CcovruwHsJH6Lta$nm|%^C@=V-rmhU{+I~0(|XHQ9jt@L7pb{gx#{4r!) zg($FyFTslcgu(~6lYr$nW?)%*l#VJ=R-jxK(x=t1bWlu(nL66T#qj%3aZ@uVhy}Co zDU_q61DD5FqqJ*#c|(M5tV)XBN?Ac^12*q)VN4yKPJ|#==S_`_QD9|0ls!`2)SwuHDRA_OfXQDq3%qW&MZB}Z!=k-9xqev8jHz(H z{^D@cIB~QiK>~wa)A&^Ll^Wi6QgCzU;iv-BHsLBs zH7=jN%|>0S`SjP%M&AF1PNVDp_FZ?2Bm@7`DC&v(pYrw!!yD#4 z6+<=HS0Ln6MhoKxF<%~H`y20{vf#pxh=;j{zY381gvAFekgG|>G1zo8$&az{V=;JR zy_puF4$L$?EMhT?;TpQoR*j16ll`#AS4e96C}yp_aGKkBe?1H|k_;gG-~Xorc<;lI zkB}fB{$c-D2mGA&{rm<*@F5)c3X+6??g~XoEwuzSuch0D@W~P5(2I8v8F$c2$Vw51 zP#YLSBDqtWW^EYBl^QYHF+MA7am6f4DOhwnJM=W9$uvMOsZ%_~?)2C#wb?CkI$7{K zEi)=#|5pFvg^){zK5kpBLjB2kZ+$ZB|L=W|aNwyyb(gC2l7bcpx{E-H@)q6@D6N^xh`{1E%ItF2$eeB_SjI@b2WgTpS1thwg&n`jiIzw^TtXUyB{00($GIq>vbj|}bav}}Q_~wp3>k8!E@hVC;OMUTu|= zAy#vXH*GrUHu7^cNZWe1>y;2(51js9wbu+R3Aa*(wzH9+X0dIsf&gc_x|_LP z>~CF^?(~U}+l~ehe|i>?4eo!xkq&Lk+RR-1duNP#o~>@1x)s&i&u zRaYL@+D&_M|JLI6fHbEr_`U;HgPTh#E3?sB)A$*gqyBgg*ql|a-m*TX5rACbWKCE6 zdeQ`v8m6>g^ugv`p|HY^#1QZrGGUj0^HVDc@{?Q0yhalbBEV{+|HzC^-{&e{5K%z9 z6Bxtnfu1!@Mp+Q&*&~;FOg&*Vm<@4b;{FG0-!UUXX!|)1w}op!B_|7_s~d(+=9Gba zKp8`LaB4D(H=cGcspJ_TjYaOwMb=sGn^gtUVhK!UI~2KKYEE-NC}F>+BEY7IVvy%KRvm00tg!Q`y=er}wpEetX}K@;}(}{s9AzV#q2@ zBy7}->|N?13POrs`;U?(qAG(I$~Gt+Rgw%aNZ_0fs_utVvRJT-7z4!@x36v@=NBX=IqkK{#Kg0w48de@?#Yb4M(Svj5=T+<ONr8-oh7l?Cji@+erqur zFhZ=9|Lk=$`c}v4u`)-!!UI=!9Jo@h&7p4RlS#u! zZ7-prn75JkV?VjptX;@$#`U`{vB!=Z?V`T*FBF>J?vsML7e6@2GbUteMFfX-TUu{2 zLNIG*;dV)8GV8gAgEf#)X3A>p3^CRka1v?~8x^anBhQ=L=LsOl=&pcOYHo98m##ye z34MtGCDK!`ptl?taGMr5q{!zVc? zG00e){TV?`YA9eB;(lA3lXI?RrB4BYQGk?vOmTIUJED=(`_*gtn2DB-t4WW54as*W zb2kD-lWX>lb$+W!VFakki>B^Vc+u$?NLF>)!U%b@Y}gYJ>m2H=^x0=nsE0TF^Yu0h ztgH8-o1%+jCk(+&`|)tTfEVHq0cMeFa{Uz)X$;fCq%Y=SOWML6bYfeP8j5hktL`KK z(18`XrUn&WN9PtFxh&dX`y~YBsmdhi7Kw%tKzM%^VEhdD<_XkulW-x=JN6OPbFI4@ zzDDRN+f=@{0h*MswwOqG6gJ?{NuHx(y-|FUGsxyZ*x0~$MW(eY>vqq4Fh#t7uzw=- zKB?|!0N~!h^AMdLa)oR!Ca#HZ9&Zf)ghuO<^RN)4twRlygHnQG(BE{cDc5E}OF4;xss6gYyV~EcJvJkX)xNWb=@yw!uq0v-sf^rvkp-;?DPWK@*SEw|V;IH=7 zfQqEV_>DjOPT~8X*J|H8=&RnzK4~S7ML~nLX^%s-Vqc^aWy7N$y57qciZGcqy#=zU zs8hcHiI=D$+RB{|62{ohCTiaML6FI4Uhzo5D{Jik@poCs0w7F)*w}F4r0sJ~#u-72 z5bK=ANt=M$Dh5NKnxGsg9NRR?WD-x|FhTwBjd zD<-K>44DB~i%frJOfnzh1R>PRY34kw!6~p3M$JLaD1r@`=h)~Ngks-(gdXh^Q?BTP zZ^Zj5w1AwtuR2$~E7s9iZdF}z%pv1em^V2rM{1tLUY@-+Sc0(9jA|iZWml1;v13=U zHf?y@#mb--7z6$ue>`qjhE~brk$AY-RG90~5wcBbDReXR2)pKg{L>;H(DI`U!MLNQ zY9rFJP@ZQ}jlcMh%WSCo%vf+nd0Gmd*F%KMIe>slCUh)8Ma|;M_I+v#;|ueg9oLg; zq2HtZX%&#F7vdpNlkX?}(C7dGC^y#NB#m4%69RzTNrk%4ol~hSI%>2r6B|*ZkW(*P z;u#s;+faHo{tfy+1L^RzWDi*^JR0iY(zJDB36y_QJ+|E-2x+cY z!V8uLNktH~q>WQZuY!Ap66WP|E!0PA1jK~)^8oJVGbspJs6QL!!-5Qm7 zHYI|_`Actg?vDzdg5{86w@GS$G6ANzff7->6i5pB$T4O}`fZ_;{217Om0gN5zTr12 z5mW{hCzCE-QubjxN$TAE-XgI-8dTY@OZmq`y+y_>dk*(qXF0{nam|q@~i}Utp*k{yurq(DW54hkDT4bbg z=_etM?Nf5W^o-HEu9_?&xEqPg^P^mTxLH8n%u$!mWvFG|{&)jtnU&6|5-`~eaNz0%D1BDo`{ zS1N5(KW5v^2eLdd_%`uaRndF@h0Uo6=M|8?b~KbOLZk{HXEnGmtgZXf2inI*1r%n! zQ3&%RI4r{f&dwW~HwH0Ked9b!k6{>_19H z_Ai>5IChDMY(FfMyG%;30?SQ{iV9KyGru62+Y)~qSQ91}b~}w<&*}R&1c#$O`H@~c z5)2S_eXx}M#N{MuGeQS9@#UJB@;W_j50b}jIhxMPloEFQZdvwxiU^RYycTzgK)-vl3LT&$L8~@68$C8~5_U{cR$E#w*x65(qw&eoL@>%ZHvj zWnEMlSh*(o&oy|J7eJ5OD`ssy%F?*Vp?`Cq;FShyl{ZoKCG5g{y}>usznni#8ki(i zO{w@n{iAj1_ooX@+s*!uW60WcH~*bNOT6z%0jVML5};wVrQp~`Uss_{cO2oud_nNA8^B$?07fJ6?iI)Q zuo9G)O-z)DqstrBqf>B%S05hf-wep0@$BFHKSrkZ{za3D)yVzRz)2{wf8(Wp+xyAM z$rtyx$gi3A=V~V!`Q3;BM0$>*VVtxEM|xDL^gew7ydy3Q6YzD&THRz*q33Ms_D;M- zbCx1Ft#UNB)V3bf`~{ImI72OTp^|bF8?G8#FRj+Biy8ET5#rA3sd|0FR@U(LAJ%w8 zS1%n8Z=Amhw)92rIsof=YVWF4jw&F*j1LG@-`+cR0-~2LqXRH8(Ccne{y#MCPncF64U`0uO zWmi$dlii~1D0rLR{qc|_2M!C$t8^=G7xQY)9!#Y331A|>N)EhmyVdLWL9I3YLJ`7? zZmpqUJB>Ni9oiL)^1IK1UoMyhWE{$9M2M6Xi zPKk7GpMsA6vjZbU7~i+u|J6Nk|Ci!Y3UMUT2|`M;JsNQACdJ%ooo9Yt{?A+0hMpxi znEa~~sxC>rKrU6bd=WRb;%wsH>A#j4{({&1GYSNR57Gama(3)2A;SM>qop}l>Jk2* zn1+C$fIxuwzg3mCU#SOqb-wOCb6mBcYlA5+mt<&_J~sBxc(GQtBFINUO~Mr7<-uu($>P HJ4oML2Lo<@i8BwbL^1~GkG`E7C$SEa_ zF^}Ea+#Je`Xy6;#D0FPnSrR%Y!QGA~NA^{oWmW8C<3dr{x6wWQ{4+bzemqV5W$i5~ z=J0jXZ>uZb>DT@0Ks?4QJ{`z?8JWl3$y;2pj#$XP*pv$>$g(z43{YH9KmmR6<#sIn zA`#=0#sgycaBQ^&}Xba!|KaZ8~b30v~nLt z9%#gz_*=~KD{3t^X~l>480*}PhKN=??g`RV|4Ud{Gyyl187MJ}r(#e+H$GEdI+p1s zq_25h;fV)$EPK%Dw-(G=f`yHB-_tttsC!?k7*#!|4a>`Ahj8nm?&n>NRs%jkZW^3-0P_yMP5&*6a26{MRj1&TPF zyE#|c)5uUHzMWx=rMKpuPih*V=S;W3MzIZTw2uTbr}8`p2bm+Z6Sa%vvWAWSf4H)p(+ zSQ8;EvUa#wqWV+9vmIio(%7wukK2SwjUS8Yl%Rq%=~PU)2$Tvm6`1!r3H@U#_|bB0 zmlT1PS3wPB(b&^+@YY7Y$n4l3mV3-X0$>z|gZp6O*Lhzn&?Gad2ZCF;+#95-Y?#y+ z?*l@Yf=a4w{Px=o!N|3~_XKfk&G;fN>Ps&dp2FpA~qD=0~=!NOS@B#XAKKkND>Y{4>rqxrViKD7;?>j8`R` z&G)3FN|dfsxnaI^!d1G%=>AbTTxZWo;n-DLrQ!sj=f~VAOe5zhGS(dgx|!ls62fbX zV@<7Ck^!}R=`Swr?(7w1rY6Nmq~sfXJ?TiKJLn=&SQdEt9$@0 zA+h1Wbwbri0s-stc8yVq;mRa6@kEf8^KXUz&jcic!+avDvvJFa>k0ioWug=T3oPw; zyj4it&0@>_*uI@2=^+T7sL1_!^aJW@Xfo8aC#3^WtQC7fET8b9C} z*u^ue6Ojn z7@(eskJ2+cNnH9~VyfIh<-|7!je~vGy*odz(sk-u$~SrYF3glruZ*W`{sqnS+9=;Z zh{D@MSG91%lr&ua8%$sJF%y1I<|e;EdfJykY8#D$Hc_81n5`$7;1N|b0tvvPLzSg& zn7!5x?T*@rQUKcUhTIjV(rw*5oQYlm5DbEO?60#mohHfbR$3_x#+PZoYi@Vd4`#YgKyTd^!4n{fN~WZDY61sAOm6 zl!d^i*a01QxpWM9Pcl?&{RgO}uq%ErOk5WpECvnfEh!*YP&1Sl)uTN4hg??Vqs~i5 zYsfufz3?{TtwuBN=`0~Qg1PlWH#OGG$ zLLWU17$v``)CE1cds_7kj8mJ{-+l8{DS|zAQ&3|qpOY=!J|kXUhXue9|H>4gqk|n) z-i34GmxLFj8asb3D#D&=ya*a5`C<=o?G;Ev^LV%;l#nH#O=7Nh@z1Do>j6Q;I5S2P zhg|AZbC&|c7}uSJt57s2IK#rSWuararn-02dkptTjo*R{c5o(bWV}_k3BBnKcE|6l zrHl&ezUyw^DmaMdDFVn<8ZY=7_{u{uW&*F<7Al6};lD(u;SB=RpIwI)PTyL=e25h* zGi{lRT}snjbMK~IUx|EGonH+w;iC2Ws)x>=5_{5$m?K z5(*1jMn%u0V1Y%m@`YS3kskt~`1p(rA4uk;Cs!w^KL$w>MH)+cP6|XKr4FfHIATJH z!EGAK4N>1yFR`-zW|w%ByRe#=&kA&#WyUldDGpt!wf-8SFWiSi!5QZL+l7*CE?u!NW1T$<1rdLJ9y3u{_zvHaM?#Rm4 zFk}^1!ffcrB|XK3gsO-s=wr*sUe&^$yN|KxrA)uW00Gu60%pw_+DcUjW`oW<35OC8 zq2{j8SgC}W$?10pvFU83(SL$%C?Kctu3*cs0aa%q!fjn1%xD*Jrm!F3HGR9-C{b?- zHp(cL;ezXMpL@0-1v0DMWddSDNZ5h?q50cOZyVi#bU3&PWE=(hpVn|M4_KYG5h9LffKNRsfhr^=SYiKg?#r&HNMi2@cd4aYL9lw(5_IvQJ zcB*DD()hUSAD^PdA0y|QrVnqwgI@pUXZXjHq3lG2OU&7sPOxxU$Y3&ytj6Qb=2#cC z;{d-{k|xI*bu+Vy&N+}{i(+1me!M;nshY_*&ZQLTGG*xNw#{RpI`3^eGfHck+*38NRgiGahkFethtVY=czJs#)VVc{T65rhU#3Vf?X)8f0)X{w!J3J{z|Sq|%?)nA+zo?$>L9@o`Kc|*7sJo4UjIqu0Ir~S5k^vEH};6K?-dZ0h*m%-1L zf!VC%YbM1~sZOG5zu&Sh>R;(md*_)kGHP)<;OA44W?y53PI%{&@MEN}9TOiqu+1a3AGetBr$c)Ao3OX>iGxmA;^^_alwS818r4Pn&uYe^;z6dh z)68T|AN=hjNdGpF7n>y+RTAZc9&opTXf zqWfK_dUv=mW{p_vN>|(cIkd(+Jy}qnK{IW%X*3!l`^H~FbAHwof+vLZ0C2ZXN1$v7 zgN&R9c8IO`fkR{6U%ERq8FN<1DQYbAN0-pH7EfcA{A&nhT!Be>jj>J!bNRw4NF|}! z1c70_#fkk!VQ!q1h2ff@`yDyrI1`np>*e#D4-Z~*!T^8#o*$V~!8bWQaie?P@KGBb z8rXc!YDL!$3ZgZZ%;-%~0Kn<+d+{xJ$stQbtN8GWV?MCJvzPU|(E(1z;rFw{&6vy) z3*@y%7Tx8rH-p$boS>bLyod?OKRE8v`QSBvGfY6f}_{Zo1q85xoyOF16n~yHx2W ziydUoYLkJmzq|n&2S(O!ZmLdP1(o1Jsq88cX)x3V-BK5eF&0e_0G!5?U7&3KN0`mc zH&Lt)q8!d_VgzxyL^(@xrbp2y)Hmr^V48));RSfE=*Ly0uh9!$3dv-vMZr2URf@l5zdwLjGZB zugY>7_fd_vbV*Qv1?H~>Z%RD%nEeFSI$n$$Lrpc6g>i4+XdBB!%zM$Bhrz5Swzyg? z$~I~n@~-wTBY3-T&pr+|gC+OHDoR?I(eLWa{Z#Rsh>lc~%u0!&R|s0pA*w<7QZ}{i z*AFr~0F3y~f$MGh_HDL7J_1?SxKL}fWIk!$G}`^{)xh*dZ5kK>xGL9>V`WZZg_ z)^Vm)EQK`yfh5KiR(vb&aHvhich z_5o+{d~0+4BEBqYJXyXBIEb1UgVDs;a!N2$9WA>CbfrWryqT25)S4E4)QXBd*3jN} z?phkAt`1rKW?xoLzEm!*IfkH|P>BtECVr0l8-IGk_`UjE#IWkUGqvyS+dMrCnFl<7RCgSMX^qn|Ld_4iYRldO zY&cHhv)GDo8nKvKwAbfyLR%t?9gG?R7~PSD#4D-;?F&!kV59O}neYut5AGbKwy-(U zqyBi=&Mgj|VIo>$u!DHM`R7O?W8-idbePuxiJMH``6c_5L-chKd}=rGC5Gfrc{f!* zWFEBm?l@_b7kzY7%1RQQbG5V<4=ZlkZ%sF74Q|mKOc7Ak7dP2#quiGcZ0_J%7Q?j{ zv9{WFw;n5G-Mn%r#0R;{jLt{yy}9J6rQ(>X9pJ`7Xy?Zv z=lNit#qXaq?CnElK^zF~sG}U5oCpR0T>FH=ZX}Prju$);?;VOhFH8L3I><9P_A|C+ z{;>~dk%9rrq(snjsEm}oUz2FQ21MCG*e?g)?{!&|eg7PX@I+Q0!hL6C7ZVY|g2E>i zr!Ri2@OfEu$)d52+>+cpgh6Z;cLYCZ&EMR0i<^~4&wEu_bdo;y^6}+U2GIQgW$|Od z_jg{O=pU>0-H$P-EOlWyQy#W0r@@_uT}Lg+!d5NxMii7aT1=|qm6BRaWOf{Pws54v zTu=}LR!V(JzI07>QR;;px0+zq=(s+XH-0~rVbmGp8<)7G+Jf)UYs<$Dd>-K+4}CsD zS}KYLmkbRvjwBO3PB%2@j(vOpm)!JABH_E7X^f#V-bzifSaKtE)|QrczC1$sC<<*Y z$hY*3E10fYk`2W09gM_U<2>+r^+ro$Bqh-O7uSa)cfPE_<#^O) zF+5V;-8LaCLKdIh3UB@idQZL`0Vx8`OE#6*1<;8(zi&E7MWB1S%~HAm%axyIHN2vd zA(pJGm_PraB0Aat3~?obWBs?iSc*NhM!{-l_WNCx4@F7I?)5&oI|z{o@JKd1HZ}zf*#}JjK3$ z-;3V*WJZvUcKvSOBH4c7C{fl8oRw8-vfgKQjNiR|KhQ%k6hWNEke(k8w-Ro| z7Y3)FsY-?7%;VT64vRM)l0%&HI~BXkSAOV#F3Bf#|3QLZM%6C{paqLTb3MU-_)`{R zRdfVQ)uX90VCa3ja$8m;cdtxQ*(tNjIfVb%#TCJWeH?o4RY#LWpyZBJHR| z6G-!4W5O^Z8U}e5GfZ!_M{B``ve{r0Z#CXV0x@~X#Pc;}{{ClY_uw^=wWurj0RKnoFzeY` z;gS!PCLCo*c}-hLc?C&wv&>P1hH75=p#;D3{Q8UZ0ctX!b)_@Ur=WCMEuz>pTs$@s z#7bIutL9Pm2FDb~d+H}uBI#pu6R}T{nzpz9U0XLb9lu@=9bTY&PEyFwhHHtXFX~6C zrcg|qqTk(|MIM%KQ<@j=DOjt|V)+8K26wE_CBNnZTg+Z+s}AU|jp6CFoIptG1{J*# z7Ne~l;ba*=bSwAMQ|Vq#fW~+je4PXA91YFzBubNF?ovIOw-$C-8=Ehed{lGD0}(Id zRe4sh8L>&T%{>8o))he}eE;5_ zxoXk3wX?MyNl-xF!q1d$G?=wp^`@09(jU&X zOqZIBI#dN`2PJNdATR3ivtub|nO$dulSaP|e4)WXF1YAGN1pDQIbIjXFG!oC85Mt; zW$eteoL{y^5t4TMRwP$jNPjZFpGsWnGe=jMMqKtcZm9Y9PFZLi*1p@qoKKub^T@2+ zk$@*KYdQ?Z`}<%4ALwk*Yc{(WTf@#u;as(fvE^9{Gk)lWbJP*SjttWofV0s?AB({~l zZI1hZVWFT~W-T?nfMMcnCS4-#6H-MU7H$KxD;yaM46K4Kc@~Q>xzB+QnD_I`b_l3m zo9pRx46b!p?a^&zCDwygqqV3epjs(s0NQI6ARA1n!Yy-qduipxQ& zUAlqRpNjBS+y-ZheD(!R;F}&^V_}b_gqH%tVZ5%%ziO7k^w=es+wZtK^i*vmrWNLMs{oWu_CIov|s1raZiS)>38>pYu;i+-t zI_DiNe6aA4KTZ2P09qPj(0~K4nUq^0+f(2$g`229zkG4jLzRvJUWE0oF1XHL4t3UN zDH466G56sy9hTZoAJB!C3;@F;ONxEk5u6Mv%zdo}Rq`=* zw1n7MOhfNSV48TS989ArIcj`C%Gk8~93~u>)!Yt2b4ZriKj9x2d`H2HQNJ=I>hkDlcZn zqRj>!;oRMTIOu zx|Zfsu~v76T{z7AC(jxj^c@tnJHZtGPsq$DE!8kqvkDx5W?KUJPL+!Ffpwfa+|5z5 zKPCiOPqZZrAG;2%OH0T$W|`C@C*!Z`@Wkop{CTjB&Tk`+{XPnt`ND`Haz;xV`H^RS zyXYtw@WlqTvToi;=mq1<-|IQ(gcOpU%)b#_46|IuWL#4$oYLbqwuk6=Q@xZaJSKVF zZcHs~ZBl;&lF3=+nK; zF`4gSCeZXlwmC_t4I`#PUNQ*)Uv&oGxMALip|sxv^lyVV73tKI7)+QY5=tEMas{vTD-BaTJ^*Y6gq~PU;F5X!sxqiq$iFCo+Uv7m%1w((=e}Vf*=dtds|6 zbX}91!G?C*KG03eHoN}RZS9DJxa&8YwNCT8?JxMXyZqZr13NA|GB{+vG`08C{V(yy zf*Lw$+tYSU_+dI`3n{bMrPdDb`A=Mkg!O=k>1|*3MC8j~- zXL79J4E=U^H=iBLTeHE_OKzE&dws8RNynsSJ!d;`zK?P92U{f)xvD7VQVosrXZrL+ z6lMVdD1YgL;%(1cq{#bS6yXmp|DS@nax#AqqlZhtUQdh<^2vr5`EpAO

LGYq)sa(w9^3-f}NHy=GR4v%t2YZly3m1G@5y`xBh_HGrD%f z>;|Ty?9FiJAc&UVD(StT4I` zfVQwxhE9bXE6r2mKO8Ag7{L^jCyqQb0QqKDPE=RAgqn8q1O^>(z7h5kE(6va%QqRZ zkIOmp(})rLSS(2{=C12e&@!W2=Jel-^_R``0xHO^+t!(oXbcv5yhD4g*$t_F)_5Dl zSVCgesW%;DtYPCFs{G;GX_o?1J3;QQPPv)rWw;>} zJ&KwnUqwNXloNXlK_+pNDfI~hON#SokVJb&ilg8d7^NWo2ZQymCqQMnjfi>ePibjr z-Z@q!?RGN$Mj}Nk){X_vaj6?Mj$>ACR*z|6MsXy3VZ^PFn@yHkPo(>m(iWepn8SC@ z>D2;R4m+gDRZ=SIX!b+CP(qE=JDIUkn=D$aUu+Ihn9-+k1LS3PreQg0N5eWIG@x${nC3v^7caS>1!PKNAY9J z#}E}Q9w#SP>(GY7Hbj&z4$Li6o5taBO|4+F`yS9zq*LJ<38wy4I>HA9(&GYrk4dLajKGww))BWli6Ln1A^Lda@N~p+snkb9C z@OthI+<##vp8!HVQT4Wk(=@zQ{OvZ$EKWS73+JHb)eYLGD-cqi6^|vd$<+IHuc?Nq zW7JertT~3))4?J|28n$I@nAD0c1%9C&IVhEZX~mUsf{efyS(XNG%ch;!N~d7S(Ri7 zb&=BuON95aVA&kLn6&MVU|x}xPMp7xwWxNU1wS+F6#y}1@^wQZB*(&ecT?RnQcI}Y z2*z!^!D?gDUhc@;M^OpLs4mq>C&p{}OWVv<)S9KMars@0JQ{c_ScGsFo3BJ)Irg++ zAWwypJdTO-_{Uh8m(Z!3KL7K{ZZzKHj;{M8I$mV>k znTM?sa0);^=X^cglL`uC+^J)M7nEa$w=VwFULg~%DJllw+7dJAj3{qnP5i3@wr7%y zjXp?Wl2%Th=my&3u?Q$RV6N5tzKMSPTsc#J+-cDDp~qFB6bL2C8AS7Y3PKtVhdhl) zIaLqH5+OnWPWSt(lQCgkN8lczc-V%_iZ{>#1%Z$N*>lu#S;0MZ$T2Y8Kg!U;hAZj> z6S#%$DQ_`Ic%Zr@?}GgjRXg@qTj^17n`65oJ@Wj0u1X8&+UVd|Xs?J+i_^GZ94m6= zUc96~Q`OJvlKB_Lr15*Yw_PUPEr?f?H&00b^-W%26mD)(n(rGGNfK9~2h=C>p-7BZ zFd&*&Msdu{w~(eyFOglwCPH^Rb}O(N7LtS+nnEwDx*pGD?|&9Si~M43a+*L(b0$5A zv`T`(G3xO;I_sx;FwTP21ZlfDpz zOo?}Vlgf~fo{YWm@n_JyD*frOg{XsvBA~|Tn4V6hu>Gd>89-rblfVJUaGvj6X%NZ} z$tFF9sx=4_$*c~G`9iPLGh@=sV+O{D2-t*K@J7H=`V+oVt}8?04WwU3h1BgS!f%1P zFak-T#7`TtLcR=Yz>g0R!ZQrH!YiZOQN=_V-UyncN1Rc18?KY?#O`v#JK+pq0K$~H z3D@v9DZF42R)b9#BBX{^$DOMlJ!g)Gc za{o-1e%F6NvgKq9tC8pV+9S$;9*zNv{J*)n&dmf~anP1)4~N%~h#c(=B#3*KgzhCKhFdgDoWi2IDog{RVyzK|Y`rCUs3T~pJMmdZJy4?b z&s5G=zhf**(t7Y^oC_mcTsE-{^}wiaoUu&?kojLKs>SJPxjcP>{a5CbXCx92AcBE) zHtqP}LjZ{W>PH?Tu(E0X=%{PBMW@F_?#7b&#!^q`<-5$ur+-q6 z{dn=(^UZw6*3-XM_(=@<1_*i&XM4=0t5u!gm6 z{UlmNGPKgO_;e;q9|#esq~Sq`<}%d{+sRmhvsA{5i*91=tub>OZZ%)xUA#4q$dDyy z1`w4%?OPLg3JeZb#cqSMO?*Xn%|-FCcuH2i2fn_{IFusub6;NQdN|7TD1N?%E8*g? z$apAt@cEe!I%jB=*q$p_3=t_5R0ph%{qaq+QDg!c99Y!Xa!&oDZOeis_ot)gNXr{l zdY$|So2Qed2Y7KMNBrS^E169kG%h<+z{Z_p_;shB!uY)>yAVcK=&!bg`lVg)4T1|7 z0}7FpfydVH4F87K@c!nEG+WGKm{Ouo)Slpl;#qcEIQ0zdMfLA#;dBxYw;p;KoVv6| z3_D5&7rJdG12CnDSvZUW?$UC6^UVSW^|vw|o-_4bz)(w5(3AiVhpeT(|=f#x_}E?s#qHZF#xA6AF_ujl$G z-jHD%q(d2}v2PhXx&6YWps~m(^+RXl91Q#xRRJBhjKl$FG4bk);|ag;ieUZ&!Ii3$ z(iGz1+0m7#g5>ASldBbNZL=ZHh=tmmJt$!71; zIML2GhEz1pg@1rQN(M^_691wAGkJ@Pga_05WuQ6! zG5RkGY2^`@(H~pp7&Ga+Pwh3L!Njj!-rc;^bTIfo5hP@H##1X8xUZJckrx>id`bAd3QUx9GuomqBYZ!uN1-&o zvTxC?;p8vL67&fW8fw(YOqt>L@bdLrEF*3OgYe$4n4{ zEB40LiU#6-0@5jdN`0w}N0qi@c0~oT2FP z)LNk&a82my?jv(tQpiMi$TK_L@lub#lsM$R{Dk?Ya@%%%huZkct~tSWM714c!45k}-ZLVA-bVM`>|_ZBbW_m-7| z3U%xrAhi}n?T(2F{_n4EZ10inkIFl#y09?7$uwBoJgqY8vylwev)fDOn;>0R!aEnV zBz%j0Mqpx~EZU3q@%+oV7;}|vt7$~ou@faEIq{p?FY$XXg&6*K)b_LP=}gi9`Bij3 zN`zEo|B6*|-;>S`rNa^BKRDbDAk>X#MsR`EvL>6bqU@SaDDs z8>bu@3YdRaWs*Te@G-UHjU%F~kTHw5(0PVJ+pwh#ha2u;DB+UMo@A5UYIl#5rtBV- zGX_hIpw}3C@H*Us(Cc-d#-gNrG#w$(9+S=GxO>3SR`SE2fHZ2KrDc#_C^$jI>Y}#; zMwY=R6@+dWi~0RXw(c@3GZ&%~9K(q&ee0Zw;pwL`E_tZak-#8^_b)Dpyi73^he?xV zXJ08&wh5-M&}qy4f7!D&=E)puDD(Nmg1d_(j`4LvxM5x_huNg-pGG%9rYqO6mImyJ@}*3Y>^3OvcnTG%EV1) zq_Ap?Z!Iw__7#D=pOWnQN$gB!Mr0!9yx|g<4icJh{cFOu3B8}&RiYm+Mb;VEK``LK zL(NcpcTiGieOIssSjr?ob}^``nNf&UcJhXyncO9m{6gD$kqSD`S69(aF8dkWz5>!9 zBLe4Sib7Hs2x_L2Ls6Ish$MGVKrGt5+_2zCyP1byaCg3upo+-I}R4&$m)8 zQ7|jc1Z^VWggpuQj*cP;>Zo9LS!VSzrqmZczaf;u`d0J(f%Z9r%An@s!e>n9%y=n!IZ_tVGu{Jmsbp}Fk%HJIU?a+-~bjfLTuH|JExA8EROowzr zqW9{YyZhR0a4clRK>1I4Ncx&WER~{iE;F^$T7K%X@3PGOA%6#Z%p3TS^&M;Dnjw@i z^o!$9nhcsmcHcY4?4j9+ofL_CWsZ4Hcch(rjsGfGD(nsH>w}^ERqGnz%iGj0j{g}h z7wMkJ-2Z2~eS>2!i}0~B63i;>SyFJU2+>VCS^AxaDOx%g6-t0eM^P<3+*z`ztvOqrG3)&#$K?& z_Y0wbWID47@cU`E1A6A&!`aZk0ZE@z-h#l1NqX2#`$Uev2gepW`rf8*!=rD5&;Jb{ zl08rU>dPo=K%-1Ao1~G-@4ve~y5#9E8x;TE0k5d^TC(=Zc>mwjW^c=+U-<9}b0ku~}gj z3sbW>R2M6DR!g#NUP;nxo>)@7*=RP{U18SDop6b2&PHce^&h97@xx3t+VK+!keE#} z;(Uf&89as9k8{$nkLbuB!-d7TP`_VJpL^Xs8OKB~ri$YUbW8fch64}7|0EWoT(TRj{ z*GT<7Y<7DsrCi79ZsM)z#c(!nNOGySOCkY1fAuQOq12&iUVC!a`#O;dBLf=d?&4*B zI~LgAO7E0qxK(uRTM;IgJ}+z^gD+bi-6I!3x{r9`l~%8TRP%UE0V8E*Sz>Nl1NVG<<7(wDHZ+HcOkQm$O&k+vyx)y)x{Pz!U8hS$*m zByc0h6BUI*BOpuL==P+H|Hx%`>7!W+1H!l9vi&)`V zyn2o9{z=lc+VX*!Vh~SF=)L}Z40XeG>LF6cP^b+R$NxSeUqbK^Q*UTalKzP8X%{9@RSCXm_NhF>{=S2 zi}ezam_^P`S!!-cyEW9y7DBbK93roz@Raccy*v}?mKXScU9E_4g;hBU7}zSofAFda zKYEe?{{I54 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b82aa23a4f..cea7a793a8 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 1aa94a4269..f3b75f3b0d 100644 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum diff --git a/gradlew.bat b/gradlew.bat index 25da30dbde..9d21a21834 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## From 4bfd020d77752c1e465b868ee1d71b6bfacc08ea Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 16 Jan 2025 23:52:29 +0100 Subject: [PATCH 059/177] Update FAPI version --- gradle.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 8f55f61cb9..76cc01bbdb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,12 +4,12 @@ org.gradle.parallel=true # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.21 -yarn_mappings=1.21+build.1 +minecraft_version=1.21.1 +yarn_mappings=1.21.1+build.3 loader_version=0.16.9 # Fabric API -fabric_version=0.110.0+1.21.1 +fabric_version=0.114.0+1.21.1 # Mod Properties mod_version = 0.5.2-dev From e0cfbbfa7815a11b48ca82ff4912717b75e7f262 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 16 Jan 2025 23:53:02 +0100 Subject: [PATCH 060/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 76cc01bbdb..1f7b347897 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version=0.16.9 fabric_version=0.114.0+1.21.1 # Mod Properties -mod_version = 0.5.2-dev +mod_version = 0.5.3-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.1 From c7cbab624b6b2ca9259d246778cefba0d43cc592 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 18 Jan 2025 20:17:21 +0100 Subject: [PATCH 061/177] Use uint32 index buffer type if required - Refactor buffer --- src/main/java/net/vulkanmod/render/VBO.java | 24 +++++-- .../vulkanmod/render/chunk/WorldRenderer.java | 6 +- .../render/chunk/buffer/AreaBuffer.java | 3 + .../render/chunk/buffer/DrawBuffers.java | 8 ++- .../render/chunk/buffer/UploadManager.java | 4 +- .../java/net/vulkanmod/vulkan/Drawer.java | 10 ++- .../java/net/vulkanmod/vulkan/Vulkan.java | 4 +- .../vulkan/memory/MemoryManager.java | 4 +- .../vulkanmod/vulkan/memory/MemoryType.java | 9 +-- .../vulkanmod/vulkan/memory/MemoryTypes.java | 28 ++++---- .../vulkan/memory/{ => buffer}/Buffer.java | 17 +++-- .../memory/{ => buffer}/IndexBuffer.java | 11 ++-- .../memory/{ => buffer}/IndirectBuffer.java | 4 +- .../memory/{ => buffer}/StagingBuffer.java | 3 +- .../memory/{ => buffer}/UniformBuffer.java | 4 +- .../memory/{ => buffer}/VertexBuffer.java | 6 +- .../{ => buffer/index}/AutoIndexBuffer.java | 64 ++++++++++++------- .../net/vulkanmod/vulkan/shader/Pipeline.java | 2 +- .../vulkan/shader/descriptor/UBO.java | 2 +- .../vulkanmod/vulkan/texture/VulkanImage.java | 2 +- .../java/net/vulkanmod/vulkan/util/VUtil.java | 2 +- 21 files changed, 140 insertions(+), 77 deletions(-) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/Buffer.java (81%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/IndexBuffer.java (80%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/IndirectBuffer.java (92%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/StagingBuffer.java (95%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/UniformBuffer.java (88%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer}/VertexBuffer.java (84%) rename src/main/java/net/vulkanmod/vulkan/memory/{ => buffer/index}/AutoIndexBuffer.java (85%) diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index afc9f26bc1..4a45326c6a 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -10,6 +10,9 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; +import net.vulkanmod.vulkan.memory.buffer.index.AutoIndexBuffer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -27,6 +30,7 @@ public class VBO { private int vertexCount; private VertexFormat.Mode mode; + AutoIndexBuffer autoIndexBuffer; private boolean autoIndexed = false; public VBO(com.mojang.blaze3d.vertex.VertexBuffer.Usage usage) { @@ -84,12 +88,13 @@ public void uploadIndexBuffer(ByteBuffer data) { default -> throw new IllegalStateException("Unexpected draw mode: %s".formatted(this.mode)); } - if (this.indexBuffer != null && !this.autoIndexed) + if (this.indexBuffer != null && !this.autoIndexed) { this.indexBuffer.scheduleFree(); + } if (autoIndexBuffer != null) { autoIndexBuffer.checkCapacity(this.vertexCount); - this.indexBuffer = autoIndexBuffer.getIndexBuffer(); + this.autoIndexBuffer = autoIndexBuffer; } this.autoIndexed = true; @@ -128,10 +133,19 @@ public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { VTextureSelector.bindShaderTextures(pipeline); renderer.uploadAndBindUBOs(pipeline); - if (this.indexBuffer != null) - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - else + IndexBuffer indexBuffer; + if (this.autoIndexBuffer != null) { + indexBuffer = this.autoIndexBuffer.getIndexBuffer(); + } else { + indexBuffer = this.indexBuffer; + } + + if (indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, indexBuffer, this.indexCount); + } + else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); + } VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 907c0ca84b..06fb17ec7e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -35,9 +35,9 @@ import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.memory.Buffer; -import net.vulkanmod.vulkan.memory.IndexBuffer; -import net.vulkanmod.vulkan.memory.IndirectBuffer; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.buffer.IndirectBuffer; import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java index b7894b4244..c2c02db66d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java @@ -4,6 +4,9 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.util.Util; import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; import org.apache.logging.log4j.Logger; import java.nio.ByteBuffer; diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 16c4b64b63..24f3c95503 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -11,7 +11,7 @@ import net.vulkanmod.render.vertex.CustomVertexFormat; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.memory.IndirectBuffer; +import net.vulkanmod.vulkan.memory.buffer.IndirectBuffer; import net.vulkanmod.vulkan.shader.Pipeline; import org.joml.Vector3i; import org.lwjgl.system.MemoryStack; @@ -79,6 +79,7 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType int indexCount = 0; var vertexBuffer = vertexBuffers[i]; + int vertexCount = 0; if (vertexBuffer != null) { AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(vertexBuffer, vertexOffset, paramPtr); @@ -87,7 +88,8 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType int baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); DrawParametersBuffer.setBaseInstance(paramPtr, baseInstance); - indexCount = vertexBuffer.limit() / VERTEX_SIZE * 6 / 4; + vertexCount = vertexBuffer.limit() / VERTEX_SIZE; + indexCount = vertexCount * 6 / 4; } if (i == QuadFacing.UNDEFINED.ordinal() && !buffer.autoIndices) { @@ -98,6 +100,8 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType int oldOffset = DrawParametersBuffer.getIndexCount(paramPtr) > 0 ? DrawParametersBuffer.getFirstIndex(paramPtr) : -1; AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), oldOffset, paramPtr); firstIndex = segment.offset / INDEX_SIZE; + } else { + Renderer.getDrawer().getQuadsIndexBuffer().checkCapacity(vertexCount); } DrawParametersBuffer.setIndexCount(paramPtr, indexCount); diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java index ef9ab1e953..5ab8bee72a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java @@ -4,8 +4,8 @@ import net.vulkanmod.vulkan.Synchronization; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; -import net.vulkanmod.vulkan.memory.Buffer; -import net.vulkanmod.vulkan.memory.StagingBuffer; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.queue.TransferQueue; diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index e0fbea59f0..1881c0974b 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -2,6 +2,11 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; +import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; +import net.vulkanmod.vulkan.memory.buffer.index.AutoIndexBuffer; import net.vulkanmod.vulkan.util.VUtil; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkCommandBuffer; @@ -39,7 +44,7 @@ public class Drawer { public Drawer() { // Index buffers - this.quadsIndexBuffer = new AutoIndexBuffer(AutoIndexBuffer.QUAD_U16_MAX_VERTEX_COUNT, AutoIndexBuffer.DrawType.QUADS); + this.quadsIndexBuffer = new AutoIndexBuffer(AutoIndexBuffer.U16_MAX_VERTEX_COUNT, AutoIndexBuffer.DrawType.QUADS); this.quadsIntIndexBuffer = new AutoIndexBuffer(100000, AutoIndexBuffer.DrawType.QUADS); this.linesIndexBuffer = new AutoIndexBuffer(10000, AutoIndexBuffer.DrawType.LINES); this.debugLineStripIndexBuffer = new AutoIndexBuffer(10000, AutoIndexBuffer.DrawType.DEBUG_LINE_STRIP); @@ -106,6 +111,7 @@ public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode if (autoIndexBuffer != null) { int indexCount = autoIndexBuffer.getIndexCount(vertexCount); + autoIndexBuffer.checkCapacity(indexCount); drawIndexed(vertexBuffer, autoIndexBuffer.getIndexBuffer(), indexCount); } @@ -190,7 +196,7 @@ private AutoIndexBuffer getAutoIndexBuffer(VertexFormat.Mode mode, int vertexCou case QUADS -> { int indexCount = vertexCount * 3 / 2; - yield indexCount > AutoIndexBuffer.U16_MAX_INDEX_COUNT + yield indexCount > AutoIndexBuffer.U16_MAX_VERTEX_COUNT ? this.quadsIntIndexBuffer : this.quadsIndexBuffer; } case LINES -> this.linesIndexBuffer; diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index ba60a3f984..9c99cc24d5 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -3,10 +3,10 @@ import net.vulkanmod.vulkan.device.Device; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.SwapChain; -import net.vulkanmod.vulkan.memory.Buffer; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryTypes; -import net.vulkanmod.vulkan.memory.StagingBuffer; +import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.SamplerManager; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java index ba10692aa9..9e9ea353ae 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java @@ -6,6 +6,7 @@ import net.vulkanmod.render.chunk.buffer.AreaBuffer; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.texture.VulkanImage; import net.vulkanmod.vulkan.util.Pair; @@ -129,8 +130,6 @@ public void createBuffer(long size, int usage, int properties, LongBuffer pBuffe public synchronized void createBuffer(Buffer buffer, long size, int usage, int properties) { try (MemoryStack stack = stackPush()) { - buffer.setBufferSize(size); - LongBuffer pBuffer = stack.mallocLong(1); PointerBuffer pAllocation = stack.pointers(VK_NULL_HANDLE); @@ -138,6 +137,7 @@ public synchronized void createBuffer(Buffer buffer, long size, int usage, int p buffer.setId(pBuffer.get(0)); buffer.setAllocation(pAllocation.get(0)); + buffer.setBufferSize(size); if ((properties & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { deviceMemory += size; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java index 68ab635f2c..3d20c94b23 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java @@ -1,5 +1,6 @@ package net.vulkanmod.vulkan.memory; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import org.lwjgl.vulkan.VkMemoryHeap; import org.lwjgl.vulkan.VkMemoryType; @@ -16,13 +17,13 @@ public abstract class MemoryType { this.vkMemoryHeap = vkMemoryHeap; } - abstract void createBuffer(Buffer buffer, long size); + public abstract void createBuffer(Buffer buffer, long size); - abstract void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); + public abstract void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); - abstract void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); + public abstract void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); - abstract boolean mappable(); + public abstract boolean mappable(); public Type getType() { return this.type; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 72fc7546e4..0206702200 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -2,6 +2,8 @@ import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.util.VUtil; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkMemoryHeap; @@ -63,35 +65,35 @@ public static class DeviceLocalMemory extends MemoryType { } @Override - void createBuffer(Buffer buffer, long size) { + public void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT); } @Override - void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { + public void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); stagingBuffer.copyBuffer((int) bufferSize, byteBuffer); - DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.id, stagingBuffer.offset, buffer.getId(), buffer.getUsedBytes(), bufferSize); + DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.getId(), stagingBuffer.getOffset(), buffer.getId(), buffer.getUsedBytes(), bufferSize); } @Override - void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { + public void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { // TODO } public long copyBuffer(Buffer src, Buffer dst) { - if (dst.bufferSize < src.bufferSize) { + if (dst.getBufferSize() < src.getBufferSize()) { throw new IllegalArgumentException("dst size is less than src size."); } - return DeviceManager.getTransferQueue().copyBufferCmd(src.getId(), 0, dst.getId(), 0, src.bufferSize); + return DeviceManager.getTransferQueue().copyBufferCmd(src.getId(), 0, dst.getId(), 0, src.getBufferSize()); } @Override - boolean mappable() { + public boolean mappable() { return false; } } @@ -103,18 +105,18 @@ static abstract class MappableMemory extends MemoryType { } @Override - void copyToBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { + public void copyToBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { VUtil.memcpy(byteBuffer, buffer, size); } @Override - void copyFromBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { + public void copyFromBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { MemoryUtil.memCopy(buffer.getDataPtr(), MemoryUtil.memAddress(byteBuffer), size); VUtil.memcpy(buffer, byteBuffer, size); } @Override - boolean mappable() { + public boolean mappable() { return true; } } @@ -126,7 +128,7 @@ static class HostCoherentMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, long size) { + public void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); @@ -141,7 +143,7 @@ static class HostLocalFallbackMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, long size) { + public void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); @@ -155,7 +157,7 @@ static class DeviceMappableMemory extends MappableMemory { } @Override - void createBuffer(Buffer buffer, long size) { + public void createBuffer(Buffer buffer, long size) { MemoryManager.getInstance().createBuffer(buffer, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | buffer.usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java similarity index 81% rename from src/main/java/net/vulkanmod/vulkan/memory/Buffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java index 910592171c..56e9b13414 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/Buffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java @@ -1,6 +1,12 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; + +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; public abstract class Buffer { + public final MemoryType type; + public final int usage; + protected long id; protected long allocation; @@ -8,9 +14,6 @@ public abstract class Buffer { protected long usedBytes; protected long offset; - protected MemoryType type; - protected int usage; - protected long dataPtr; protected Buffer(int usage, MemoryType type) { @@ -60,15 +63,15 @@ public long getDataPtr() { return dataPtr; } - protected void setBufferSize(long size) { + public void setBufferSize(long size) { this.bufferSize = size; } - protected void setId(long id) { + public void setId(long id) { this.id = id; } - protected void setAllocation(long allocation) { + public void setAllocation(long allocation) { this.allocation = allocation; } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java similarity index 80% rename from src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java index 7a96097b80..6947402299 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java @@ -1,4 +1,7 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; + +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; import java.nio.ByteBuffer; @@ -9,7 +12,7 @@ public class IndexBuffer extends Buffer { public IndexType indexType; public IndexBuffer(int size, MemoryType type) { - this(size, type, IndexType.SHORT); + this(size, type, IndexType.UINT16); } public IndexBuffer(int size, MemoryType type, IndexType indexType) { @@ -37,8 +40,8 @@ private void resizeBuffer(long newSize) { } public enum IndexType { - SHORT(2, VK_INDEX_TYPE_UINT16), - INT(4, VK_INDEX_TYPE_UINT32); + UINT16(2, VK_INDEX_TYPE_UINT16), + UINT32(4, VK_INDEX_TYPE_UINT32); public final int size; public final int type; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java similarity index 92% rename from src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java index b39cb60689..ddcbc31edc 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java @@ -1,8 +1,10 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; import net.vulkanmod.vulkan.Synchronization; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.queue.TransferQueue; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java similarity index 95% rename from src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java index 6cb35d35fc..d45835fff9 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/StagingBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java @@ -1,9 +1,10 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; import net.vulkanmod.render.chunk.buffer.UploadManager; import net.vulkanmod.render.chunk.util.Util; import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.Synchronization; +import net.vulkanmod.vulkan.memory.MemoryTypes; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java similarity index 88% rename from src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java index d7c7368d45..5f056644a2 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java @@ -1,6 +1,8 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; import static net.vulkanmod.vulkan.util.VUtil.align; import static org.lwjgl.vulkan.VK10.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java similarity index 84% rename from src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java index c1e66f8dc8..7551696b21 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/VertexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java @@ -1,4 +1,8 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer; + +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; +import net.vulkanmod.vulkan.memory.MemoryTypes; import java.nio.ByteBuffer; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java similarity index 85% rename from src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java rename to src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java index 4ed088fecb..d5140bdcee 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java @@ -1,6 +1,8 @@ -package net.vulkanmod.vulkan.memory; +package net.vulkanmod.vulkan.memory.buffer.index; import net.vulkanmod.Initializer; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.MemoryTypes; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -8,8 +10,8 @@ import java.nio.ShortBuffer; public class AutoIndexBuffer { - public static final int U16_MAX_INDEX_COUNT = 65536; - public static final int QUAD_U16_MAX_VERTEX_COUNT = U16_MAX_INDEX_COUNT * 3 / 2; + public static final int U16_MAX_VERTEX_COUNT = 65536; + public static final int QUAD_U16_MAX_INDEX_COUNT = U16_MAX_VERTEX_COUNT * 3 / 2; int vertexCount; DrawType drawType; @@ -25,14 +27,19 @@ private void createIndexBuffer(int vertexCount) { this.vertexCount = vertexCount; ByteBuffer buffer; - IndexBuffer.IndexType indexType = IndexBuffer.IndexType.SHORT; + IndexBuffer.IndexType indexType = IndexBuffer.IndexType.UINT16; + + if (vertexCount > U16_MAX_VERTEX_COUNT && + (this.drawType == DrawType.QUADS || this.drawType == DrawType.LINES)) + { + indexType = IndexBuffer.IndexType.UINT32; + } switch (this.drawType) { case QUADS -> { - if (vertexCount <= QUAD_U16_MAX_VERTEX_COUNT) + if (indexType == IndexBuffer.IndexType.UINT16) buffer = genQuadIndices(vertexCount); else { - indexType = IndexBuffer.IndexType.INT; buffer = genIntQuadIndices(vertexCount); } } @@ -50,29 +57,46 @@ private void createIndexBuffer(int vertexCount) { MemoryUtil.memFree(buffer); } + public void checkCapacity(int vertexCount) { + if(vertexCount > this.vertexCount) { + int newVertexCount = this.vertexCount * 2; + Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); + + this.indexBuffer.scheduleFree(); + createIndexBuffer(newVertexCount); + } + } + + public IndexBuffer getIndexBuffer() { return this.indexBuffer; } + + public void freeBuffer() { + this.indexBuffer.scheduleFree(); + } public int getIndexCount(int vertexCount) { - switch (this.drawType) { + return getIndexCount(this.drawType, vertexCount); + } + + public static int getIndexCount(DrawType drawType, int vertexCount) { + switch (drawType) { case QUADS, LINES -> { return vertexCount * 3 / 2; } - case TRIANGLE_FAN, TRIANGLE_STRIP -> { + case TRIANGLE_FAN, TRIANGLE_STRIP -> { return (vertexCount - 2) * 3; } - case DEBUG_LINE_STRIP -> { + case DEBUG_LINE_STRIP -> { return (vertexCount - 1) * 2; } - default -> throw new RuntimeException(String.format("unknown drawMode: %s", this.drawType)); + default -> throw new RuntimeException(String.format("unknown drawMode: %s", drawType)); } } - public void checkCapacity(int vertexCount) { - if(vertexCount > this.vertexCount) { - int newVertexCount = this.vertexCount * 2; - Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); + public static int maxVertexCount(DrawType drawType, int maxIndexCount) { + return switch (drawType) { + case QUADS, LINES -> maxIndexCount * 3 / 2; - this.indexBuffer.scheduleFree(); - createIndexBuffer(newVertexCount); - } + default -> maxIndexCount; + }; } public static ByteBuffer genQuadIndices(int vertexCount) { @@ -197,12 +221,6 @@ public static int roundUpToDivisible(int n, int d) { return ((n + d - 1) / d) * d; } - public IndexBuffer getIndexBuffer() { return this.indexBuffer; } - - public void freeBuffer() { - this.indexBuffer.scheduleFree(); - } - public enum DrawType { QUADS(7), TRIANGLE_FAN(6), diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 10208d948e..49d146cf2c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -10,7 +10,7 @@ import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.RenderPass; import net.vulkanmod.vulkan.memory.MemoryManager; -import net.vulkanmod.vulkan.memory.UniformBuffer; +import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; import net.vulkanmod.vulkan.shader.SPIRVUtils.SPIRV; import net.vulkanmod.vulkan.shader.SPIRVUtils.ShaderKind; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java index 4614285fe6..1d0a76daa8 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java @@ -1,6 +1,6 @@ package net.vulkanmod.vulkan.shader.descriptor; -import net.vulkanmod.vulkan.memory.UniformBuffer; +import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.layout.Uniform; diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index f0b681e747..e447a0b719 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -5,7 +5,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.memory.MemoryManager; -import net.vulkanmod.vulkan.memory.StagingBuffer; +import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.queue.CommandPool; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; diff --git a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java index 9b31ee3a54..37a9671f03 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java @@ -1,6 +1,6 @@ package net.vulkanmod.vulkan.util; -import net.vulkanmod.vulkan.memory.Buffer; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; From a42450b223db4731743ae67a68d5bb02d304dc64 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 3 Feb 2025 00:01:44 +0100 Subject: [PATCH 062/177] Implement flush method - Refactor --- .../net/vulkanmod/config/gui/GuiRenderer.java | 55 ++++++++++++++----- .../net/vulkanmod/config/gui/VOptionList.java | 2 + .../render/profiling/ProfilerOverlay.java | 2 +- 3 files changed, 43 insertions(+), 16 deletions(-) diff --git a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java index 7dce130971..b4b3216c10 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java @@ -20,9 +20,10 @@ public abstract class GuiRenderer { public static Font font; public static GuiGraphics guiGraphics; public static PoseStack pose; - public static BufferBuilder bufferBuilder; - public static boolean batching = false; + + private static boolean batching = false; + private static boolean drawing = false; public static void setPoseStack(PoseStack poseStack) { pose = poseStack; @@ -61,16 +62,14 @@ public static void fill(float x0, float y0, float x1, float y1, float z, int col RenderSystem.setShader(GameRenderer::getPositionColorShader); - if (!batching) - bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + setupBufferBuilder(); bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r, g, b, a); bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r, g, b, a); bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r, g, b, a); bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r, g, b, a); - if (!batching) - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + submitIfNeeded(); } public static void fillGradient(float x0, float y0, float x1, float y1, int color1, int color2) { @@ -89,18 +88,14 @@ public static void fillGradient(float x0, float y0, float x1, float y1, float z, Matrix4f matrix4f = pose.last().pose(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); - - if (!batching) - bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + setupBufferBuilder(); bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r1, g1, b1, a1); bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r2, g2, b2, a2); bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r2, g2, b2, a2); bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r1, g1, b1, a1); - if (!batching) - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + submitIfNeeded(); } public static void renderBoxBorder(float x0, float y0, float width, float height, float borderWidth, int color) { @@ -147,13 +142,43 @@ public static int getMaxTextWidth(Font font, List list) { return maxWidth; } - public static void beginBatch(VertexFormat.Mode mode, VertexFormat format) { - bufferBuilder = Tesselator.getInstance().begin(mode, format); + public static void beginBatch() { batching = true; } public static void endBatch() { - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + RenderSystem.setShader(GameRenderer::getPositionColorShader); + MeshData meshData = bufferBuilder.build(); + + if (meshData != null) { + BufferUploader.drawWithShader(meshData); + meshData.close(); + } + batching = false; + drawing = false; + } + + public static void flush() { + guiGraphics.flush(); + + if (batching) { + endBatch(); + } + } + + private static void setupBufferBuilder() { + if (!batching || !drawing) { + bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + drawing = true; + } + } + + private static void submitIfNeeded() { + if (!batching) { + RenderSystem.setShader(GameRenderer::getPositionColorShader); + BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + drawing = false; + } } } diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index f114dee642..854f1f59aa 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -272,6 +272,8 @@ protected void renderList(int mouseX, int mouseY) { rowTop += entry.getTotalHeight(); } + + GuiRenderer.flush(); } private Entry getEntry(int j) { diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index 8fec0f5508..8f0ffdd9fe 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -68,7 +68,7 @@ public void render(GuiGraphics guiGraphics) { Objects.requireNonNull(this.font); RenderSystem.enableBlend(); - GuiRenderer.beginBatch(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + GuiRenderer.beginBatch(); for (int i = 0; i < infoList.size(); ++i) { String line = infoList.get(i); From 0506db25014c13bacc74c295ae61a211590eab78 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 3 Feb 2025 00:05:16 +0100 Subject: [PATCH 063/177] Improve quad writing performance - Fix: normalize normal vector if needed --- .../vulkanmod/mixin/matrix/PoseAccessor.java | 12 ++++ .../render/particle/SingleQuadParticleM.java | 50 ++++++++----- .../mixin/render/vertex/BufferBuilderM.java | 65 +++++++++++++++-- .../mixin/render/vertex/VertexConsumerM.java | 70 ------------------- .../net/vulkanmod/render/util/MathUtil.java | 47 +++++++++++++ src/main/resources/vulkanmod.mixins.json | 2 +- 6 files changed, 152 insertions(+), 94 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java diff --git a/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java b/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java new file mode 100644 index 0000000000..cc2acf61a5 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java @@ -0,0 +1,12 @@ +package net.vulkanmod.mixin.matrix; + +import com.mojang.blaze3d.vertex.PoseStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(PoseStack.Pose.class) +public interface PoseAccessor { + + @Accessor("trustedNormals") + boolean trustedNormals(); +} diff --git a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java b/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java index 9ffe1077f8..220b9235d8 100644 --- a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java +++ b/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java @@ -20,12 +20,16 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; @Mixin(SingleQuadParticle.class) public abstract class SingleQuadParticleM extends Particle { @Shadow protected float quadSize; + @Unique private final Quaternionf quaternionf = new Quaternionf(); + @Unique private final Vector3f vector3f = new Vector3f(); + @Shadow protected abstract float getU0(); @Shadow protected abstract float getU1(); @Shadow protected abstract float getV0(); @@ -33,6 +37,8 @@ public abstract class SingleQuadParticleM extends Particle { @Shadow public abstract float getQuadSize(float f); + @Shadow public abstract SingleQuadParticle.FacingCameraMode getFacingCameraMode(); + protected SingleQuadParticleM(ClientLevel clientLevel, double d, double e, double f, double g, double h, double i) { super(clientLevel, d, e, f, g, h, i); this.quadSize = 0.1F * (this.random.nextFloat() * 0.5F + 0.5F) * 2.0F; @@ -48,7 +54,7 @@ public void render(VertexConsumer vertexConsumer, Camera camera, float f) { double ly = (Mth.lerp(f, this.yo, this.y)); double lz = (Mth.lerp(f, this.zo, this.z)); - if(cull(WorldRenderer.getInstance(), (float) lx, (float) ly, (float) lz)) + if (cull(WorldRenderer.getInstance(), lx, ly, lz)) return; Vec3 vec3 = camera.getPosition(); @@ -56,24 +62,18 @@ public void render(VertexConsumer vertexConsumer, Camera camera, float f) { float offsetY = (float) (ly - vec3.y()); float offsetZ = (float) (lz - vec3.z()); - Quaternionf quaternionf; + quaternionf.identity(); + this.getFacingCameraMode().setRotation(quaternionf, camera, f); if (this.roll != 0.0F) { - quaternionf = new Quaternionf(camera.rotation()); quaternionf.rotateZ(Mth.lerp(f, this.oRoll, this.roll)); - } else { - quaternionf = camera.rotation(); } - Vector3f[] vector3fs = new Vector3f[]{new Vector3f(-1.0F, -1.0F, 0.0F), new Vector3f(-1.0F, 1.0F, 0.0F), new Vector3f(1.0F, 1.0F, 0.0F), new Vector3f(1.0F, -1.0F, 0.0F)}; - float j = this.getQuadSize(f); - - for(int k = 0; k < 4; ++k) { - Vector3f vector3f = vector3fs[k]; - vector3f.rotate(quaternionf); - vector3f.mul(j); - vector3f.add(offsetX, offsetY, offsetZ); - } + this.renderRotatedQuad(vertexConsumer, quaternionf, offsetX, offsetY, offsetZ, f); + } + @Unique + private void renderRotatedQuad(VertexConsumer vertexConsumer, Quaternionf quaternionf, float x, float y, float z, float f) { + float j = this.getQuadSize(f); float u0 = this.getU0(); float u1 = this.getU1(); float v0 = this.getV0(); @@ -83,10 +83,22 @@ public void render(VertexConsumer vertexConsumer, Camera camera, float f) { ExtendedVertexBuilder vertexBuilder = (ExtendedVertexBuilder)vertexConsumer; int packedColor = ColorUtil.RGBA.pack(this.rCol, this.gCol, this.bCol, this.alpha); - vertexBuilder.vertex(vector3fs[1].x(), vector3fs[1].y(), vector3fs[1].z(), u1, v0, packedColor, light); - vertexBuilder.vertex(vector3fs[0].x(), vector3fs[0].y(), vector3fs[0].z(), u1, v1, packedColor, light); - vertexBuilder.vertex(vector3fs[3].x(), vector3fs[3].y(), vector3fs[3].z(), u0, v1, packedColor, light); - vertexBuilder.vertex(vector3fs[2].x(), vector3fs[2].y(), vector3fs[2].z(), u0, v0, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, -1.0F, j, u1, v1, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, 1.0F, j, u1, v0, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, 1.0F, j, u0, v0, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, -1.0F, j, u0, v1, packedColor, light); + } + + @Unique + private void renderVertex( + ExtendedVertexBuilder vertexConsumer, Quaternionf quaternionf, float x, float y, float z, float i, float j, float k, float u, float v, int color, int light + ) { + vector3f.set(i, j, 0.0f) + .rotate(quaternionf) + .mul(k) + .add(x, y, z); + + vertexConsumer.vertex(vector3f.x(), vector3f.y(), vector3f.z(), u, v, color, light); } protected int getLightColor(float f) { @@ -94,7 +106,7 @@ protected int getLightColor(float f) { return this.level.hasChunkAt(blockPos) ? LevelRenderer.getLightColor(this.level, blockPos) : 0; } - private boolean cull(WorldRenderer worldRenderer, float x, float y, float z) { + private boolean cull(WorldRenderer worldRenderer, double x, double y, double z) { RenderSection section = worldRenderer.getSectionGrid().getSectionAtBlockPos((int) x, (int) y, (int) z); return section != null && section.getLastFrame() != worldRenderer.getLastFrame(); } diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java index 8187882fd3..a7e5c696e4 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java @@ -1,13 +1,16 @@ package net.vulkanmod.mixin.render.vertex; import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Vec3i; import net.vulkanmod.interfaces.ExtendedVertexBuilder; +import net.vulkanmod.mixin.matrix.PoseAccessor; +import net.vulkanmod.render.util.MathUtil; import net.vulkanmod.render.vertex.format.I32_SNorm; +import net.vulkanmod.vulkan.util.ColorUtil; +import org.joml.Matrix4f; import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.*; @Mixin(BufferBuilder.class) public abstract class BufferBuilderM @@ -150,4 +153,58 @@ public void addVertex(float x, float y, float z, int color, float u, float v, in } } + @Override + public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, + float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { + putQuadData(matrixEntry, quad, brightness, red, green, blue, alpha, lights, overlay, useQuadColorData); + } + + @SuppressWarnings("UnreachableCode") + @Unique + private void putQuadData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { + int[] quadData = quad.getVertices(); + Vec3i vec3i = quad.getDirection().getNormal(); + Matrix4f matrix4f = matrixEntry.pose(); + + boolean trustedNormals = ((PoseAccessor)(Object)matrixEntry).trustedNormals(); + int normal = MathUtil.packTransformedNorm(matrixEntry.normal(), trustedNormals, vec3i.getX(), vec3i.getY(), vec3i.getZ()); + + for (int k = 0; k < 4; ++k) { + float r, g, b; + + float quadR, quadG, quadB; + + int i = k * 8; + float x = Float.intBitsToFloat(quadData[i]); + float y = Float.intBitsToFloat(quadData[i + 1]); + float z = Float.intBitsToFloat(quadData[i + 2]); + + float tx = MathUtil.transformX(matrix4f, x, y, z); + float ty = MathUtil.transformY(matrix4f, x, y, z); + float tz = MathUtil.transformZ(matrix4f, x, y, z); + + if (useQuadColorData) { + int color = quadData[i + 3]; + quadR = ColorUtil.RGBA.unpackR(color); + quadG = ColorUtil.RGBA.unpackG(color); + quadB = ColorUtil.RGBA.unpackB(color); + r = quadR * brightness[k] * red; + g = quadG * brightness[k] * green; + b = quadB * brightness[k] * blue; + } else { + r = brightness[k] * red; + g = brightness[k] * green; + b = brightness[k] * blue; + } + + int color = ColorUtil.RGBA.pack(r, g, b, alpha); + + int light = lights[k]; + float u = Float.intBitsToFloat(quadData[i + 4]); + float v = Float.intBitsToFloat(quadData[i + 5]); + + this.vertex(tx, ty, tz, color, u, v, overlay, light, normal); + } + } + } diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java deleted file mode 100644 index 4c158910a8..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexConsumerM.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.vulkanmod.mixin.render.vertex; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Vec3i; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(VertexConsumer.class) -public interface VertexConsumerM { - - - @Shadow void addVertex(float f, float g, float h, int i, float j, float k, int l, int m, float n, float o, float p); - - /** - * @author - */ - @Overwrite - default void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { - int[] js = quad.getVertices(); - Vec3i vec3i = quad.getDirection().getNormal(); - Vector3f normal = new Vector3f(vec3i.getX(), vec3i.getY(), vec3i.getZ()); - Matrix4f matrix4f = matrixEntry.pose(); - normal.mul(matrixEntry.normal()); - - int j = js.length / 8; - - for (int k = 0; k < j; ++k) { - float r, g, b; - - float quadR, quadG, quadB; - - int i = k * 8; - float x = Float.intBitsToFloat(js[i]); - float y = Float.intBitsToFloat(js[i + 1]); - float z = Float.intBitsToFloat(js[i + 2]); - - if (useQuadColorData) { - quadR = ColorUtil.RGBA.unpackR(js[i + 3]); - quadG = ColorUtil.RGBA.unpackG(js[i + 3]); - quadB = ColorUtil.RGBA.unpackB(js[i + 3]); - r = quadR * brightness[k] * red; - g = quadG * brightness[k] * green; - b = quadB * brightness[k] * blue; - } else { - r = brightness[k] * red; - g = brightness[k] * green; - b = brightness[k] * blue; - } - - int color = ColorUtil.RGBA.pack(r, g, b, alpha); - - int light = lights[k]; - float u = Float.intBitsToFloat(js[i + 4]); - float v = Float.intBitsToFloat(js[i + 5]); - - Vector4f vector4f = new Vector4f(x, y, z, 1.0f); - vector4f.mul(matrix4f); - - this.addVertex(vector4f.x(), vector4f.y(), vector4f.z(), color, u, v, overlay, light, normal.x(), normal.y(), normal.z()); - } - - } -} diff --git a/src/main/java/net/vulkanmod/render/util/MathUtil.java b/src/main/java/net/vulkanmod/render/util/MathUtil.java index 99f26cbcb6..0d8e42fe8a 100644 --- a/src/main/java/net/vulkanmod/render/util/MathUtil.java +++ b/src/main/java/net/vulkanmod/render/util/MathUtil.java @@ -1,5 +1,10 @@ package net.vulkanmod.render.util; +import net.vulkanmod.render.vertex.format.I32_SNorm; +import org.joml.Math; +import org.joml.Matrix3f; +import org.joml.Matrix4f; + public class MathUtil { public static float clamp(float min, float max, float x) { @@ -17,4 +22,46 @@ public static float saturate(float x) { public static float lerp(float v0, float v1, float t) { return v0 + t * (v1 - v0); } + + // JOML Math util + + public static float transformX(Matrix4f mat, float x, float y, float z) { + return Math.fma(mat.m00(), x, Math.fma(mat.m10(), y, Math.fma(mat.m20(), z, mat.m30()))); + } + + public static float transformY(Matrix4f mat, float x, float y, float z) { + return Math.fma(mat.m01(), x, Math.fma(mat.m11(), y, Math.fma(mat.m21(), z, mat.m31()))); + } + + public static float transformZ(Matrix4f mat, float x, float y, float z) { + return Math.fma(mat.m02(), x, Math.fma(mat.m12(), y, Math.fma(mat.m22(), z, mat.m32()))); + } + + public static int packTransformedNorm(Matrix3f mat, boolean trustedNormals, float x, float y, float z) { + float nx = transformNormX(mat, x, y, z); + float ny = transformNormY(mat, x, y, z); + float nz = transformNormZ(mat, x, y, z); + + if (!trustedNormals) { + float scalar = Math.invsqrt(Math.fma(nx, nx, Math.fma(ny, ny, nz * nz))); + nx = nx * scalar; + ny = ny * scalar; + nz = nz * scalar; + } + + int packedNormal = I32_SNorm.packNormal(nx, ny, nz); + return packedNormal; + } + + public static float transformNormX(Matrix3f mat, float x, float y, float z) { + return Math.fma(mat.m00(), x, Math.fma(mat.m10(), y, mat.m20() * z)); + } + + public static float transformNormY(Matrix3f mat, float x, float y, float z) { + return Math.fma(mat.m01(), x, Math.fma(mat.m11(), y, mat.m21() * z)); + } + + public static float transformNormZ(Matrix3f mat, float x, float y, float z) { + return Math.fma(mat.m02(), x, Math.fma(mat.m12(), y, mat.m22() * z)); + } } diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 69d941237f..996c8973aa 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -33,6 +33,7 @@ "debug.KeyboardHandlerM", "matrix.Matrix4fM", + "matrix.PoseAccessor", "profiling.GuiMixin", "profiling.KeyboardHandlerM", @@ -68,7 +69,6 @@ "render.vertex.FaceBakeryM", "render.vertex.IndexTypeMixin", "render.vertex.VertexBufferM", - "render.vertex.VertexConsumerM", "render.vertex.VertexFormatMixin", "screen.ScreenM", From 51664ff6ef3b41fd6879c220f8b43429120fddb0 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 6 Feb 2025 18:40:29 +0100 Subject: [PATCH 064/177] Update file permissions --- gradlew | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 From 857607f95cce9f5f66bd1a0f52d531e5ba39f817 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 9 Feb 2025 13:04:56 +0100 Subject: [PATCH 065/177] Fix early return on queue selection --- .../net/vulkanmod/vulkan/queue/Queue.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index c2775d05ea..c6bb611821 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -140,30 +140,33 @@ public static QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { Initializer.LOGGER.warn("Using compute queue as present fallback"); } + // In case there's no dedicated transfer queue, we need choose another one + // preferably a different one from the already selected queues if (indices.transferFamily == -1) { - int fallback = -1; + int transferIndex = -1; for (int i = 0; i < queueFamilies.capacity(); i++) { int queueFlags = queueFamilies.get(i).queueFlags(); if ((queueFlags & VK_QUEUE_TRANSFER_BIT) != 0) { - if (fallback == -1) - fallback = i; + if (transferIndex == -1) + transferIndex = i; if ((queueFlags & (VK_QUEUE_GRAPHICS_BIT)) == 0) { indices.transferFamily = i; if (i != indices.computeFamily) break; - fallback = i; + + transferIndex = i; } } + } - if (fallback == -1) - throw new RuntimeException("Failed to find queue family with transfer support"); + if (transferIndex == -1) + throw new RuntimeException("Failed to find queue family with transfer support"); - indices.transferFamily = fallback; - } + indices.transferFamily = transferIndex; } if (indices.computeFamily == -1) { From 03d470ee52d32addb33479b312e6b8f614a696cb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 9 Feb 2025 13:05:34 +0100 Subject: [PATCH 066/177] Add file not found exception --- src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index b7b036307c..ffc0f3db6f 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -97,7 +97,7 @@ public static JsonObject getJsonConfig(String path, String rendertype) { } if (stream == null) { - return null; + throw new FileNotFoundException("Config at %s not found".formatted(path)); } JsonElement jsonElement = JsonParser.parseReader(new BufferedReader(new InputStreamReader(stream))); From acc069960b20217cb2aa401b71a2fc1652a16408 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 9 Feb 2025 16:15:59 +0100 Subject: [PATCH 067/177] Add src upload offset check --- .../java/net/vulkanmod/vulkan/texture/VulkanImage.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index e447a0b719..a07f6bb26f 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -14,6 +14,7 @@ import org.lwjgl.vulkan.VkImageMemoryBarrier; import org.lwjgl.vulkan.VkImageViewCreateInfo; +import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.LongBuffer; import java.util.Arrays; @@ -215,7 +216,13 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs try (MemoryStack stack = stackPush()) { transferDstLayout(stack, commandBuffer); - final int srcOffset = (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize); + int uploadOffset = (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize; + + if (uploadOffset > uploadSize) { + throw new BufferOverflowException(); + } + + final int srcOffset = (int) (stagingBuffer.getOffset() + uploadOffset); ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, srcOffset, unpackRowLength, height); From b416317b5d96f2ea3e3118fcaf22a91f40a5cb25 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 9 Feb 2025 23:07:19 +0100 Subject: [PATCH 068/177] Revert "Add file not found exception" This reverts commit 03d470ee52d32addb33479b312e6b8f614a696cb. --- src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index ffc0f3db6f..b7b036307c 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -97,7 +97,7 @@ public static JsonObject getJsonConfig(String path, String rendertype) { } if (stream == null) { - throw new FileNotFoundException("Config at %s not found".formatted(path)); + return null; } JsonElement jsonElement = JsonParser.parseReader(new BufferedReader(new InputStreamReader(stream))); From df2e380e8b6599d1e0702dc63cb75d30697d6908 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 27 Feb 2025 00:18:42 +0100 Subject: [PATCH 069/177] Add getTexParameteri redirect --- src/main/java/net/vulkanmod/gl/GlTexture.java | 22 +++++++++++++++++++ .../mixin/compatibility/gl/GL11M.java | 10 ++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/gl/GlTexture.java b/src/main/java/net/vulkanmod/gl/GlTexture.java index ae7f2be19b..0643c1f8dd 100644 --- a/src/main/java/net/vulkanmod/gl/GlTexture.java +++ b/src/main/java/net/vulkanmod/gl/GlTexture.java @@ -189,6 +189,28 @@ public static void texParameteri(int target, int pName, int param) { //TODO } + public static int getTexParameteri(int target, int pName) { + if (target != GL11.GL_TEXTURE_2D) + throw new UnsupportedOperationException("target != GL_TEXTURE_2D not supported"); + + if (boundTexture == null) + return -1; + + return switch (pName) { + case GL11.GL_TEXTURE_INTERNAL_FORMAT -> GlUtil.getGlFormat(boundTexture.vulkanImage.format); + case GL11.GL_TEXTURE_WIDTH -> boundTexture.vulkanImage.width; + case GL11.GL_TEXTURE_HEIGHT -> boundTexture.vulkanImage.height; + + case GL30.GL_TEXTURE_MAX_LEVEL -> boundTexture.maxLevel; + case GL30.GL_TEXTURE_MAX_LOD -> boundTexture.maxLod; + + case GL11.GL_TEXTURE_MAG_FILTER -> boundTexture.magFilter; + case GL11.GL_TEXTURE_MIN_FILTER -> boundTexture.minFilter; + + default -> -1; + }; + } + public static int getTexLevelParameter(int target, int level, int pName) { if (target != GL11.GL_TEXTURE_2D) throw new UnsupportedOperationException("target != GL_TEXTURE_2D not supported"); diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index 369eba7c95..be87ac9d4f 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -4,7 +4,6 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; @@ -183,6 +182,15 @@ public static void glTexParameterf(@NativeType("GLenum") int target, @NativeType } + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static int glGetTexParameteri(@NativeType("GLenum") int target, @NativeType("GLenum") int pname) { + return GlTexture.getTexParameteri(target, pname); + } + /** * @author * @reason From 78cc6f16358c19e57d75fbfbf9de3610f3303a91 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 2 Mar 2025 16:17:13 +0100 Subject: [PATCH 070/177] Fix polygon offset swapped parameters --- .../net/vulkanmod/mixin/compatibility/gl/GL11M.java | 12 ++++++++++++ .../vulkanmod/mixin/render/RenderSystemMixin.java | 4 ++-- .../java/net/vulkanmod/vulkan/VRenderSystem.java | 13 ++++++++----- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index be87ac9d4f..be600e1705 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -4,6 +4,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; @@ -304,4 +305,15 @@ public static void glCopyTexSubImage2D(@NativeType("GLenum") int target, @Native public static void glBlendFunc(@NativeType("GLenum") int sfactor, @NativeType("GLenum") int dfactor) { // TODO } + + + + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glPolygonOffset(@NativeType("GLfloat") float factor, @NativeType("GLfloat") float units) { + VRenderSystem.polygonOffset(factor, units); + } } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 2fd1cfa7dd..d0a8596e58 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -303,9 +303,9 @@ public static void disablePolygonOffset() { * @author */ @Overwrite(remap = false) - public static void polygonOffset(float p_69864_, float p_69865_) { + public static void polygonOffset(float factor, float units) { assertOnRenderThread(); - VRenderSystem.polygonOffset(p_69864_, p_69865_); + VRenderSystem.polygonOffset(factor, units); } /** diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index 7f647f9d59..f52bf9174e 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -56,7 +56,8 @@ public abstract class VRenderSystem { public static float alphaCutout = 0.0f; - private static final float[] depthBias = new float[2]; + private static float depthBiasUnits = 0.0f; + private static float depthBiasFactor = 0.0f; public static void initRenderer() { Vulkan.initVulkan(window); @@ -255,13 +256,15 @@ public static void logicOp(GlStateManager.LogicOp logicOp) { logicOpFun = logicOp.value; } - public static void polygonOffset(float v, float v1) { - depthBias[0] = v; - depthBias[1] = v1; + public static void polygonOffset(float factor, float units) { + depthBiasUnits = units; + depthBiasFactor = factor; + + Renderer.setDepthBias(depthBiasUnits, depthBiasFactor); } public static void enablePolygonOffset() { - Renderer.setDepthBias(depthBias[0], depthBias[1]); + Renderer.setDepthBias(depthBiasUnits, depthBiasFactor); } public static void disablePolygonOffset() { From 318d5ca100e8cf46105b3ecc3eb02c8d6418e070 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 2 Mar 2025 16:32:00 +0100 Subject: [PATCH 071/177] Improve mod compatibility - Update rendering mixins - Add ChunkOffset uniform - Fixes #586 --- .../mixin/compatibility/UniformM.java | 23 +++++- .../mixin/render/BufferUploaderM.java | 24 ++---- .../mixin/render/ShaderInstanceM.java | 82 +++++++++++++------ src/main/java/net/vulkanmod/render/VBO.java | 69 ++++++++-------- .../vulkanmod/render/chunk/WorldRenderer.java | 2 - .../rendertype_cutout/rendertype_cutout.json | 3 +- .../rendertype_cutout/rendertype_cutout.vsh | 8 +- .../rendertype_cutout_mipped.json | 3 +- .../rendertype_cutout_mipped.vsh | 8 +- .../rendertype_solid/rendertype_solid.json | 3 +- .../rendertype_solid/rendertype_solid.vsh | 8 +- .../rendertype_translucent.json | 3 +- .../rendertype_translucent.vsh | 8 +- .../rendertype_tripwire.json | 3 +- .../rendertype_tripwire.vsh | 8 +- 15 files changed, 157 insertions(+), 98 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java index 75c2985cd4..e722d874fe 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java @@ -1,9 +1,17 @@ package net.vulkanmod.mixin.compatibility; +import com.mojang.blaze3d.shaders.Shader; import com.mojang.blaze3d.shaders.Uniform; import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.renderer.ShaderInstance; +import net.vulkanmod.interfaces.ShaderMixed; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -11,6 +19,8 @@ @Mixin(Uniform.class) public class UniformM { + @Shadow @Final private Shader parent; + /** * @author * @reason @@ -31,7 +41,18 @@ public static int glGetAttribLocation(int i, CharSequence charSequence) { } @Inject(method = "upload", at = @At("HEAD"), cancellable = true) - public void cancelUpload(CallbackInfo ci) { + public void redirectUpload(CallbackInfo ci) { + Renderer renderer = Renderer.getInstance(); + Pipeline boundPipeline = renderer.getBoundPipeline(); + + if (this.parent instanceof ShaderInstance) { + Pipeline pipeline = ShaderMixed.of((ShaderInstance) this.parent).getPipeline(); + + // Update descriptors only if the pipeline has already been bound + if (boundPipeline == pipeline) + renderer.uploadAndBindUBOs(boundPipeline); + } + ci.cancel(); } diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java index a381125a6c..c270e749c2 100644 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java @@ -3,19 +3,18 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.texture.VTextureSelector; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @Mixin(BufferUploader.class) -public class BufferUploaderM { +public abstract class BufferUploaderM { /** * @author @@ -31,9 +30,6 @@ public static void drawWithShader(MeshData meshData) { RenderSystem.assertOnRenderThread(); MeshData.DrawState parameters = meshData.drawState(); - - Renderer renderer = Renderer.getInstance(); - if (parameters.vertexCount() > 0) { ShaderInstance shaderInstance = RenderSystem.getShader(); @@ -43,20 +39,14 @@ public static void drawWithShader(MeshData meshData) { return; } + VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); + // Used to update legacy shader uniforms // TODO it would be faster to allocate a buffer from stack and set all values + shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, RenderSystem.getModelViewMatrix(), + RenderSystem.getProjectionMatrix(), Minecraft.getInstance().getWindow()); shaderInstance.apply(); - GraphicsPipeline pipeline = ((ShaderMixed)(shaderInstance)).getPipeline(); - - if (pipeline == null) - throw new NullPointerException("Shader %s has no initialized pipeline".formatted(shaderInstance.getName())); - - VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); - renderer.bindGraphicsPipeline(pipeline); - VTextureSelector.bindShaderTextures(pipeline); - renderer.uploadAndBindUBOs(pipeline); - Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); } diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java index 375647f74a..b90d49fbbe 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -15,14 +15,17 @@ import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.render.shader.ShaderLoadUtil; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.shader.converter.GlslConverter; +import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; @@ -61,6 +64,7 @@ public class ShaderInstanceM implements ShaderMixed { @Shadow @Final private List samplerLocations; @Shadow @Final private List samplerNames; + @Shadow @Final private List uniforms; @Unique private String vsPath; @Unique private String fsName; @@ -127,36 +131,52 @@ public void close() { */ @Overwrite public void apply() { - if (!this.doUniformUpdate) - return; - - for(int j = 0; j < this.samplerLocations.size(); ++j) { - String string = this.samplerNames.get(j); - if (this.samplerMap.get(string) != null) { - RenderSystem.activeTexture(33984 + j); - Object object = this.samplerMap.get(string); - int texId = -1; - if (object instanceof RenderTarget) { - texId = ((RenderTarget)object).getColorTextureId(); - } else if (object instanceof AbstractTexture) { - texId = ((AbstractTexture)object).getId(); - } else if (object instanceof Integer) { - texId = (Integer)object; + if (this.doUniformUpdate) { + + for(int j = 0; j < this.samplerLocations.size(); ++j) { + String string = this.samplerNames.get(j); + if (this.samplerMap.get(string) != null) { + RenderSystem.activeTexture(33984 + j); + Object object = this.samplerMap.get(string); + int texId = -1; + if (object instanceof RenderTarget) { + texId = ((RenderTarget)object).getColorTextureId(); + } else if (object instanceof AbstractTexture) { + texId = ((AbstractTexture)object).getId(); + } else if (object instanceof Integer) { + texId = (Integer)object; + } + + if (texId != -1) { + RenderSystem.bindTexture(texId); + RenderSystem.setShaderTexture(j, texId); + } } + } - if (texId != -1) { - RenderSystem.bindTexture(texId); - RenderSystem.setShaderTexture(j, texId); - } + for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { + uniform.upload(); } + } + bindPipeline(); + } + + /** + * @author + */ + @Overwrite + public void setDefaultUniforms(VertexFormat.Mode mode, Matrix4f modelView, Matrix4f projection, Window window) { + if (!this.doUniformUpdate) + return; + if (this.MODEL_VIEW_MATRIX != null) { - this.MODEL_VIEW_MATRIX.set(RenderSystem.getModelViewMatrix()); + this.MODEL_VIEW_MATRIX.set(modelView); } if (this.PROJECTION_MATRIX != null) { - this.PROJECTION_MATRIX.set(RenderSystem.getProjectionMatrix()); + this.PROJECTION_MATRIX.set(projection); } if (this.COLOR_MODULATOR != null) { @@ -192,13 +212,14 @@ public void apply() { } if (this.SCREEN_SIZE != null) { - Window window = Minecraft.getInstance().getWindow(); - this.SCREEN_SIZE.set((float) window.getWidth(), (float) window.getHeight()); + this.SCREEN_SIZE.set((float)window.getWidth(), (float)window.getHeight()); } - if (this.LINE_WIDTH != null) { + if (this.LINE_WIDTH != null && (mode == VertexFormat.Mode.LINES || mode == VertexFormat.Mode.LINE_STRIP)) { this.LINE_WIDTH.set(RenderSystem.getShaderLineWidth()); } + + RenderSystem.setupShaderLights((ShaderInstance) (Object) this); } /** @@ -207,6 +228,18 @@ public void apply() { @Overwrite public void clear() {} + @Unique + private void bindPipeline() { + if (this.pipeline == null) { + throw new NullPointerException("Shader %s has no initialized pipeline".formatted(this.name)); + } + + Renderer renderer = Renderer.getInstance(); + renderer.bindGraphicsPipeline(pipeline); + VTextureSelector.bindShaderTextures(pipeline); + renderer.uploadAndBindUBOs(pipeline); + } + public void setupUniformSuppliers(UBO ubo) { for (Uniform vUniform : ubo.getUniforms()) { com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(vUniform.getName()); @@ -290,6 +323,7 @@ private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat converter.process(vshSrc, fshSrc); UBO ubo = converter.createUBO(); this.setupUniformSuppliers(ubo); + this.setDoUniformsUpdate(); builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 4a45326c6a..c82795b256 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -5,8 +5,8 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.*; @@ -14,7 +14,6 @@ import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; import net.vulkanmod.vulkan.memory.buffer.index.AutoIndexBuffer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.joml.Matrix4f; @@ -26,12 +25,10 @@ public class VBO { private VertexBuffer vertexBuffer; private IndexBuffer indexBuffer; - private int indexCount; - private int vertexCount; private VertexFormat.Mode mode; - - AutoIndexBuffer autoIndexBuffer; private boolean autoIndexed = false; + private int indexCount; + private int vertexCount; public VBO(com.mojang.blaze3d.vertex.VertexBuffer.Usage usage) { this.memoryType = usage == com.mojang.blaze3d.vertex.VertexBuffer.Usage.STATIC ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; @@ -94,38 +91,50 @@ public void uploadIndexBuffer(ByteBuffer data) { if (autoIndexBuffer != null) { autoIndexBuffer.checkCapacity(this.vertexCount); - this.autoIndexBuffer = autoIndexBuffer; + this.indexBuffer = autoIndexBuffer.getIndexBuffer(); } this.autoIndexed = true; - - } else { - if (this.indexBuffer != null) + } + else { + if (this.indexBuffer != null && !this.autoIndexed) { this.indexBuffer.scheduleFree(); + } this.indexBuffer = new IndexBuffer(data.remaining(), MemoryTypes.GPU_MEM); this.indexBuffer.copyBuffer(data); } - } - public void drawWithShader(Matrix4f MV, Matrix4f P, ShaderInstance shader) { + public void drawWithShader(Matrix4f modelView, Matrix4f projection, ShaderInstance shaderInstance) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); - RenderSystem.setShader(() -> shader); + RenderSystem.setShader(() -> shaderInstance); + + VRenderSystem.applyMVP(modelView, projection); + VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); - drawWithShader(MV, P, ((ShaderMixed) shader).getPipeline()); + shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, modelView, projection, Minecraft.getInstance().getWindow()); + shaderInstance.apply(); + if (this.indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); + } + else { + Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); + } + + // Reset MVP to previous state + VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); } } - public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { + public void drawWithShader(Matrix4f modelView, Matrix4f projection, GraphicsPipeline pipeline) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); - VRenderSystem.applyMVP(MV, P); - + VRenderSystem.applyMVP(modelView, projection); VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); Renderer renderer = Renderer.getInstance(); @@ -133,34 +142,26 @@ public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { VTextureSelector.bindShaderTextures(pipeline); renderer.uploadAndBindUBOs(pipeline); - IndexBuffer indexBuffer; - if (this.autoIndexBuffer != null) { - indexBuffer = this.autoIndexBuffer.getIndexBuffer(); - } else { - indexBuffer = this.indexBuffer; - } - - if (indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, indexBuffer, this.indexCount); + if (this.indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); } else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); } + // Reset MVP to previous state VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); - } } public void draw() { if (this.indexCount != 0) { - RenderSystem.assertOnRenderThread(); - - Renderer renderer = Renderer.getInstance(); - Pipeline pipeline = renderer.getBoundPipeline(); - renderer.uploadAndBindUBOs(pipeline); - - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); + if (this.indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); + } + else { + Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); + } } } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 06fb17ec7e..67bb89d572 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -352,8 +352,6 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, this.minecraft.getProfiler().pop(); renderType.clearRenderState(); - - VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); } private void sortTranslucentSections(double camX, double camY, double camZ) { diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json index 225b0c0731..18d86581cf 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json @@ -25,7 +25,8 @@ ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh index 901a6df43a..c1f4566970 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh @@ -10,7 +10,8 @@ layout(location = 3) in ivec2 UV2; layout(location = 4) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + vec3 ChunkOffset; }; layout(binding = 3) uniform sampler2D Sampler2; @@ -20,9 +21,10 @@ layout(location = 1) out vec4 vertexColor; layout(location = 2) out vec2 texCoord0; void main() { - gl_Position = MVP * vec4(Position, 1.0); + vec3 pos = Position + ChunkOffset; + gl_Position = MVP * vec4(pos, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + vertexDistance = fog_distance(pos, 0); vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); texCoord0 = UV0; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json index 3cc4ad8110..79065cfeab 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json @@ -25,7 +25,8 @@ ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh index 901a6df43a..c1f4566970 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh @@ -10,7 +10,8 @@ layout(location = 3) in ivec2 UV2; layout(location = 4) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + vec3 ChunkOffset; }; layout(binding = 3) uniform sampler2D Sampler2; @@ -20,9 +21,10 @@ layout(location = 1) out vec4 vertexColor; layout(location = 2) out vec2 texCoord0; void main() { - gl_Position = MVP * vec4(Position, 1.0); + vec3 pos = Position + ChunkOffset; + gl_Position = MVP * vec4(pos, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + vertexDistance = fog_distance(pos, 0); vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); texCoord0 = UV0; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json index 7126b7b920..f4cd0c92d2 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json @@ -25,7 +25,8 @@ ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh index 901a6df43a..c1f4566970 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh @@ -10,7 +10,8 @@ layout(location = 3) in ivec2 UV2; layout(location = 4) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + vec3 ChunkOffset; }; layout(binding = 3) uniform sampler2D Sampler2; @@ -20,9 +21,10 @@ layout(location = 1) out vec4 vertexColor; layout(location = 2) out vec2 texCoord0; void main() { - gl_Position = MVP * vec4(Position, 1.0); + vec3 pos = Position + ChunkOffset; + gl_Position = MVP * vec4(pos, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + vertexDistance = fog_distance(pos, 0); vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); texCoord0 = UV0; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json index e466427aa8..19d8c6f7d2 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json @@ -25,7 +25,8 @@ ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh index 626cad61d2..511c92c803 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh @@ -10,7 +10,8 @@ layout(location = 3) in ivec2 UV2; layout(location = 4) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + vec3 ChunkOffset; }; layout(binding = 3) uniform sampler2D Sampler2; @@ -20,9 +21,10 @@ layout(location = 1) out vec2 texCoord0; layout(location = 2) out float vertexDistance; void main() { - gl_Position = MVP * vec4(Position, 1.0); + vec3 pos = Position + ChunkOffset; + gl_Position = MVP * vec4(pos, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + vertexDistance = fog_distance(pos, 0); vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); texCoord0 = UV0; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json index d6044d9773..6a5d92cce5 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json @@ -25,7 +25,8 @@ ], "UBOs": [ { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } + { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh index 626cad61d2..511c92c803 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh @@ -10,7 +10,8 @@ layout(location = 3) in ivec2 UV2; layout(location = 4) in vec3 Normal; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + vec3 ChunkOffset; }; layout(binding = 3) uniform sampler2D Sampler2; @@ -20,9 +21,10 @@ layout(location = 1) out vec2 texCoord0; layout(location = 2) out float vertexDistance; void main() { - gl_Position = MVP * vec4(Position, 1.0); + vec3 pos = Position + ChunkOffset; + gl_Position = MVP * vec4(pos, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + vertexDistance = fog_distance(pos, 0); vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); texCoord0 = UV0; } \ No newline at end of file From b35e7a36b6693f94c1e993767bb3391f66939db8 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 2 Mar 2025 16:36:17 +0100 Subject: [PATCH 072/177] Use 16 bytes vertex format for terrain --- .../render/vertex/CustomVertexFormat.java | 13 +++++------ .../render/vertex/VertexBuilder.java | 2 +- .../vulkan/shader/GraphicsPipeline.java | 22 ++++++++++++++++--- .../shaders/basic/terrain/terrain.vsh | 6 +++-- 4 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java index 78e7987357..47f66033a7 100644 --- a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java +++ b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java @@ -8,14 +8,13 @@ public class CustomVertexFormat { public static final VertexFormatElement ELEMENT_POSITION = new VertexFormatElement(0, 0,VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.POSITION, 4); public static final VertexFormatElement ELEMENT_COLOR = new VertexFormatElement(1, 0, VertexFormatElement.Type.UBYTE, VertexFormatElement.Usage.COLOR, 4); public static final VertexFormatElement ELEMENT_UV0 = new VertexFormatElement(2, 0, VertexFormatElement.Type.USHORT, VertexFormatElement.Usage.UV, 2); - public static final VertexFormatElement ELEMENT_UV2 = new VertexFormatElement(3, 2, VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.UV, 2); - public static final VertexFormat COMPRESSED_TERRAIN = VertexFormat.builder() - .add("Position", ELEMENT_POSITION) - .add("Color", ELEMENT_COLOR) - .add("UV0", ELEMENT_UV0) - .add("UV2", ELEMENT_UV2) - .build(); + public static final VertexFormat COMPRESSED_TERRAIN = + VertexFormat.builder() + .add("Position", ELEMENT_POSITION) + .add("Color", ELEMENT_COLOR) + .add("UV0", ELEMENT_UV0) + .build(); public static final VertexFormat NONE = VertexFormat.builder().build(); } diff --git a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java index c26f580824..737d8ef478 100644 --- a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java @@ -69,7 +69,7 @@ public int getStride() { } class CompressedVertexBuilder implements VertexBuilder { - private static final int VERTEX_SIZE = 20; + private static final int VERTEX_SIZE = 16; public static final float POS_CONV_MUL = 2048.0f; public static final float POS_OFFSET = -4.0f; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java index e4e74043a5..bca907d3cc 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -306,10 +306,20 @@ private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions } case COLOR -> { - posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); - posDescription.offset(offset); + switch (type) { + case UBYTE -> { + posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); + posDescription.offset(offset); - offset += 4; + offset += 4; + } + case UINT -> { + posDescription.format(VK_FORMAT_R32_UINT); + posDescription.offset(offset); + + offset += 4; + } + } } case UV -> { @@ -330,6 +340,12 @@ private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions posDescription.format(VK_FORMAT_R16G16_UINT); posDescription.offset(offset); + offset += 4; + } + case UINT -> { + posDescription.format(VK_FORMAT_R32_UINT); + posDescription.offset(offset); + offset += 4; } } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh index ea99bd0f14..37981de842 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh @@ -22,8 +22,8 @@ layout (location = 2) out float vertexDistance; #ifdef COMPRESSED_VERTEX layout (location = 0) in ivec4 Position; - layout (location = 1) in vec4 Color; - layout (location = 2) in uvec2 UV0; + layout (location = 1) in uvec2 UV0; + layout (location = 2) in uint PackedColor; #else layout (location = 0) in vec3 Position; layout (location = 1) in vec4 Color; @@ -51,6 +51,8 @@ void main() { gl_Position = MVP * pos; vertexDistance = fog_distance(pos.xyz, 0); + const vec4 Color = unpackUnorm4x8(PackedColor); vertexColor = Color * sample_lightmap2(Sampler2, Position.a); + texCoord0 = UV0 * UV_INV; } \ No newline at end of file From f88af3566055432ff62de2b97fadf6f5fd3beee2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 2 Mar 2025 16:41:36 +0100 Subject: [PATCH 073/177] Bump version --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 1f7b347897..017ec398f2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,12 +6,12 @@ org.gradle.parallel=true # check these on https://fabricmc.net/develop minecraft_version=1.21.1 yarn_mappings=1.21.1+build.3 -loader_version=0.16.9 +loader_version=0.16.10 # Fabric API fabric_version=0.114.0+1.21.1 # Mod Properties -mod_version = 0.5.3-dev +mod_version = 0.5.4-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.1 From 5d974433d546acb061ff7275f1a7d1999d9bdf4e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 2 Mar 2025 23:54:02 +0100 Subject: [PATCH 074/177] Fix terrain vertex format errors --- .../vulkanmod/render/vertex/CustomVertexFormat.java | 4 ++-- .../net/vulkanmod/render/vertex/VertexBuilder.java | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java index 47f66033a7..437345ff82 100644 --- a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java +++ b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java @@ -6,14 +6,14 @@ public class CustomVertexFormat { public static final VertexFormatElement ELEMENT_POSITION = new VertexFormatElement(0, 0,VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.POSITION, 4); - public static final VertexFormatElement ELEMENT_COLOR = new VertexFormatElement(1, 0, VertexFormatElement.Type.UBYTE, VertexFormatElement.Usage.COLOR, 4); + public static final VertexFormatElement ELEMENT_COLOR = new VertexFormatElement(1, 0, VertexFormatElement.Type.UINT, VertexFormatElement.Usage.COLOR, 1); public static final VertexFormatElement ELEMENT_UV0 = new VertexFormatElement(2, 0, VertexFormatElement.Type.USHORT, VertexFormatElement.Usage.UV, 2); public static final VertexFormat COMPRESSED_TERRAIN = VertexFormat.builder() .add("Position", ELEMENT_POSITION) - .add("Color", ELEMENT_COLOR) .add("UV0", ELEMENT_UV0) + .add("Color", ELEMENT_COLOR) .build(); public static final VertexFormat NONE = VertexFormat.builder().build(); diff --git a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java index 737d8ef478..5f65554597 100644 --- a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java @@ -89,10 +89,10 @@ public void vertex(long ptr, float x, float y, float z, int color, float u, floa final short l = (short) (((light >>> 8) & 0xFF00) | (light & 0xFF)); MemoryUtil.memPutShort(ptr + 6, l); - MemoryUtil.memPutInt(ptr + 8, color); + MemoryUtil.memPutShort(ptr + 8, (short) (u * UV_CONV_MUL)); + MemoryUtil.memPutShort(ptr + 10, (short) (v * UV_CONV_MUL)); - MemoryUtil.memPutShort(ptr + 12, (short) (u * UV_CONV_MUL)); - MemoryUtil.memPutShort(ptr + 14, (short) (v * UV_CONV_MUL)); + MemoryUtil.memPutInt(ptr + 12, color); } @Override @@ -108,13 +108,13 @@ public void position(long ptr, float x, float y, float z) { @Override public void color(long ptr, int color) { - MemoryUtil.memPutInt(ptr + 8, color); + MemoryUtil.memPutInt(ptr + 12, color); } @Override public void uv(long ptr, float u, float v) { - MemoryUtil.memPutShort(ptr + 12, (short) (u * UV_CONV_MUL)); - MemoryUtil.memPutShort(ptr + 14, (short) (v * UV_CONV_MUL)); + MemoryUtil.memPutShort(ptr + 8, (short) (u * UV_CONV_MUL)); + MemoryUtil.memPutShort(ptr + 10, (short) (v * UV_CONV_MUL)); } @Override From e317a249b8914771921166bcbe015d7834c3c878 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 11 Mar 2025 17:53:20 +0100 Subject: [PATCH 075/177] Fix rendertype_leash bug Fixes #230 --- .../shaders/core/rendertype_leash/rendertype_leash.fsh | 2 +- .../shaders/core/rendertype_leash/rendertype_leash.vsh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh index 2981a57765..aacb8525d8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh @@ -7,7 +7,7 @@ layout(binding = 1) uniform UBO{ float FogEnd; }; -layout(location = 0) in vec4 vertexColor; +layout(location = 0) flat in vec4 vertexColor; layout(location = 1) in float vertexDistance; layout(location = 0) out vec4 fragColor; diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh index 267e945919..5613737ebd 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh @@ -13,7 +13,7 @@ layout(binding = 0) uniform UniformBufferObject { layout(binding = 2) uniform sampler2D Sampler2; -layout(location = 0) out vec4 vertexColor; +layout(location = 0) flat out vec4 vertexColor; layout(location = 1) out float vertexDistance; void main() { From e42a5dae13cebb7d8dbe94a3bc05867c4d3deb9b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 11 Mar 2025 17:55:39 +0100 Subject: [PATCH 076/177] Update texture sampler on upload --- .../java/net/vulkanmod/mixin/texture/image/MNativeImage.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java index 31a01f58f9..dcbff6f87d 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java @@ -66,6 +66,7 @@ private void _upload(int level, int xOffset, int yOffset, int unpackSkipPixels, RenderSystem.assertOnRenderThreadOrInit(); VTextureSelector.uploadSubTexture(level, widthIn, heightIn, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, this.getWidth(), this.buffer); + VTextureSelector.getBoundTexture().updateTextureSampler(blur, clamp, mipmap); if (autoClose) { this.close(); From abbdcc8d9b9a00ce86746a7f613922ba7162879a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 11 Mar 2025 18:03:36 +0100 Subject: [PATCH 077/177] Fix: apply correct light data on quad shading --- .../build/frapi/mesh/MutableQuadViewImpl.java | 1 - .../render/AbstractBlockRenderContext.java | 4 +- .../frapi/render/BlockRenderContext.java | 73 +++++++------------ 3 files changed, 29 insertions(+), 49 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 6c83814bdf..3b3fb644ef 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -204,7 +204,6 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate Direction lightFace = quadView.lightFace(); data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); - data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], quadView.getFlags()); this.facing = quadView.getQuadFacing(); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index 2d7f86520a..0262756128 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -245,12 +245,12 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, if (emissive) { for (int i = 0; i < 4; i++) { quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); - quad.lightmap(i, LightTexture.FULL_BRIGHT); + data.lm[i] = LightTexture.FULL_BRIGHT; } } else { for (int i = 0; i < 4; i++) { quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); - quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i])); + data.lm[i] = ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i]); } } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java index b00e6be85a..4ea9392be7 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -1,19 +1,3 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package net.vulkanmod.render.chunk.build.frapi.render; import com.mojang.blaze3d.vertex.PoseStack; @@ -21,9 +5,6 @@ import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; import net.fabricmc.fabric.api.util.TriState; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -62,33 +43,26 @@ public BlockRenderContext() { } public void render(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrixStack, VertexConsumer buffer, boolean cull, RandomSource random, long seed, int overlay) { - try { - Vec3 offset = state.getOffset(blockView, pos); - matrixStack.translate(offset.x, offset.y, offset.z); - - this.blockPos = pos; - this.vertexConsumer = buffer; - this.matrix = matrixStack.last().pose(); - this.normalMatrix = matrixStack.last().normal(); - this.overlay = overlay; - - this.random = random; - this.seed = seed; - - this.lightDataCache.reset(blockView, pos); - - this.prepareForWorld(blockView, cull); - this.prepareForBlock(state, pos, model.useAmbientOcclusion()); - - model.emitBlockQuads(blockView, state, pos, this.randomSupplier, this); - } catch (Throwable throwable) { - CrashReport crashReport = CrashReport.forThrowable(throwable, "Tessellating block model - Indigo Renderer"); - CrashReportCategory crashReportSection = crashReport.addCategory("Block model being tessellated"); - CrashReportCategory.populateBlockDetails(crashReportSection, blockView, pos, state); - throw new ReportedException(crashReport); - } finally { - this.vertexConsumer = null; - } + Vec3 offset = state.getOffset(blockView, pos); + matrixStack.translate(offset.x, offset.y, offset.z); + + this.blockPos = pos; + this.vertexConsumer = buffer; + this.matrix = matrixStack.last().pose(); + this.normalMatrix = matrixStack.last().normal(); + this.overlay = overlay; + + this.random = random; + this.seed = seed; + + this.lightDataCache.reset(blockView, pos); + + this.prepareForWorld(blockView, cull); + this.prepareForBlock(state, pos, model.useAmbientOcclusion()); + + model.emitBlockQuads(blockView, state, pos, this.randomSupplier, this); + + this.vertexConsumer = null; } protected void endRenderQuad(MutableQuadViewImpl quad) { @@ -103,7 +77,14 @@ protected void endRenderQuad(MutableQuadViewImpl quad) { colorizeQuad(quad, colorIndex); shadeQuad(quad, lightPipeline, emissive, vanillaShade); + copyLightData(quad); bufferQuad(quad, vertexConsumer); } + private void copyLightData(MutableQuadViewImpl quad) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, this.quadLightData.lm[i]); + } + } + } From 5d2315d857c6c4e2fb35185eb556efed73059636 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 11 Mar 2025 18:04:17 +0100 Subject: [PATCH 078/177] Fix: apply quad transform if needed --- .../build/frapi/render/ItemRenderContext.java | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index 6ece16a2d0..0aef4c9a87 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -151,16 +151,34 @@ public void renderModel(ItemStack itemStack, ItemDisplayContext transformMode, b } public void emitItemQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - endRenderQuad(editorQuad); + if (!this.hasTransform()) { + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); + + //noinspection ForLoopReplaceableByForEach + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); + + endRenderQuad(editorQuad); + } + } + } + else { + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); + + //noinspection ForLoopReplaceableByForEach + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); + + this.renderQuad(editorQuad); + } } } } From 5441949dd78f3c27c327c6d91d84aaa75a7cd966 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 11 Mar 2025 18:05:58 +0100 Subject: [PATCH 079/177] Add flush batched cmds --- src/main/java/net/vulkanmod/config/gui/VOptionList.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index 854f1f59aa..e814f5cc62 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -207,6 +207,7 @@ public void renderWidget(int mouseX, int mouseY) { GuiRenderer.enableScissor(x, y, width, height); this.renderList(mouseX, mouseY); + GuiRenderer.flush(); GuiRenderer.disableScissor(); // Scroll bar From 320e32f2869cdc708816cdeef2be69cd5f50afd2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 16 Mar 2025 11:23:04 +0100 Subject: [PATCH 080/177] Fix: apply filtering state on reload --- .../mixin/texture/MAbstractTexture.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java index 634ce1af33..42270aab8c 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java @@ -7,6 +7,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; @Mixin(AbstractTexture.class) public abstract class MAbstractTexture { @@ -32,18 +33,17 @@ public void bind() { */ @Overwrite public void setFilter(boolean blur, boolean mipmap) { - if (blur != this.blur || mipmap != this.mipmap) { - this.blur = blur; - this.mipmap = mipmap; + this.blur = blur; + this.mipmap = mipmap; - GlTexture glTexture = GlTexture.getTexture(this.id); - VulkanImage vulkanImage = glTexture.getVulkanImage(); + GlTexture glTexture = GlTexture.getTexture(this.id); + VulkanImage vulkanImage = glTexture.getVulkanImage(); - if (vulkanImage != null) - vulkanImage.updateTextureSampler(this.blur, false, this.mipmap); - } + if (vulkanImage != null) + vulkanImage.updateTextureSampler(this.blur, false, this.mipmap); } + @Unique private void bindTexture() { GlTexture.bindTexture(this.id); } From 3a0d4b876f9e25b23a60dfa9882708fb1c4fdaf3 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 16 Mar 2025 11:26:00 +0100 Subject: [PATCH 081/177] Improve program and uniform compatibility --- src/main/java/net/vulkanmod/gl/GlProgram.java | 55 +++++++++++++++++++ .../mixin/compatibility/EffectInstanceM.java | 7 ++- .../mixin/compatibility/UniformM.java | 19 ++++--- .../mixin/render/GlProgramManagerMixin.java | 5 -- .../mixin/render/GlStateManagerM.java | 24 ++++++-- .../mixin/render/ShaderInstanceM.java | 39 +++++++++---- 6 files changed, 117 insertions(+), 32 deletions(-) create mode 100644 src/main/java/net/vulkanmod/gl/GlProgram.java diff --git a/src/main/java/net/vulkanmod/gl/GlProgram.java b/src/main/java/net/vulkanmod/gl/GlProgram.java new file mode 100644 index 0000000000..95682d91e1 --- /dev/null +++ b/src/main/java/net/vulkanmod/gl/GlProgram.java @@ -0,0 +1,55 @@ +package net.vulkanmod.gl; + +import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; +import net.vulkanmod.vulkan.shader.Pipeline; + +public class GlProgram { + private static int ID_COUNTER = 1; + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int boundProgramId = 0; + private static GlProgram boundProgram; + + public static GlProgram getBoundProgram() { + return boundProgram; + } + + public static GlProgram getProgram(int id) { + return map.get(id); + } + + public static int genProgramId() { + int id = ID_COUNTER; + map.put(id, new GlProgram(id)); + ID_COUNTER++; + return id; + } + + public static void glUseProgram(int id) { + boundProgramId = id; + boundProgram = map.get(id); + + if (id <= 0) { + return; + } + + if (boundProgram == null) { + throw new NullPointerException("bound texture is null"); + } + + } + + int id; + Pipeline pipeline; + + GlProgram(int i) { + this.id = i; + } + + public void bindPipeline(Pipeline pipeline) { + this.pipeline = pipeline; + } + + public Pipeline getPipeline() { + return this.pipeline; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index a38d9d62f2..1b94f4b955 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -12,6 +12,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; +import net.vulkanmod.gl.GlProgram; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; @@ -90,7 +91,6 @@ public void close() { } private void createShaders(ResourceProvider resourceManager, String vertexShader, String fragShader) { - try { String[] vshPathInfo = this.decompose(vertexShader, ':'); ResourceLocation vshLocation = ResourceLocation.fromNamespaceAndPath(vshPathInfo[0], "shaders/program/" + vshPathInfo[1] + ".vsh"); @@ -116,10 +116,11 @@ private void createShaders(ResourceProvider resourceManager, String vertexShader this.pipeline = builder.createGraphicsPipeline(); + GlProgram program = GlProgram.getProgram(this.programId); + program.bindPipeline(this.pipeline); } catch (IOException e) { throw new RuntimeException(e); } - } private void setUniformSuppliers(UBO ubo) { @@ -170,6 +171,8 @@ public void apply() { this.dirty = false; this.blend.apply(); + ProgramManager.glUseProgram(this.programId); + Renderer renderer = Renderer.getInstance(); if (this.pipeline != lastPipeline) { diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java index e722d874fe..ee634a28d9 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java @@ -2,12 +2,11 @@ import com.mojang.blaze3d.shaders.Shader; import com.mojang.blaze3d.shaders.Uniform; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.renderer.ShaderInstance; +import net.vulkanmod.gl.GlProgram; import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.texture.VTextureSelector; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -45,15 +44,19 @@ public void redirectUpload(CallbackInfo ci) { Renderer renderer = Renderer.getInstance(); Pipeline boundPipeline = renderer.getBoundPipeline(); - if (this.parent instanceof ShaderInstance) { - Pipeline pipeline = ShaderMixed.of((ShaderInstance) this.parent).getPipeline(); + ci.cancel(); + + GlProgram program = GlProgram.getBoundProgram(); - // Update descriptors only if the pipeline has already been bound - if (boundPipeline == pipeline) - renderer.uploadAndBindUBOs(boundPipeline); + if (program == null) { + return; } - ci.cancel(); + // Update descriptors only if the pipeline has already been bound + Pipeline pipeline = program.getPipeline(); + if (boundPipeline == pipeline) { + renderer.uploadAndBindUBOs(boundPipeline); + } } @Inject(method = "uploadInteger", at = @At("HEAD"), cancellable = true) diff --git a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java index 7c6fea9e89..b195f1a88f 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java @@ -13,11 +13,6 @@ @Mixin(ProgramManager.class) public class GlProgramManagerMixin { - @Inject(method = "createProgram", at = @At("HEAD"), cancellable = true) - private static void createProgram(CallbackInfoReturnable cir) throws IOException { - cir.setReturnValue(-1); - } - @Inject(method = "linkShader", at = @At("HEAD"), cancellable = true) private static void linkProgram(Shader shader, CallbackInfo ci) throws IOException { ci.cancel(); diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 594a3cfaf6..d093b93ba8 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -2,13 +2,11 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.GlBuffer; -import net.vulkanmod.gl.GlFramebuffer; -import net.vulkanmod.gl.GlRenderbuffer; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.*; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL20; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -231,7 +229,9 @@ public static void _clearColor(float f, float g, float h, float i) { * @author */ @Overwrite(remap = false) - public static void _clearDepth(double d) {} + public static void _clearDepth(double d) { + // TODO + } /** * @author @@ -246,7 +246,19 @@ public static void _clear(int mask, boolean bl) { * @author */ @Overwrite(remap = false) - public static void _glUseProgram(int i) {} + public static int glCreateProgram() { + RenderSystem.assertOnRenderThread(); + return GlProgram.genProgramId(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void _glUseProgram(int i) { + RenderSystem.assertOnRenderThread(); + GlProgram.glUseProgram(i); + } /** * @author diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java index b90d49fbbe..951f7d59ad 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -4,15 +4,16 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.shaders.Program; +import com.mojang.blaze3d.shaders.ProgramManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; import net.vulkanmod.Initializer; +import net.vulkanmod.gl.GlProgram; import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.render.shader.ShaderLoadUtil; import net.vulkanmod.vulkan.Renderer; @@ -65,6 +66,9 @@ public class ShaderInstanceM implements ShaderMixed { @Shadow @Final private List samplerNames; @Shadow @Final private List uniforms; + @Shadow @Final private VertexFormat vertexFormat; + @Shadow @Final private int programId; + @Shadow private static int lastProgramId; @Unique private String vsPath; @Unique private String fsName; @@ -82,18 +86,12 @@ private void create(ResourceProvider resourceProvider, String name, VertexFormat if (config == null) { createLegacyShader(resourceProvider, format); - return; + } else { + createPipeline(configName, format, config); } - Pipeline.Builder builder = new Pipeline.Builder(format, configName); - builder.setUniformSupplierGetter(info -> this.getUniformSupplier(info.name)); - - builder.parseBindings(config); - - ShaderLoadUtil.loadShaders(builder, config, configName, "core"); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - this.pipeline = pipeline; + GlProgram program = GlProgram.getProgram(this.programId); + program.bindPipeline(this.pipeline); } @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;")) @@ -160,6 +158,11 @@ public void apply() { } + if (this.programId != lastProgramId) { + ProgramManager.glUseProgram(this.programId); + lastProgramId = this.programId; + } + bindPipeline(); } @@ -305,6 +308,20 @@ public void setPipeline(GraphicsPipeline graphicsPipeline) { this.pipeline = graphicsPipeline; } + @Unique + private void createPipeline(String configName, VertexFormat format, JsonObject config) { + Pipeline.Builder builder = new Pipeline.Builder(format, configName); + builder.setUniformSupplierGetter(info -> this.getUniformSupplier(info.name)); + + builder.parseBindings(config); + + ShaderLoadUtil.loadShaders(builder, config, configName, "core"); + + GraphicsPipeline pipeline = builder.createGraphicsPipeline(); + this.pipeline = pipeline; + } + + @Unique private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat format) { try { String vertPath = this.vsPath + ".vsh"; From fd3568c70b427b206147d293013e693d11d00755 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 16 Mar 2025 12:55:53 +0100 Subject: [PATCH 082/177] Fix FAPI fluid rendering implementation Remove mixin that didn't allow vanilla fluid rendering invocation --- .../frapi/fluid/FluidRenderingImplMixin.java | 26 -------------- .../chunk/build/renderer/FluidRenderer.java | 34 ++++++++----------- src/main/resources/vulkanmod.mixins.json | 1 - 3 files changed, 14 insertions(+), 47 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java deleted file mode 100644 index 4565922c98..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/fluid/FluidRenderingImplMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.vulkanmod.mixin.render.frapi.fluid; - -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler; -import net.fabricmc.fabric.impl.client.rendering.fluid.FluidRenderingImpl; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.vulkanmod.render.chunk.build.renderer.DefaultFluidRenderers; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@SuppressWarnings("UnstableApiUsage") -@Mixin(FluidRenderingImpl.class) -public class FluidRenderingImplMixin { - - /** - * @author - * @reason - */ - @Overwrite - public static void renderDefault(FluidRenderHandler handler, BlockAndTintGetter world, BlockPos pos, VertexConsumer vertexConsumer, BlockState blockState, FluidState fluidState) { - DefaultFluidRenderers.add(handler); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java index b70970f410..30c5317f88 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java @@ -1,12 +1,15 @@ package net.vulkanmod.render.chunk.build.renderer; +import com.mojang.blaze3d.vertex.VertexConsumer; import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandler; import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRenderHandlerRegistry; +import net.fabricmc.fabric.api.client.render.fluid.v1.FluidRendering; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.tags.FluidTags; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.BlockGetter; @@ -31,7 +34,7 @@ import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Vector3f; -public class FluidRenderer { +public class FluidRenderer implements FluidRendering.DefaultRenderer { private static final float MAX_FLUID_HEIGHT = 0.8888889F; private final BlockPos.MutableBlockPos mBlockPos = new BlockPos.MutableBlockPos(); @@ -61,13 +64,13 @@ public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos renderType = TerrainRenderType.getRemapped(renderType); TerrainBufferBuilder bufferBuilder = this.resources.builderPack.builder(renderType).getBufferBuilder(QuadFacing.UNDEFINED.ordinal()); - if (handler != null) { - handler.renderFluid(blockPos, this.resources.getRegion(), bufferBuilder, blockState, fluidState); + // Fallback to water/lava in case there's no handler + if (handler == null) { + boolean isLava = fluidState.is(FluidTags.LAVA); + handler = FluidRenderHandlerRegistry.INSTANCE.get(isLava ? Fluids.LAVA : Fluids.WATER); } - if (DefaultFluidRenderers.has(handler)) { - tessellate(blockState, fluidState, blockPos, bufferBuilder); - } + FluidRendering.render(handler, this.resources.getRegion(),blockPos, bufferBuilder, blockState, fluidState, this); } private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Direction direction, BlockPos blockPos, BlockState blockState) { @@ -107,12 +110,14 @@ public BlockState getAdjBlockState(BlockAndTintGetter blockAndTintGetter, int x, return blockAndTintGetter.getBlockState(mBlockPos); } - public void tessellate(BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBufferBuilder bufferBuilder) { + public void render(FluidRenderHandler handler, BlockAndTintGetter world, BlockPos pos, VertexConsumer vertexConsumer, BlockState blockState, FluidState fluidState) { + render(handler, blockState, fluidState, pos, (TerrainBufferBuilder) vertexConsumer); + } + + public void render(FluidRenderHandler handler, BlockState blockState, FluidState fluidState, BlockPos blockPos, TerrainBufferBuilder bufferBuilder) { BlockAndTintGetter region = this.resources.getRegion(); - final FluidRenderHandler handler = getFluidRenderHandler(fluidState); int color = handler.getFluidColor(region, blockPos, fluidState); - TextureAtlasSprite[] sprites = handler.getFluidSprites(region, blockPos, fluidState); float r = ColorUtil.ARGB.unpackR(color); @@ -377,17 +382,6 @@ public void tessellate(BlockState blockState, FluidState fluidState, BlockPos bl } } - private static FluidRenderHandler getFluidRenderHandler(FluidState fluidState) { - FluidRenderHandler handler = FluidRenderHandlerRegistry.INSTANCE.get(fluidState.getType()); - - // Fallback to water in case no handler was found - if (handler == null) { - handler = FluidRenderHandlerRegistry.INSTANCE.get(Fluids.WATER); - } - - return handler; - } - private float calculateAverageHeight(BlockAndTintGetter blockAndTintGetter, Fluid fluid, float f, float g, float h, BlockPos blockPos) { if (!(h >= 1.0F) && !(g >= 1.0F)) { float[] fs = new float[2]; diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 996c8973aa..a24cadc918 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -57,7 +57,6 @@ "render.entity.model.ModelPartM", "render.frame.MinecraftMixin", "render.frame.RenderSystemMixin", - "render.frapi.fluid.FluidRenderingImplMixin", "render.frapi.BakedModelM", "render.frapi.ItemRendererAccessor", "render.frapi.ItemRendererMixin", From 11a19bb3933e4881c681c6d56098bbd79d706c4a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 10 May 2025 16:17:00 +0200 Subject: [PATCH 083/177] Add builder threads setting --- src/main/java/net/vulkanmod/config/Config.java | 4 ++-- .../java/net/vulkanmod/config/option/Options.java | 14 ++++++++++++++ .../net/vulkanmod/render/chunk/WorldRenderer.java | 4 +--- .../render/chunk/build/task/TaskDispatcher.java | 5 +++++ .../resources/assets/vulkanmod/lang/en_us.json | 5 ++++- 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index f59034624f..05b4e7c622 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -13,8 +13,6 @@ import java.util.Collections; public class Config { - - public int frameQueueSize = 2; public VideoModeSet.VideoMode videoMode = VideoModeManager.getFirstAvailable().getVideoMode(); public int windowMode = 0; @@ -26,6 +24,8 @@ public class Config { public int device = -1; public int ambientOcclusion = 1; + public int frameQueueSize = 2; + public int builderThreads = 0; public boolean backFaceCulling = true; diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index e211412374..c52a8de73b 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -9,6 +9,7 @@ import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.video.VideoModeSet; import net.vulkanmod.config.video.WindowMode; +import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.build.light.LightMode; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; @@ -277,6 +278,19 @@ public static OptionBlock[] getOptimizationOpts() { public static OptionBlock[] getOtherOpts() { return new OptionBlock[]{ new OptionBlock("", new Option[]{ + new RangeOption(Component.translatable("vulkanmod.options.builderThreads"), + 0, (Runtime.getRuntime().availableProcessors() - 1), 1, + value -> { + config.builderThreads = value; + WorldRenderer.getInstance().getTaskDispatcher().createThreads(value); + }, + () -> config.builderThreads) + .setTranslator(value -> { + if (value == 0) + return Component.translatable("vulkanmod.options.builderThreads.auto"); + else + return Component.nullToEmpty(String.valueOf(value)); + }), new RangeOption(Component.translatable("vulkanmod.options.frameQueue"), 2, 5, 1, value -> { diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 67bb89d572..0cf904027d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -225,14 +225,12 @@ public boolean isSectionCompiled(BlockPos blockPos) { public void allChanged() { if (this.level != null) { -// this.graphicsChanged(); this.level.clearTintCaches(); this.renderRegionCache.clear(); - this.taskDispatcher.createThreads(); + this.taskDispatcher.createThreads(Initializer.CONFIG.builderThreads); this.graphNeedsUpdate = true; -// this.generateClouds = true; this.renderDistance = this.minecraft.options.getEffectiveRenderDistance(); if (this.sectionGrid != null) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java index 0a3cf4def9..e9bdac8452 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java @@ -50,6 +50,11 @@ public void createThreads(int n) { } } + // Auto select thread count + if (n == 0) { + n = Math.max((Runtime.getRuntime().availableProcessors() - 1) / 2, 1); + } + this.threads = new Thread[n]; this.resources = new BuilderResources[n]; diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 5880f84fce..6947a8a905 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -41,5 +41,8 @@ "vulkanmod.options.windowMode": "Window Mode", "vulkanmod.options.windowMode.windowed": "Windowed", - "vulkanmod.options.windowMode.windowedFullscreen": "Windowed Fullscreen" + "vulkanmod.options.windowMode.windowedFullscreen": "Windowed Fullscreen", + + "vulkanmod.options.builderThreads": "Chunk Builder Threads", + "vulkanmod.options.builderThreads.auto": "Auto" } \ No newline at end of file From b8eb72e9a663951fa5b69100129d9ca7574816e2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 10 May 2025 16:23:10 +0200 Subject: [PATCH 084/177] Fix y-axis biome tint bug --- .../render/chunk/build/color/TintCache.java | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java index 2a8828d447..e31cc965e9 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java @@ -8,18 +8,18 @@ import net.minecraft.world.level.biome.Biome; import net.vulkanmod.render.chunk.build.biome.BiomeData; -import java.util.Arrays; - public class TintCache { private static final int SECTION_WIDTH = 16; + private static final int BOUNDARY_WIDTH = 16; + private static final int LAYER_COUNT = SECTION_WIDTH + (BOUNDARY_WIDTH * 2); private final Reference2ReferenceOpenHashMap layers; private BiomeData biomeData; private int blendRadius, totalWidth; private int secX, secY, secZ; - private int minX, minZ; - private int maxX, maxZ; + private int minX, minY, minZ; + private int maxX, maxY, maxZ; private int dataSize; private int[] temp; @@ -44,8 +44,11 @@ public void init(BiomeData biomeData, int blendRadius, int secX, int secY, int s this.minX = (secX << 4) - blendRadius; this.minZ = (secZ << 4) - blendRadius; - this.maxX = (secX << 4) + 16 + blendRadius; - this.maxZ = (secZ << 4) + 16 + blendRadius; + this.maxX = (secX << 4) + 15 + blendRadius; + this.maxZ = (secZ << 4) + 15 + blendRadius; + + this.minY = (secY << 4) - 2; + this.maxY = this.minY + 15 + 4; int size = totalWidth * totalWidth; @@ -70,7 +73,7 @@ public void init(BiomeData biomeData, int blendRadius, int secX, int secY, int s } public int getColor(BlockPos blockPos, ColorResolver colorResolver) { - int relY = blockPos.getY() & 15; + int relY = blockPos.getY() - this.minY; if (!this.layers.containsKey(colorResolver)) { addResolver(colorResolver); @@ -84,9 +87,10 @@ public int getColor(BlockPos blockPos, ColorResolver colorResolver) { int[] values = layer.getValues(); - int relX = blockPos.getX() & 15; - int relZ = blockPos.getZ() & 15; - int idx = this.totalWidth * (relZ + this.blendRadius) + (relX + this.blendRadius); + int relX = blockPos.getX() - this.minX; + int relZ = blockPos.getZ() - this.minZ; + + int idx = this.totalWidth * (relZ) + (relX); return values[idx]; } @@ -101,19 +105,22 @@ private void addResolver(ColorResolver colorResolver) { } private Layer[] allocateLayers() { - Layer[] layers = new Layer[SECTION_WIDTH]; + Layer[] layers = new Layer[LAYER_COUNT]; + + for (int i = 0; i < LAYER_COUNT; i++) { + layers[i] = new Layer(); + } - Arrays.fill(layers, new Layer()); return layers; } private void calculateLayer(Layer layer, ColorResolver colorResolver, int y) { - int absY = (secY << 4) + y; + int absY = minY + y; int[] values = layer.values; - for (int absZ = minZ; absZ < maxZ; absZ++) { - for (int absX = minX; absX < maxX; absX++) { + for (int absZ = minZ; absZ <= maxZ; absZ++) { + for (int absX = minX; absX <= maxX; absX++) { Biome biome = this.biomeData.getBiome(absX, absY, absZ); final int idx = (absX - minX) + (absZ - minZ) * totalWidth; From ed80bc4ecfefbcaa9ee59926d8327aeffc7e8084 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 11 May 2025 17:44:33 +0200 Subject: [PATCH 085/177] Refactor VRenderSystem --- .../mixin/render/RenderSystemMixin.java | 8 ++-- .../java/net/vulkanmod/vulkan/Renderer.java | 4 +- .../net/vulkanmod/vulkan/VRenderSystem.java | 38 +++++++++---------- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index d0a8596e58..a6ba821130 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -81,7 +81,7 @@ public static void disableColorLogicOp() { @Overwrite public static void logicOp(GlStateManager.LogicOp op) { assertOnRenderThread(); - VRenderSystem.logicOp(op); + VRenderSystem.logicOp(op.value); } /** @@ -227,7 +227,7 @@ public static void disableBlend() { */ @Overwrite(remap = false) public static void blendFunc(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - VRenderSystem.blendFunc(sourceFactor, destFactor); + VRenderSystem.blendFunc(sourceFactor.value, destFactor.value); } /** @@ -242,8 +242,8 @@ public static void blendFunc(int srcFactor, int dstFactor) { * @author */ @Overwrite(remap = false) - public static void blendFuncSeparate(GlStateManager.SourceFactor p_69417_, GlStateManager.DestFactor p_69418_, GlStateManager.SourceFactor p_69419_, GlStateManager.DestFactor p_69420_) { - VRenderSystem.blendFuncSeparate(p_69417_, p_69418_, p_69419_, p_69420_); + public static void blendFuncSeparate(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor, GlStateManager.SourceFactor sourceFactor1, GlStateManager.DestFactor destFactor1) { + VRenderSystem.blendFuncSeparate(sourceFactor.value, destFactor.value, sourceFactor1.value, destFactor1.value); } /** diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index fc21d3a8e3..0eaf4286ab 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -598,10 +598,10 @@ private static void resetDynamicState(VkCommandBuffer commandBuffer) { vkCmdSetLineWidth(commandBuffer, 1.0F); } - public static void setDepthBias(float units, float factor) { + public static void setDepthBias(float constant, float slope) { VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; - vkCmdSetDepthBias(commandBuffer, units, 0.0f, factor); + vkCmdSetDepthBias(commandBuffer, constant, 0.0f, slope); } public static void clearAttachments(int v) { diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index f52bf9174e..e9e7ee88e3 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -1,6 +1,5 @@ package net.vulkanmod.vulkan; -import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Window; import net.minecraft.client.Minecraft; @@ -56,8 +55,9 @@ public abstract class VRenderSystem { public static float alphaCutout = 0.0f; - private static float depthBiasUnits = 0.0f; - private static float depthBiasFactor = 0.0f; + private static boolean depthBiasEnabled = false; + private static float depthBiasConstant = 0.0f; + private static float depthBiasSlope = 0.0f; public static void initRenderer() { Vulkan.initVulkan(window); @@ -228,18 +228,10 @@ public static void disableBlend() { PipelineState.blendInfo.enabled = false; } - public static void blendFunc(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - PipelineState.blendInfo.setBlendFunction(sourceFactor, destFactor); - } - public static void blendFunc(int srcFactor, int dstFactor) { PipelineState.blendInfo.setBlendFunction(srcFactor, dstFactor); } - public static void blendFuncSeparate(GlStateManager.SourceFactor p_69417_, GlStateManager.DestFactor p_69418_, GlStateManager.SourceFactor p_69419_, GlStateManager.DestFactor p_69420_) { - PipelineState.blendInfo.setBlendFuncSeparate(p_69417_, p_69418_, p_69419_, p_69420_); - } - public static void blendFuncSeparate(int srcFactorRGB, int dstFactorRGB, int srcFactorAlpha, int dstFactorAlpha) { PipelineState.blendInfo.setBlendFuncSeparate(srcFactorRGB, dstFactorRGB, srcFactorAlpha, dstFactorAlpha); } @@ -252,23 +244,31 @@ public static void disableColorLogicOp() { logicOp = false; } - public static void logicOp(GlStateManager.LogicOp logicOp) { - logicOpFun = logicOp.value; + public static void logicOp(int glLogicOp) { + logicOpFun = glLogicOp; } - public static void polygonOffset(float factor, float units) { - depthBiasUnits = units; - depthBiasFactor = factor; + public static void polygonOffset(float slope, float biasConstant) { + if (depthBiasConstant != biasConstant || depthBiasSlope != slope) { + depthBiasConstant = biasConstant; + depthBiasSlope = slope; - Renderer.setDepthBias(depthBiasUnits, depthBiasFactor); + Renderer.setDepthBias(depthBiasConstant, depthBiasSlope); + } } public static void enablePolygonOffset() { - Renderer.setDepthBias(depthBiasUnits, depthBiasFactor); + if (!depthBiasEnabled) { + Renderer.setDepthBias(depthBiasConstant, depthBiasSlope); + depthBiasEnabled = true; + } } public static void disablePolygonOffset() { - Renderer.setDepthBias(0.0F, 0.0F); + if (depthBiasEnabled) { + Renderer.setDepthBias(0.0F, 0.0F); + depthBiasEnabled = false; + } } } From d0f47155e28df6c498df128474069b6da6f459ac Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 11 May 2025 18:11:36 +0200 Subject: [PATCH 086/177] Refactor: - Buffer classes - Memory copy --- src/main/java/net/vulkanmod/render/VBO.java | 7 +-- .../vulkanmod/render/chunk/WorldRenderer.java | 3 +- .../java/net/vulkanmod/vulkan/Drawer.java | 19 ++++--- .../vulkanmod/vulkan/memory/MemoryType.java | 2 +- .../vulkanmod/vulkan/memory/MemoryTypes.java | 10 ++-- .../vulkan/memory/buffer/Buffer.java | 36 ++++++++++--- .../vulkan/memory/buffer/IndexBuffer.java | 26 ++-------- .../vulkan/memory/buffer/IndirectBuffer.java | 12 ++--- .../vulkan/memory/buffer/StagingBuffer.java | 9 ++-- .../vulkan/memory/buffer/UniformBuffer.java | 11 +--- .../vulkan/memory/buffer/VertexBuffer.java | 25 --------- .../memory/buffer/index/AutoIndexBuffer.java | 2 +- .../vulkanmod/vulkan/texture/ImageUtil.java | 51 ++++++++++++------- .../vulkanmod/vulkan/texture/VulkanImage.java | 20 ++++---- .../java/net/vulkanmod/vulkan/util/VUtil.java | 12 +++++ 15 files changed, 123 insertions(+), 122 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index c82795b256..48f10decbd 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -52,8 +52,9 @@ private void uploadVertexBuffer(MeshData.DrawState parameters, ByteBuffer data) if (this.vertexBuffer != null) this.vertexBuffer.scheduleFree(); - this.vertexBuffer = new VertexBuffer(data.remaining(), this.memoryType); - this.vertexBuffer.copyToVertexBuffer(parameters.format().getVertexSize(), parameters.vertexCount(), data); + int size = parameters.format().getVertexSize() * parameters.vertexCount(); + this.vertexBuffer = new VertexBuffer(size, this.memoryType); + this.vertexBuffer.copyBuffer(data, size); } } @@ -102,7 +103,7 @@ public void uploadIndexBuffer(ByteBuffer data) { } this.indexBuffer = new IndexBuffer(data.remaining(), MemoryTypes.GPU_MEM); - this.indexBuffer.copyBuffer(data); + this.indexBuffer.copyBuffer(data, data.remaining()); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 0cf904027d..c8fed57c51 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -1,7 +1,6 @@ package net.vulkanmod.render.chunk; import com.google.common.collect.Sets; -import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.SheetedDecalTextureGenerator; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -311,7 +310,7 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, VTextureSelector.bindShaderTextures(pipeline); IndexBuffer indexBuffer = Renderer.getDrawer().getQuadsIndexBuffer().getIndexBuffer(); - Renderer.getDrawer().bindIndexBuffer(Renderer.getCommandBuffer(), indexBuffer); + Renderer.getDrawer().bindIndexBuffer(Renderer.getCommandBuffer(), indexBuffer, indexBuffer.indexType.value); int currentFrame = Renderer.getCurrentFrame(); Set allowedRenderTypes = Initializer.CONFIG.uniqueOpaqueLayer ? TerrainRenderType.COMPACT_RENDER_TYPES : TerrainRenderType.SEMI_COMPACT_RENDER_TYPES; diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index 1881c0974b..fd2ae33f81 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -96,11 +96,12 @@ public void draw(ByteBuffer vertexData, VertexFormat.Mode mode, VertexFormat ver public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode mode, VertexFormat vertexFormat, int vertexCount) { VertexBuffer vertexBuffer = this.vertexBuffers[this.currentFrame]; - vertexBuffer.copyToVertexBuffer(vertexFormat.getVertexSize(), vertexCount, vertexData); + int size = vertexFormat.getVertexSize() * vertexCount; + vertexBuffer.copyBuffer(vertexData, size); if (indexData != null) { IndexBuffer indexBuffer = this.indexBuffers[this.currentFrame]; - indexBuffer.copyBuffer(indexData); + indexBuffer.copyBuffer(indexData, indexData.remaining()); int indexCount = vertexCount * 3 / 2; @@ -121,14 +122,18 @@ public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode } } - public void drawIndexed(VertexBuffer vertexBuffer, IndexBuffer indexBuffer, int indexCount) { + public void drawIndexed(Buffer vertexBuffer, IndexBuffer indexBuffer, int indexCount) { + drawIndexed(vertexBuffer, indexBuffer, indexCount, indexBuffer.indexType.value); + } + + public void drawIndexed(Buffer vertexBuffer, Buffer indexBuffer, int indexCount, int indexType) { VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); VUtil.UNSAFE.putLong(pBuffers, vertexBuffer.getId()); VUtil.UNSAFE.putLong(pOffsets, vertexBuffer.getOffset()); nvkCmdBindVertexBuffers(commandBuffer, 0, 1, pBuffers, pOffsets); - bindIndexBuffer(commandBuffer, indexBuffer); + bindIndexBuffer(commandBuffer, indexBuffer, indexType); vkCmdDrawIndexed(commandBuffer, indexCount, 1, 0, 0, 0); } @@ -142,8 +147,8 @@ public void draw(VertexBuffer vertexBuffer, int vertexCount) { vkCmdDraw(commandBuffer, vertexCount, 1, 0, 0); } - public void bindIndexBuffer(VkCommandBuffer commandBuffer, IndexBuffer indexBuffer) { - vkCmdBindIndexBuffer(commandBuffer, indexBuffer.getId(), indexBuffer.getOffset(), indexBuffer.indexType.type); + public void bindIndexBuffer(VkCommandBuffer commandBuffer, Buffer indexBuffer, int indexType) { + vkCmdBindIndexBuffer(commandBuffer, indexBuffer.getId(), indexBuffer.getOffset(), indexType); } public void cleanUpResources() { @@ -191,7 +196,7 @@ public UniformBuffer getUniformBuffer() { return this.uniformBuffers[this.currentFrame]; } - private AutoIndexBuffer getAutoIndexBuffer(VertexFormat.Mode mode, int vertexCount) { + public AutoIndexBuffer getAutoIndexBuffer(VertexFormat.Mode mode, int vertexCount) { return switch (mode) { case QUADS -> { int indexCount = vertexCount * 3 / 2; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java index 3d20c94b23..15bf8d6dfe 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java @@ -19,7 +19,7 @@ public abstract class MemoryType { public abstract void createBuffer(Buffer buffer, long size); - public abstract void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); + public abstract void copyToBuffer(Buffer buffer, ByteBuffer src, long size, long srcOffset, long dstOffset); public abstract void copyFromBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 0206702200..9becd6202d 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -72,11 +72,11 @@ public void createBuffer(Buffer buffer, long size) { } @Override - public void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { + public void copyToBuffer(Buffer buffer, ByteBuffer src, long size, long srcOffset, long dstOffset) { StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - stagingBuffer.copyBuffer((int) bufferSize, byteBuffer); + stagingBuffer.copyBuffer((int) size, src); - DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.getId(), stagingBuffer.getOffset(), buffer.getId(), buffer.getUsedBytes(), bufferSize); + DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.getId(), stagingBuffer.getOffset(), buffer.getId(), dstOffset, size); } @Override @@ -105,8 +105,8 @@ static abstract class MappableMemory extends MemoryType { } @Override - public void copyToBuffer(Buffer buffer, long size, ByteBuffer byteBuffer) { - VUtil.memcpy(byteBuffer, buffer, size); + public void copyToBuffer(Buffer buffer, ByteBuffer src, long size, long srcOffset, long dstOffset) { + VUtil.memcpy(src, buffer, size, srcOffset, dstOffset); } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java index 56e9b13414..ac8ac91e45 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java @@ -3,7 +3,9 @@ import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryType; -public abstract class Buffer { +import java.nio.ByteBuffer; + +public class Buffer { public final MemoryType type; public final int usage; @@ -16,14 +18,12 @@ public abstract class Buffer { protected long dataPtr; - protected Buffer(int usage, MemoryType type) { - //TODO: check usage + public Buffer(int usage, MemoryType type) { this.usage = usage; this.type = type; - } - protected void createBuffer(long bufferSize) { + public void createBuffer(long bufferSize) { this.type.createBuffer(this, bufferSize); if (this.type.mappable()) { @@ -31,6 +31,31 @@ protected void createBuffer(long bufferSize) { } } + public void resizeBuffer(long newSize) { + MemoryManager.getInstance().addToFreeable(this); + this.createBuffer(newSize); + } + + public void copyBuffer(ByteBuffer byteBuffer, int size) { + if (size > this.bufferSize - this.usedBytes) { + resizeBuffer((this.bufferSize + size) * 2); + } + + this.type.copyToBuffer(this, byteBuffer, size, 0, this.usedBytes); + this.offset = this.usedBytes; + this.usedBytes += size; + } + + public void copyBuffer(ByteBuffer byteBuffer, int size, int dstOffset) { + if (size > this.bufferSize - dstOffset) { + resizeBuffer((this.bufferSize + size) * 2); + } + + this.type.copyToBuffer(this, byteBuffer, size, 0, dstOffset); + this.offset = dstOffset; + this.usedBytes = dstOffset + size; + } + public void scheduleFree() { MemoryManager.getInstance().addToFreeable(this); } @@ -80,6 +105,5 @@ public BufferInfo getBufferInfo() { } public record BufferInfo(long id, long allocation, long bufferSize, MemoryType.Type type) { - } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java index 6947402299..1b2ad4c8b0 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java @@ -1,10 +1,7 @@ package net.vulkanmod.vulkan.memory.buffer; -import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryType; -import java.nio.ByteBuffer; - import static org.lwjgl.vulkan.VK10.*; public class IndexBuffer extends Buffer { @@ -22,33 +19,16 @@ public IndexBuffer(int size, MemoryType type, IndexType indexType) { this.createBuffer(size); } - public void copyBuffer(ByteBuffer byteBuffer) { - int size = byteBuffer.remaining(); - - if(size > this.bufferSize - this.usedBytes) { - resizeBuffer((this.bufferSize + size) * 2); - } - - this.type.copyToBuffer(this, size, byteBuffer); - offset = usedBytes; - usedBytes += size; - } - - private void resizeBuffer(long newSize) { - MemoryManager.getInstance().addToFreeable(this); - this.createBuffer(newSize); - } - public enum IndexType { UINT16(2, VK_INDEX_TYPE_UINT16), UINT32(4, VK_INDEX_TYPE_UINT32); public final int size; - public final int type; + public final int value; - IndexType(int size, int type) { + IndexType(int size, int value) { this.size = size; - this.type = type; + this.value = value; } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java index ddcbc31edc..6b09cb0cb3 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java @@ -24,11 +24,12 @@ public void recordCopyCmd(ByteBuffer byteBuffer) { int size = byteBuffer.remaining(); if (size > this.bufferSize - this.usedBytes) { - resizeBuffer(); + resizeBuffer((long) (this.bufferSize * 1.5f)); + this.usedBytes = 0; } if (this.type.mappable()) { - this.type.copyToBuffer(this, size, byteBuffer); + this.type.copyToBuffer(this, byteBuffer, size, 0, this.usedBytes); } else { if (commandBuffer == null) commandBuffer = DeviceManager.getTransferQueue().beginCommands(); @@ -43,13 +44,6 @@ public void recordCopyCmd(ByteBuffer byteBuffer) { usedBytes += size; } - private void resizeBuffer() { - MemoryManager.getInstance().addToFreeable(this); - long newSize = this.bufferSize + (this.bufferSize >> 1); - this.createBuffer(newSize); - this.usedBytes = 0; - } - public void submitUploads() { if (commandBuffer == null) return; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java index d45835fff9..03d764c5a1 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java @@ -21,13 +21,14 @@ public StagingBuffer() { public StagingBuffer(long size) { super(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, MemoryTypes.HOST_MEM); - this.usedBytes = 0; - this.offset = 0; - this.createBuffer(size); } public void copyBuffer(int size, ByteBuffer byteBuffer) { + this.copyBuffer(size, MemoryUtil.memAddress(byteBuffer)); + } + + public void copyBuffer(int size, long scrPtr) { if (size > this.bufferSize) { throw new IllegalArgumentException("Upload size is greater than staging buffer size."); } @@ -36,7 +37,7 @@ public void copyBuffer(int size, ByteBuffer byteBuffer) { submitUploads(); } - nmemcpy(this.dataPtr + this.usedBytes, MemoryUtil.memAddress(byteBuffer), size); + nmemcpy(this.dataPtr + this.usedBytes, scrPtr, size); this.offset = this.usedBytes; this.usedBytes += size; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java index 5f056644a2..b9d102d185 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java @@ -1,18 +1,16 @@ package net.vulkanmod.vulkan.memory.buffer; import net.vulkanmod.vulkan.device.DeviceManager; -import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryType; import static net.vulkanmod.vulkan.util.VUtil.align; import static org.lwjgl.vulkan.VK10.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; public class UniformBuffer extends Buffer { - - private final static int minOffset = (int) DeviceManager.deviceProperties.limits().minUniformBufferOffsetAlignment(); + private final static int MIN_OFFSET_ALIGNMENT = (int) DeviceManager.deviceProperties.limits().minUniformBufferOffsetAlignment(); public static int getAlignedSize(int uploadSize) { - return align(uploadSize, minOffset); + return align(uploadSize, MIN_OFFSET_ALIGNMENT); } public UniformBuffer(int size, MemoryType memoryType) { @@ -30,11 +28,6 @@ public void updateOffset(int alignedSize) { usedBytes += alignedSize; } - private void resizeBuffer(long newSize) { - MemoryManager.getInstance().addToFreeable(this); - createBuffer(newSize); - } - public long getPointer() { return this.dataPtr + usedBytes; } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java index 7551696b21..fb9858c9bd 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java @@ -1,11 +1,8 @@ package net.vulkanmod.vulkan.memory.buffer; -import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryType; import net.vulkanmod.vulkan.memory.MemoryTypes; -import java.nio.ByteBuffer; - import static org.lwjgl.vulkan.VK10.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; public class VertexBuffer extends Buffer { @@ -17,28 +14,6 @@ public VertexBuffer(int size) { public VertexBuffer(int size, MemoryType type) { super(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, type); this.createBuffer(size); - - } - - public void copyToVertexBuffer(long vertexSize, long vertexCount, ByteBuffer byteBuffer) { - int bufferSize = (int) (vertexSize * vertexCount); -// long bufferSize = byteBuffer.limit(); - - if(bufferSize > this.bufferSize - this.usedBytes) { - resizeBuffer((this.bufferSize + bufferSize) * 2); - } - - this.type.copyToBuffer(this, bufferSize, byteBuffer); - offset = usedBytes; - usedBytes += bufferSize; - - } - - private void resizeBuffer(long newSize) { - MemoryManager.getInstance().addToFreeable(this); - this.createBuffer(newSize); - -// System.out.println("resized vertexBuffer to: " + newSize); } } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java index d5140bdcee..a05ae38cf1 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java @@ -52,7 +52,7 @@ private void createIndexBuffer(int vertexCount) { int size = buffer.capacity(); this.indexBuffer = new IndexBuffer(size, MemoryTypes.GPU_MEM, indexType); - this.indexBuffer.copyBuffer(buffer); + this.indexBuffer.copyBuffer(buffer, buffer.remaining()); MemoryUtil.memFree(buffer); } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java index 6ec57980f3..c6b4ea2a03 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java @@ -3,6 +3,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.util.VUtil; import org.lwjgl.PointerBuffer; @@ -21,8 +22,8 @@ public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer comma int bufferOffset, int bufferRowLenght, int bufferImageHeight) { VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); region.bufferOffset(bufferOffset); - region.bufferRowLength(bufferRowLenght); // Tightly packed - region.bufferImageHeight(bufferImageHeight); // Tightly packed + region.bufferRowLength(bufferRowLenght); + region.bufferImageHeight(bufferImageHeight); region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); region.imageSubresource().mipLevel(mipLevel); region.imageSubresource().baseArrayLayer(0); @@ -47,7 +48,7 @@ public static void downloadTexture(VulkanImage image, long ptr) { VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, pStagingBuffer, pStagingAllocation); - copyImageToBuffer(commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, + copyImageToBufferCmd(stack, commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, image.height, 0, 0, 0, 0, 0); image.transitionImageLayout(stack, commandBuffer.getHandle(), prevLayout); @@ -61,26 +62,40 @@ public static void downloadTexture(VulkanImage image, long ptr) { } } - public static void copyImageToBuffer(VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, - int width, int height, int xOffset, int yOffset, int bufferOffset, - int bufferRowLenght, int bufferImageHeight) { + public static void copyImageToBuffer(VulkanImage image, Buffer buffer, int mipLevel, + int width, int height, int xOffset, int yOffset, + int bufferOffset, int bufferRowLength, int bufferImageHeight) { try (MemoryStack stack = stackPush()) { + int prevLayout = image.getCurrentLayout(); + CommandPool.CommandBuffer commandBuffer = DeviceManager.getGraphicsQueue().beginCommands(); + image.transitionImageLayout(stack, commandBuffer.getHandle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + copyImageToBufferCmd(stack, commandBuffer.getHandle(), buffer.getId(), image.getId(), mipLevel, width, + height, xOffset, yOffset, bufferOffset, bufferRowLength, bufferImageHeight); + image.transitionImageLayout(stack, commandBuffer.getHandle(), prevLayout); - VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); - region.bufferOffset(bufferOffset); - region.bufferRowLength(bufferRowLenght); // Tightly packed - region.bufferImageHeight(bufferImageHeight); // Tightly packed - region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); - region.imageSubresource().mipLevel(mipLevel); - region.imageSubresource().baseArrayLayer(0); - region.imageSubresource().layerCount(1); - region.imageOffset().set(xOffset, yOffset, 0); - region.imageExtent().set(width, height, 1); - - vkCmdCopyImageToBuffer(commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, region); + long fence = DeviceManager.getGraphicsQueue().submitCommands(commandBuffer); + vkWaitForFences(DeviceManager.vkDevice, fence, true, VUtil.UINT64_MAX); } } + public static void copyImageToBufferCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, + int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, + int bufferRowLength, int bufferImageHeight) { + VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); + region.bufferOffset(bufferOffset); + region.bufferRowLength(bufferRowLength); + region.bufferImageHeight(bufferImageHeight); + region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); + region.imageSubresource().mipLevel(mipLevel); + region.imageSubresource().baseArrayLayer(0); + region.imageSubresource().layerCount(1); + region.imageOffset().set(xOffset, yOffset, 0); + region.imageExtent().set(width, height, 1); + + vkCmdCopyImageToBuffer(commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, region); + } + public static void blitFramebuffer(VulkanImage dstImage, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1) { try (MemoryStack stack = stackPush()) { diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index a07f6bb26f..fe21e09fde 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -196,7 +196,13 @@ public static long createImageView(long image, int format, int aspectFlags, int } public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { - long uploadSize = buffer.limit(); + this.uploadSubTextureAsync(mipLevel, width, height, + xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, + MemoryUtil.memAddress(buffer)); + } + + public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, long srcPtr) { + long uploadSize = (long) unpackRowLength * height * this.formatSize; StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); @@ -207,8 +213,10 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs stagingBuffer.scheduleFree(); } + srcPtr += ((long) unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize; + stagingBuffer.align(this.formatSize); - stagingBuffer.copyBuffer((int) uploadSize, buffer); + stagingBuffer.copyBuffer((int) uploadSize, srcPtr); long bufferId = stagingBuffer.getId(); @@ -216,13 +224,7 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs try (MemoryStack stack = stackPush()) { transferDstLayout(stack, commandBuffer); - int uploadOffset = (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize; - - if (uploadOffset > uploadSize) { - throw new BufferOverflowException(); - } - - final int srcOffset = (int) (stagingBuffer.getOffset() + uploadOffset); + final int srcOffset = (int) (stagingBuffer.getOffset()); ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, srcOffset, unpackRowLength, height); diff --git a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java index 37a9671f03..ab359b71a5 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java @@ -75,6 +75,18 @@ public static void memcpy(Buffer src, ByteBuffer dst, long size) { MemoryUtil.memCopy(srcPtr, dstPtr, size); } + public static void memcpy(ByteBuffer src, Buffer dst, long size, long srcOffset, long dstOffset) { + if (CHECKS) { + if (size > dst.getBufferSize() - dstOffset) { + throw new IllegalArgumentException("Upload size is greater than available dst buffer size"); + } + } + + final long dstPtr = dst.getDataPtr() + dstOffset; + final long srcPtr = MemoryUtil.memAddress(src) + srcOffset; + MemoryUtil.memCopy(srcPtr, dstPtr, size); + } + public static int align(int x, int align) { int r = x % align; return r == 0 ? x : x + align - r; From df460ba16e88051e2bac98671e538ebb60d67f5a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 11 May 2025 18:21:25 +0200 Subject: [PATCH 087/177] Refactor: - Rename gl emulation classes - Refactor SwapChain color attachment interface --- src/main/java/net/vulkanmod/gl/GlUtil.java | 11 +--- .../gl/{GlBuffer.java => VkGlBuffer.java} | 24 ++++---- ...lFramebuffer.java => VkGlFramebuffer.java} | 57 ++++++++++--------- .../gl/{GlProgram.java => VkGlProgram.java} | 14 ++--- ...enderbuffer.java => VkGlRenderbuffer.java} | 16 +++--- .../gl/{GlTexture.java => VkGlTexture.java} | 28 ++++----- .../mixin/compatibility/EffectInstanceM.java | 4 +- .../mixin/compatibility/UniformM.java | 6 +- .../mixin/compatibility/gl/GL11M.java | 35 ++++++------ .../mixin/compatibility/gl/GL15M.java | 20 +++---- .../mixin/compatibility/gl/GL30M.java | 29 +++++----- .../mixin/render/GlStateManagerM.java | 53 +++++++++-------- .../mixin/render/RenderSystemMixin.java | 6 +- .../mixin/render/ShaderInstanceM.java | 4 +- .../mixin/render/target/MainTargetMixin.java | 2 +- .../render/target/RenderTargetMixin.java | 24 ++++---- .../mixin/texture/MAbstractTexture.java | 6 +- .../vulkanmod/mixin/texture/MTextureUtil.java | 23 ++++++-- .../mixin/texture/update/MLightTexture.java | 4 +- .../mixin/util/ScreenshotRecorderM.java | 4 +- .../java/net/vulkanmod/vulkan/Renderer.java | 11 +++- .../vulkan/framebuffer/SwapChain.java | 22 +------ .../vulkan/pass/DefaultMainPass.java | 39 ++++++++++--- .../net/vulkanmod/vulkan/pass/MainPass.java | 9 +-- .../vulkan/texture/VTextureSelector.java | 27 +++++---- .../net/vulkanmod/vulkan/util/DrawUtil.java | 4 +- 26 files changed, 252 insertions(+), 230 deletions(-) rename src/main/java/net/vulkanmod/gl/{GlBuffer.java => VkGlBuffer.java} (84%) rename src/main/java/net/vulkanmod/gl/{GlFramebuffer.java => VkGlFramebuffer.java} (80%) rename src/main/java/net/vulkanmod/gl/{GlProgram.java => VkGlProgram.java} (72%) rename src/main/java/net/vulkanmod/gl/{GlRenderbuffer.java => VkGlRenderbuffer.java} (94%) rename src/main/java/net/vulkanmod/gl/{GlTexture.java => VkGlTexture.java} (94%) diff --git a/src/main/java/net/vulkanmod/gl/GlUtil.java b/src/main/java/net/vulkanmod/gl/GlUtil.java index 5cd12df118..fe8edea75b 100644 --- a/src/main/java/net/vulkanmod/gl/GlUtil.java +++ b/src/main/java/net/vulkanmod/gl/GlUtil.java @@ -88,11 +88,8 @@ public static int vulkanFormat(int glFormat, int type) { case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8_UNORM; default -> throw new IllegalStateException("Unexpected type: " + type); }; - case GL11.GL_DEPTH_COMPONENT, GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT24 -> -// switch (type) { -// case GL11.GL_FLOAT -> VK_FORMAT_D32_SFLOAT; -// default -> throw new IllegalStateException("Unexpected value: " + type); -// }; + case GL11.GL_DEPTH_COMPONENT, GL30.GL_DEPTH_COMPONENT32, + GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT24 -> Vulkan.getDefaultDepthFormat(); default -> throw new IllegalStateException("Unexpected format: " + glFormat); @@ -104,10 +101,6 @@ public static int vulkanFormat(int glInternalFormat) { return switch (glInternalFormat) { case GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> VK_FORMAT_R8G8B8A8_UINT; case GL11.GL_DEPTH_COMPONENT, GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT24 -> -// switch (type) { -// case GL11.GL_FLOAT -> VK_FORMAT_D32_SFLOAT; -// default -> throw new IllegalStateException("Unexpected value: " + type); -// }; Vulkan.getDefaultDepthFormat(); default -> throw new IllegalStateException("Unexpected value: " + glInternalFormat); diff --git a/src/main/java/net/vulkanmod/gl/GlBuffer.java b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java similarity index 84% rename from src/main/java/net/vulkanmod/gl/GlBuffer.java rename to src/main/java/net/vulkanmod/gl/VkGlBuffer.java index 09091728ec..05cc59be17 100644 --- a/src/main/java/net/vulkanmod/gl/GlBuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java @@ -9,25 +9,25 @@ // TODO: This class is only used to emulate a CPU buffer for texture copying purposes // any other use is not supported -public class GlBuffer { +public class VkGlBuffer { private static int ID_COUNTER = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundId = 0; - private static GlBuffer boundBuffer; + private static VkGlBuffer boundBuffer; - private static GlBuffer pixelPackBufferBound; - private static GlBuffer pixelUnpackBufferBound; + private static VkGlBuffer pixelPackBufferBound; + private static VkGlBuffer pixelUnpackBufferBound; public static int glGenBuffers() { int id = ID_COUNTER; - map.put(id, new GlBuffer(id)); + map.put(id, new VkGlBuffer(id)); ID_COUNTER++; return id; } public static void glBindBuffer(int target, int buffer) { boundId = buffer; - GlBuffer glBuffer = map.get(buffer); + VkGlBuffer glBuffer = map.get(buffer); if (buffer > 0 && glBuffer == null) throw new NullPointerException("bound texture is null"); @@ -52,7 +52,7 @@ public static void glBufferData(int target, ByteBuffer byteBuffer, int usage) { } public static void glBufferData(int target, long size, int usage) { - GlBuffer buffer = switch (target) { + VkGlBuffer buffer = switch (target) { case GL32.GL_PIXEL_PACK_BUFFER -> pixelPackBufferBound; case GL32.GL_PIXEL_UNPACK_BUFFER -> pixelUnpackBufferBound; default -> throw new IllegalStateException("Unexpected value: " + target); @@ -62,7 +62,7 @@ public static void glBufferData(int target, long size, int usage) { } public static ByteBuffer glMapBuffer(int target, int access) { - GlBuffer buffer = switch (target) { + VkGlBuffer buffer = switch (target) { case GL32.GL_PIXEL_PACK_BUFFER -> pixelPackBufferBound; case GL32.GL_PIXEL_UNPACK_BUFFER -> pixelUnpackBufferBound; default -> throw new IllegalStateException("Unexpected value: " + target); @@ -90,11 +90,11 @@ public static void glDeleteBuffers(int id) { buffer.freeData(); } - public static GlBuffer getPixelUnpackBufferBound() { + public static VkGlBuffer getPixelUnpackBufferBound() { return pixelUnpackBufferBound; } - public static GlBuffer getPixelPackBufferBound() { + public static VkGlBuffer getPixelPackBufferBound() { return pixelPackBufferBound; } @@ -108,7 +108,7 @@ private static void checkTarget(int target) { ByteBuffer data; - public GlBuffer(int id) { + public VkGlBuffer(int id) { this.id = id; } diff --git a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java similarity index 80% rename from src/main/java/net/vulkanmod/gl/GlFramebuffer.java rename to src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java index b61995a00d..9981da56f6 100644 --- a/src/main/java/net/vulkanmod/gl/GlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java @@ -1,8 +1,6 @@ package net.vulkanmod.gl; -import com.mojang.blaze3d.pipeline.RenderTarget; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; -import net.minecraft.client.Minecraft; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.framebuffer.Framebuffer; @@ -15,18 +13,18 @@ import static org.lwjgl.vulkan.VK11.VK_ATTACHMENT_LOAD_OP_LOAD; import static org.lwjgl.vulkan.VK11.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; -public class GlFramebuffer { +public class VkGlFramebuffer { private static int idCounter = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); - private static GlFramebuffer boundFramebuffer; - private static GlFramebuffer readFramebuffer; + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static VkGlFramebuffer boundFramebuffer; + private static VkGlFramebuffer readFramebuffer; public static void resetBoundFramebuffer() { boundFramebuffer = null; } - public static void beginRendering(GlFramebuffer glFramebuffer) { + public static void beginRendering(VkGlFramebuffer glFramebuffer) { boolean begunRendering = glFramebuffer.beginRendering(); if (begunRendering) { @@ -46,32 +44,33 @@ public static void beginRendering(GlFramebuffer glFramebuffer) { public static int genFramebufferId() { int id = idCounter; - map.put(id, new GlFramebuffer(id)); + map.put(id, new VkGlFramebuffer(id)); idCounter++; return id; } public static void bindFramebuffer(int target, int id) { - if (id == 0) { - Renderer.getInstance().endRenderPass(); + Renderer.getInstance() + .endRenderPass(); if (Renderer.isRecording()) { - RenderTarget renderTarget = Minecraft.getInstance().getMainRenderTarget(); - renderTarget.bindWrite(true); + Renderer.getInstance() + .getMainPass() + .rebindMainTarget(); } boundFramebuffer = null; return; } - GlFramebuffer glFramebuffer = map.get(id); + VkGlFramebuffer glFramebuffer = map.get(id); if (glFramebuffer == null) throw new NullPointerException("No Framebuffer with ID: %d ".formatted(id)); switch (target) { - case GL30.GL_DRAW_FRAMEBUFFER , GL30.GL_FRAMEBUFFER -> { + case GL30.GL_DRAW_FRAMEBUFFER, GL30.GL_FRAMEBUFFER -> { if (glFramebuffer.framebuffer != null) { beginRendering(glFramebuffer); } @@ -120,7 +119,8 @@ public static void framebufferRenderbuffer(int target, int attachment, int rende boundFramebuffer.setAttachmentRenderbuffer(attachment, renderbuffer); } - public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, + int dstY1, int mask, int filter) { // TODO: add missing parameters ImageUtil.blitFramebuffer(boundFramebuffer.colorAttachment, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1); } @@ -130,22 +130,22 @@ public static int glCheckFramebufferStatus(int target) { return GL30.GL_FRAMEBUFFER_COMPLETE; } - public static GlFramebuffer getBoundFramebuffer() { + public static VkGlFramebuffer getBoundFramebuffer() { return boundFramebuffer; } - public static GlFramebuffer getFramebuffer(int id) { + public static VkGlFramebuffer getFramebuffer(int id) { return map.get(id); } - private final int id; + public final int id; Framebuffer framebuffer; RenderPass renderPass; VulkanImage colorAttachment; VulkanImage depthAttachment; - GlFramebuffer(int i) { + VkGlFramebuffer(int i) { this.id = i; } @@ -154,7 +154,7 @@ boolean beginRendering() { } void setAttachmentTexture(int attachment, int texture) { - GlTexture glTexture = GlTexture.getTexture(texture); + VkGlTexture glTexture = VkGlTexture.getTexture(texture); if (glTexture == null) throw new NullPointerException(String.format("Texture %d is null", texture)); @@ -171,7 +171,7 @@ void setAttachmentTexture(int attachment, int texture) { } void setAttachmentRenderbuffer(int attachment, int texture) { - GlRenderbuffer renderbuffer = GlRenderbuffer.getRenderbuffer(texture); + VkGlRenderbuffer renderbuffer = VkGlRenderbuffer.getRenderbuffer(texture); if (renderbuffer == null) throw new NullPointerException(String.format("Texture %d is null", texture)); @@ -210,19 +210,22 @@ void createAndBind() { boolean hasDepthImage = this.depthAttachment != null; VulkanImage depthImage = this.depthAttachment; - this.framebuffer = Framebuffer.builder(this.colorAttachment, depthImage).build(); + this.framebuffer = Framebuffer.builder(this.colorAttachment, depthImage) + .build(); RenderPass.Builder builder = RenderPass.builder(this.framebuffer); builder.getColorAttachmentInfo() - .setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD) - .setFinalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + .setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD) + .setFinalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - if (hasDepthImage) - builder.getDepthAttachmentInfo().setOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD); + if (hasDepthImage) { + builder.getDepthAttachmentInfo() + .setOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD); + } this.renderPass = builder.build(); - GlFramebuffer.beginRendering(this); + VkGlFramebuffer.beginRendering(this); } public Framebuffer getFramebuffer() { diff --git a/src/main/java/net/vulkanmod/gl/GlProgram.java b/src/main/java/net/vulkanmod/gl/VkGlProgram.java similarity index 72% rename from src/main/java/net/vulkanmod/gl/GlProgram.java rename to src/main/java/net/vulkanmod/gl/VkGlProgram.java index 95682d91e1..2cce606f21 100644 --- a/src/main/java/net/vulkanmod/gl/GlProgram.java +++ b/src/main/java/net/vulkanmod/gl/VkGlProgram.java @@ -3,23 +3,23 @@ import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import net.vulkanmod.vulkan.shader.Pipeline; -public class GlProgram { +public class VkGlProgram { private static int ID_COUNTER = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundProgramId = 0; - private static GlProgram boundProgram; + private static VkGlProgram boundProgram; - public static GlProgram getBoundProgram() { + public static VkGlProgram getBoundProgram() { return boundProgram; } - public static GlProgram getProgram(int id) { + public static VkGlProgram getProgram(int id) { return map.get(id); } public static int genProgramId() { int id = ID_COUNTER; - map.put(id, new GlProgram(id)); + map.put(id, new VkGlProgram(id)); ID_COUNTER++; return id; } @@ -41,7 +41,7 @@ public static void glUseProgram(int id) { int id; Pipeline pipeline; - GlProgram(int i) { + VkGlProgram(int i) { this.id = i; } diff --git a/src/main/java/net/vulkanmod/gl/GlRenderbuffer.java b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java similarity index 94% rename from src/main/java/net/vulkanmod/gl/GlRenderbuffer.java rename to src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java index 47c3376eac..e811144a2c 100644 --- a/src/main/java/net/vulkanmod/gl/GlRenderbuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java @@ -13,15 +13,15 @@ import static org.lwjgl.vulkan.VK10.*; -public class GlRenderbuffer { +public class VkGlRenderbuffer { private static int ID_COUNTER = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundId = 0; - private static GlRenderbuffer bound; + private static VkGlRenderbuffer bound; public static int genId() { int id = ID_COUNTER; - map.put(id, new GlRenderbuffer(id)); + map.put(id, new VkGlRenderbuffer(id)); ID_COUNTER++; return id; } @@ -45,7 +45,7 @@ public static void deleteRenderbuffer(int i) { map.remove(i); } - public static GlRenderbuffer getRenderbuffer(int id) { + public static VkGlRenderbuffer getRenderbuffer(int id) { return map.get(id); } @@ -99,12 +99,12 @@ public static void generateMipmap(int target) { } public static void setVulkanImage(int id, VulkanImage vulkanImage) { - GlRenderbuffer texture = map.get(id); + VkGlRenderbuffer texture = map.get(id); texture.vulkanImage = vulkanImage; } - public static GlRenderbuffer getBound() { + public static VkGlRenderbuffer getBound() { return bound; } @@ -117,7 +117,7 @@ public static GlRenderbuffer getBound() { int maxLod = 0; int minFilter, magFilter = GL11.GL_LINEAR; - public GlRenderbuffer(int id) { + public VkGlRenderbuffer(int id) { this.id = id; } diff --git a/src/main/java/net/vulkanmod/gl/GlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java similarity index 94% rename from src/main/java/net/vulkanmod/gl/GlTexture.java rename to src/main/java/net/vulkanmod/gl/VkGlTexture.java index 0643c1f8dd..ef2143c2f2 100644 --- a/src/main/java/net/vulkanmod/gl/GlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -16,11 +16,11 @@ import static org.lwjgl.vulkan.VK10.*; -public class GlTexture { +public class VkGlTexture { private static int ID_COUNTER = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundTextureId = 0; - private static GlTexture boundTexture; + private static VkGlTexture boundTexture; private static int activeTexture = 0; private static int unpackRowLength; @@ -28,13 +28,13 @@ public class GlTexture { private static int unpackSkipPixels; public static void bindIdToImage(int id, VulkanImage vulkanImage) { - GlTexture texture = map.get(id); + VkGlTexture texture = map.get(id); texture.vulkanImage = vulkanImage; } public static int genTextureId() { int id = ID_COUNTER; - map.put(id, new GlTexture(id)); + map.put(id, new VkGlTexture(id)); ID_COUNTER++; return id; } @@ -61,13 +61,13 @@ public static void glDeleteTextures(IntBuffer intBuffer) { } public static void glDeleteTextures(int i) { - GlTexture glTexture = map.remove(i); + VkGlTexture glTexture = map.remove(i); VulkanImage image = glTexture != null ? glTexture.vulkanImage : null; if (image != null) MemoryManager.getInstance().addToFreeable(image); } - public static GlTexture getTexture(int id) { + public static VkGlTexture getTexture(int id) { if (id == 0) return null; @@ -116,7 +116,7 @@ public static void texSubImage2D(int target, int level, int xOffset, int yOffset ByteBuffer src; - GlBuffer glBuffer = GlBuffer.getPixelUnpackBufferBound(); + VkGlBuffer glBuffer = VkGlBuffer.getPixelUnpackBufferBound(); if (glBuffer != null) { glBuffer.data.position((int) pixels); @@ -149,7 +149,7 @@ public static void texSubImage2D(int target, int level, int xOffset, int yOffset ByteBuffer src; - GlBuffer glBuffer = GlBuffer.getPixelUnpackBufferBound(); + VkGlBuffer glBuffer = VkGlBuffer.getPixelUnpackBufferBound(); if (glBuffer != null) { if (pixels != null) { throw new IllegalStateException("Trying to use pixel buffer when there is a Pixel Unpack Buffer bound."); @@ -246,7 +246,7 @@ public static void generateMipmap(int target) { public static void getTexImage(int tex, int level, int format, int type, long pixels) { VulkanImage image = boundTexture.vulkanImage; - GlBuffer buffer = GlBuffer.getPixelPackBufferBound(); + VkGlBuffer buffer = VkGlBuffer.getPixelPackBufferBound(); long ptr; if (buffer != null) { buffer.data.position((int) pixels); @@ -261,16 +261,16 @@ public static void getTexImage(int tex, int level, int format, int type, long pi } public static void setVulkanImage(int id, VulkanImage vulkanImage) { - GlTexture texture = map.get(id); + VkGlTexture texture = map.get(id); texture.vulkanImage = vulkanImage; } - public static GlTexture getBoundTexture() { + public static VkGlTexture getBoundTexture() { return boundTexture; } - final int id; + public final int id; VulkanImage vulkanImage; int width, height; @@ -283,7 +283,7 @@ public static GlTexture getBoundTexture() { boolean clamp = true; - public GlTexture(int id) { + public VkGlTexture(int id) { this.id = id; } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index 1b94f4b955..c3f49c08c2 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -12,7 +12,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.gl.GlProgram; +import net.vulkanmod.gl.VkGlProgram; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; @@ -116,7 +116,7 @@ private void createShaders(ResourceProvider resourceManager, String vertexShader this.pipeline = builder.createGraphicsPipeline(); - GlProgram program = GlProgram.getProgram(this.programId); + VkGlProgram program = VkGlProgram.getProgram(this.programId); program.bindPipeline(this.pipeline); } catch (IOException e) { throw new RuntimeException(e); diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java index ee634a28d9..588e7d1678 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java @@ -2,9 +2,7 @@ import com.mojang.blaze3d.shaders.Shader; import com.mojang.blaze3d.shaders.Uniform; -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.gl.GlProgram; -import net.vulkanmod.interfaces.ShaderMixed; +import net.vulkanmod.gl.VkGlProgram; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.shader.Pipeline; import org.spongepowered.asm.mixin.Final; @@ -46,7 +44,7 @@ public void redirectUpload(CallbackInfo ci) { ci.cancel(); - GlProgram program = GlProgram.getBoundProgram(); + VkGlProgram program = VkGlProgram.getBoundProgram(); if (program == null) { return; diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index be600e1705..e004b0aa20 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -1,10 +1,9 @@ package net.vulkanmod.mixin.compatibility.gl; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; @@ -41,7 +40,7 @@ public static void glViewport(@NativeType("GLint") int x, @NativeType("GLint") i */ @Overwrite(remap = false) public static void glBindTexture(@NativeType("GLenum") int target, @NativeType("GLuint") int texture) { - GlTexture.bindTexture(texture); + VkGlTexture.bindTexture(texture); } /** @@ -60,7 +59,7 @@ public static void glLineWidth(@NativeType("GLfloat") float width) { @NativeType("void") @Overwrite(remap = false) public static int glGenTextures() { - return GlTexture.genTextureId(); + return VkGlTexture.genTextureId(); } /** @@ -126,7 +125,7 @@ public static int glGetInteger(@NativeType("GLenum") int pname) { */ @Overwrite(remap = false) public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) { - GlTexture.texImage2D(target, level, internalformat, width, height, border, format, type, pixels); + VkGlTexture.texImage2D(target, level, internalformat, width, height, border, format, type, pixels); } /** @@ -135,7 +134,7 @@ public static void glTexImage2D(int target, int level, int internalformat, int w */ @Overwrite(remap = false) public static void glTexImage2D(@NativeType("GLenum") int target, @NativeType("GLint") int level, @NativeType("GLint") int internalformat, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height, @NativeType("GLint") int border, @NativeType("GLenum") int format, @NativeType("GLenum") int type, @NativeType("void const *") long pixels) { - GlTexture.texImage2D(target, level, internalformat, width, height, border, format, type, pixels); + VkGlTexture.texImage2D(target, level, internalformat, width, height, border, format, type, pixels); } /** @@ -144,7 +143,7 @@ public static void glTexImage2D(@NativeType("GLenum") int target, @NativeType("G */ @Overwrite(remap = false) public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, long pixels) { - GlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); + VkGlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); } /** @@ -153,7 +152,7 @@ public static void glTexSubImage2D(int target, int level, int xOffset, int yOffs */ @Overwrite(remap = false) public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, @Nullable ByteBuffer pixels) { - GlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); + VkGlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); } /** @@ -162,7 +161,7 @@ public static void glTexSubImage2D(int target, int level, int xOffset, int yOffs */ @Overwrite(remap = false) public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, @Nullable IntBuffer pixels) { - GlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); + VkGlTexture.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, MemoryUtil.memByteBuffer(pixels)); } /** @@ -171,7 +170,7 @@ public static void glTexSubImage2D(int target, int level, int xOffset, int yOffs */ @Overwrite(remap = false) public static void glTexParameteri(@NativeType("GLenum") int target, @NativeType("GLenum") int pname, @NativeType("GLint") int param) { - GlTexture.texParameteri(target, pname, param); + VkGlTexture.texParameteri(target, pname, param); } /** @@ -189,7 +188,7 @@ public static void glTexParameterf(@NativeType("GLenum") int target, @NativeType */ @Overwrite(remap = false) public static int glGetTexParameteri(@NativeType("GLenum") int target, @NativeType("GLenum") int pname) { - return GlTexture.getTexParameteri(target, pname); + return VkGlTexture.getTexParameteri(target, pname); } /** @@ -198,7 +197,7 @@ public static int glGetTexParameteri(@NativeType("GLenum") int target, @NativeTy */ @Overwrite(remap = false) public static int glGetTexLevelParameteri(@NativeType("GLenum") int target, @NativeType("GLint") int level, @NativeType("GLenum") int pname) { - return GlTexture.getTexLevelParameter(target, level, pname); + return VkGlTexture.getTexLevelParameter(target, level, pname); } /** @@ -207,7 +206,7 @@ public static int glGetTexLevelParameteri(@NativeType("GLenum") int target, @Nat */ @Overwrite(remap = false) public static void glPixelStorei(@NativeType("GLenum") int pname, @NativeType("GLint") int param) { - GlTexture.pixelStoreI(pname, param); + VkGlTexture.pixelStoreI(pname, param); } /** @@ -249,7 +248,7 @@ public static void glHint(@NativeType("GLenum") int target, @NativeType("GLenum" */ @Overwrite(remap = false) public static void glDeleteTextures(@NativeType("GLuint const *") int texture) { - GlTexture.glDeleteTextures(texture); + VkGlTexture.glDeleteTextures(texture); } /** @@ -258,7 +257,7 @@ public static void glDeleteTextures(@NativeType("GLuint const *") int texture) { */ @Overwrite(remap = false) public static void glDeleteTextures(@NativeType("GLuint const *") IntBuffer textures) { - GlTexture.glDeleteTextures(textures); + VkGlTexture.glDeleteTextures(textures); } /** @@ -267,7 +266,7 @@ public static void glDeleteTextures(@NativeType("GLuint const *") IntBuffer text */ @Overwrite(remap = false) public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLint") int level, @NativeType("GLenum") int format, @NativeType("GLenum") int type, @NativeType("void *") long pixels) { - GlTexture.getTexImage(tex, level, format, type, pixels); + VkGlTexture.getTexImage(tex, level, format, type, pixels); } /** @@ -276,7 +275,7 @@ public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLi */ @Overwrite(remap = false) public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLint") int level, @NativeType("GLenum") int format, @NativeType("GLenum") int type, @NativeType("void *") ByteBuffer pixels) { - GlTexture.getTexImage(tex, level, format, type, MemoryUtil.memAddress(pixels)); + VkGlTexture.getTexImage(tex, level, format, type, MemoryUtil.memAddress(pixels)); } /** @@ -285,7 +284,7 @@ public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLi */ @Overwrite(remap = false) public static void glGetTexImage(@NativeType("GLenum") int tex, @NativeType("GLint") int level, @NativeType("GLenum") int format, @NativeType("GLenum") int type, @NativeType("void *") IntBuffer pixels) { - GlTexture.getTexImage(tex, level, format, type, MemoryUtil.memAddress(pixels)); + VkGlTexture.getTexImage(tex, level, format, type, MemoryUtil.memAddress(pixels)); } /** diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java index 6c63534966..65cc49840c 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java @@ -1,6 +1,6 @@ package net.vulkanmod.mixin.compatibility.gl; -import net.vulkanmod.gl.GlBuffer; +import net.vulkanmod.gl.VkGlBuffer; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL15; import org.lwjgl.system.NativeType; @@ -19,7 +19,7 @@ public class GL15M { @Overwrite(remap = false) @NativeType("void") public static int glGenBuffers() { - return GlBuffer.glGenBuffers(); + return VkGlBuffer.glGenBuffers(); } /** @@ -27,7 +27,7 @@ public static int glGenBuffers() { */ @Overwrite(remap = false) public static void glBindBuffer(@NativeType("GLenum") int target, @NativeType("GLuint") int buffer) { - GlBuffer.glBindBuffer(target, buffer); + VkGlBuffer.glBindBuffer(target, buffer); } /** @@ -35,7 +35,7 @@ public static void glBindBuffer(@NativeType("GLenum") int target, @NativeType("G */ @Overwrite(remap = false) public static void glBufferData(@NativeType("GLenum") int target, @NativeType("void const *") ByteBuffer data, @NativeType("GLenum") int usage) { - GlBuffer.glBufferData(target, data, usage); + VkGlBuffer.glBufferData(target, data, usage); } /** @@ -43,7 +43,7 @@ public static void glBufferData(@NativeType("GLenum") int target, @NativeType("v */ @Overwrite(remap = false) public static void glBufferData(int i, long l, int j) { - GlBuffer.glBufferData(i, l, j); + VkGlBuffer.glBufferData(i, l, j); } /** @@ -52,7 +52,7 @@ public static void glBufferData(int i, long l, int j) { @Overwrite(remap = false) @NativeType("void *") public static ByteBuffer glMapBuffer(@NativeType("GLenum") int target, @NativeType("GLenum") int access) { - return GlBuffer.glMapBuffer(target, access); + return VkGlBuffer.glMapBuffer(target, access); } /** @@ -62,7 +62,7 @@ public static ByteBuffer glMapBuffer(@NativeType("GLenum") int target, @NativeTy @Nullable @NativeType("void *") public static ByteBuffer glMapBuffer(@NativeType("GLenum") int target, @NativeType("GLenum") int access, long length, @Nullable ByteBuffer old_buffer) { - return GlBuffer.glMapBuffer(target, access); + return VkGlBuffer.glMapBuffer(target, access); } /** @@ -71,7 +71,7 @@ public static ByteBuffer glMapBuffer(@NativeType("GLenum") int target, @NativeTy @Overwrite(remap = false) @NativeType("GLboolean") public static boolean glUnmapBuffer(@NativeType("GLenum") int target) { - return GlBuffer.glUnmapBuffer(target); + return VkGlBuffer.glUnmapBuffer(target); } /** @@ -79,7 +79,7 @@ public static boolean glUnmapBuffer(@NativeType("GLenum") int target) { */ @Overwrite(remap = false) public static void glDeleteBuffers(int i) { - GlBuffer.glDeleteBuffers(i); + VkGlBuffer.glDeleteBuffers(i); } /** @@ -87,6 +87,6 @@ public static void glDeleteBuffers(int i) { */ @Overwrite(remap = false) public static void glDeleteBuffers(@NativeType("GLuint const *") IntBuffer buffers) { - GlBuffer.glDeleteBuffers(buffers); + VkGlBuffer.glDeleteBuffers(buffers); } } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java index fc4a2ce07a..0823849ecf 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java @@ -1,10 +1,9 @@ package net.vulkanmod.mixin.compatibility.gl; -import net.vulkanmod.gl.GlFramebuffer; -import net.vulkanmod.gl.GlRenderbuffer; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.gl.VkGlRenderbuffer; +import net.vulkanmod.gl.VkGlTexture; import org.lwjgl.opengl.GL30; -import org.lwjgl.opengl.GL30C; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -18,7 +17,7 @@ public class GL30M { */ @Overwrite(remap = false) public static void glGenerateMipmap(@NativeType("GLenum") int target) { - GlTexture.generateMipmap(target); + VkGlTexture.generateMipmap(target); } /** @@ -28,7 +27,7 @@ public static void glGenerateMipmap(@NativeType("GLenum") int target) { @NativeType("void") @Overwrite(remap = false) public static int glGenFramebuffers() { - return GlFramebuffer.genFramebufferId(); + return VkGlFramebuffer.genFramebufferId(); } /** @@ -37,7 +36,7 @@ public static int glGenFramebuffers() { */ @Overwrite(remap = false) public static void glBindFramebuffer(@NativeType("GLenum") int target, @NativeType("GLuint") int framebuffer) { - GlFramebuffer.bindFramebuffer(target, framebuffer); + VkGlFramebuffer.bindFramebuffer(target, framebuffer); } /** @@ -46,7 +45,7 @@ public static void glBindFramebuffer(@NativeType("GLenum") int target, @NativeTy */ @Overwrite(remap = false) public static void glFramebufferTexture2D(@NativeType("GLenum") int target, @NativeType("GLenum") int attachment, @NativeType("GLenum") int textarget, @NativeType("GLuint") int texture, @NativeType("GLint") int level) { - GlFramebuffer.framebufferTexture2D(target, attachment, textarget, texture, level); + VkGlFramebuffer.framebufferTexture2D(target, attachment, textarget, texture, level); } /** @@ -64,7 +63,7 @@ public static void glFramebufferRenderbuffer(@NativeType("GLenum") int target, @ */ @Overwrite(remap = false) public static void glDeleteFramebuffers(@NativeType("GLuint const *") int framebuffer) { - GlFramebuffer.deleteFramebuffer(framebuffer); + VkGlFramebuffer.deleteFramebuffer(framebuffer); } /** @@ -74,7 +73,7 @@ public static void glDeleteFramebuffers(@NativeType("GLuint const *") int frameb @Overwrite(remap = false) @NativeType("GLenum") public static int glCheckFramebufferStatus(@NativeType("GLenum") int target) { - return GlFramebuffer.glCheckFramebufferStatus(target); + return VkGlFramebuffer.glCheckFramebufferStatus(target); } /** @@ -83,7 +82,7 @@ public static int glCheckFramebufferStatus(@NativeType("GLenum") int target) { */ @Overwrite(remap = false) public static void glBlitFramebuffer(@NativeType("GLint") int srcX0, @NativeType("GLint") int srcY0, @NativeType("GLint") int srcX1, @NativeType("GLint") int srcY1, @NativeType("GLint") int dstX0, @NativeType("GLint") int dstY0, @NativeType("GLint") int dstX1, @NativeType("GLint") int dstY1, @NativeType("GLbitfield") int mask, @NativeType("GLenum") int filter) { - GlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + VkGlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } //RENDER BUFFER @@ -95,7 +94,7 @@ public static void glBlitFramebuffer(@NativeType("GLint") int srcX0, @NativeType @NativeType("void") @Overwrite(remap = false) public static int glGenRenderbuffers() { - return GlRenderbuffer.genId(); + return VkGlRenderbuffer.genId(); } /** @@ -104,7 +103,7 @@ public static int glGenRenderbuffers() { */ @Overwrite(remap = false) public static void glBindRenderbuffer(@NativeType("GLenum") int target, @NativeType("GLuint") int framebuffer) { - GlRenderbuffer.bindRenderbuffer(target, framebuffer); + VkGlRenderbuffer.bindRenderbuffer(target, framebuffer); } /** @@ -113,7 +112,7 @@ public static void glBindRenderbuffer(@NativeType("GLenum") int target, @NativeT */ @Overwrite(remap = false) public static void glRenderbufferStorage(@NativeType("GLenum") int target, @NativeType("GLenum") int internalformat, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) { - GlRenderbuffer.renderbufferStorage(target, internalformat, width, height); + VkGlRenderbuffer.renderbufferStorage(target, internalformat, width, height); } /** @@ -122,6 +121,6 @@ public static void glRenderbufferStorage(@NativeType("GLenum") int target, @Nati */ @Overwrite(remap = false) public static void glDeleteRenderbuffers(@NativeType("GLuint const *") int renderbuffer) { - GlRenderbuffer.deleteRenderbuffer(renderbuffer); + VkGlRenderbuffer.deleteRenderbuffer(renderbuffer); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index d093b93ba8..a56cdee00e 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -6,7 +6,6 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL20; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -24,7 +23,7 @@ public class GlStateManagerM { */ @Overwrite(remap = false) public static void _bindTexture(int i) { - GlTexture.bindTexture(i); + VkGlTexture.bindTexture(i); } /** @@ -126,7 +125,7 @@ public static int _getError() { @Overwrite(remap = false) public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); + VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); } /** @@ -135,7 +134,7 @@ public static void _texImage2D(int target, int level, int internalFormat, int wi @Overwrite(remap = false) public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); + VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** @@ -143,7 +142,7 @@ public static void _texSubImage2D(int target, int level, int offsetX, int offset */ @Overwrite(remap = false) public static void _activeTexture(int i) { - GlTexture.activeTexture(i); + VkGlTexture.activeTexture(i); } /** @@ -151,7 +150,7 @@ public static void _activeTexture(int i) { */ @Overwrite(remap = false) public static void _texParameter(int i, int j, int k) { - GlTexture.texParameteri(i, j, k); + VkGlTexture.texParameteri(i, j, k); } /** @@ -167,7 +166,7 @@ public static void _texParameter(int i, int j, float k) { */ @Overwrite(remap = false) public static int _getTexLevelParameter(int i, int j, int k) { - return GlTexture.getTexLevelParameter(i, j, k); + return VkGlTexture.getTexLevelParameter(i, j, k); } /** @@ -177,7 +176,7 @@ public static int _getTexLevelParameter(int i, int j, int k) { public static void _pixelStore(int pname, int param) { //Used during upload to set copy offsets RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.pixelStoreI(pname, param); + VkGlTexture.pixelStoreI(pname, param); } /** @@ -186,7 +185,7 @@ public static void _pixelStore(int pname, int param) { @Overwrite(remap = false) public static int _genTexture() { RenderSystem.assertOnRenderThreadOrInit(); - return GlTexture.genTextureId(); + return VkGlTexture.genTextureId(); } /** @@ -195,7 +194,7 @@ public static int _genTexture() { @Overwrite(remap = false) public static void _deleteTexture(int i) { RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.glDeleteTextures(i); + VkGlTexture.glDeleteTextures(i); } /** @@ -248,7 +247,7 @@ public static void _clear(int mask, boolean bl) { @Overwrite(remap = false) public static int glCreateProgram() { RenderSystem.assertOnRenderThread(); - return GlProgram.genProgramId(); + return VkGlProgram.genProgramId(); } /** @@ -257,7 +256,7 @@ public static int glCreateProgram() { @Overwrite(remap = false) public static void _glUseProgram(int i) { RenderSystem.assertOnRenderThread(); - GlProgram.glUseProgram(i); + VkGlProgram.glUseProgram(i); } /** @@ -294,7 +293,7 @@ public static void _depthMask(boolean bl) { @Overwrite(remap = false) public static int glGenFramebuffers() { RenderSystem.assertOnRenderThreadOrInit(); - return GlFramebuffer.genFramebufferId(); + return VkGlFramebuffer.genFramebufferId(); } /** @@ -303,7 +302,7 @@ public static int glGenFramebuffers() { @Overwrite(remap = false) public static int glGenRenderbuffers() { RenderSystem.assertOnRenderThreadOrInit(); - return GlRenderbuffer.genId(); + return VkGlRenderbuffer.genId(); } /** @@ -312,7 +311,7 @@ public static int glGenRenderbuffers() { @Overwrite(remap = false) public static void _glBindFramebuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.bindFramebuffer(i, j); + VkGlFramebuffer.bindFramebuffer(i, j); } /** @@ -321,7 +320,7 @@ public static void _glBindFramebuffer(int i, int j) { @Overwrite(remap = false) public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.framebufferTexture2D(i, j, k, l, m); + VkGlFramebuffer.framebufferTexture2D(i, j, k, l, m); } /** @@ -330,7 +329,7 @@ public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { @Overwrite(remap = false) public static void _glBindRenderbuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - GlRenderbuffer.bindRenderbuffer(i, j); + VkGlRenderbuffer.bindRenderbuffer(i, j); } /** @@ -339,7 +338,7 @@ public static void _glBindRenderbuffer(int i, int j) { @Overwrite(remap = false) public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.framebufferRenderbuffer(i, j, k, l); + VkGlFramebuffer.framebufferRenderbuffer(i, j, k, l); } /** @@ -348,7 +347,7 @@ public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { @Overwrite(remap = false) public static void _glRenderbufferStorage(int i, int j, int k, int l) { RenderSystem.assertOnRenderThreadOrInit(); - GlRenderbuffer.renderbufferStorage(i, j, k, l); + VkGlRenderbuffer.renderbufferStorage(i, j, k, l); } /** @@ -357,7 +356,7 @@ public static void _glRenderbufferStorage(int i, int j, int k, int l) { @Overwrite(remap = false) public static int glCheckFramebufferStatus(int i) { RenderSystem.assertOnRenderThreadOrInit(); - return GlFramebuffer.glCheckFramebufferStatus(i); + return VkGlFramebuffer.glCheckFramebufferStatus(i); } /** @@ -366,7 +365,7 @@ public static int glCheckFramebufferStatus(int i) { @Overwrite(remap = false) public static int _glGenBuffers() { RenderSystem.assertOnRenderThreadOrInit(); - return GlBuffer.glGenBuffers(); + return VkGlBuffer.glGenBuffers(); } /** @@ -375,7 +374,7 @@ public static int _glGenBuffers() { @Overwrite(remap = false) public static void _glBindBuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBindBuffer(i, j); + VkGlBuffer.glBindBuffer(i, j); } /** @@ -384,7 +383,7 @@ public static void _glBindBuffer(int i, int j) { @Overwrite(remap = false) public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBufferData(i, byteBuffer, j); + VkGlBuffer.glBufferData(i, byteBuffer, j); } /** @@ -393,7 +392,7 @@ public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { @Overwrite(remap = false) public static void _glBufferData(int i, long l, int j) { RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBufferData(i, l, j); + VkGlBuffer.glBufferData(i, l, j); } /** @@ -403,7 +402,7 @@ public static void _glBufferData(int i, long l, int j) { @Nullable public static ByteBuffer _glMapBuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - return GlBuffer.glMapBuffer(i, j); + return VkGlBuffer.glMapBuffer(i, j); } /** @@ -412,7 +411,7 @@ public static ByteBuffer _glMapBuffer(int i, int j) { @Overwrite(remap = false) public static void _glUnmapBuffer(int i) { RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glUnmapBuffer(i); + VkGlBuffer.glUnmapBuffer(i); } /** @@ -421,7 +420,7 @@ public static void _glUnmapBuffer(int i) { @Overwrite(remap = false) public static void _glDeleteBuffers(int i) { RenderSystem.assertOnRenderThread(); - GlBuffer.glDeleteBuffers(i); + VkGlBuffer.glDeleteBuffers(i); } /** diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index a6ba821130..624d44589e 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -3,7 +3,7 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexSorting; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; @@ -89,7 +89,7 @@ public static void logicOp(GlStateManager.LogicOp op) { */ @Overwrite(remap = false) public static void activeTexture(int texture) { - GlTexture.activeTexture(texture); + VkGlTexture.activeTexture(texture); } /** @@ -444,6 +444,6 @@ private static void _restoreProjectionMatrix() { */ @Overwrite(remap = false) public static void texParameter(int target, int pname, int param) { - GlTexture.texParameteri(target, pname, param); + VkGlTexture.texParameteri(target, pname, param); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java index 951f7d59ad..b63cd779f7 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -13,7 +13,7 @@ import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.GlProgram; +import net.vulkanmod.gl.VkGlProgram; import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.render.shader.ShaderLoadUtil; import net.vulkanmod.vulkan.Renderer; @@ -90,7 +90,7 @@ private void create(ResourceProvider resourceProvider, String name, VertexFormat createPipeline(configName, format, config); } - GlProgram program = GlProgram.getProgram(this.programId); + VkGlProgram program = VkGlProgram.getProgram(this.programId); program.bindPipeline(this.pipeline); } diff --git a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java index 5d5dbf1fd5..61adacc7cc 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java @@ -41,6 +41,6 @@ public void bindRead() { @Override public int getColorTextureId() { - return Renderer.getInstance().getMainPass().getColorAttachmentGlId(); + return Renderer.getInstance().getMainPass().getColorAttachment().id; } } diff --git a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java index 7c1ebabd9a..4579ba83c3 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java @@ -3,8 +3,8 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.GlFramebuffer; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -46,8 +46,8 @@ public void clear(boolean getError) { return; // If the framebuffer is not bound postpone clear - GlFramebuffer glFramebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId); - if(!bound || GlFramebuffer.getBoundFramebuffer() != glFramebuffer) { + VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId); + if(!bound || VkGlFramebuffer.getBoundFramebuffer() != glFramebuffer) { needClear = true; return; } @@ -72,11 +72,11 @@ public void bindRead() { applyClear(); - GlTexture.bindTexture(this.colorTextureId); + VkGlTexture.bindTexture(this.colorTextureId); try (MemoryStack stack = MemoryStack.stackPush()) { - GlTexture.getBoundTexture().getVulkanImage() - .readOnlyLayout(stack, Renderer.getCommandBuffer()); + VkGlTexture.getBoundTexture().getVulkanImage() + .readOnlyLayout(stack, Renderer.getCommandBuffer()); } } @@ -86,7 +86,7 @@ public void bindRead() { @Overwrite public void unbindRead() { RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.bindTexture(0); + VkGlTexture.bindTexture(0); } /** @@ -96,7 +96,7 @@ public void unbindRead() { private void _bindWrite(boolean bl) { RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); if (bl) { GlStateManager._viewport(0, 0, this.viewWidth, this.viewHeight); } @@ -126,7 +126,7 @@ public void unbindWrite() { private void _blitToScreen(int width, int height, boolean disableBlend, CallbackInfo ci) { // If the target needs clear it means it has not been used, thus we can skip blit if (!this.needClear) { - Framebuffer framebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); + Framebuffer framebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); VTextureSelector.bindTexture(0, framebuffer.getColorAttachment()); DrawUtil.blitToScreen(); @@ -143,12 +143,12 @@ private void injClear(CallbackInfoReturnable cir) { @Unique private void applyClear() { if (this.needClear) { - GlFramebuffer currentFramebuffer = GlFramebuffer.getBoundFramebuffer(); + VkGlFramebuffer currentFramebuffer = VkGlFramebuffer.getBoundFramebuffer(); this._bindWrite(false); if (currentFramebuffer != null) { - GlFramebuffer.beginRendering(currentFramebuffer); + VkGlFramebuffer.beginRendering(currentFramebuffer); } } } diff --git a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java index 42270aab8c..fa7a99ce5f 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java @@ -2,7 +2,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.renderer.texture.AbstractTexture; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.texture.VulkanImage; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -36,7 +36,7 @@ public void setFilter(boolean blur, boolean mipmap) { this.blur = blur; this.mipmap = mipmap; - GlTexture glTexture = GlTexture.getTexture(this.id); + VkGlTexture glTexture = VkGlTexture.getTexture(this.id); VulkanImage vulkanImage = glTexture.getVulkanImage(); if (vulkanImage != null) @@ -45,6 +45,6 @@ public void setFilter(boolean blur, boolean mipmap) { @Unique private void bindTexture() { - GlTexture.bindTexture(this.id); + VkGlTexture.bindTexture(this.id); } } diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java index 70e9347afb..499ba0c83c 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java @@ -4,13 +4,17 @@ import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.platform.TextureUtil; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.texture.VulkanImage; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Unique; + +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8G8B8A8_UNORM; +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8_UNORM; @Mixin(TextureUtil.class) public class MTextureUtil { @@ -21,7 +25,7 @@ public class MTextureUtil { @Overwrite(remap = false) public static int generateTextureId() { RenderSystem.assertOnRenderThreadOrInit(); - return GlTexture.genTextureId(); + return VkGlTexture.genTextureId(); } /** @@ -30,8 +34,8 @@ public static int generateTextureId() { @Overwrite(remap = false) public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, int id, int mipLevels, int width, int height) { RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.bindTexture(id); - GlTexture glTexture = GlTexture.getBoundTexture(); + VkGlTexture.bindTexture(id); + VkGlTexture glTexture = VkGlTexture.getBoundTexture(); VulkanImage image = glTexture.getVulkanImage(); if (mipLevels > 0) { @@ -47,7 +51,7 @@ public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, i image = new VulkanImage.Builder(width, height) .setMipLevels(mipLevels + 1) - .setFormat(internalGlFormat) + .setFormat(convertFormat(internalGlFormat)) .setLinearFiltering(false) .setClamp(false) .createVulkanImage(); @@ -56,4 +60,13 @@ public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, i VTextureSelector.bindTexture(image); } } + + @Unique + private static int convertFormat(NativeImage.InternalGlFormat format) { + return switch (format) { + case RGBA -> VK_FORMAT_R8G8B8A8_UNORM; + case RED -> VK_FORMAT_R8_UNORM; + default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); + }; + } } diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java index 5cfadf94b7..e807e35bfd 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java @@ -11,7 +11,7 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.LivingEntity; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.mixin.texture.image.NativeImageAccessor; import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.queue.CommandPool; @@ -159,7 +159,7 @@ public void updateLightTexture(float partialTicks, CallbackInfo ci) { this.lightTexture.upload(); try (MemoryStack stack = MemoryStack.stackPush()) { - GlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); + VkGlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); } ImageUploadHelper.INSTANCE.submitCommands(); diff --git a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java b/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java index 58ae4ff90c..703a79b77d 100644 --- a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java +++ b/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java @@ -3,7 +3,7 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.client.Screenshot; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -20,7 +20,7 @@ public static NativeImage takeScreenshot(RenderTarget target) { int height = target.height; NativeImage nativeimage = new NativeImage(width, height, false); - GlTexture.bindTexture(target.getColorTextureId()); + VkGlTexture.bindTexture(target.getColorTextureId()); // Need to submit and wait cmds if screenshot was requested // before the end of the frame diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 0eaf4286ab..45267dcb4a 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -5,7 +5,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.client.Minecraft; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.GlFramebuffer; +import net.vulkanmod.gl.VkGlFramebuffer; import net.vulkanmod.mixin.window.WindowAccessor; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.WorldRenderer; @@ -359,7 +359,7 @@ private void submitFrame() { } /** - * Called in case draw results are needed before the of the frame + * Called in case draw results are needed before the end of the frame */ public void flushCmds() { if (!this.recordingCmds) @@ -407,7 +407,7 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { this.boundRenderPass = null; this.boundFramebuffer = null; - GlFramebuffer.resetBoundFramebuffer(); + VkGlFramebuffer.resetBoundFramebuffer(); } public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) { @@ -497,6 +497,7 @@ private void recreateSwapChain() { } createSyncObjects(); + this.mainPass.onResize(); this.onResizeCallbacks.forEach(Runnable::run); ((WindowAccessor) (Object) Minecraft.getInstance().getWindow()).getEventHandler().resizeDisplay(); @@ -572,6 +573,10 @@ public void setBoundFramebuffer(Framebuffer framebuffer) { this.boundFramebuffer = framebuffer; } + public Framebuffer getBoundFramebuffer() { + return boundFramebuffer; + } + public void setBoundRenderPass(RenderPass boundRenderPass) { this.boundRenderPass = boundRenderPass; } diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 9b68ec2d7f..3d1f6c8109 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -2,7 +2,6 @@ import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.GlTexture; import net.vulkanmod.render.util.MathUtil; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; @@ -41,8 +40,6 @@ public class SwapChain extends Framebuffer { public boolean isBGRAformat; private boolean vsync = false; - private int[] glIds; - public SwapChain() { this.attachmentCount = 2; this.depthFormat = Vulkan.getDefaultDepthFormat(); @@ -160,24 +157,9 @@ private void createSwapChain() { } } - createGlIds(); createDepthResources(); } - private void createGlIds() { - this.glIds = new int[this.swapChainImages.size()]; - - for (int i = 0; i < this.swapChainImages.size(); i++) { - int id = GlTexture.genTextureId(); - this.glIds[i] = id; - GlTexture.bindIdToImage(id, this.swapChainImages.get(i)); - } - } - - public int getColorAttachmentGlId() { - return this.glIds[Renderer.getCurrentImage()]; - } - private long[] createFramebuffers(RenderPass renderPass) { try (MemoryStack stack = MemoryStack.stackPush()) { @@ -309,7 +291,7 @@ private static VkExtent2D getExtent(VkSurfaceCapabilitiesKHR capabilities) { return capabilities.currentExtent(); } - //Fallback + // Fallback IntBuffer width = stackGet().ints(0); IntBuffer height = stackGet().ints(0); @@ -336,7 +318,7 @@ private static int checkPresentMode(int... requestedModes) { } } } - return VK_PRESENT_MODE_FIFO_KHR; //If None of the request modes exist/are supported by Driver + return VK_PRESENT_MODE_FIFO_KHR; // If None of the request modes exist/are supported by Driver } } diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index f6c2e07a49..d063a42e66 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -2,8 +2,8 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import net.minecraft.client.Minecraft; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; import net.vulkanmod.vulkan.framebuffer.SwapChain; @@ -29,11 +29,14 @@ public static DefaultMainPass create() { private RenderPass mainRenderPass; private RenderPass auxRenderPass; + private VkGlTexture[] colorAttachmentTextures; + DefaultMainPass() { this.mainTarget = Minecraft.getInstance().getMainRenderTarget(); this.mainFramebuffer = Renderer.getInstance().getSwapChain(); createRenderPasses(); + createSwapChainTextures(); } private void createRenderPasses() { @@ -73,13 +76,13 @@ public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { public void end(VkCommandBuffer commandBuffer) { Renderer.getInstance().endRenderPass(commandBuffer); - try(MemoryStack stack = MemoryStack.stackPush()) { + try (MemoryStack stack = MemoryStack.stackPush()) { SwapChain framebuffer = Renderer.getInstance().getSwapChain(); framebuffer.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); } int result = vkEndCommandBuffer(commandBuffer); - if(result != VK_SUCCESS) { + if (result != VK_SUCCESS) { throw new RuntimeException("Failed to record command buffer:" + result); } } @@ -90,18 +93,23 @@ public void cleanUp() { this.auxRenderPass.cleanUp(); } + @Override + public void onResize() { + this.createSwapChainTextures(); + } + public void rebindMainTarget() { SwapChain swapChain = Renderer.getInstance().getSwapChain(); VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); // Do not rebind if the framebuffer is already bound RenderPass boundRenderPass = Renderer.getInstance().getBoundRenderPass(); - if(boundRenderPass == this.mainRenderPass || boundRenderPass == this.auxRenderPass) + if (boundRenderPass == this.mainRenderPass || boundRenderPass == this.auxRenderPass) return; Renderer.getInstance().endRenderPass(commandBuffer); - try(MemoryStack stack = MemoryStack.stackPush()) { + try (MemoryStack stack = MemoryStack.stackPush()) { swapChain.beginRenderPass(commandBuffer, this.auxRenderPass, stack); } @@ -114,7 +122,7 @@ public void bindAsTexture() { // Check if render pass is using the framebuffer RenderPass boundRenderPass = Renderer.getInstance().getBoundRenderPass(); - if(boundRenderPass == this.mainRenderPass || boundRenderPass == this.auxRenderPass) + if (boundRenderPass == this.mainRenderPass || boundRenderPass == this.auxRenderPass) Renderer.getInstance().endRenderPass(commandBuffer); try (MemoryStack stack = MemoryStack.stackPush()) { @@ -124,8 +132,23 @@ public void bindAsTexture() { VTextureSelector.bindTexture(swapChain.getColorAttachment()); } - public int getColorAttachmentGlId() { + @Override + public VkGlTexture getColorAttachment() { + return this.colorAttachmentTextures[Renderer.getCurrentImage()]; + } + + private void createSwapChainTextures() { SwapChain swapChain = Renderer.getInstance().getSwapChain(); - return swapChain.getColorAttachmentGlId(); + var swapChainImages = swapChain.getImages(); + int imageCount = swapChainImages.size(); + this.colorAttachmentTextures = new VkGlTexture[imageCount]; + + for (int i = 0; i < swapChainImages.size(); i++) { + int id = VkGlTexture.genTextureId(); + VkGlTexture glTexture = VkGlTexture.getTexture(id); + VkGlTexture.bindIdToImage(id, swapChainImages.get(i)); + this.colorAttachmentTextures[i] = glTexture; + } } + } diff --git a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java index f84b52daf2..7ce2197488 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java @@ -1,7 +1,6 @@ package net.vulkanmod.vulkan.pass; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.framebuffer.SwapChain; +import net.vulkanmod.gl.VkGlTexture; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkCommandBuffer; @@ -13,6 +12,8 @@ public interface MainPass { void cleanUp(); + void onResize(); + default void mainTargetBindWrite() {} default void mainTargetUnbindWrite() {} @@ -21,7 +22,7 @@ default void rebindMainTarget() {} default void bindAsTexture() {} - default int getColorAttachmentGlId() { - return -1; + default VkGlTexture getColorAttachment() { + throw new UnsupportedOperationException(); } } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index b8b9fee587..dfc85ec77c 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -3,7 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; @@ -25,7 +25,7 @@ public static void bindTexture(VulkanImage texture) { } public static void bindTexture(int i, VulkanImage texture) { - if(i < 0 || i >= SIZE) { + if (i < 0 || i >= SIZE) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -35,7 +35,7 @@ public static void bindTexture(int i, VulkanImage texture) { } public static void bindImage(int i, VulkanImage texture, int level) { - if(i < 0 || i > 7) { + if (i < 0 || i > 7) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -73,13 +73,13 @@ public static void bindShaderTextures(Pipeline pipeline) { for (ImageDescriptor state : imageDescriptors) { final int shaderTexture = RenderSystem.getShaderTexture(state.imageIdx); - GlTexture texture = GlTexture.getTexture(shaderTexture); + VkGlTexture texture = VkGlTexture.getTexture(shaderTexture); if (texture != null && texture.getVulkanImage() != null) { VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); } else { - texture = GlTexture.getTexture(MissingTextureAtlasSprite.getTexture().getId()); + texture = VkGlTexture.getTexture(MissingTextureAtlasSprite.getTexture().getId()); VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); } } @@ -98,16 +98,23 @@ public static void setOverlayTexture(VulkanImage texture) { } public static void setActiveTexture(int activeTexture) { - if(activeTexture < 0 || activeTexture >= SIZE) { - Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); + if (activeTexture < 0 || activeTexture >= SIZE) { + Initializer.LOGGER.error( + String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); } VTextureSelector.activeTexture = activeTexture; } - public static VulkanImage getBoundTexture() { return boundTextures[activeTexture]; } + public static VulkanImage getBoundTexture() { + return boundTextures[activeTexture]; + } - public static VulkanImage getBoundTexture(int i) { return boundTextures[i]; } + public static VulkanImage getBoundTexture(int i) { + return boundTextures[i]; + } - public static VulkanImage getWhiteTexture() { return whiteTexture; } + public static VulkanImage getWhiteTexture() { + return whiteTexture; + } } diff --git a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java index b5d187e3b5..b5ba525811 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java @@ -25,7 +25,7 @@ public static void blitToScreen() { public static void fastBlit() { GraphicsPipeline blitPipeline = PipelineManager.getFastBlitPipeline(); - RenderSystem.disableCull(); + VRenderSystem.disableCull(); VRenderSystem.setPrimitiveTopologyGL(GL11.GL_TRIANGLES); Renderer renderer = Renderer.getInstance(); @@ -35,7 +35,7 @@ public static void fastBlit() { VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); VK11.vkCmdDraw(commandBuffer, 3, 1, 0, 0); - RenderSystem.enableCull(); + VRenderSystem.enableCull(); } public static void defualtBlit() { From e2a1fc250be2645260e5f4b11d4c27ff1459b4fd Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 11 May 2025 18:23:57 +0200 Subject: [PATCH 088/177] Refactor downloadTexture --- .../net/vulkanmod/mixin/texture/image/MNativeImage.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java index dcbff6f87d..6eecb8cc31 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java @@ -7,6 +7,7 @@ import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.system.MemoryUtil; +import org.lwjgl.vulkan.VK10; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -87,11 +88,15 @@ public void downloadTexture(int level, boolean removeAlpha) { throw new IllegalArgumentException(String.format(Locale.ROOT, "getPixelRGBA only works on RGBA images; have %s", this.format)); } + var colorAttachment = ( Renderer.getInstance() + .getMainPass() + .getColorAttachment()); + boolean isBGRAFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); + for (long l = 0; l < this.width * this.height * 4L; l+=4) { int v = MemoryUtil.memGetInt(this.pixels + l); - //TODO - if(Renderer.getInstance().getSwapChain().isBGRAformat) + if (isBGRAFormat) v = ColorUtil.BGRAtoRGBA(v); v = v | 255 << this.format.alphaOffset(); From 81b56685f9c28eb99288f5fb65d3e6a1253cc472 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 11 May 2025 18:33:36 +0200 Subject: [PATCH 089/177] Add image debug label --- .../java/net/vulkanmod/gl/VkGlTexture.java | 1 + .../vulkanmod/mixin/texture/MTextureUtil.java | 1 + .../java/net/vulkanmod/vulkan/Vulkan.java | 14 +++++++-- .../vulkan/framebuffer/SwapChain.java | 2 +- .../vulkanmod/vulkan/texture/VulkanImage.java | 31 +++++++++---------- 5 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/VkGlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java index ef2143c2f2..7f01144a24 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -328,6 +328,7 @@ void allocateImage(int width, int height, int vkFormat) { } else { this.vulkanImage = new VulkanImage.Builder(width, height) + .setName(String.format("GlTexture %d", this.id)) .setMipLevels(maxLevel + 1) .setFormat(vkFormat) .addUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java index 499ba0c83c..d04bc43ef6 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java @@ -50,6 +50,7 @@ public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, i image.free(); image = new VulkanImage.Builder(width, height) + .setName(String.format("Texture %d", id)) .setMipLevels(mipLevels + 1) .setFormat(convertFormat(internalGlFormat)) .setLinearFiltering(false) diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 9c99cc24d5..0ab7e71249 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -26,8 +26,7 @@ import static net.vulkanmod.vulkan.util.VUtil.asPointerBuffer; import static org.lwjgl.glfw.GLFWVulkan.glfwCreateWindowSurface; import static org.lwjgl.glfw.GLFWVulkan.glfwGetRequiredInstanceExtensions; -import static org.lwjgl.system.MemoryStack.stackGet; -import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.NULL; import static org.lwjgl.util.vma.Vma.vmaCreateAllocator; import static org.lwjgl.util.vma.Vma.vmaDestroyAllocator; @@ -296,6 +295,17 @@ private static void setupDebugMessenger() { } } + public static void setDebugLabel(MemoryStack stack, int objectType, long handle, String label) { + if (ENABLE_VALIDATION_LAYERS) { + VkDebugUtilsObjectNameInfoEXT nameInfo = VkDebugUtilsObjectNameInfoEXT.calloc(stack); + nameInfo.sType$Default(); + nameInfo.objectType(objectType); + nameInfo.objectHandle(handle); + nameInfo.pObjectName(stackUTF8(label)); + EXTDebugUtils.vkSetDebugUtilsObjectNameEXT(Vulkan.getVkDevice(), nameInfo); + } + } + private static void createSurface(long handle) { window = handle; diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 3d1f6c8109..857a801238 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -151,7 +151,7 @@ private void createSwapChain() { long imageId = pSwapchainImages.get(i); long imageView = VulkanImage.createImageView(imageId, this.format, VK_IMAGE_ASPECT_COLOR_BIT, 1); - VulkanImage image = new VulkanImage(imageId, this.format, 1, this.width, this.height, 4, 0, imageView); + VulkanImage image = new VulkanImage("Swapchain", imageId, this.format, 1, this.width, this.height, 4, 0, imageView); image.updateTextureSampler(true, true, false); this.swapChainImages.add(image); } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index fe21e09fde..3dde077176 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -1,6 +1,5 @@ package net.vulkanmod.vulkan.texture; -import com.mojang.blaze3d.platform.NativeImage; import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Vulkan; @@ -9,12 +8,12 @@ import net.vulkanmod.vulkan.queue.CommandPool; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkCommandBuffer; import org.lwjgl.vulkan.VkDevice; import org.lwjgl.vulkan.VkImageMemoryBarrier; import org.lwjgl.vulkan.VkImageViewCreateInfo; -import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.LongBuffer; import java.util.Arrays; @@ -29,6 +28,7 @@ public class VulkanImage { private static final VkDevice DEVICE = Vulkan.getVkDevice(); + public final String name; public final int format; public final int aspect; public final int mipLevels; @@ -48,11 +48,12 @@ public class VulkanImage { private int currentLayout; - //Used for swap chain images - public VulkanImage(long id, int format, int mipLevels, int width, int height, int formatSize, int usage, long imageView) { + // Used for already allocated images e.g. swap chain images + public VulkanImage(String name, long id, int format, int mipLevels, int width, int height, int formatSize, int usage, long imageView) { this.id = id; this.mainImageView = imageView; + this.name = name; this.mipLevels = mipLevels; this.width = width; this.height = height; @@ -67,6 +68,7 @@ public VulkanImage(long id, int format, int mipLevels, int width, int height, in } private VulkanImage(Builder builder) { + this.name = builder.name; this.mipLevels = builder.mipLevels; this.width = builder.width; this.height = builder.height; @@ -142,6 +144,10 @@ private void createImage() { allocation = pAllocation.get(0); MemoryManager.addImage(this); + + if (this.name != null) { + Vulkan.setDebugLabel(stack, VK_OBJECT_TYPE_IMAGE, pTextureImage.get(), this.name); + } } } @@ -443,6 +449,7 @@ public static class Builder { final int width; final int height; + String name; int format = VulkanImage.DefaultFormat; int formatSize; byte mipLevels = 1; @@ -457,13 +464,13 @@ public Builder(int width, int height) { this.height = height; } - public Builder setFormat(int format) { - this.format = format; + public Builder setName(String name) { + this.name = name; return this; } - public Builder setFormat(NativeImage.InternalGlFormat format) { - this.format = convertFormat(format); + public Builder setFormat(int format) { + this.format = format; return this; } @@ -512,14 +519,6 @@ public VulkanImage createVulkanImage() { return VulkanImage.createTextureImage(this); } - private static int convertFormat(NativeImage.InternalGlFormat format) { - return switch (format) { - case RGBA -> VK_FORMAT_R8G8B8A8_UNORM; - case RED -> VK_FORMAT_R8_UNORM; - default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); - }; - } - private static int formatSize(int format) { return switch (format) { case VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB, From 6c854fa4e3f69071a031d69645a481c7ded93a6f Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Wed, 21 May 2025 23:30:25 +0200 Subject: [PATCH 090/177] Fix upload size --- src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index 3dde077176..e44790bbc8 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -208,7 +208,7 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs } public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, long srcPtr) { - long uploadSize = (long) unpackRowLength * height * this.formatSize; + long uploadSize = (long) (unpackRowLength * height - unpackSkipPixels) * this.formatSize; StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); From 153879d6d31fe96c4ac351f99edc58b3f87eccd2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Wed, 21 May 2025 23:55:09 +0200 Subject: [PATCH 091/177] Refactor render state mixins - Add blend op state --- .../mixin/render/GlStateManagerM.java | 150 +++++++--- .../mixin/render/RenderSystemMixin.java | 258 +----------------- .../net/vulkanmod/vulkan/VRenderSystem.java | 4 + .../vulkan/shader/GraphicsPipeline.java | 4 +- .../vulkan/shader/PipelineState.java | 39 +-- 5 files changed, 147 insertions(+), 308 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index a56cdee00e..17b59927e8 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -51,7 +51,6 @@ public static void _enableBlend() { public static void _blendFunc(int i, int j) { RenderSystem.assertOnRenderThread(); VRenderSystem.blendFunc(i, j); - } /** @@ -61,7 +60,15 @@ public static void _blendFunc(int i, int j) { public static void _blendFuncSeparate(int i, int j, int k, int l) { RenderSystem.assertOnRenderThread(); VRenderSystem.blendFuncSeparate(i, j, k, l); + } + /** + * @author + */ + @Overwrite(remap = false) + public static void _blendEquation(int i) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.blendOp(i); } /** @@ -110,7 +117,6 @@ public static void _scissorBox(int x, int y, int width, int height) { Renderer.setScissor(x, y, width, height); } - //TODO /** * @author */ @@ -124,7 +130,7 @@ public static int _getError() { */ @Overwrite(remap = false) public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); } @@ -133,7 +139,7 @@ public static void _texImage2D(int target, int level, int internalFormat, int wi */ @Overwrite(remap = false) public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } @@ -174,8 +180,7 @@ public static int _getTexLevelParameter(int i, int j, int k) { */ @Overwrite(remap = false) public static void _pixelStore(int pname, int param) { - //Used during upload to set copy offsets - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlTexture.pixelStoreI(pname, param); } @@ -184,7 +189,7 @@ public static void _pixelStore(int pname, int param) { */ @Overwrite(remap = false) public static int _genTexture() { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); return VkGlTexture.genTextureId(); } @@ -193,7 +198,7 @@ public static int _genTexture() { */ @Overwrite(remap = false) public static void _deleteTexture(int i) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlTexture.glDeleteTextures(i); } @@ -210,53 +215,90 @@ public static void _colorMask(boolean red, boolean green, boolean blue, boolean * @author */ @Overwrite(remap = false) - public static void _depthFunc(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.depthFunc(i); + public static void _polygonMode(int face, int mode) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.setPolygonModeGL(mode); } /** * @author */ @Overwrite(remap = false) - public static void _clearColor(float f, float g, float h, float i) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.setClearColor(f, g, h, i); + public static void _enablePolygonOffset() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.enablePolygonOffset(); } /** * @author */ @Overwrite(remap = false) - public static void _clearDepth(double d) { - // TODO + public static void _disablePolygonOffset() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.disablePolygonOffset(); } /** * @author */ @Overwrite(remap = false) - public static void _clear(int mask, boolean bl) { + public static void _polygonOffset(float f, float g) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.polygonOffset(g, f); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void _enableColorLogicOp() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.enableColorLogicOp(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void _disableColorLogicOp() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.disableColorLogicOp(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void _logicOp(int i) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.logicOp(i); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void _clearColor(float f, float g, float h, float i) { RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.clear(mask); + VRenderSystem.setClearColor(f, g, h, i); } /** * @author */ @Overwrite(remap = false) - public static int glCreateProgram() { + public static void _clearDepth(double d) { RenderSystem.assertOnRenderThread(); - return VkGlProgram.genProgramId(); + VRenderSystem.clearDepth(d); } /** * @author */ @Overwrite(remap = false) - public static void _glUseProgram(int i) { + public static void _clear(int mask, boolean bl) { RenderSystem.assertOnRenderThread(); - VkGlProgram.glUseProgram(i); + VRenderSystem.clear(mask); } /** @@ -264,7 +306,7 @@ public static void _glUseProgram(int i) { */ @Overwrite(remap = false) public static void _disableDepthTest() { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VRenderSystem.disableDepthTest(); } @@ -273,10 +315,19 @@ public static void _disableDepthTest() { */ @Overwrite(remap = false) public static void _enableDepthTest() { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VRenderSystem.enableDepthTest(); } + /** + * @author + */ + @Overwrite(remap = false) + public static void _depthFunc(int i) { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.depthFunc(i); + } + /** * @author */ @@ -292,7 +343,7 @@ public static void _depthMask(boolean bl) { */ @Overwrite(remap = false) public static int glGenFramebuffers() { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); return VkGlFramebuffer.genFramebufferId(); } @@ -310,7 +361,7 @@ public static int glGenRenderbuffers() { */ @Overwrite(remap = false) public static void _glBindFramebuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlFramebuffer.bindFramebuffer(i, j); } @@ -319,7 +370,7 @@ public static void _glBindFramebuffer(int i, int j) { */ @Overwrite(remap = false) public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlFramebuffer.framebufferTexture2D(i, j, k, l, m); } @@ -373,7 +424,7 @@ public static int _glGenBuffers() { */ @Overwrite(remap = false) public static void _glBindBuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlBuffer.glBindBuffer(i, j); } @@ -382,7 +433,7 @@ public static void _glBindBuffer(int i, int j) { */ @Overwrite(remap = false) public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlBuffer.glBufferData(i, byteBuffer, j); } @@ -391,7 +442,7 @@ public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { */ @Overwrite(remap = false) public static void _glBufferData(int i, long l, int j) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlBuffer.glBufferData(i, l, j); } @@ -410,7 +461,7 @@ public static ByteBuffer _glMapBuffer(int i, int j) { */ @Overwrite(remap = false) public static void _glUnmapBuffer(int i) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VkGlBuffer.glUnmapBuffer(i); } @@ -428,4 +479,41 @@ public static void _glDeleteBuffers(int i) { */ @Overwrite(remap = false) public static void _disableVertexAttribArray(int i) {} + + /** + * @author + */ + @Overwrite(remap = false) + public static void _glUseProgram(int i) { + RenderSystem.assertOnRenderThread(); + VkGlProgram.glUseProgram(i); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static int glCreateProgram() { + RenderSystem.assertOnRenderThread(); + return VkGlProgram.genProgramId(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void glDeleteProgram(int i) { + RenderSystem.assertOnRenderThread(); +// GL20.glDeleteProgram(i); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static int _glGenVertexArrays() { + RenderSystem.assertOnRenderThreadOrInit(); + // TODO + return 0; + } } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 624d44589e..1a173834ab 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -1,10 +1,7 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexSorting; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; @@ -15,8 +12,6 @@ import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import java.util.function.Consumer; - import static com.mojang.blaze3d.systems.RenderSystem.*; @Mixin(RenderSystem.class) @@ -38,8 +33,7 @@ public abstract class RenderSystemMixin { @Shadow private static VertexSorting savedVertexSorting; @Shadow - public static void assertOnRenderThread() { - } + public static void assertOnRenderThread() {} /** * @author @@ -57,53 +51,6 @@ public static void initRenderer(int debugVerbosity, boolean debugSync) { @Overwrite(remap = false) public static void setupDefaultState(int x, int y, int width, int height) { } - /** - * @author - */ - @Overwrite(remap = false) - public static void enableColorLogicOp() { - assertOnRenderThread(); - VRenderSystem.enableColorLogicOp(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableColorLogicOp() { - assertOnRenderThread(); - VRenderSystem.disableColorLogicOp(); - } - - /** - * @author - */ - @Overwrite - public static void logicOp(GlStateManager.LogicOp op) { - assertOnRenderThread(); - VRenderSystem.logicOp(op.value); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void activeTexture(int texture) { - VkGlTexture.activeTexture(texture); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void glGenBuffers(Consumer consumer) {} - - /** - * @author - */ - @Overwrite(remap = false) - public static void glGenVertexArrays(Consumer consumer) {} - /** * @author */ @@ -112,202 +59,6 @@ public static int maxSupportedTextureSize() { return VRenderSystem.maxSupportedTextureSize(); } - /** - * @author - */ - @Overwrite(remap = false) - public static void clear(int mask, boolean getError) { - VRenderSystem.clear(mask); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void clearColor(float r, float g, float b, float a) { - VRenderSystem.setClearColor(r, g, b, a); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void clearDepth(double d) { - VRenderSystem.clearDepth(d); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableScissor(int x, int y, int width, int height) { - Renderer.setScissor(x, y, width, height); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableScissor() { - Renderer.resetScissor(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableDepthTest() { - assertOnRenderThread(); - //GlStateManager._disableDepthTest(); - VRenderSystem.disableDepthTest(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableDepthTest() { - assertOnRenderThreadOrInit(); - VRenderSystem.enableDepthTest(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void depthFunc(int i) { - assertOnRenderThread(); - VRenderSystem.depthFunc(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void depthMask(boolean b) { - assertOnRenderThread(); - VRenderSystem.depthMask(b); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - VRenderSystem.colorMask(red, green, blue, alpha); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendEquation(int i) { - assertOnRenderThread(); - //TODO - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableBlend() { - VRenderSystem.enableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableBlend() { - VRenderSystem.disableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFunc(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - VRenderSystem.blendFunc(sourceFactor.value, destFactor.value); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFunc(int srcFactor, int dstFactor) { - VRenderSystem.blendFunc(srcFactor, dstFactor); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFuncSeparate(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor, GlStateManager.SourceFactor sourceFactor1, GlStateManager.DestFactor destFactor1) { - VRenderSystem.blendFuncSeparate(sourceFactor.value, destFactor.value, sourceFactor1.value, destFactor1.value); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFuncSeparate(int srcFactorRGB, int dstFactorRGB, int srcFactorAlpha, int dstFactorAlpha) { - VRenderSystem.blendFuncSeparate(srcFactorRGB, dstFactorRGB, srcFactorAlpha, dstFactorAlpha); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableCull() { - assertOnRenderThread(); - VRenderSystem.enableCull(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableCull() { - assertOnRenderThread(); - VRenderSystem.disableCull(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void polygonMode(final int face, final int mode) { - assertOnRenderThread(); - VRenderSystem.setPolygonModeGL(mode); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enablePolygonOffset() { - assertOnRenderThread(); - VRenderSystem.enablePolygonOffset(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disablePolygonOffset() { - assertOnRenderThread(); - VRenderSystem.disablePolygonOffset(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void polygonOffset(float factor, float units) { - assertOnRenderThread(); - VRenderSystem.polygonOffset(factor, units); - } - /** * @author */ @@ -439,11 +190,4 @@ private static void _restoreProjectionMatrix() { VRenderSystem.calculateMVP(); } - /** - * @author - */ - @Overwrite(remap = false) - public static void texParameter(int target, int pname, int param) { - VkGlTexture.texParameteri(target, pname, param); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index e9e7ee88e3..db4996d69f 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -236,6 +236,10 @@ public static void blendFuncSeparate(int srcFactorRGB, int dstFactorRGB, int src PipelineState.blendInfo.setBlendFuncSeparate(srcFactorRGB, dstFactorRGB, srcFactorAlpha, dstFactorAlpha); } + public static void blendOp(int op) { + PipelineState.blendInfo.setBlendOp(op); + } + public static void enableColorLogicOp() { logicOp = true; } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java index bca907d3cc..d94ad1b024 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -143,10 +143,10 @@ private long createGraphicsPipeline(PipelineState state) { colorBlendAttachment.blendEnable(true); colorBlendAttachment.srcColorBlendFactor(PipelineState.BlendState.getSrcRgbFactor(state.blendState_i)); colorBlendAttachment.dstColorBlendFactor(PipelineState.BlendState.getDstRgbFactor(state.blendState_i)); - colorBlendAttachment.colorBlendOp(VK_BLEND_OP_ADD); + colorBlendAttachment.colorBlendOp(PipelineState.BlendState.blendOp(state.blendState_i)); colorBlendAttachment.srcAlphaBlendFactor(PipelineState.BlendState.getSrcAlphaFactor(state.blendState_i)); colorBlendAttachment.dstAlphaBlendFactor(PipelineState.BlendState.getDstAlphaFactor(state.blendState_i)); - colorBlendAttachment.alphaBlendOp(VK_BLEND_OP_ADD); + colorBlendAttachment.alphaBlendOp(PipelineState.BlendState.blendOp(state.blendState_i)); } else { colorBlendAttachment.blendEnable(false); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java index af857d0705..8015cbf1b0 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java @@ -1,13 +1,12 @@ package net.vulkanmod.vulkan.shader; import com.mojang.blaze3d.platform.GlStateManager; -import net.vulkanmod.vulkan.framebuffer.RenderPass; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.framebuffer.RenderPass; import java.util.Objects; import static org.lwjgl.vulkan.VK10.*; -import static org.lwjgl.vulkan.VK10.VK_COMPARE_OP_EQUAL; public class PipelineState { private static final int DEFAULT_DEPTH_OP = 515; @@ -26,7 +25,7 @@ public static PipelineState getCurrentPipelineState(RenderPass renderPass) { int depthState = getDepthState(); int logicOp = getLogicOpState(); - if(currentState.checkEquals(assemblyRasterState, blendState, depthState, logicOp, currentColorMask, renderPass)) + if (currentState.checkEquals(assemblyRasterState, blendState, depthState, logicOp, currentColorMask, renderPass)) return currentState; else return currentState = new PipelineState(assemblyRasterState, blendState, depthState, logicOp, currentColorMask, renderPass); @@ -69,7 +68,8 @@ public static int getLogicOpState() { int colorMask_i; int logicOp_i; - public PipelineState(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, RenderPass renderPass) { + public PipelineState(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, + RenderPass renderPass) { this.renderPass = renderPass; this.assemblyRasterState = assemblyRasterState; @@ -79,11 +79,12 @@ public PipelineState(int assemblyRasterState, int blendState, int depthState, in this.logicOp_i = logicOp; } - private boolean checkEquals(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, RenderPass renderPass) { + private boolean checkEquals(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, + RenderPass renderPass) { return (blendState == this.blendState_i) && (depthState == this.depthState_i) - && renderPass == this.renderPass && logicOp == this.logicOp_i - && (assemblyRasterState == this.assemblyRasterState) - && colorMask == this.colorMask_i; + && renderPass == this.renderPass && logicOp == this.logicOp_i + && (assemblyRasterState == this.assemblyRasterState) + && colorMask == this.colorMask_i; } @Override @@ -95,9 +96,9 @@ public boolean equals(Object o) { PipelineState that = (PipelineState) o; return (blendState_i == that.blendState_i) && (depthState_i == that.depthState_i) - && this.renderPass == that.renderPass && logicOp_i == that.logicOp_i - && this.assemblyRasterState == that.assemblyRasterState - && this.colorMask_i == that.colorMask_i; + && this.renderPass == that.renderPass && logicOp_i == that.logicOp_i + && this.assemblyRasterState == that.assemblyRasterState + && this.colorMask_i == that.colorMask_i; } @Override @@ -107,7 +108,7 @@ public int hashCode() { public static BlendInfo defaultBlendInfo() { return new BlendInfo(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, - VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); + VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); } public static class BlendInfo { @@ -118,7 +119,8 @@ public static class BlendInfo { public int dstAlphaFactor; public int blendOp; - public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlphaFactor, int dstAlphaFactor, int blendOp) { + public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlphaFactor, int dstAlphaFactor, + int blendOp) { this.enabled = enabled; this.srcRgbFactor = srcRgbFactor; this.dstRgbFactor = dstRgbFactor; @@ -134,7 +136,8 @@ public void setBlendFunction(GlStateManager.SourceFactor sourceFactor, GlStateMa this.dstAlphaFactor = glToVulkanBlendFactor(destFactor.value); } - public void setBlendFuncSeparate(GlStateManager.SourceFactor srcRgb, GlStateManager.DestFactor dstRgb, GlStateManager.SourceFactor srcAlpha, GlStateManager.DestFactor dstAlpha) { + public void setBlendFuncSeparate(GlStateManager.SourceFactor srcRgb, GlStateManager.DestFactor dstRgb, + GlStateManager.SourceFactor srcAlpha, GlStateManager.DestFactor dstAlpha) { this.srcRgbFactor = glToVulkanBlendFactor(srcRgb.value); this.srcAlphaFactor = glToVulkanBlendFactor(srcAlpha.value); this.dstRgbFactor = glToVulkanBlendFactor(dstRgb.value); @@ -269,7 +272,7 @@ public static int getDstAlphaFactor(int s) { } public static int blendOp(int state) { - return state >>> FUN_OFFSET; + return decode(state, FUN_OFFSET, OP_MASK); } } @@ -340,9 +343,9 @@ public static abstract class ColorMask { public static int getColorMask(boolean r, boolean g, boolean b, boolean a) { return (r ? VK_COLOR_COMPONENT_R_BIT : 0) - | (g ? VK_COLOR_COMPONENT_G_BIT : 0) - | (b ? VK_COLOR_COMPONENT_B_BIT : 0) - | (a ? VK_COLOR_COMPONENT_A_BIT : 0); + | (g ? VK_COLOR_COMPONENT_G_BIT : 0) + | (b ? VK_COLOR_COMPONENT_B_BIT : 0) + | (a ? VK_COLOR_COMPONENT_A_BIT : 0); } } From bd4db35f8ecdaa3dcc32089e01e1f4702d83d678 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 22 May 2025 23:51:55 +0200 Subject: [PATCH 092/177] Fix missed global block entities set update - Refactor --- .../vulkanmod/render/chunk/RenderSection.java | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index 81dca75d92..7e4d790466 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -2,7 +2,6 @@ import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import net.minecraft.client.Minecraft; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; @@ -22,12 +21,9 @@ import net.vulkanmod.render.vertex.TerrainRenderType; import java.util.Collection; -import java.util.Map; import java.util.Set; public class RenderSection { - static final Map> globalBlockEntitiesMap = new Reference2ReferenceOpenHashMap<>(); - private ChunkArea chunkArea; public byte frustumIndex; public short lastFrame = -1; @@ -361,25 +357,18 @@ public boolean containsBlockEntities() { } public void updateGlobalBlockEntities(Collection fullSet) { - if (fullSet.isEmpty()) - return; - - Set set = Sets.newHashSet(fullSet); - Set set1; - Set sectionSet; - synchronized (globalBlockEntitiesMap) { - sectionSet = globalBlockEntitiesMap.computeIfAbsent(this, (section) -> new ObjectOpenHashSet<>()); - } + Set sectionSet = compileStatus.globalBlockEntities; if (sectionSet.size() != fullSet.size() || !sectionSet.containsAll(fullSet)) { - set1 = Sets.newHashSet(sectionSet); - set.removeAll(sectionSet); - set1.removeAll(fullSet); + Set toRemove = Sets.newHashSet(sectionSet); + Set toAdd = Sets.newHashSet(fullSet); + toAdd.removeAll(sectionSet); + toRemove.removeAll(fullSet); sectionSet.clear(); sectionSet.addAll(fullSet); - Minecraft.getInstance().levelRenderer.updateGlobalBlockEntities(set1, set); + Minecraft.getInstance().levelRenderer.updateGlobalBlockEntities(toRemove, toAdd); } } @@ -440,6 +429,7 @@ public short getLastFrame2() { static class CompileStatus { CompiledSection compiledSection = CompiledSection.UNCOMPILED; + Set globalBlockEntities = new ObjectOpenHashSet<>(); BuildTask buildTask; SortTransparencyTask sortTask; } From 91bf9e83caddf93fba781aaaebf9b348fd83147e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 22 May 2025 23:52:33 +0200 Subject: [PATCH 093/177] Fix beacon beam rendering bug --- .../core/rendertype_beacon_beam/rendertype_beacon_beam.fsh | 3 ++- .../core/rendertype_beacon_beam/rendertype_beacon_beam.vsh | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh index 3e0d10ea64..e8c3a5316c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh @@ -2,7 +2,8 @@ #include "fog.glsl" layout(binding = 0) uniform UniformBufferObject { - mat4 ProjMat; + mat4 MVP; + mat4 ProjMat; }; layout(binding = 1) uniform UBO{ diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh index 817669d61c..edab87decc 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh @@ -5,7 +5,8 @@ layout(location = 1) in vec4 Color; layout(location = 2) in vec2 UV0; layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; + mat4 MVP; + mat4 ProjMat; }; layout(location = 0) out vec4 vertexColor; From f23855f2675f1efb52fb8aa2c26bc23dccfb5543 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 22 May 2025 23:53:22 +0200 Subject: [PATCH 094/177] Use cloud texture color --- .../vulkanmod/render/sky/CloudRenderer.java | 73 +++++++++++-------- .../net/vulkanmod/vulkan/util/ColorUtil.java | 9 +++ 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index c7e3d3b4db..2227c7b225 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -170,10 +170,10 @@ public void resetBuffer() { } private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerCellZ, double cloudY) { - final int upFaceColor = ColorUtil.RGBA.pack(1.0f, 1.0f, 1.0f, 1.0f); - final int xDirColor = ColorUtil.RGBA.pack(0.9f, 0.9f, 0.9f, 1.0f); - final int downFaceColor = ColorUtil.RGBA.pack(0.7f, 0.7f, 0.7f, 1.0f); - final int zDirColor = ColorUtil.RGBA.pack(0.8f, 0.8f, 0.8f, 1.0f); + final float upFaceBrightness = 1.0f; + final float xDirBrightness = 0.9f; + final float downFaceBrightness = 0.7f; + final float zDirBrightness = 0.8f; BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); @@ -186,50 +186,57 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { int cellIdx = this.cloudGrid.getWrappedIdx(centerCellX + cellX, centerCellZ + cellZ); byte renderFaces = this.cloudGrid.renderFaces[cellIdx]; + int baseColor = this.cloudGrid.pixels[cellIdx]; float x = cellX * CELL_WIDTH; float z = cellZ * CELL_WIDTH; if ((renderFaces & DIR_POS_Y_BIT) != 0 && cloudY <= 0.0f) { - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, upFaceColor); - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, upFaceColor); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, upFaceColor); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, upFaceColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, upFaceBrightness); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); } if ((renderFaces & DIR_NEG_Y_BIT) != 0 && cloudY >= -CELL_HEIGHT) { - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, downFaceColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, downFaceColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, downFaceColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, downFaceColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, downFaceBrightness); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); } if ((renderFaces & DIR_POS_X_BIT) != 0 && (x < 1.0f || insideClouds)) { - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, xDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, xDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, xDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, xDirColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, xDirBrightness); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); } if ((renderFaces & DIR_NEG_X_BIT) != 0 && (x > -1.0f || insideClouds)) { - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, xDirColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, xDirColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, xDirColor); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, xDirColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, xDirBrightness); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); } if ((renderFaces & DIR_POS_Z_BIT) != 0 && (z < 1.0f || insideClouds)) { - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, zDirColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, zDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, zDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, zDirColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, zDirBrightness); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); } if ((renderFaces & DIR_NEG_Z_BIT) != 0 && (z > -1.0f || insideClouds)) { - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, zDirColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, zDirColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, zDirColor); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, zDirColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, zDirBrightness); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); } } @@ -241,15 +248,17 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { int cellIdx = this.cloudGrid.getWrappedIdx(centerCellX + cellX, centerCellZ + cellZ); byte renderFaces = this.cloudGrid.renderFaces[cellIdx]; + int baseColor = this.cloudGrid.pixels[cellIdx]; float x = cellX * CELL_WIDTH; float z = cellZ * CELL_WIDTH; if ((renderFaces & DIR_NEG_Y_BIT) != 0) { - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, upFaceColor); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, upFaceColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, upFaceColor); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, upFaceColor); + final int color = ColorUtil.ARGB.multiplyRGB(baseColor, upFaceBrightness); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); } } diff --git a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java index 145935a85b..0c2c0990bd 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java @@ -48,6 +48,15 @@ public static int multiplyAlpha(int color, float m) { return (color & 0x00FFFFFF) | newA << 24; } + public static int multiplyRGB(int color, float m) { + final int alpha = ((color >>> 24) & 0xFF); + final int red = (int) (((color >>> 16) & 0xFF) * m); + final int green = (int) (((color >>> 8) & 0xFF) * m); + final int blue = (int) ((color & 0xFF) * m); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + public static int toRGBA(int color) { return (color & 0xFF00FF00) | ((color >> 16) & 0xFF) | ((color << 16) & 0xFF0000); } From d5cf53022d5ecda013253dfedd9240786f61d5c6 Mon Sep 17 00:00:00 2001 From: Tirth Patel <52333828+Haberno@users.noreply.github.com> Date: Sat, 5 Jul 2025 10:20:52 -0400 Subject: [PATCH 095/177] Fix F3 + L (default profiler) crash (#614) --- .../ClientMetricsSamplersProviderMixin.java | 19 ++++++++++ src/main/resources/vulkanmod.mixins.json | 38 ++++++------------- 2 files changed, 31 insertions(+), 26 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java diff --git a/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java new file mode 100644 index 0000000000..d5067ecfa0 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java @@ -0,0 +1,19 @@ +// In a new file, e.g., ClientMetricsSamplersProviderMixin.java +package net.vulkanmod.mixin.profiling; // Or an appropriate package + +import com.mojang.blaze3d.systems.TimerQuery; +import net.minecraft.client.profiling.ClientMetricsSamplersProvider; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import java.util.Optional; + +@Mixin(ClientMetricsSamplersProvider.class) +public class ClientMetricsSamplersProviderMixin { + + @Redirect(method = "registerStaticSamplers", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) + private Optional preventTimerQuery() { + return Optional.empty(); + } +} \ No newline at end of file diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index a24cadc918..7ada95708d 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -7,11 +7,8 @@ "mixins": [ ], "client": [ - "window.WindowMixin", - "window.WindowAccessor", - - "chunk.ClientPacketListenerM", "chunk.ClientChunkCacheM", + "chunk.ClientPacketListenerM", "chunk.DirectionMixin", "chunk.FrustumMixin", "chunk.LevelRendererMixin", @@ -19,26 +16,24 @@ "chunk.SectionRenderDispatcherM", "chunk.ViewAreaM", "chunk.VisibilitySetMixin", - "compatibility.EffectInstanceM", + "compatibility.PostChainM", + "compatibility.PostPassM", "compatibility.ProgramM", "compatibility.UniformM", "compatibility.gl.GL11M", "compatibility.gl.GL15M", "compatibility.gl.GL30M", - - "debug.crash_report.SystemReportM", "debug.DebugScreenOverlayM", "debug.GlDebugInfoM", "debug.KeyboardHandlerM", - + "debug.crash_report.SystemReportM", "matrix.Matrix4fM", "matrix.PoseAccessor", - + "profiling.ClientMetricsSamplersProviderMixin", "profiling.GuiMixin", "profiling.KeyboardHandlerM", "profiling.LevelRendererMixin", - "render.BufferUploaderM", "render.GameRendererMixin", "render.GlProgramManagerMixin", @@ -69,37 +64,28 @@ "render.vertex.IndexTypeMixin", "render.vertex.VertexBufferM", "render.vertex.VertexFormatMixin", - - "screen.ScreenM", "screen.OptionsScreenM", - - "texture.mip.MipmapGeneratorM", + "screen.ScreenM", + "texture.MAbstractTexture", + "texture.MTextureUtil", "texture.image.MNativeImage", "texture.image.NativeImageAccessor", + "texture.mip.MipmapGeneratorM", "texture.update.GameRendererM", "texture.update.MLightTexture", "texture.update.MSpriteContents", "texture.update.MTextureManager", - "texture.MAbstractTexture", - "texture.MTextureUtil", - "util.ScreenshotRecorderM", - "vertex.EntityOutlineGeneratorM", "vertex.SpriteCoordinateExpanderM", "vertex.VertexMultiConsumersM$DoubleM", "vertex.VertexMultiConsumersM$MultipleM", "vertex.VertexMultiConsumersM$SheetDecalM", - + "voxel.VoxelShapeMixin", "wayland.InputConstantsM", "wayland.MinecraftMixin", - - "texture.mip.MipmapGeneratorM", - - "compatibility.PostChainM", - "compatibility.PostPassM", - - "voxel.VoxelShapeMixin" + "window.WindowAccessor", + "window.WindowMixin" ], "injectors": { "defaultRequire": 1 From e55e4328f879235c61408dc14616672d8071b8cc Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 17 Nov 2024 16:42:55 +0100 Subject: [PATCH 096/177] Port to 1.21.2 --- gradle.properties | 12 +- .../net/vulkanmod/config/gui/GuiRenderer.java | 43 +-- .../net/vulkanmod/config/gui/VOptionList.java | 3 +- .../vulkanmod/config/gui/VOptionScreen.java | 5 +- .../gui/widget/CyclingOptionWidget.java | 5 +- .../config/gui/widget/OptionWidget.java | 3 +- .../config/gui/widget/VButtonWidget.java | 3 +- .../net/vulkanmod/config/option/Options.java | 250 ++++++------ src/main/java/net/vulkanmod/gl/GlShader.java | 48 +++ .../interfaces/shader/PipelineConfig.java | 14 + .../interfaces/{ => shader}/ShaderMixed.java | 8 +- .../mixin/chunk/ClientChunkCacheM.java | 2 +- .../mixin/chunk/ClientPacketListenerM.java | 2 +- .../mixin/chunk/LevelRendererMixin.java | 10 +- .../mixin/chunk/SectionRenderDispatcherM.java | 6 +- .../mixin/compatibility/EffectInstanceM.java | 224 ----------- .../mixin/compatibility/PostChainM.java | 266 ++----------- .../mixin/compatibility/PostPassM.java | 156 ++++---- .../mixin/compatibility/ProgramM.java | 44 --- .../mixin/compatibility/UniformM.java | 9 - .../net/vulkanmod/mixin/matrix/Matrix4fM.java | 8 +- .../mixin/profiling/GameLoadTimeEventM.java | 86 +++++ .../mixin/profiling/LevelRendererMixin.java | 101 ++--- .../mixin/render/BufferUploaderM.java | 47 ++- .../mixin/render/GameRendererMixin.java | 69 ---- .../mixin/render/GlProgramManagerMixin.java | 20 - .../mixin/render/GlStateManagerM.java | 234 ++++++------ .../mixin/render/MinecraftMixin.java | 50 ++- .../mixin/render/RenderSystemMixin.java | 315 +++++++++++++--- .../mixin/render/ShaderInstanceM.java | 356 ------------------ .../mixin/render/block/BakedQuadM.java | 2 +- .../mixin/render/clouds/LevelRendererM.java | 40 +- .../mixin/render/entity/LevelRendererM.java | 19 +- .../mixin/render/entity/model/ModelPartM.java | 16 +- .../mixin/render/frapi/ItemRendererMixin.java | 2 +- .../render/shader/CompilationCacheM.java | 111 ++++++ .../render/shader/CompiledShaderProgramM.java | 219 +++++++++++ .../render/shader/ShadeProgramConfigM.java | 22 ++ .../mixin/render/shader/ShaderManagerM.java | 297 +++++++++++++++ .../render/target/RenderTargetMixin.java | 83 +++- .../mixin/render/vertex/VertexBufferM.java | 17 +- .../net/vulkanmod/mixin/screen/ScreenM.java | 2 +- .../mixin/texture/MAbstractTexture.java | 6 +- .../mixin/texture/image/MNativeImage.java | 6 - .../mixin/texture/update/MLightTexture.java | 31 +- .../mixin/vertex/VertexMultiConsumersM.java | 2 +- .../vulkanmod/mixin/window/WindowMixin.java | 17 +- src/main/java/net/vulkanmod/render/VBO.java | 78 ++-- .../vulkanmod/render/chunk/SectionGrid.java | 8 +- .../vulkanmod/render/chunk/WorldRenderer.java | 29 +- .../render/chunk/build/RenderRegion.java | 4 +- .../chunk/build/RenderRegionBuilder.java | 3 +- .../build/frapi/helper/NormalHelper.java | 4 +- .../build/frapi/mesh/MutableQuadViewImpl.java | 11 +- .../render/AbstractBlockRenderContext.java | 31 +- .../frapi/render/BlockRenderContext.java | 21 +- .../build/frapi/render/ItemRenderContext.java | 70 +--- .../build/light/data/LightDataAccess.java | 7 +- .../chunk/build/renderer/BlockRenderer.java | 4 +- .../chunk/build/renderer/FluidRenderer.java | 22 +- .../render/chunk/build/task/BuildTask.java | 2 +- .../render/chunk/graph/SectionGraph.java | 14 +- .../vulkanmod/render/sky/CloudRenderer.java | 22 +- .../net/vulkanmod/render/util/DrawUtil.java | 17 +- .../net/vulkanmod/vulkan/VRenderSystem.java | 2 + .../net/vulkanmod/vulkan/shader/Uniforms.java | 7 +- .../net/vulkanmod/vulkan/util/DrawUtil.java | 66 ++-- .../rendertype_clouds/rendertype_clouds.json | 2 + src/main/resources/vulkanmod.accesswidener | 11 +- src/main/resources/vulkanmod.mixins.json | 44 ++- 70 files changed, 2023 insertions(+), 1747 deletions(-) create mode 100644 src/main/java/net/vulkanmod/gl/GlShader.java create mode 100644 src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java rename src/main/java/net/vulkanmod/interfaces/{ => shader}/ShaderMixed.java (70%) delete mode 100644 src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java create mode 100644 src/main/java/net/vulkanmod/mixin/profiling/GameLoadTimeEventM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java diff --git a/gradle.properties b/gradle.properties index 017ec398f2..ff41672eec 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,14 +4,14 @@ org.gradle.parallel=true # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.21.1 -yarn_mappings=1.21.1+build.3 -loader_version=0.16.10 +minecraft_version=1.21.3 +yarn_mappings=1.21.3+build.2 +loader_version=0.16.7 # Fabric API -fabric_version=0.114.0+1.21.1 +fabric_version=0.106.1+1.21.3 # Mod Properties -mod_version = 0.5.4-dev +mod_version = 0.5.0-dev maven_group = net.vulkanmod -archives_base_name = VulkanMod_1.21.1 +archives_base_name = VulkanMod_1.21.3 diff --git a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java index b4b3216c10..a446d71b24 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java @@ -6,9 +6,9 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.CoreShaders; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; -import net.minecraft.util.FastColor; import net.minecraft.util.FormattedCharSequence; import org.joml.Matrix4f; @@ -55,19 +55,14 @@ public static void fill(float x0, float y0, float x1, float y1, int color) { public static void fill(float x0, float y0, float x1, float y1, float z, int color) { Matrix4f matrix4f = pose.last().pose(); - float a = (float) FastColor.ARGB32.alpha(color) / 255.0F; - float r = (float) FastColor.ARGB32.red(color) / 255.0F; - float g = (float) FastColor.ARGB32.green(color) / 255.0F; - float b = (float) FastColor.ARGB32.blue(color) / 255.0F; - - RenderSystem.setShader(GameRenderer::getPositionColorShader); + RenderSystem.setShader(CoreShaders.POSITION_COLOR); setupBufferBuilder(); - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r, g, b, a); + bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color); + bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(color); + bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(color); + bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(color); submitIfNeeded(); } @@ -77,23 +72,18 @@ public static void fillGradient(float x0, float y0, float x1, float y1, int colo } public static void fillGradient(float x0, float y0, float x1, float y1, float z, int color1, int color2) { - float a1 = (float) FastColor.ARGB32.alpha(color1) / 255.0F; - float r1 = (float) FastColor.ARGB32.red(color1) / 255.0F; - float g1 = (float) FastColor.ARGB32.green(color1) / 255.0F; - float b1 = (float) FastColor.ARGB32.blue(color1) / 255.0F; - float a2 = (float) FastColor.ARGB32.alpha(color2) / 255.0F; - float r2 = (float) FastColor.ARGB32.red(color2) / 255.0F; - float g2 = (float) FastColor.ARGB32.green(color2) / 255.0F; - float b2 = (float) FastColor.ARGB32.blue(color2) / 255.0F; - Matrix4f matrix4f = pose.last().pose(); + RenderSystem.setShader(CoreShaders.POSITION_COLOR); + + if (!batching) + bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); setupBufferBuilder(); - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r1, g1, b1, a1); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r2, g2, b2, a2); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r2, g2, b2, a2); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r1, g1, b1, a1); + bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color1); + bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(color2); + bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(color2); + bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(color1); submitIfNeeded(); } @@ -146,6 +136,11 @@ public static void beginBatch() { batching = true; } + public static void endBatch() { + BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + batching = false; + } + public static void endBatch() { RenderSystem.setShader(GameRenderer::getPositionColorShader); MeshData meshData = bufferBuilder.build(); diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index e814f5cc62..a3d99a4776 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.gui.components.events.GuiEventListener; +import net.minecraft.client.renderer.CoreShaders; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.util.Mth; import net.vulkanmod.config.gui.widget.OptionWidget; @@ -214,7 +215,7 @@ public void renderWidget(int mouseX, int mouseY) { int maxScroll = this.getMaxScroll(); if (maxScroll > 0) { RenderSystem.enableBlend(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); + RenderSystem.setShader(CoreShaders.POSITION_COLOR); int height = this.getHeight(); int totalLength = this.getTotalLength(); diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java index 1a6d255b36..c53775ae18 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java @@ -6,6 +6,7 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.RenderType; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -231,7 +232,7 @@ public void renderBackground(GuiGraphics guiGraphics, int i, int j, float f) { this.renderPanorama(guiGraphics, f); } - this.renderBlurredBackground(f); + this.renderBlurredBackground(); this.renderMenuBackground(guiGraphics); } @@ -247,7 +248,7 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) int size = minecraft.font.lineHeight * 4; - guiGraphics.blit(ICON, 30, 4, 0f, 0f, size, size, size, size); + guiGraphics.blit(RenderType::guiTextured, ICON, 30, 4, 0f, 0f, size, size, size, size); VOptionList currentList = this.optionPages.get(this.currentListIdx).getOptionList(); currentList.updateState(mouseX, mouseY); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java index 20c601476c..415db96459 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.vertex.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.CoreShaders; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.vulkanmod.config.gui.GuiRenderer; @@ -133,7 +134,7 @@ void renderButton(PoseStack matrices, double mouseX, double mouseY) { Matrix4f matrix4f = matrices.last().pose(); - RenderSystem.setShader(GameRenderer::getPositionShader); + RenderSystem.setShader(CoreShaders.POSITION); RenderSystem.enableBlend(); if(this.isHovered(mouseX, mouseY) && this.active) @@ -160,7 +161,7 @@ else if(this.active) BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShader(CoreShaders.POSITION); } enum Direction { diff --git a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java index a9fe679ce4..a5210a01b7 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java @@ -7,6 +7,7 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.client.renderer.CoreShaders; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.client.sounds.SoundManager; @@ -69,7 +70,7 @@ public void updateState() { public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); - RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShader(CoreShaders.POSITION_TEX); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); int i = this.getYImage(this.isHovered()); RenderSystem.enableBlend(); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java index 3664d94295..64269c6b67 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.CoreShaders; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; @@ -27,7 +28,7 @@ public VButtonWidget(int x, int y, int width, int height, Component message, Con public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); Font textRenderer = minecraftClient.font; - RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShader(CoreShaders.POSITION_TEX); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha); RenderSystem.enableBlend(); diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index c52a8de73b..ffe471b7e1 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.Window; import net.minecraft.client.*; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ParticleStatus; import net.vulkanmod.Initializer; import net.vulkanmod.config.Config; import net.vulkanmod.config.gui.OptionBlock; @@ -92,56 +93,63 @@ public static OptionBlock[] getVideoOpts() { () -> WindowMode.fromValue(config.windowMode)) .setTranslator(value -> Component.translatable(WindowMode.getComponentName(value))), new RangeOption(Component.translatable("options.framerateLimit"), - 10, 260, 10, - value -> Component.nullToEmpty(value == 260 ? - Component.translatable("options.framerateLimit.max").getString() : - String.valueOf(value)), - value -> { - minecraftOptions.framerateLimit().set(value); - window.setFramerateLimit(value); - }, - () -> minecraftOptions.framerateLimit().get()), + 10, 260, 10, + value -> Component.nullToEmpty(value == 260 ? + Component.translatable( + "options.framerateLimit.max") + .getString() : + String.valueOf(value)), + value -> { + minecraftOptions.framerateLimit().set(value); + minecraft.getFramerateLimitTracker().setFramerateLimit(value); + }, + () -> minecraftOptions.framerateLimit().get()), new SwitchOption(Component.translatable("options.vsync"), - value -> { - minecraftOptions.enableVsync().set(value); - window.updateVsync(value); - }, - () -> minecraftOptions.enableVsync().get()), + value -> { + minecraftOptions.enableVsync().set(value); + window.updateVsync(value); + }, + () -> minecraftOptions.enableVsync().get()), + new CyclingOption<>(Component.translatable("options.inactivityFpsLimit"), + InactivityFpsLimit.values(), + value -> minecraftOptions.inactivityFpsLimit().set(value), + () -> minecraftOptions.inactivityFpsLimit().get()) + .setTranslator(inactivityFpsLimit -> Component.translatable(inactivityFpsLimit.getKey())) }), new OptionBlock("", new Option[]{ new RangeOption(Component.translatable("options.guiScale"), - 0, window.calculateScale(0, minecraft.isEnforceUnicode()), 1, - value -> Component.translatable((value == 0) - ? "options.guiScale.auto" - : String.valueOf(value)), - value -> { - minecraftOptions.guiScale().set(value); - minecraft.resizeDisplay(); - }, - () -> (minecraftOptions.guiScale().get())), + 0, window.calculateScale(0, minecraft.isEnforceUnicode()), 1, + value -> Component.translatable((value == 0) + ? "options.guiScale.auto" + : String.valueOf(value)), + value -> { + minecraftOptions.guiScale().set(value); + minecraft.resizeDisplay(); + }, + () -> (minecraftOptions.guiScale().get())), new RangeOption(Component.translatable("options.gamma"), - 0, 100, 1, - value -> Component.translatable(switch (value) { - case 0 -> "options.gamma.min"; - case 50 -> "options.gamma.default"; - case 100 -> "options.gamma.max"; - default -> String.valueOf(value); - }), - value -> minecraftOptions.gamma().set(value * 0.01), - () -> (int) (minecraftOptions.gamma().get() * 100.0)), + 0, 100, 1, + value -> Component.translatable(switch (value) { + case 0 -> "options.gamma.min"; + case 50 -> "options.gamma.default"; + case 100 -> "options.gamma.max"; + default -> String.valueOf(value); + }), + value -> minecraftOptions.gamma().set(value * 0.01), + () -> (int) (minecraftOptions.gamma().get() * 100.0)), }), new OptionBlock("", new Option[]{ new SwitchOption(Component.translatable("options.viewBobbing"), - (value) -> minecraftOptions.bobView().set(value), - () -> minecraftOptions.bobView().get()), + (value) -> minecraftOptions.bobView().set(value), + () -> minecraftOptions.bobView().get()), new CyclingOption<>(Component.translatable("options.attackIndicator"), - AttackIndicatorStatus.values(), - value -> minecraftOptions.attackIndicator().set(value), - () -> minecraftOptions.attackIndicator().get()) + AttackIndicatorStatus.values(), + value -> minecraftOptions.attackIndicator().set(value), + () -> minecraftOptions.attackIndicator().get()) .setTranslator(value -> Component.translatable(value.getKey())), new SwitchOption(Component.translatable("options.autosaveIndicator"), - value -> minecraftOptions.showAutosaveIndicator().set(value), - () -> minecraftOptions.showAutosaveIndicator().get()), + value -> minecraftOptions.showAutosaveIndicator().set(value), + () -> minecraftOptions.showAutosaveIndicator().get()), }) }; } @@ -150,48 +158,48 @@ public static OptionBlock[] getGraphicsOpts() { return new OptionBlock[]{ new OptionBlock("", new Option[]{ new RangeOption(Component.translatable("options.renderDistance"), - 2, 32, 1, - (value) -> minecraftOptions.renderDistance().set(value), - () -> minecraftOptions.renderDistance().get()), + 2, 32, 1, + (value) -> minecraftOptions.renderDistance().set(value), + () -> minecraftOptions.renderDistance().get()), new RangeOption(Component.translatable("options.simulationDistance"), - 5, 32, 1, - (value) -> minecraftOptions.simulationDistance().set(value), - () -> minecraftOptions.simulationDistance().get()), + 5, 32, 1, + (value) -> minecraftOptions.simulationDistance().set(value), + () -> minecraftOptions.simulationDistance().get()), new CyclingOption<>(Component.translatable("options.prioritizeChunkUpdates"), - PrioritizeChunkUpdates.values(), - value -> minecraftOptions.prioritizeChunkUpdates().set(value), - () -> minecraftOptions.prioritizeChunkUpdates().get()) + PrioritizeChunkUpdates.values(), + value -> minecraftOptions.prioritizeChunkUpdates().set(value), + () -> minecraftOptions.prioritizeChunkUpdates().get()) .setTranslator(value -> Component.translatable(value.getKey())), }), new OptionBlock("", new Option[]{ new CyclingOption<>(Component.translatable("options.graphics"), - new GraphicsStatus[]{GraphicsStatus.FAST, GraphicsStatus.FANCY}, - value -> minecraftOptions.graphicsMode().set(value), - () -> minecraftOptions.graphicsMode().get()) + new GraphicsStatus[]{GraphicsStatus.FAST, GraphicsStatus.FANCY}, + value -> minecraftOptions.graphicsMode().set(value), + () -> minecraftOptions.graphicsMode().get()) .setTranslator(graphicsMode -> Component.translatable(graphicsMode.getKey())), new CyclingOption<>(Component.translatable("options.particles"), - new ParticleStatus[]{ParticleStatus.MINIMAL, ParticleStatus.DECREASED, ParticleStatus.ALL}, - value -> minecraftOptions.particles().set(value), - () -> minecraftOptions.particles().get()) + new ParticleStatus[]{ParticleStatus.MINIMAL, ParticleStatus.DECREASED, ParticleStatus.ALL}, + value -> minecraftOptions.particles().set(value), + () -> minecraftOptions.particles().get()) .setTranslator(particlesMode -> Component.translatable(particlesMode.getKey())), new CyclingOption<>(Component.translatable("options.renderClouds"), - CloudStatus.values(), - value -> minecraftOptions.cloudStatus().set(value), - () -> minecraftOptions.cloudStatus().get()) + CloudStatus.values(), + value -> minecraftOptions.cloudStatus().set(value), + () -> minecraftOptions.cloudStatus().get()) .setTranslator(value -> Component.translatable(value.getKey())), new CyclingOption<>(Component.translatable("options.ao"), - new Integer[]{LightMode.FLAT, LightMode.SMOOTH, LightMode.SUB_BLOCK}, - (value) -> { - if (value > LightMode.FLAT) - minecraftOptions.ambientOcclusion().set(true); - else - minecraftOptions.ambientOcclusion().set(false); + new Integer[]{LightMode.FLAT, LightMode.SMOOTH, LightMode.SUB_BLOCK}, + (value) -> { + if (value > LightMode.FLAT) + minecraftOptions.ambientOcclusion().set(true); + else + minecraftOptions.ambientOcclusion().set(false); - config.ambientOcclusion = value; + config.ambientOcclusion = value; - minecraft.levelRenderer.allChanged(); - }, - () -> config.ambientOcclusion) + minecraft.levelRenderer.allChanged(); + }, + () -> config.ambientOcclusion) .setTranslator(value -> Component.translatable(switch (value) { case LightMode.FLAT -> "options.off"; case LightMode.SMOOTH -> "options.on"; @@ -200,33 +208,33 @@ public static OptionBlock[] getGraphicsOpts() { })) .setTooltip(Component.translatable("vulkanmod.options.ao.subBlock.tooltip")), new RangeOption(Component.translatable("options.biomeBlendRadius"), - 0, 7, 1, - value -> { - int v = value * 2 + 1; - return Component.nullToEmpty("%d x %d".formatted(v, v)); - }, - (value) -> { - minecraftOptions.biomeBlendRadius().set(value); - minecraft.levelRenderer.allChanged(); - }, - () -> minecraftOptions.biomeBlendRadius().get()), + 0, 7, 1, + value -> { + int v = value * 2 + 1; + return Component.nullToEmpty("%d x %d".formatted(v, v)); + }, + (value) -> { + minecraftOptions.biomeBlendRadius().set(value); + minecraft.levelRenderer.allChanged(); + }, + () -> minecraftOptions.biomeBlendRadius().get()), }), new OptionBlock("", new Option[]{ new SwitchOption(Component.translatable("options.entityShadows"), - value -> minecraftOptions.entityShadows().set(value), - () -> minecraftOptions.entityShadows().get()), + value -> minecraftOptions.entityShadows().set(value), + () -> minecraftOptions.entityShadows().get()), new RangeOption(Component.translatable("options.entityDistanceScaling"), - 50, 500, 25, - value -> minecraftOptions.entityDistanceScaling().set(value * 0.01), - () -> minecraftOptions.entityDistanceScaling().get().intValue() * 100), + 50, 500, 25, + value -> minecraftOptions.entityDistanceScaling().set(value * 0.01), + () -> minecraftOptions.entityDistanceScaling().get().intValue() * 100), new CyclingOption<>(Component.translatable("options.mipmapLevels"), - new Integer[]{0, 1, 2, 3, 4}, - value -> { - minecraftOptions.mipmapLevels().set(value); - minecraft.updateMaxMipLevel(value); - minecraft.delayTextureReload(); - }, - () -> minecraftOptions.mipmapLevels().get()) + new Integer[]{0, 1, 2, 3, 4}, + value -> { + minecraftOptions.mipmapLevels().set(value); + minecraft.updateMaxMipLevel(value); + minecraft.delayTextureReload(); + }, + () -> minecraftOptions.mipmapLevels().get()) .setTranslator(value -> Component.nullToEmpty(value.toString())) }) }; @@ -236,9 +244,9 @@ public static OptionBlock[] getOptimizationOpts() { return new OptionBlock[]{ new OptionBlock("", new Option[]{ new CyclingOption<>(Component.translatable("vulkanmod.options.advCulling"), - new Integer[]{1, 2, 3, 10}, - value -> config.advCulling = value, - () -> config.advCulling) + new Integer[]{1, 2, 3, 10}, + value -> config.advCulling = value, + () -> config.advCulling) .setTranslator(value -> Component.translatable(switch (value) { case 1 -> "vulkanmod.options.advCulling.aggressive"; case 2 -> "vulkanmod.options.advCulling.normal"; @@ -248,27 +256,27 @@ public static OptionBlock[] getOptimizationOpts() { })) .setTooltip(Component.translatable("vulkanmod.options.advCulling.tooltip")), new SwitchOption(Component.translatable("vulkanmod.options.entityCulling"), - value -> config.entityCulling = value, - () -> config.entityCulling) + value -> config.entityCulling = value, + () -> config.entityCulling) .setTooltip(Component.translatable("vulkanmod.options.entityCulling.tooltip")), new SwitchOption(Component.translatable("vulkanmod.options.uniqueOpaqueLayer"), - value -> { - config.uniqueOpaqueLayer = value; - TerrainRenderType.updateMapping(); - minecraft.levelRenderer.allChanged(); - }, - () -> config.uniqueOpaqueLayer) + value -> { + config.uniqueOpaqueLayer = value; + TerrainRenderType.updateMapping(); + minecraft.levelRenderer.allChanged(); + }, + () -> config.uniqueOpaqueLayer) .setTooltip(Component.translatable("vulkanmod.options.uniqueOpaqueLayer.tooltip")), new SwitchOption(Component.translatable("vulkanmod.options.backfaceCulling"), - value -> { - config.backFaceCulling = value; - Minecraft.getInstance().levelRenderer.allChanged(); - }, - () -> config.backFaceCulling) + value -> { + config.backFaceCulling = value; + Minecraft.getInstance().levelRenderer.allChanged(); + }, + () -> config.backFaceCulling) .setTooltip(Component.translatable("vulkanmod.options.backfaceCulling.tooltip")), new SwitchOption(Component.translatable("vulkanmod.options.indirectDraw"), - value -> config.indirectDraw = value, - () -> config.indirectDraw) + value -> config.indirectDraw = value, + () -> config.indirectDraw) .setTooltip(Component.translatable("vulkanmod.options.indirectDraw.tooltip")), }) }; @@ -292,24 +300,26 @@ public static OptionBlock[] getOtherOpts() { return Component.nullToEmpty(String.valueOf(value)); }), new RangeOption(Component.translatable("vulkanmod.options.frameQueue"), - 2, 5, 1, - value -> { - config.frameQueueSize = value; - Renderer.scheduleSwapChainUpdate(); - }, () -> config.frameQueueSize) + 2, 5, 1, + value -> { + config.frameQueueSize = value; + Renderer.scheduleSwapChainUpdate(); + }, () -> config.frameQueueSize) .setTooltip(Component.translatable("vulkanmod.options.frameQueue.tooltip")), new CyclingOption<>(Component.translatable("vulkanmod.options.deviceSelector"), - IntStream.range(-1, DeviceManager.suitableDevices.size()).boxed().toArray(Integer[]::new), - value -> config.device = value, - () -> config.device) + IntStream.range(-1, DeviceManager.suitableDevices.size()).boxed() + .toArray(Integer[]::new), + value -> config.device = value, + () -> config.device) .setTranslator(value -> Component.translatable((value == -1) - ? "vulkanmod.options.deviceSelector.auto" - : DeviceManager.suitableDevices.get(value).deviceName) + ? "vulkanmod.options.deviceSelector.auto" + : DeviceManager.suitableDevices.get( + value).deviceName) ) .setTooltip(Component.nullToEmpty("%s: %s".formatted( - Component.translatable("vulkanmod.options.deviceSelector.tooltip").getString(), - DeviceManager.device.deviceName - )) + Component.translatable("vulkanmod.options.deviceSelector.tooltip").getString(), + DeviceManager.device.deviceName + )) ) }) }; diff --git a/src/main/java/net/vulkanmod/gl/GlShader.java b/src/main/java/net/vulkanmod/gl/GlShader.java new file mode 100644 index 0000000000..0585f62725 --- /dev/null +++ b/src/main/java/net/vulkanmod/gl/GlShader.java @@ -0,0 +1,48 @@ +package net.vulkanmod.gl; + +import com.mojang.blaze3d.systems.RenderSystem; +import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; +import org.lwjgl.opengl.GL20; +import org.spongepowered.asm.mixin.Overwrite; + +public class GlShader { + private static int ID_COUNTER = 1; + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int boundTextureId = 0; + + public static int glCreateShader(int type) { + int id = ID_COUNTER++; + GlShader shader = new GlShader(id, type); + + map.put(id, shader); + return id; + } + + public static void glDeleteShader(int i) { + map.remove(i); + } + + public static void glShaderSource(int i, String string) { + GlShader shader = map.get(i); + shader.source = string; + } + + public static void glCompileShader(int i) { + + } + + public static int glGetShaderi(int i, int j) { + return 0; + } + + final int id; + final int type; + + String source; + + GlShader(int id, int type) { + this.id = id; + this.type = type; + } + +} diff --git a/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java b/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java new file mode 100644 index 0000000000..34910ea47b --- /dev/null +++ b/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java @@ -0,0 +1,14 @@ +package net.vulkanmod.interfaces.shader; + +import net.minecraft.client.renderer.ShaderProgramConfig; + +public interface PipelineConfig { + + static PipelineConfig of(ShaderProgramConfig shaderProgramConfig) { + return (PipelineConfig) (Object) shaderProgramConfig; + } + + String getName(); + + void setName(String s); +} diff --git a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java b/src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java similarity index 70% rename from src/main/java/net/vulkanmod/interfaces/ShaderMixed.java rename to src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java index e05a698d41..f158141dee 100644 --- a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java +++ b/src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java @@ -1,6 +1,6 @@ -package net.vulkanmod.interfaces; +package net.vulkanmod.interfaces.shader; -import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.CompiledShaderProgram; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.util.MappedBuffer; @@ -9,7 +9,7 @@ public interface ShaderMixed { - static ShaderMixed of(ShaderInstance compiledShaderProgram) { + static ShaderMixed of(CompiledShaderProgram compiledShaderProgram) { return (ShaderMixed) compiledShaderProgram; } @@ -21,5 +21,5 @@ static ShaderMixed of(ShaderInstance compiledShaderProgram) { Supplier getUniformSupplier(String name); - void setDoUniformsUpdate(); + void setUniformsUpdate(); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java index 0b32f688b0..0acf28529f 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java @@ -26,7 +26,7 @@ private void setChunkStatus(int x, int z, FriendlyByteBuf friendlyByteBuf, Compo } @Inject(method = "drop", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/multiplayer/ClientChunkCache$Storage;replace(ILnet/minecraft/world/level/chunk/LevelChunk;Lnet/minecraft/world/level/chunk/LevelChunk;)Lnet/minecraft/world/level/chunk/LevelChunk;")) + target = "Lnet/minecraft/client/multiplayer/ClientChunkCache$Storage;drop(ILnet/minecraft/world/level/chunk/LevelChunk;)V")) private void resetChunkStatus(ChunkPos chunkPos, CallbackInfo ci) { ChunkStatusMap.INSTANCE.resetChunkStatus(chunkPos.x, chunkPos.z, ChunkStatusMap.DATA_READY); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java b/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java index dd23682592..aaa05df763 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java @@ -14,7 +14,7 @@ public class ClientPacketListenerM { @Inject(method = "applyLightData", at = @At("RETURN")) - private void setChunkStatus(int x, int z, ClientboundLightUpdatePacketData clientboundLightUpdatePacketData, CallbackInfo ci) { + private void setChunkStatus(int x, int z, ClientboundLightUpdatePacketData clientboundLightUpdatePacketData, boolean bl, CallbackInfo ci) { ChunkStatusMap.INSTANCE.setChunkStatus(x, z, ChunkStatusMap.LIGHT_READY); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java index 394213f7bc..b282665aa1 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java @@ -50,12 +50,12 @@ private void onAllChanged(CallbackInfo ci) { this.worldRenderer.allChanged(); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;checkPoseStack(Lcom/mojang/blaze3d/vertex/PoseStack;)V", ordinal = 1, shift = At.Shift.BEFORE)) - private void renderBlockEntities(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "renderBlockEntities", at = @At(value = "RETURN")) + private void renderBlockEntities(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, MultiBufferSource.BufferSource bufferSource2, Camera camera, float partialTicks, CallbackInfo ci) { Vec3 pos = camera.getPosition(); - PoseStack poseStack = new PoseStack(); +// PoseStack poseStack = new PoseStack(); - this.worldRenderer.renderBlockEntities(poseStack, pos.x(), pos.y(), pos.z(), this.destructionProgress, deltaTracker.getGameTimeDeltaPartialTick(false)); + this.worldRenderer.renderBlockEntities(poseStack, pos.x(), pos.y(), pos.z(), this.destructionProgress, partialTicks); } /** @@ -129,7 +129,7 @@ public int countRenderedSections() { return this.worldRenderer.getVisibleSectionsCount(); } - @Redirect(method = "renderWorldBorder", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;getDepthFar()F")) + @Redirect(method = "addWeatherPass", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;getDepthFar()F")) private float getRenderDistanceZFar(GameRenderer instance) { return instance.getRenderDistance() * 4F; } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java b/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java index 9dbdab7739..35a1bafc71 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java @@ -1,7 +1,6 @@ package net.vulkanmod.mixin.chunk; import net.minecraft.client.renderer.chunk.SectionRenderDispatcher; -import net.minecraft.util.thread.ProcessorMailbox; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -9,6 +8,7 @@ @Mixin(SectionRenderDispatcher.class) public class SectionRenderDispatcherM { - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/thread/ProcessorMailbox;tell(Ljava/lang/Object;)V")) - private void redirectTask(ProcessorMailbox instance, Object object) {} + // TODO +// @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/thread/ProcessorMailbox;tell(Ljava/lang/Object;)V")) +// private void redirectTask(ProcessorMailbox instance, Object object) {} } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java deleted file mode 100644 index c3f49c08c2..0000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ /dev/null @@ -1,224 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.google.gson.JsonObject; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.shaders.BlendMode; -import com.mojang.blaze3d.shaders.EffectProgram; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import net.minecraft.client.renderer.EffectInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.layout.Uniform; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.converter.GlslConverter; -import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.io.IOUtils; -import org.lwjgl.opengl.GL30; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.IntSupplier; -import java.util.function.Supplier; - -@Mixin(EffectInstance.class) -public class EffectInstanceM { - - @Shadow @Final private Map uniformMap; - @Shadow @Final private List uniforms; - - @Shadow private boolean dirty; - @Shadow private static EffectInstance lastAppliedEffect; - @Shadow @Final private BlendMode blend; - @Shadow private static int lastProgramId; - @Shadow @Final private int programId; - @Shadow @Final private List samplerLocations; - @Shadow @Final private List samplerNames; - @Shadow @Final private Map samplerMap; - - @Shadow @Final private String name; - - @Unique private static GraphicsPipeline lastPipeline; - @Unique private GraphicsPipeline pipeline; - - @Inject(method = "", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/EffectInstance;updateLocations()V", - shift = At.Shift.AFTER), - locals = LocalCapture.CAPTURE_FAILHARD - ) - private void inj(ResourceProvider resourceProvider, String string, CallbackInfo ci, ResourceLocation resourceLocation, Resource resource, Reader reader, JsonObject jsonObject, String string2, String string3) { - createShaders(resourceProvider, string2, string3); - } - - @Redirect(method = "", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/EffectInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/EffectProgram;")) - private EffectProgram redirectShader(ResourceProvider resourceProvider, Program.Type type, String string) { - return null; - } - - /** - * @author - * @reason - */ - @Overwrite - public void close() { - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.close(); - } - - this.pipeline.scheduleCleanUp(); - } - - private void createShaders(ResourceProvider resourceManager, String vertexShader, String fragShader) { - try { - String[] vshPathInfo = this.decompose(vertexShader, ':'); - ResourceLocation vshLocation = ResourceLocation.fromNamespaceAndPath(vshPathInfo[0], "shaders/program/" + vshPathInfo[1] + ".vsh"); - Resource resource = resourceManager.getResourceOrThrow(vshLocation); - InputStream inputStream = resource.open(); - String vshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - String[] fshPathInfo = this.decompose(fragShader, ':'); - ResourceLocation fshLocation = ResourceLocation.fromNamespaceAndPath(fshPathInfo[0], "shaders/program/" + fshPathInfo[1] + ".fsh"); - resource = resourceManager.getResourceOrThrow(fshLocation); - inputStream = resource.open(); - String fshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - GlslConverter converter = new GlslConverter(); - - converter.process(vshSrc, fshSrc); - UBO ubo = converter.createUBO(); - this.setUniformSuppliers(ubo); - - Pipeline.Builder builder = new Pipeline.Builder(DefaultVertexFormat.POSITION, this.name); - builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); - builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); - - this.pipeline = builder.createGraphicsPipeline(); - - VkGlProgram program = VkGlProgram.getProgram(this.programId); - program.bindPipeline(this.pipeline); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void setUniformSuppliers(UBO ubo) { - - for(Uniform v_uniform : ubo.getUniforms()) { - com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(v_uniform.getName()); - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); - } - else if (uniform.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); - } - else { - throw new RuntimeException("out of bounds value for uniform " + uniform); - } - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - v_uniform.setSupplier(supplier); - } - - } - - private String[] decompose(String string, char c) { - String[] strings = new String[]{"minecraft", string}; - int i = string.indexOf(c); - if (i >= 0) { - strings[1] = string.substring(i + 1); - if (i >= 1) { - strings[0] = string.substring(0, i); - } - } - - return strings; - } - - /** - * @author - * @reason - */ - @Overwrite - public void apply() { - this.dirty = false; - this.blend.apply(); - - ProgramManager.glUseProgram(this.programId); - - Renderer renderer = Renderer.getInstance(); - - if (this.pipeline != lastPipeline) { - renderer.bindGraphicsPipeline(pipeline); - lastPipeline = this.pipeline; - } - - for(int i = 0; i < this.samplerLocations.size(); ++i) { - String string = this.samplerNames.get(i); - IntSupplier intSupplier = this.samplerMap.get(string); - if (intSupplier != null) { - RenderSystem.activeTexture(GL30.GL_TEXTURE0 + i); - int j = intSupplier.getAsInt(); - if (j != -1) { - RenderSystem.bindTexture(j); - com.mojang.blaze3d.shaders.Uniform.uploadInteger(this.samplerLocations.get(i), i); - } - } - } - - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.upload(); - } - - renderer.uploadAndBindUBOs(pipeline); - - } - - /** - * @author - * @reason - */ - @Overwrite - public void clear() { - RenderSystem.assertOnRenderThread(); - ProgramManager.glUseProgram(0); - lastProgramId = -1; - lastAppliedEffect = null; - lastPipeline = null; - - for(int i = 0; i < this.samplerLocations.size(); ++i) { - if (this.samplerMap.get(this.samplerNames.get(i)) != null) { - GlStateManager._activeTexture(GL30.GL_TEXTURE0 + i); - GlStateManager._bindTexture(0); - } - } - - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java index 885440c65a..ee24f81304 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java @@ -29,263 +29,55 @@ @Mixin(PostChain.class) public abstract class PostChainM { - @Shadow private int screenWidth; - @Shadow private int screenHeight; - - @Shadow @Final private Map customRenderTargets; - @Shadow @Final private RenderTarget screenTarget; - @Shadow @Final private List passes; - - @Shadow private float lastStamp; - @Shadow private float time; - - @Shadow public abstract void addTempTarget(String string, int i, int j); - @Shadow protected abstract void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException; - @Shadow protected abstract void parseUniformNode(JsonElement jsonElement) throws ChainedJsonException; - -// /** -// * @author -// * @reason -// */ -// @Overwrite -// private void load(TextureManager textureManager, ResourceLocation resourceLocation) throws IOException, JsonSyntaxException { -// Resource resource = this.resourceManager.getResourceOrThrow(resourceLocation); -// -// try { -// Reader reader = resource.openAsReader(); -// -// try { -// JsonObject jsonObject = GsonHelper.parse(reader); -// JsonArray jsonArray; -// int i; -// JsonElement jsonElement; -// if (GsonHelper.isArrayNode(jsonObject, "targets")) { -// jsonArray = jsonObject.getAsJsonArray("targets"); -// i = 0; -// -// Iterator iterator; -// for(iterator = jsonArray.iterator(); iterator.hasNext(); ++i) { -// jsonElement = iterator.next(); -// -// try { -// this.parseTargetNode(jsonElement); -// } catch (Exception var14) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(var14); -// chainedJsonException.prependJsonKey("targets[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } + // TODO: port +// @Shadow private int screenWidth; +// @Shadow private int screenHeight; // -// if (GsonHelper.isArrayNode(jsonObject, "passes")) { -// jsonArray = jsonObject.getAsJsonArray("passes"); -// i = 0; +// @Shadow @Final private Map customRenderTargets; +// @Shadow @Final private RenderTarget screenTarget; +// @Shadow @Final private List passes; // -// Iterator iterator; -// for(iterator = jsonArray.iterator(); iterator.hasNext(); ++i) { -// jsonElement = iterator.next(); +// @Shadow private float lastStamp; +// @Shadow private float time; // -// try { -// this.parsePassNode(textureManager, jsonElement); -// } catch (Exception var13) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(var13); -// chainedJsonException.prependJsonKey("passes[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } -// } catch (Throwable var15) { -// try { -// reader.close(); -// } catch (Throwable var12) { -// var15.addSuppressed(var12); -// } +// @Shadow public abstract void addTempTarget(String string, int i, int j); +// @Shadow protected abstract void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException; +// @Shadow protected abstract void parseUniformNode(JsonElement jsonElement) throws ChainedJsonException; // -// throw var15; -// } -// -// reader.close(); -// -// } catch (Exception var16) { -// ChainedJsonException chainedJsonException2 = ChainedJsonException.forException(var16); -// String var10001 = resourceLocation.getPath(); -// chainedJsonException2.setFilenameAndFlush(var10001 + " (" + resource.sourcePackId() + ")"); -// throw chainedJsonException2; -// } -// } - // /** // * @author // * @reason // */ // @Overwrite -// private void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException { -// if (GsonHelper.isStringValue(jsonElement)) { -// this.addTempTarget(jsonElement.getAsString(), this.screenWidth, this.screenHeight); +// public void process(float f) { +// if (f < this.lastStamp) { +// this.time += 1.0F - this.lastStamp; +// this.time += f; // } else { -// JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "target"); -// String string = GsonHelper.getAsString(jsonObject, "name"); -// int i = GsonHelper.getAsInt(jsonObject, "width", this.screenWidth); -// int j = GsonHelper.getAsInt(jsonObject, "height", this.screenHeight); -// if (this.customRenderTargets.containsKey(string)) { -// throw new ChainedJsonException(string + " is already defined"); -// } -// -// this.addTempTarget(string, i, j); +// this.time += f - this.lastStamp; // } // -// } - -// /** -// * @author -// * @reason -// */ -// @Overwrite -// private void parsePassNode(TextureManager textureManager, JsonElement jsonElement) throws IOException { -// JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "pass"); -// String string = GsonHelper.getAsString(jsonObject, "name"); -// String string2 = GsonHelper.getAsString(jsonObject, "intarget"); -// String string3 = GsonHelper.getAsString(jsonObject, "outtarget"); -// RenderTarget renderTarget = this.getRenderTarget(string2); -// RenderTarget renderTarget2 = this.getRenderTarget(string3); -// if (renderTarget == null) { -// throw new ChainedJsonException("Input target '" + string2 + "' does not exist"); -// } else if (renderTarget2 == null) { -// throw new ChainedJsonException("Output target '" + string3 + "' does not exist"); -// } else { -// PostPass postPass = this.addPass(string, renderTarget, renderTarget2); -// JsonArray jsonArray = GsonHelper.getAsJsonArray(jsonObject, "auxtargets", null); -// if (jsonArray != null) { -// int i = 0; -// -// for(Iterator var12 = jsonArray.iterator(); var12.hasNext(); ++i) { -// JsonElement jsonElement2 = (JsonElement)var12.next(); -// -// try { -// JsonObject jsonObject2 = GsonHelper.convertToJsonObject(jsonElement2, "auxtarget"); -// String string4 = GsonHelper.getAsString(jsonObject2, "name"); -// String string5 = GsonHelper.getAsString(jsonObject2, "id"); -// boolean bl; -// String string6; -// if (string5.endsWith(":depth")) { -// bl = true; -// string6 = string5.substring(0, string5.lastIndexOf(58)); -// } else { -// bl = false; -// string6 = string5; -// } +// this.lastStamp = f; // -// RenderTarget renderTarget3 = this.getRenderTarget(string6); -// if (renderTarget3 == null) { -// if (bl) { -// throw new ChainedJsonException("Render target '" + string6 + "' can't be used as depth buffer"); -// } -// -// ResourceLocation resourceLocation = new ResourceLocation("textures/effect/" + string6 + ".png"); -// this.resourceManager.getResource(resourceLocation).orElseThrow(() -> { -// return new ChainedJsonException("Render target or texture '" + string6 + "' does not exist"); -// }); -// RenderSystem.setShaderTexture(0, resourceLocation); -// textureManager.bindForSetup(resourceLocation); -// AbstractTexture abstractTexture = textureManager.getTexture(resourceLocation); -// int j = GsonHelper.getAsInt(jsonObject2, "width"); -// int k = GsonHelper.getAsInt(jsonObject2, "height"); -// boolean bl2 = GsonHelper.getAsBoolean(jsonObject2, "bilinear"); -// if (bl2) { -// RenderSystem.texParameter(3553, 10241, 9729); -// RenderSystem.texParameter(3553, 10240, 9729); -// } else { -// RenderSystem.texParameter(3553, 10241, 9728); -// RenderSystem.texParameter(3553, 10240, 9728); -// } -// -// Objects.requireNonNull(abstractTexture); -// postPass.addAuxAsset(string4, abstractTexture::getId, j, k); -// } else if (bl) { -// Objects.requireNonNull(renderTarget3); -// postPass.addAuxAsset(string4, renderTarget3::getDepthTextureId, renderTarget3.width, renderTarget3.height); -// } else { -// Objects.requireNonNull(renderTarget3); -// postPass.addAuxAsset(string4, renderTarget3::getColorTextureId, renderTarget3.width, renderTarget3.height); -// } -// } catch (Exception e) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(e); -// chainedJsonException.prependJsonKey("auxtargets[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } -// -// JsonArray jsonArray2 = GsonHelper.getAsJsonArray(jsonObject, "uniforms", null); -// if (jsonArray2 != null) { -// int l = 0; +// while(this.time > 20.0F) { +// this.time -= 20.0F; +// } // -// for(Iterator var29 = jsonArray2.iterator(); var29.hasNext(); ++l) { -// JsonElement jsonElement3 = var29.next(); +// int filterMode = 9728; // -// try { -// this.parseUniformNode(jsonElement3); -// } catch (Exception var25) { -// ChainedJsonException chainedJsonException2 = ChainedJsonException.forException(var25); -// chainedJsonException2.prependJsonKey("uniforms[" + l + "]"); -// throw chainedJsonException2; -// } -// } +// for(PostPass postPass : this.passes) { +// int passFilterMode = postPass.getFilterMode(); +// if (filterMode != passFilterMode) { +// this.setFilterMode(passFilterMode); +// filterMode = passFilterMode; // } // +// postPass.process(this.time / 20.0F); // } -// } // -// private RenderTarget getRenderTarget(@Nullable String string) { -// if (string == null) { -// return null; -// } else { -// return string.equals("minecraft:main") ? this.screenTarget : this.customRenderTargets.get(string); -// } -// } +// this.setFilterMode(9728); // -// public PostPass addPass(String string, RenderTarget renderTarget, RenderTarget renderTarget2) throws IOException { -// PostPass postPass = new PostPass(this.resourceManager, string, renderTarget, renderTarget2); -// this.passes.add(this.passes.size(), postPass); -// return postPass; +// Renderer.resetViewport(); // } - @Shadow protected abstract void setFilterMode(int i); - - /** - * @author - * @reason - */ - @Overwrite - public void process(float f) { - if (f < this.lastStamp) { - this.time += 1.0F - this.lastStamp; - this.time += f; - } else { - this.time += f - this.lastStamp; - } - - this.lastStamp = f; - - while(this.time > 20.0F) { - this.time -= 20.0F; - } - - int filterMode = 9728; - - for(PostPass postPass : this.passes) { - int passFilterMode = postPass.getFilterMode(); - if (filterMode != passFilterMode) { - this.setFilterMode(passFilterMode); - filterMode = passFilterMode; - } - - postPass.process(this.time / 20.0F); - } - - this.setFilterMode(9728); - - Renderer.resetViewport(); - } - } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java index 14c1116904..f81d9e23b2 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java @@ -1,104 +1,114 @@ package net.vulkanmod.mixin.compatibility; +import com.mojang.blaze3d.ProjectionType; +import com.mojang.blaze3d.framegraph.FrameGraphBuilder; +import com.mojang.blaze3d.framegraph.FramePass; import com.mojang.blaze3d.pipeline.MainTarget; import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.resource.ResourceHandle; +import com.mojang.blaze3d.shaders.Uniform; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.EffectInstance; +import net.minecraft.client.renderer.CompiledShaderProgram; +import net.minecraft.client.renderer.PostChainConfig; import net.minecraft.client.renderer.PostPass; +import net.minecraft.resources.ResourceLocation; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.util.DrawUtil; import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import java.util.List; -import java.util.Objects; -import java.util.function.IntSupplier; +import java.util.Map; @Mixin(PostPass.class) -public class PostPassM { +public abstract class PostPassM { + @Shadow @Final private String name; - @Shadow @Final public RenderTarget inTarget; + @Shadow @Final private List inputs; + @Shadow @Final private ResourceLocation outputTargetId; + @Shadow @Final private CompiledShaderProgram shader; + @Shadow @Final private List uniforms; - @Shadow @Final public RenderTarget outTarget; - - @Shadow @Final private EffectInstance effect; - - @Shadow @Final private List auxAssets; - - @Shadow @Final private List auxNames; - - @Shadow @Final private List auxWidths; - - @Shadow @Final private List auxHeights; - - @Shadow private Matrix4f shaderOrthoMatrix; + @Shadow protected abstract void restoreDefaultUniforms(); /** * @author * @reason */ @Overwrite - public void process(float f) { - this.inTarget.unbindWrite(); - float g = (float)this.outTarget.width; - float h = (float)this.outTarget.height; - RenderSystem.viewport(0, 0, (int)g, (int)h); - - Objects.requireNonNull(this.inTarget); - this.effect.setSampler("DiffuseSampler", this.inTarget::getColorTextureId); - - if(this.inTarget instanceof MainTarget) - this.inTarget.bindRead(); + public void addToFrame(FrameGraphBuilder frameGraphBuilder, Map> map, Matrix4f matrix4f) { + FramePass framePass = frameGraphBuilder.addPass(this.name); - for(int i = 0; i < this.auxAssets.size(); ++i) { - this.effect.setSampler(this.auxNames.get(i), this.auxAssets.get(i)); - this.effect.safeGetUniform("AuxSize" + i).set((float) this.auxWidths.get(i), (float) this.auxHeights.get(i)); + for (PostPass.Input input : this.inputs) { + input.addToPass(framePass, map); } - this.effect.safeGetUniform("ProjMat").set(this.shaderOrthoMatrix); - this.effect.safeGetUniform("InSize").set((float)this.inTarget.width, (float)this.inTarget.height); - this.effect.safeGetUniform("OutSize").set(g, h); - this.effect.safeGetUniform("Time").set(f); - Minecraft minecraft = Minecraft.getInstance(); - this.effect.safeGetUniform("ScreenSize").set((float)minecraft.getWindow().getWidth(), (float)minecraft.getWindow().getHeight()); - - this.outTarget.clear(Minecraft.ON_OSX); - this.outTarget.bindWrite(false); - - VRenderSystem.disableCull(); - VRenderSystem.depthFunc(519); - VRenderSystem.setPrimitiveTopologyGL(GL11.GL_TRIANGLES); - - Renderer.setInvertedViewport(0, 0, this.outTarget.width, this.outTarget.height); - Renderer.resetScissor(); - - this.effect.apply(); - - BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); - bufferBuilder.addVertex(0.0f, 0.0f, 500.0f); - bufferBuilder.addVertex(g, 0.0f, 500.0f); - bufferBuilder.addVertex(g, h, 500.0f); - bufferBuilder.addVertex(0.0f, h, 500.0f); - BufferUploader.draw(bufferBuilder.buildOrThrow()); - RenderSystem.depthFunc(515); - - this.effect.clear(); - this.outTarget.unbindWrite(); - this.inTarget.unbindRead(); - - for (Object object : this.auxAssets) { - if (object instanceof RenderTarget) { - ((RenderTarget) object).unbindRead(); - } + ResourceHandle resourceHandle = map.computeIfPresent( + this.outputTargetId, (resourceLocation, resourceHandlex) -> framePass.readsAndWrites(resourceHandlex) + ); + if (resourceHandle == null) { + throw new IllegalStateException("Missing handle for target " + this.outputTargetId); + } else { + framePass.executes(() -> { + RenderTarget renderTarget = resourceHandle.get(); + RenderSystem.viewport(0, 0, renderTarget.width, renderTarget.height); + + for (PostPass.Input inputx : this.inputs) { + if (inputx instanceof PostPass.TargetInput) { + var targetId = ((PostPass.TargetInput) inputx).targetId(); + var inTarget = map.get(targetId).get(); + + if (inTarget instanceof MainTarget) { + inTarget.bindRead(); + } + } + + inputx.bindTo(this.shader, map); + } + + this.shader.safeGetUniform("OutSize").set((float)renderTarget.width, (float)renderTarget.height); + + for (PostChainConfig.Uniform uniform : this.uniforms) { + Uniform uniform2 = this.shader.getUniform(uniform.name()); + if (uniform2 != null) { + uniform2.setFromConfig(uniform.values(), uniform.values().size()); + } + } + + renderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); + renderTarget.clear(); + renderTarget.bindWrite(false); + RenderSystem.depthFunc(519); + RenderSystem.setShader(this.shader); + RenderSystem.backupProjectionMatrix(); + RenderSystem.setProjectionMatrix(matrix4f, ProjectionType.ORTHOGRAPHIC); + + Renderer.setInvertedViewport(0, 0, renderTarget.width, renderTarget.height); + Renderer.resetScissor(); + + BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); + bufferBuilder.addVertex(0.0F, 0.0F, 500.0F); + bufferBuilder.addVertex((float)renderTarget.width, 0.0F, 500.0F); + bufferBuilder.addVertex((float)renderTarget.width, (float)renderTarget.height, 500.0F); + bufferBuilder.addVertex(0.0F, (float)renderTarget.height, 500.0F); + + BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + RenderSystem.depthFunc(515); + RenderSystem.restoreProjectionMatrix(); + renderTarget.unbindWrite(); + + Renderer.resetViewport(); + + for (PostPass.Input input2 : this.inputs) { + input2.cleanup(map); + } + + this.restoreDefaultUniforms(); + }); } - - VRenderSystem.enableCull(); } + } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java b/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java deleted file mode 100644 index 7771c43f93..0000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import com.mojang.blaze3d.shaders.Program; -import net.vulkanmod.gl.GlUtil; -import net.vulkanmod.vulkan.shader.SPIRVUtils; -import org.apache.commons.io.IOUtils; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -@Mixin(Program.class) -public class ProgramM { - - /** - * @author - * @reason - */ - @Overwrite - public static int compileShaderInternal(Program.Type type, String string, InputStream inputStream, String string2, GlslPreprocessor glslPreprocessor) throws IOException { - String string3 = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - if (string3 == null) { - throw new IOException("Could not load program " + type.getName()); - } else { -// int i = GlStateManager.glCreateShader(type.getGlType()); -// GlStateManager.glShaderSource(i, glslPreprocessor.process(string3)); -// GlStateManager.glCompileShader(i); -// if (GlStateManager.glGetShaderi(i, 35713) == 0) { -// String string4 = StringUtils.trim(GlStateManager.glGetShaderInfoLog(i, 32768)); -// throw new IOException("Couldn't compile " + type.getName() + " program (" + string2 + ", " + string + ") : " + string4); -// } else { -// return i; -// } - - //TODO maybe not needed? - glslPreprocessor.process(string3); - SPIRVUtils.compileShader(string2 + ":" + string, string3, GlUtil.extToShaderKind(type.getExtension())); - } - return 0; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java index 588e7d1678..d8a4289135 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java @@ -28,15 +28,6 @@ public static int glGetUniformLocation(int i, CharSequence charSequence) { return 1; } - /** - * @author - * @reason - */ - @Overwrite - public static int glGetAttribLocation(int i, CharSequence charSequence) { - return 0; - } - @Inject(method = "upload", at = @At("HEAD"), cancellable = true) public void redirectUpload(CallbackInfo ci) { Renderer renderer = Renderer.getInstance(); diff --git a/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java b/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java index 071a62fd6f..d39d9647b5 100644 --- a/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java +++ b/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java @@ -10,6 +10,8 @@ public abstract class Matrix4fM { @Shadow public abstract Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne); @Shadow public abstract Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne); + @Shadow public abstract Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne); + @Shadow public abstract Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne); /** * @author @@ -17,7 +19,8 @@ public abstract class Matrix4fM { */ @Overwrite(remap = false) public Matrix4f setOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { - return new Matrix4f().setOrtho(left, right, bottom, top, zNear, zFar, true); + this.setOrtho(left, right, bottom, top, zNear, zFar, true); + return (Matrix4f)(Object)this; } /** @@ -44,6 +47,7 @@ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { */ @Overwrite(remap = false) public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { - return new Matrix4f().setPerspective(fovy, aspect, zNear, zFar, true); + this.setPerspective(fovy, aspect, zNear, zFar, true); + return (Matrix4f)(Object)this; } } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/GameLoadTimeEventM.java b/src/main/java/net/vulkanmod/mixin/profiling/GameLoadTimeEventM.java new file mode 100644 index 0000000000..985d36d76a --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/profiling/GameLoadTimeEventM.java @@ -0,0 +1,86 @@ +package net.vulkanmod.mixin.profiling; + +import com.google.common.base.Stopwatch; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import net.minecraft.client.telemetry.TelemetryEventSender; +import net.minecraft.client.telemetry.TelemetryEventType; +import net.minecraft.client.telemetry.TelemetryProperty; +import net.minecraft.client.telemetry.TelemetryPropertyMap; +import net.minecraft.client.telemetry.events.GameLoadTimesEvent; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.Map; +import java.util.OptionalLong; +import java.util.concurrent.TimeUnit; + +@Mixin(GameLoadTimesEvent.class) +public class GameLoadTimeEventM { + + @Shadow @Final private Map, Stopwatch> measurements; + + @Shadow @Final private static Logger LOGGER; + + @Shadow private OptionalLong bootstrapTime; + + public void send(TelemetryEventSender telemetryEventSender) { + Map measurements = new Reference2ReferenceOpenHashMap<>(); + + synchronized (this) { + this.measurements + .forEach( + (telemetryProperty, stopwatch) -> { + if (!stopwatch.isRunning()) { + long l = stopwatch.elapsed(TimeUnit.MILLISECONDS); + measurements.put(telemetryProperty, new GameLoadTimesEvent.Measurement((int)l)); + } else { + LOGGER.warn( + "Measurement {} was discarded since it was still ongoing when the event {} was sent.", + telemetryProperty.id(), + TelemetryEventType.GAME_LOAD_TIMES.id() + ); + } + } + ); + this.bootstrapTime.ifPresent(l -> measurements.put(TelemetryProperty.LOAD_TIME_BOOTSTRAP_MS, new GameLoadTimesEvent.Measurement((int)l))); + this.measurements.clear(); + } + + StringBuilder stringBuilder = new StringBuilder("\n"); + + for (TelemetryProperty property : measurements.keySet()) { + var measurement = measurements.get(property); + + stringBuilder.append("%s: %sms\n".formatted(property.id(), measurement.millis())); + } + + LOGGER.info(stringBuilder.toString()); + +// telemetryEventSender.send( +// TelemetryEventType.GAME_LOAD_TIMES, +// builder -> { +// synchronized (this) { +// this.measurements +// .forEach( +// (telemetryProperty, stopwatch) -> { +// if (!stopwatch.isRunning()) { +// long l = stopwatch.elapsed(TimeUnit.MILLISECONDS); +// builder.put(telemetryProperty, new GameLoadTimesEvent.Measurement((int)l)); +// } else { +// LOGGER.warn( +// "Measurement {} was discarded since it was still ongoing when the event {} was sent.", +// telemetryProperty.id(), +// TelemetryEventType.GAME_LOAD_TIMES.id() +// ); +// } +// } +// ); +// this.bootstrapTime.ifPresent(l -> builder.put(TelemetryProperty.LOAD_TIME_BOOTSTRAP_MS, new GameLoadTimesEvent.Measurement((int)l))); +// this.measurements.clear(); +// } +// } +// ); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java index d1b69098c7..8fc36fbc4d 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java @@ -1,11 +1,18 @@ package net.vulkanmod.mixin.profiling; +import com.mojang.blaze3d.framegraph.FrameGraphBuilder; +import com.mojang.blaze3d.resource.ResourceHandle; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Camera; +import net.minecraft.client.CloudStatus; import net.minecraft.client.DeltaTracker; +import net.minecraft.client.renderer.FogParameters; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.profiling.Profiler; import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; @@ -16,88 +23,84 @@ @Mixin(LevelRenderer.class) public class LevelRendererMixin { - @Inject(method = "renderClouds", at = @At("HEAD")) - private void pushProfiler(PoseStack poseStack, Matrix4f matrix4f, Matrix4f matrix4f2, float f, double d, double e, double g, CallbackInfo ci) { + @Inject(method = "method_62205", at = @At("HEAD")) + private void pushProfiler(ResourceHandle resourceHandle, int i, CloudStatus cloudStatus, float f, Matrix4f matrix4f, + Matrix4f matrix4f2, Vec3 vec3, float g, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Clouds"); } - @Inject(method = "renderClouds", at = @At("RETURN")) - private void popProfiler(PoseStack poseStack, Matrix4f matrix4f, Matrix4f matrix4f2, float f, double d, double e, double g, CallbackInfo ci) { + @Inject(method = "method_62205", at = @At("RETURN")) + private void popProfiler(ResourceHandle resourceHandle, int i, CloudStatus cloudStatus, float f, Matrix4f matrix4f, + Matrix4f matrix4f2, Vec3 vec3, float g, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V", - shift = At.Shift.BEFORE)) - private void pushProfiler3(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + // TODO: fix + @Inject(method = "method_62213", at = @At(value = "HEAD")) + private void pushProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, + ResourceHandle resourceHandle2, LightTexture lightTexture, Camera camera, float f, + CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Particles"); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V", - shift = At.Shift.AFTER)) - private void popProfiler3(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "method_62213", at = @At(value = "RETURN")) + private void popProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, + ResourceHandle resourceHandle2, LightTexture lightTexture, Camera camera, float f, + CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 0, - shift = At.Shift.BEFORE)) - private void profilerTerrain1(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "method_62214", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", + ordinal = 0, + shift = At.Shift.BEFORE)) + private void profilerTerrain1(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, + ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, + boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Opaque_terrain"); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 2, - shift = At.Shift.BEFORE)) - private void profilerTerrain2(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "method_62214", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/Camera;Lnet/minecraft/client/DeltaTracker;Ljava/util/List;)V")) + private void profilerTerrain2(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, + ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, + boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); profiler.push("entities"); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 3, - shift = At.Shift.BEFORE)) - private void profilerTerrain3_0(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "method_62214", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", + ordinal = 3, + shift = At.Shift.BEFORE)) + private void profilerTerrain3(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, + ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, + boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); profiler.push("Translucent_terrain"); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 5, - shift = At.Shift.BEFORE)) - private void profilerTerrain3_1(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "method_62214", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", + ordinal = 4, + shift = At.Shift.AFTER)) + private void profilerTerrain4(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, + ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, + boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); - profiler.push("Translucent_terrain"); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 4, - shift = At.Shift.BEFORE)) - private void profilerTerrain4_0(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.pop(); - } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 6, - shift = At.Shift.BEFORE)) - private void profilerTerrain4_1(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.pop(); - } } diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java index c270e749c2..9268a925e2 100644 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java @@ -3,18 +3,20 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.MeshData; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.CompiledShaderProgram; +import net.vulkanmod.interfaces.shader.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @Mixin(BufferUploader.class) -public abstract class BufferUploaderM { +public class BufferUploaderM { /** * @author @@ -30,22 +32,39 @@ public static void drawWithShader(MeshData meshData) { RenderSystem.assertOnRenderThread(); MeshData.DrawState parameters = meshData.drawState(); + + Renderer renderer = Renderer.getInstance(); + + Matrix4f projection = RenderSystem.getProjectionMatrix(); + Matrix4f modelView = RenderSystem.getModelViewStack(); + + VRenderSystem.applyMVP(modelView, projection); + if (parameters.vertexCount() > 0) { - ShaderInstance shaderInstance = RenderSystem.getShader(); + CompiledShaderProgram shaderProgram = RenderSystem.getShader(); // Prevent drawing if formats don't match to avoid disturbing visual bugs - if (shaderInstance.getVertexFormat() != parameters.format()) { - meshData.close(); - return; - } - - VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); +// if (shaderProgram.getVertexFormat() != parameters.format()) { +// meshData.close(); +// return; +// } // Used to update legacy shader uniforms // TODO it would be faster to allocate a buffer from stack and set all values - shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, RenderSystem.getModelViewMatrix(), - RenderSystem.getProjectionMatrix(), Minecraft.getInstance().getWindow()); - shaderInstance.apply(); + shaderProgram.apply(); +// shaderProgram.setDefaultUniforms(parameters.mode(), modelView, projection, Minecraft.getInstance().getWindow()); + + GraphicsPipeline pipeline = ((ShaderMixed)(shaderProgram)).getPipeline(); + + if (pipeline == null) { +// throw new NullPointerException("Shader %s has no initialized pipeline".formatted(shaderProgram.getName())); + throw new NullPointerException("Shader %d has no initialized pipeline".formatted(shaderProgram.getProgramId())); + } + + VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); + renderer.bindGraphicsPipeline(pipeline); + VTextureSelector.bindShaderTextures(pipeline); + renderer.uploadAndBindUBOs(pipeline); Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); } diff --git a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java index d516895d6a..b9c09713de 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java @@ -1,81 +1,12 @@ package net.vulkanmod.mixin.render; -import com.google.common.collect.ImmutableList; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.vulkan.memory.MemoryManager; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.io.IOException; -import java.util.Map; @Mixin(GameRenderer.class) public abstract class GameRendererMixin { - @Shadow @Final private Map shaders; - - @Shadow private @Nullable static ShaderInstance positionShader; - @Shadow private @Nullable static ShaderInstance positionColorShader; - @Shadow private @Nullable static ShaderInstance positionTexShader; - @Shadow private @Nullable static ShaderInstance positionTexColorShader; - @Shadow private @Nullable static ShaderInstance rendertypeTextShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiOverlayShader; - - @Shadow public ShaderInstance blitShader; - - @Shadow protected abstract ShaderInstance preloadShader(ResourceProvider resourceProvider, String string, VertexFormat vertexFormat); - - @Shadow public abstract float getRenderDistance(); - - /** - * @author - * @reason - */ - @Overwrite - private void shutdownShaders() { - RenderSystem.assertOnRenderThread(); - - final var clearList = ImmutableList.copyOf(this.shaders.values()); - MemoryManager.getInstance().addFrameOp(() -> clearList.forEach((ShaderInstance::close))); - - this.shaders.clear(); - } - - /** - * @author - * @reason - */ - @Overwrite - public void preloadUiShader(ResourceProvider resourceProvider) { - if (this.blitShader != null) { - throw new RuntimeException("Blit shader already preloaded"); - } else { - try { - this.blitShader = new ShaderInstance(resourceProvider, "blit_screen", DefaultVertexFormat.POSITION_TEX); - } catch (IOException var3) { - throw new RuntimeException("could not preload blit shader", var3); - } - - positionShader = this.preloadShader(resourceProvider, "position", DefaultVertexFormat.POSITION); - positionColorShader = this.preloadShader(resourceProvider, "position_color", DefaultVertexFormat.POSITION_COLOR); - positionTexShader = this.preloadShader(resourceProvider, "position_tex", DefaultVertexFormat.POSITION_TEX); - positionTexColorShader = this.preloadShader(resourceProvider, "position_tex_color", DefaultVertexFormat.POSITION_TEX_COLOR); - rendertypeTextShader = this.preloadShader(resourceProvider, "rendertype_text", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP); - - rendertypeGuiShader = positionColorShader; - rendertypeGuiOverlayShader = positionColorShader; - } - } - /** * @author * @reason diff --git a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java deleted file mode 100644 index b195f1a88f..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.shaders.Shader; -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.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.IOException; - -@Mixin(ProgramManager.class) -public class GlProgramManagerMixin { - - @Inject(method = "linkShader", at = @At("HEAD"), cancellable = true) - private static void linkProgram(Shader shader, CallbackInfo ci) throws IOException { - ci.cancel(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 17b59927e8..f538baa813 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -1,16 +1,25 @@ package net.vulkanmod.mixin.render; +import com.google.common.base.Charsets; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.jtracy.Plot; import net.vulkanmod.gl.*; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; +import org.lwjgl.PointerBuffer; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL20C; +import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.Shadow; import java.nio.ByteBuffer; import java.nio.IntBuffer; @@ -18,12 +27,16 @@ @Mixin(GlStateManager.class) public class GlStateManagerM { + @Shadow @Final private static Plot PLOT_BUFFERS; + + @Shadow private static int numBuffers; + /** * @author */ @Overwrite(remap = false) public static void _bindTexture(int i) { - VkGlTexture.bindTexture(i); + GlTexture.bindTexture(i); } /** @@ -51,6 +64,7 @@ public static void _enableBlend() { public static void _blendFunc(int i, int j) { RenderSystem.assertOnRenderThread(); VRenderSystem.blendFunc(i, j); + } /** @@ -60,15 +74,7 @@ public static void _blendFunc(int i, int j) { public static void _blendFuncSeparate(int i, int j, int k, int l) { RenderSystem.assertOnRenderThread(); VRenderSystem.blendFuncSeparate(i, j, k, l); - } - /** - * @author - */ - @Overwrite(remap = false) - public static void _blendEquation(int i) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.blendOp(i); } /** @@ -117,6 +123,7 @@ public static void _scissorBox(int x, int y, int width, int height) { Renderer.setScissor(x, y, width, height); } + //TODO /** * @author */ @@ -130,8 +137,8 @@ public static int _getError() { */ @Overwrite(remap = false) public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); } /** @@ -139,8 +146,8 @@ public static void _texImage2D(int target, int level, int internalFormat, int wi */ @Overwrite(remap = false) public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** @@ -148,7 +155,7 @@ public static void _texSubImage2D(int target, int level, int offsetX, int offset */ @Overwrite(remap = false) public static void _activeTexture(int i) { - VkGlTexture.activeTexture(i); + GlTexture.activeTexture(i); } /** @@ -156,7 +163,7 @@ public static void _activeTexture(int i) { */ @Overwrite(remap = false) public static void _texParameter(int i, int j, int k) { - VkGlTexture.texParameteri(i, j, k); + GlTexture.texParameteri(i, j, k); } /** @@ -172,7 +179,7 @@ public static void _texParameter(int i, int j, float k) { */ @Overwrite(remap = false) public static int _getTexLevelParameter(int i, int j, int k) { - return VkGlTexture.getTexLevelParameter(i, j, k); + return GlTexture.getTexLevelParameter(i, j, k); } /** @@ -180,8 +187,9 @@ public static int _getTexLevelParameter(int i, int j, int k) { */ @Overwrite(remap = false) public static void _pixelStore(int pname, int param) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.pixelStoreI(pname, param); + //Used during upload to set copy offsets + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.pixelStoreI(pname, param); } /** @@ -189,8 +197,8 @@ public static void _pixelStore(int pname, int param) { */ @Overwrite(remap = false) public static int _genTexture() { - RenderSystem.assertOnRenderThread(); - return VkGlTexture.genTextureId(); + RenderSystem.assertOnRenderThreadOrInit(); + return GlTexture.genTextureId(); } /** @@ -198,8 +206,8 @@ public static int _genTexture() { */ @Overwrite(remap = false) public static void _deleteTexture(int i) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.glDeleteTextures(i); + RenderSystem.assertOnRenderThreadOrInit(); + GlTexture.glDeleteTextures(i); } /** @@ -215,278 +223,261 @@ public static void _colorMask(boolean red, boolean green, boolean blue, boolean * @author */ @Overwrite(remap = false) - public static void _polygonMode(int face, int mode) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.setPolygonModeGL(mode); + public static void _depthFunc(int i) { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.depthFunc(i); } /** * @author */ @Overwrite(remap = false) - public static void _enablePolygonOffset() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enablePolygonOffset(); + public static void _clearColor(float f, float g, float h, float i) { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.setClearColor(f, g, h, i); } /** * @author */ @Overwrite(remap = false) - public static void _disablePolygonOffset() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disablePolygonOffset(); - } + public static void _clearDepth(double d) {} /** * @author */ @Overwrite(remap = false) - public static void _polygonOffset(float f, float g) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.polygonOffset(g, f); + public static void _clear(int mask) { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.clear(mask); } /** * @author */ @Overwrite(remap = false) - public static void _enableColorLogicOp() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enableColorLogicOp(); + public static void _disableDepthTest() { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.disableDepthTest(); } /** * @author */ @Overwrite(remap = false) - public static void _disableColorLogicOp() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disableColorLogicOp(); + public static void _enableDepthTest() { + RenderSystem.assertOnRenderThreadOrInit(); + VRenderSystem.enableDepthTest(); } /** * @author */ @Overwrite(remap = false) - public static void _logicOp(int i) { + public static void _depthMask(boolean bl) { RenderSystem.assertOnRenderThread(); - VRenderSystem.logicOp(i); + VRenderSystem.depthMask(bl); + } /** * @author */ @Overwrite(remap = false) - public static void _clearColor(float f, float g, float h, float i) { + public static int glGenFramebuffers() { RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.setClearColor(f, g, h, i); + return GlFramebuffer.genFramebufferId(); } /** * @author */ @Overwrite(remap = false) - public static void _clearDepth(double d) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.clearDepth(d); + public static int glGenRenderbuffers() { + RenderSystem.assertOnRenderThreadOrInit(); + return GlRenderbuffer.genId(); } /** * @author */ @Overwrite(remap = false) - public static void _clear(int mask, boolean bl) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.clear(mask); + public static void _glBindFramebuffer(int i, int j) { + RenderSystem.assertOnRenderThreadOrInit(); + GlFramebuffer.bindFramebuffer(i, j); } /** * @author */ @Overwrite(remap = false) - public static void _disableDepthTest() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disableDepthTest(); + public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { + RenderSystem.assertOnRenderThreadOrInit(); + GlFramebuffer.framebufferTexture2D(i, j, k, l, m); } /** * @author */ @Overwrite(remap = false) - public static void _enableDepthTest() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enableDepthTest(); + public static void _glBindRenderbuffer(int i, int j) { + RenderSystem.assertOnRenderThreadOrInit(); + GlRenderbuffer.bindRenderbuffer(i, j); } /** * @author */ @Overwrite(remap = false) - public static void _depthFunc(int i) { + public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.depthFunc(i); + GlFramebuffer.framebufferRenderbuffer(i, j, k, l); } /** * @author */ @Overwrite(remap = false) - public static void _depthMask(boolean bl) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.depthMask(bl); - + public static void _glRenderbufferStorage(int i, int j, int k, int l) { + RenderSystem.assertOnRenderThreadOrInit(); + GlRenderbuffer.renderbufferStorage(i, j, k, l); } /** * @author */ @Overwrite(remap = false) - public static int glGenFramebuffers() { - RenderSystem.assertOnRenderThread(); - return VkGlFramebuffer.genFramebufferId(); + public static int glCheckFramebufferStatus(int i) { + RenderSystem.assertOnRenderThreadOrInit(); + return GlFramebuffer.glCheckFramebufferStatus(i); } /** * @author */ @Overwrite(remap = false) - public static int glGenRenderbuffers() { + public static int _glGenBuffers() { RenderSystem.assertOnRenderThreadOrInit(); - return VkGlRenderbuffer.genId(); - } - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBindFramebuffer(int i, int j) { - RenderSystem.assertOnRenderThread(); - VkGlFramebuffer.bindFramebuffer(i, j); - } + numBuffers++; + PLOT_BUFFERS.setValue(numBuffers); - /** - * @author - */ - @Overwrite(remap = false) - public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { - RenderSystem.assertOnRenderThread(); - VkGlFramebuffer.framebufferTexture2D(i, j, k, l, m); + return GlBuffer.glGenBuffers(); } /** * @author */ @Overwrite(remap = false) - public static void _glBindRenderbuffer(int i, int j) { + public static void _glBindBuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - VkGlRenderbuffer.bindRenderbuffer(i, j); + GlBuffer.glBindBuffer(i, j); } /** * @author */ @Overwrite(remap = false) - public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { + public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { RenderSystem.assertOnRenderThreadOrInit(); - VkGlFramebuffer.framebufferRenderbuffer(i, j, k, l); + GlBuffer.glBufferData(i, byteBuffer, j); } /** * @author */ @Overwrite(remap = false) - public static void _glRenderbufferStorage(int i, int j, int k, int l) { + public static void _glBufferData(int i, long l, int j) { RenderSystem.assertOnRenderThreadOrInit(); - VkGlRenderbuffer.renderbufferStorage(i, j, k, l); + GlBuffer.glBufferData(i, l, j); } /** * @author */ @Overwrite(remap = false) - public static int glCheckFramebufferStatus(int i) { + @Nullable + public static ByteBuffer _glMapBuffer(int i, int j) { RenderSystem.assertOnRenderThreadOrInit(); - return VkGlFramebuffer.glCheckFramebufferStatus(i); + return GlBuffer.glMapBuffer(i, j); } /** * @author */ @Overwrite(remap = false) - public static int _glGenBuffers() { + public static void _glUnmapBuffer(int i) { RenderSystem.assertOnRenderThreadOrInit(); - return VkGlBuffer.glGenBuffers(); + GlBuffer.glUnmapBuffer(i); } /** * @author */ @Overwrite(remap = false) - public static void _glBindBuffer(int i, int j) { + public static void _glDeleteBuffers(int i) { RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBindBuffer(i, j); + GlBuffer.glDeleteBuffers(i); } /** * @author */ @Overwrite(remap = false) - public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBufferData(i, byteBuffer, j); - } + public static void _disableVertexAttribArray(int i) {} /** * @author */ @Overwrite(remap = false) - public static void _glBufferData(int i, long l, int j) { + public static void glDeleteShader(int i) { RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBufferData(i, l, j); + GlShader.glDeleteShader(i); } /** * @author */ @Overwrite(remap = false) - @Nullable - public static ByteBuffer _glMapBuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlBuffer.glMapBuffer(i, j); + public static int glCreateShader(int i) { + RenderSystem.assertOnRenderThread(); + return GlShader.glCreateShader(i); } /** * @author */ @Overwrite(remap = false) - public static void _glUnmapBuffer(int i) { + public static void glShaderSource(int i, String string) { RenderSystem.assertOnRenderThread(); - VkGlBuffer.glUnmapBuffer(i); + GlShader.glShaderSource(i, string); } /** * @author */ @Overwrite(remap = false) - public static void _glDeleteBuffers(int i) { + public static void glCompileShader(int i) { RenderSystem.assertOnRenderThread(); - VkGlBuffer.glDeleteBuffers(i); + GlShader.glCompileShader(i); } /** * @author */ @Overwrite(remap = false) - public static void _disableVertexAttribArray(int i) {} + public static int glGetShaderi(int i, int j) { + RenderSystem.assertOnRenderThread(); + return GlShader.glGetShaderi(i, j); + } /** * @author */ @Overwrite(remap = false) public static void _glUseProgram(int i) { - RenderSystem.assertOnRenderThread(); - VkGlProgram.glUseProgram(i); +// RenderSystem.assertOnRenderThread(); +// GL20.glUseProgram(i); } /** @@ -494,8 +485,9 @@ public static void _glUseProgram(int i) { */ @Overwrite(remap = false) public static int glCreateProgram() { - RenderSystem.assertOnRenderThread(); - return VkGlProgram.genProgramId(); +// RenderSystem.assertOnRenderThread(); +// return GL20.glCreateProgram(); + return 0; } /** @@ -503,17 +495,7 @@ public static int glCreateProgram() { */ @Overwrite(remap = false) public static void glDeleteProgram(int i) { - RenderSystem.assertOnRenderThread(); +// RenderSystem.assertOnRenderThread(); // GL20.glDeleteProgram(i); } - - /** - * @author - */ - @Overwrite(remap = false) - public static int _glGenVertexArrays() { - RenderSystem.assertOnRenderThreadOrInit(); - // TODO - return 0; - } } diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 2b42bbcdd1..3e36b6ff8a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -1,10 +1,12 @@ package net.vulkanmod.mixin.render; +import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.systems.TimerQuery; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; import net.minecraft.client.main.GameConfig; +import net.minecraft.util.profiling.ProfilerFiller; import net.vulkanmod.Initializer; import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.Renderer; @@ -17,6 +19,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Optional; @@ -24,6 +27,7 @@ @Mixin(Minecraft.class) public class MinecraftMixin { + @Shadow public boolean noRender; @Shadow @Final public Options options; @Inject(method = "", at = @At(value = "RETURN")) @@ -36,14 +40,55 @@ private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { } } + @Inject(method = "runTick", at = @At(value = "HEAD")) + private void preFrameOps(boolean bl, CallbackInfo ci) { + Renderer.getInstance().preInitFrame(); + } + + //Main target (framebuffer) ops + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(I)V")) + private void beginRender(int i, boolean bl) { + Renderer.getInstance().beginFrame(); +// RenderSystem.clear(i); + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;updateDisplay(Lcom/mojang/blaze3d/TracyFrameCapture;)V", shift = At.Shift.BEFORE)) + private void submitRender(boolean tick, CallbackInfo ci) { + Renderer.getInstance().endFrame(); + } + + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) + private void beginRender2(CallbackInfo ci) { + Renderer.getInstance().beginFrame(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) + private void redirectMainTarget1(RenderTarget instance, boolean bl) { + Renderer.getInstance().getMainPass().mainTargetBindWrite(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) + private void redirectMainTarget2(RenderTarget instance) { + Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); + } + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) + private void removeBlit(RenderTarget instance, int i, int j) { + } + + + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Ljava/lang/Thread;yield()V")) + private void removeThreadYield() { + } + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) private Optional removeTimer() { return Optional.empty(); } @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;tick()V"), - locals = LocalCapture.CAPTURE_FAILHARD) - private void redirectResourceTick(boolean bl, CallbackInfo ci, Runnable runnable, int i, int j) { + locals = LocalCapture.CAPTURE_FAILHARD) + private void redirectResourceTick(boolean bl, CallbackInfo ci, Runnable runnable, int i, ProfilerFiller profilerFiller, int j) { int n = Math.min(10, i) - 1; boolean doUpload = j == n; SpriteUpdateUtil.setDoUpload(doUpload); @@ -54,6 +99,7 @@ public void close(CallbackInfo ci) { Vulkan.waitIdle(); } + @Inject(method = "close", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/VirtualScreen;close()V")) public void close2(CallbackInfo ci) { Vulkan.cleanUp(); diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 1a173834ab..0b3a39ba76 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -1,7 +1,12 @@ package net.vulkanmod.mixin.render; +import com.mojang.blaze3d.ProjectionType; +import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexSorting; +import net.minecraft.client.renderer.FogParameters; +import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; @@ -12,6 +17,8 @@ import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import java.util.function.Consumer; + import static com.mojang.blaze3d.systems.RenderSystem.*; @Mixin(RenderSystem.class) @@ -20,20 +27,22 @@ public abstract class RenderSystemMixin { @Shadow private static Matrix4f projectionMatrix; @Shadow private static Matrix4f savedProjectionMatrix; @Shadow @Final private static Matrix4fStack modelViewStack; - @Shadow private static Matrix4f modelViewMatrix; @Shadow private static Matrix4f textureMatrix; @Shadow @Final private static float[] shaderColor; @Shadow @Final private static Vector3f[] shaderLightDirections; - @Shadow @Final private static float[] shaderFogColor; @Shadow private static @Nullable Thread renderThread; - @Shadow public static VertexSorting vertexSorting; - @Shadow private static VertexSorting savedVertexSorting; - @Shadow - public static void assertOnRenderThread() {} + public static void assertOnRenderThread() { + } + + @Shadow private static ProjectionType projectionType; + + @Shadow private static ProjectionType savedProjectionType; + + @Shadow private static FogParameters shaderFog; /** * @author @@ -51,6 +60,41 @@ public static void initRenderer(int debugVerbosity, boolean debugSync) { @Overwrite(remap = false) public static void setupDefaultState(int x, int y, int width, int height) { } + /** + * @author + */ + @Overwrite(remap = false) + public static void enableColorLogicOp() { + assertOnRenderThread(); + VRenderSystem.enableColorLogicOp(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disableColorLogicOp() { + assertOnRenderThread(); + VRenderSystem.disableColorLogicOp(); + } + + /** + * @author + */ + @Overwrite + public static void logicOp(GlStateManager.LogicOp op) { + assertOnRenderThread(); + VRenderSystem.logicOp(op); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void activeTexture(int texture) { + GlTexture.activeTexture(texture); + } + /** * @author */ @@ -59,6 +103,202 @@ public static int maxSupportedTextureSize() { return VRenderSystem.maxSupportedTextureSize(); } + /** + * @author + */ + @Overwrite(remap = false) + public static void clear(int mask) { + VRenderSystem.clear(mask); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void clearColor(float r, float g, float b, float a) { + VRenderSystem.setClearColor(r, g, b, a); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void clearDepth(double d) { + VRenderSystem.clearDepth(d); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void enableScissor(int x, int y, int width, int height) { + Renderer.setScissor(x, y, width, height); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disableScissor() { + Renderer.resetScissor(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disableDepthTest() { + assertOnRenderThread(); + //GlStateManager._disableDepthTest(); + VRenderSystem.disableDepthTest(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void enableDepthTest() { + assertOnRenderThreadOrInit(); + VRenderSystem.enableDepthTest(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void depthFunc(int i) { + assertOnRenderThread(); + VRenderSystem.depthFunc(i); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void depthMask(boolean b) { + assertOnRenderThread(); + VRenderSystem.depthMask(b); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + VRenderSystem.colorMask(red, green, blue, alpha); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void blendEquation(int i) { + assertOnRenderThread(); + //TODO + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void enableBlend() { + VRenderSystem.enableBlend(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disableBlend() { + VRenderSystem.disableBlend(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void blendFunc(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { + VRenderSystem.blendFunc(sourceFactor, destFactor); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void blendFunc(int srcFactor, int dstFactor) { + VRenderSystem.blendFunc(srcFactor, dstFactor); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void blendFuncSeparate(GlStateManager.SourceFactor p_69417_, GlStateManager.DestFactor p_69418_, GlStateManager.SourceFactor p_69419_, GlStateManager.DestFactor p_69420_) { + VRenderSystem.blendFuncSeparate(p_69417_, p_69418_, p_69419_, p_69420_); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void blendFuncSeparate(int srcFactorRGB, int dstFactorRGB, int srcFactorAlpha, int dstFactorAlpha) { + VRenderSystem.blendFuncSeparate(srcFactorRGB, dstFactorRGB, srcFactorAlpha, dstFactorAlpha); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void enableCull() { + assertOnRenderThread(); + VRenderSystem.enableCull(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disableCull() { + assertOnRenderThread(); + VRenderSystem.disableCull(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void polygonMode(final int face, final int mode) { + assertOnRenderThread(); + VRenderSystem.setPolygonModeGL(mode); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void enablePolygonOffset() { + assertOnRenderThread(); + VRenderSystem.enablePolygonOffset(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void disablePolygonOffset() { + assertOnRenderThread(); + VRenderSystem.disablePolygonOffset(); + } + + /** + * @author + */ + @Overwrite(remap = false) + public static void polygonOffset(float factor, float units) { + assertOnRenderThread(); + VRenderSystem.polygonOffset(factor, units); + } + /** * @author */ @@ -80,7 +320,7 @@ public static void setShaderLights(Vector3f dir0, Vector3f dir1) { * @author */ @Overwrite(remap = false) - private static void _setShaderColor(float r, float g, float b, float a) { + public static void setShaderColor(float r, float g, float b, float a) { shaderColor[0] = r; shaderColor[1] = g; shaderColor[2] = b; @@ -93,37 +333,24 @@ private static void _setShaderColor(float r, float g, float b, float a) { * @author */ @Overwrite(remap = false) - public static void setShaderFogColor(float f, float g, float h, float i) { - shaderFogColor[0] = f; - shaderFogColor[1] = g; - shaderFogColor[2] = h; - shaderFogColor[3] = i; + public static void setShaderFog(FogParameters fogParameters) { + assertOnRenderThread(); + shaderFog = fogParameters; - VRenderSystem.setShaderFogColor(f, g, h, i); + VRenderSystem.setShaderFogColor(fogParameters.red(), fogParameters.green(), fogParameters.blue(), fogParameters.alpha()); } /** * @author */ @Overwrite(remap = false) - public static void setProjectionMatrix(Matrix4f projectionMatrix, VertexSorting vertexSorting) { + public static void setProjectionMatrix(Matrix4f projectionMatrix, ProjectionType projectionType) { Matrix4f matrix4f = new Matrix4f(projectionMatrix); - if (!isOnRenderThread()) { - recordRenderCall(() -> { - RenderSystemMixin.projectionMatrix = matrix4f; - RenderSystem.vertexSorting = vertexSorting; - - VRenderSystem.applyProjectionMatrix(matrix4f); - VRenderSystem.calculateMVP(); - }); - } else { - RenderSystemMixin.projectionMatrix = matrix4f; - RenderSystem.vertexSorting = vertexSorting; - - VRenderSystem.applyProjectionMatrix(matrix4f); - VRenderSystem.calculateMVP(); - } + RenderSystemMixin.projectionMatrix = matrix4f; + RenderSystemMixin.projectionType = projectionType; + VRenderSystem.applyProjectionMatrix(matrix4f); + VRenderSystem.calculateMVP(); } /** @@ -156,38 +383,24 @@ public static void resetTextureMatrix() { } } + /** * @author */ @Overwrite(remap = false) - public static void applyModelViewMatrix() { - Matrix4f matrix4f = new Matrix4f(modelViewStack); - if (!isOnRenderThread()) { - recordRenderCall(() -> { - modelViewMatrix = matrix4f; - //Vulkan - VRenderSystem.applyModelViewMatrix(matrix4f); - VRenderSystem.calculateMVP(); - }); - } else { - modelViewMatrix = matrix4f; - - VRenderSystem.applyModelViewMatrix(matrix4f); - VRenderSystem.calculateMVP(); - } + public static void restoreProjectionMatrix() { + projectionMatrix = savedProjectionMatrix; + projectionType = savedProjectionType; + VRenderSystem.applyProjectionMatrix(projectionMatrix); + VRenderSystem.calculateMVP(); } /** * @author */ @Overwrite(remap = false) - private static void _restoreProjectionMatrix() { - projectionMatrix = savedProjectionMatrix; - vertexSorting = savedVertexSorting; - - VRenderSystem.applyProjectionMatrix(projectionMatrix); - VRenderSystem.calculateMVP(); + public static void texParameter(int target, int pname, int param) { + GlTexture.texParameteri(target, pname, param); } - } diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java deleted file mode 100644 index b63cd779f7..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ /dev/null @@ -1,356 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.google.gson.JsonObject; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.Initializer; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.interfaces.ShaderMixed; -import net.vulkanmod.render.shader.ShaderLoadUtil; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.layout.Uniform; -import net.vulkanmod.vulkan.shader.converter.GlslConverter; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.io.IOUtils; -import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -@Mixin(ShaderInstance.class) -public class ShaderInstanceM implements ShaderMixed { - - @Shadow @Final private Map uniformMap; - @Shadow @Final private String name; - - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform MODEL_VIEW_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform PROJECTION_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform COLOR_MODULATOR; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform LINE_WIDTH; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GLINT_ALPHA; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_START; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_END; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_COLOR; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_SHAPE; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform TEXTURE_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GAME_TIME; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform SCREEN_SIZE; - - @Shadow @Final private Map samplerMap; - @Shadow @Final private List samplerLocations; - @Shadow @Final private List samplerNames; - - @Shadow @Final private List uniforms; - @Shadow @Final private VertexFormat vertexFormat; - @Shadow @Final private int programId; - @Shadow private static int lastProgramId; - @Unique private String vsPath; - @Unique private String fsName; - - @Unique private GraphicsPipeline pipeline; - @Unique boolean doUniformUpdate = false; - - public GraphicsPipeline getPipeline() { - return pipeline; - } - - @Inject(method = "", at = @At("RETURN")) - private void create(ResourceProvider resourceProvider, String name, VertexFormat format, CallbackInfo ci) { - String configName = name; - JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); - - if (config == null) { - createLegacyShader(resourceProvider, format); - } else { - createPipeline(configName, format, config); - } - - VkGlProgram program = VkGlProgram.getProgram(this.programId); - program.bindPipeline(this.pipeline); - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;")) - private Program loadNames(ResourceProvider resourceProvider, Program.Type type, String name) { - String path; - if (this.name.contains(String.valueOf(ResourceLocation.NAMESPACE_SEPARATOR))) { - ResourceLocation location = ResourceLocation.tryParse(name); - path = location.withPath("shaders/core/%s".formatted(location.getPath())).toString(); - } else { - path = "shaders/core/%s".formatted(name); - } - - switch (type) { - case VERTEX -> this.vsPath = path; - case FRAGMENT -> this.fsName = path; - } - - return null; - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/shaders/Uniform;glBindAttribLocation(IILjava/lang/CharSequence;)V")) - private void bindAttr(int program, int index, CharSequence name) {} - - /** - * @author - */ - @Overwrite - public void close() { - if (this.pipeline != null) - this.pipeline.cleanUp(); - } - - /** - * @author - */ - @Overwrite - public void apply() { - if (this.doUniformUpdate) { - - for(int j = 0; j < this.samplerLocations.size(); ++j) { - String string = this.samplerNames.get(j); - if (this.samplerMap.get(string) != null) { - RenderSystem.activeTexture(33984 + j); - Object object = this.samplerMap.get(string); - int texId = -1; - if (object instanceof RenderTarget) { - texId = ((RenderTarget)object).getColorTextureId(); - } else if (object instanceof AbstractTexture) { - texId = ((AbstractTexture)object).getId(); - } else if (object instanceof Integer) { - texId = (Integer)object; - } - - if (texId != -1) { - RenderSystem.bindTexture(texId); - RenderSystem.setShaderTexture(j, texId); - } - } - } - - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.upload(); - } - - } - - if (this.programId != lastProgramId) { - ProgramManager.glUseProgram(this.programId); - lastProgramId = this.programId; - } - - bindPipeline(); - } - - /** - * @author - */ - @Overwrite - public void setDefaultUniforms(VertexFormat.Mode mode, Matrix4f modelView, Matrix4f projection, Window window) { - if (!this.doUniformUpdate) - return; - - if (this.MODEL_VIEW_MATRIX != null) { - this.MODEL_VIEW_MATRIX.set(modelView); - } - - if (this.PROJECTION_MATRIX != null) { - this.PROJECTION_MATRIX.set(projection); - } - - if (this.COLOR_MODULATOR != null) { - this.COLOR_MODULATOR.set(RenderSystem.getShaderColor()); - } - - if (this.GLINT_ALPHA != null) { - this.GLINT_ALPHA.set(RenderSystem.getShaderGlintAlpha()); - } - - if (this.FOG_START != null) { - this.FOG_START.set(RenderSystem.getShaderFogStart()); - } - - if (this.FOG_END != null) { - this.FOG_END.set(RenderSystem.getShaderFogEnd()); - } - - if (this.FOG_COLOR != null) { - this.FOG_COLOR.set(RenderSystem.getShaderFogColor()); - } - - if (this.FOG_SHAPE != null) { - this.FOG_SHAPE.set(RenderSystem.getShaderFogShape().getIndex()); - } - - if (this.TEXTURE_MATRIX != null) { - this.TEXTURE_MATRIX.set(RenderSystem.getTextureMatrix()); - } - - if (this.GAME_TIME != null) { - this.GAME_TIME.set(RenderSystem.getShaderGameTime()); - } - - if (this.SCREEN_SIZE != null) { - this.SCREEN_SIZE.set((float)window.getWidth(), (float)window.getHeight()); - } - - if (this.LINE_WIDTH != null && (mode == VertexFormat.Mode.LINES || mode == VertexFormat.Mode.LINE_STRIP)) { - this.LINE_WIDTH.set(RenderSystem.getShaderLineWidth()); - } - - RenderSystem.setupShaderLights((ShaderInstance) (Object) this); - } - - /** - * @author - */ - @Overwrite - public void clear() {} - - @Unique - private void bindPipeline() { - if (this.pipeline == null) { - throw new NullPointerException("Shader %s has no initialized pipeline".formatted(this.name)); - } - - Renderer renderer = Renderer.getInstance(); - renderer.bindGraphicsPipeline(pipeline); - VTextureSelector.bindShaderTextures(pipeline); - renderer.uploadAndBindUBOs(pipeline); - } - - public void setupUniformSuppliers(UBO ubo) { - for (Uniform vUniform : ubo.getUniforms()) { - com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(vUniform.getName()); - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); - - int size = vUniform.getSize(); - byteBuffer = MemoryUtil.memAlloc(size * 4); - } - else if (uniform.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); - } else if (uniform.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform); - } - - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - vUniform.setSupplier(supplier); - } - - } - - public Supplier getUniformSupplier(String name) { - com.mojang.blaze3d.shaders.Uniform uniform1 = this.uniformMap.get(name); - - if (uniform1 == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", name)); - return null; - } - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform1.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getIntBuffer()); - } else if (uniform1.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform1); - } - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - return supplier; - } - - @Override - public void setDoUniformsUpdate() { - this.doUniformUpdate = true; - } - - @Override - public void setPipeline(GraphicsPipeline graphicsPipeline) { - this.pipeline = graphicsPipeline; - } - - @Unique - private void createPipeline(String configName, VertexFormat format, JsonObject config) { - Pipeline.Builder builder = new Pipeline.Builder(format, configName); - builder.setUniformSupplierGetter(info -> this.getUniformSupplier(info.name)); - - builder.parseBindings(config); - - ShaderLoadUtil.loadShaders(builder, config, configName, "core"); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - this.pipeline = pipeline; - } - - @Unique - private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat format) { - try { - String vertPath = this.vsPath + ".vsh"; - Resource resource = resourceProvider.getResourceOrThrow(ResourceLocation.tryParse(vertPath)); - InputStream inputStream = resource.open(); - String vshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - String fragPath = this.fsName + ".fsh"; - resource = resourceProvider.getResourceOrThrow(ResourceLocation.tryParse(fragPath)); - inputStream = resource.open(); - String fshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - GlslConverter converter = new GlslConverter(); - Pipeline.Builder builder = new Pipeline.Builder(format, this.name); - - converter.process(vshSrc, fshSrc); - UBO ubo = converter.createUBO(); - this.setupUniformSuppliers(ubo); - this.setDoUniformsUpdate(); - - builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); - builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); - - this.pipeline = builder.createGraphicsPipeline(); - this.doUniformUpdate = true; - } catch (Exception e) { - Initializer.LOGGER.error("Error on shader {} conversion/compilation", this.name); - e.printStackTrace(); - } - } -} - diff --git a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java index 1f012d4721..2d07ba7803 100644 --- a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java +++ b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java @@ -28,7 +28,7 @@ public class BakedQuadM implements ModelQuadView { private QuadFacing facing; @Inject(method = "", at = @At("RETURN")) - private void onInit(int[] vertices, int tintIndex, Direction face, TextureAtlasSprite textureAtlasSprite, boolean shade, CallbackInfo ci) { + private void onInit(int[] vertices, int tintIndex, Direction face, TextureAtlasSprite textureAtlasSprite, boolean shade, int lightEmission, CallbackInfo ci) { this.flags = ModelQuadFlags.getQuadFlags(this, face); int packedNormal = NormalHelper.computePackedNormal(this); diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index a5680870ac..186d6ebd88 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -1,9 +1,14 @@ package net.vulkanmod.mixin.render.clouds; -import com.mojang.blaze3d.vertex.*; +import com.mojang.blaze3d.framegraph.FrameGraphBuilder; +import com.mojang.blaze3d.framegraph.FramePass; +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.resource.ResourceHandle; +import net.minecraft.client.CloudStatus; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.*; import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.sky.CloudRenderer; import org.jetbrains.annotations.Nullable; @@ -18,18 +23,39 @@ public abstract class LevelRendererM { @Shadow private int ticks; @Shadow private @Nullable ClientLevel level; + @Shadow @Final private LevelTargetBundle targets; - @Unique - private CloudRenderer cloudRenderer; + @Unique private CloudRenderer cloudRenderer; - @Inject(method = "renderClouds", at = @At("HEAD"), cancellable = true) - public void renderClouds(PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float partialTicks, double camX, double camY, double camZ, CallbackInfo ci) { + @Inject(method = "addCloudsPass", at = @At("HEAD"), cancellable = true) + public void addCloudsPass(FrameGraphBuilder frameGraphBuilder, Matrix4f modelView, Matrix4f projection, CloudStatus cloudStatus, Vec3 camPos, float partialTicks, int i, float g, CallbackInfo ci) { if (this.cloudRenderer == null) { this.cloudRenderer = new CloudRenderer(); } - this.cloudRenderer.renderClouds(this.level, poseStack, modelView, projection, this.ticks, partialTicks, camX, camY, camZ); - Profiler.getMainProfiler().pop(); + FramePass framePass = frameGraphBuilder.addPass("clouds"); + if (this.targets.clouds != null) { + this.targets.clouds = framePass.readsAndWrites(this.targets.clouds); + } else { + this.targets.main = framePass.readsAndWrites(this.targets.main); + } + + ResourceHandle resourceHandle = this.targets.clouds; + framePass.executes(() -> { + Profiler profiler = Profiler.getMainProfiler(); + profiler.push("Clouds"); + + if (resourceHandle != null) { + resourceHandle.get().setClearColor(0.0F, 0.0F, 0.0F, 0.0F); + resourceHandle.get().clear(); + } + + this.cloudRenderer.renderClouds(this.level, modelView, projection, this.ticks, partialTicks, + camPos.x(), camPos.y(), camPos.z()); + + profiler.pop(); + }); + ci.cancel(); } diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java index 30b9f31946..99c37ded09 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.render.entity; +import com.mojang.blaze3d.resource.GraphicsResourceAllocator; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -23,6 +24,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import java.util.List; import java.util.Map; @Mixin(LevelRenderer.class) @@ -39,7 +41,7 @@ public class LevelRendererM { target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V", shift = At.Shift.AFTER) ) - private void clearMap(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + private void clearMap(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { for (var bufferSource : this.bufferSourceMap.keySet()) { var entityMap = this.bufferSourceMap.get(bufferSource); entityMap.clear(); @@ -58,8 +60,7 @@ private void renderEntity(Entity entity, double d, double e, double f, float par double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - float k = Mth.lerp(partialTicks, entity.yRotO, entity.getYRot()); - this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, k, partialTicks, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); + this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, partialTicks, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); return; } @@ -70,18 +71,15 @@ private void renderEntity(Entity entity, double d, double e, double f, float par list.add(entity); } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;endLastBatch()V", - shift = At.Shift.AFTER, ordinal = 0) - ) - private void renderEntities(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + @Inject(method = "renderEntities", at = @At("RETURN")) + private void renderEntities(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource1, Camera camera, DeltaTracker deltaTracker, List entityList, CallbackInfo ci) { if (!Initializer.CONFIG.entityCulling) return; Vec3 cameraPos = WorldRenderer.getCameraPos(); TickRateManager tickRateManager = this.minecraft.level.tickRateManager(); - PoseStack poseStack = new PoseStack(); +// PoseStack poseStack = new PoseStack(); for (var bufferSource : this.bufferSourceMap.keySet()) { var entityMap = this.bufferSourceMap.get(bufferSource); @@ -93,8 +91,7 @@ private void renderEntities(DeltaTracker deltaTracker, boolean bl, Camera camera double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - float k = Mth.lerp(partialTicks, entity.yRotO, entity.getYRot()); - this.entityRenderDispatcher.render(entity, h - cameraPos.x, i - cameraPos.y, j - cameraPos.z, k, partialTicks, poseStack, bufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); + this.entityRenderDispatcher.render(entity, h - cameraPos.x, i - cameraPos.y, j - cameraPos.z, partialTicks, poseStack, bufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); } } } diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java index ecb2ffe272..871f7d1ae8 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java @@ -49,16 +49,16 @@ public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int cubeModel.transformVertices(matrix4f); for (ModelPart.Polygon polygon : polygons) { - matrix3f.transform(this.normal.set(polygon.normal)); + matrix3f.transform(this.normal.set(polygon.normal())); this.normal.normalize(); int packedNormal = I32_SNorm.packNormal(normal.x(), normal.y(), normal.z()); - ModelPart.Vertex[] vertices = polygon.vertices; + ModelPart.Vertex[] vertices = polygon.vertices(); for (ModelPart.Vertex vertex : vertices) { - Vector3f pos = vertex.pos; - vertexBuilder.vertex(pos.x(), pos.y(), pos.z(), color, vertex.u, vertex.v, overlay, light, packedNormal); + Vector3f pos = vertex.pos(); + vertexBuilder.vertex(pos.x(), pos.y(), pos.z(), color, vertex.u(), vertex.v(), overlay, light, packedNormal); } } } @@ -73,14 +73,14 @@ public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int cubeModel.transformVertices(matrix4f); for (ModelPart.Polygon polygon : polygons) { - matrix3f.transform(this.normal.set(polygon.normal)); + matrix3f.transform(this.normal.set(polygon.normal())); this.normal.normalize(); - ModelPart.Vertex[] vertices = polygon.vertices; + ModelPart.Vertex[] vertices = polygon.vertices(); for (ModelPart.Vertex vertex : vertices) { - Vector3f pos = vertex.pos; - vertexConsumer.addVertex(pos.x(), pos.y(), pos.z(), color, vertex.u, vertex.v, overlay, light, + Vector3f pos = vertex.pos(); + vertexConsumer.addVertex(pos.x(), pos.y(), pos.z(), color, vertex.u(), vertex.v(), overlay, light, normal.x(), normal.y(), normal.z()); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java index 5ab6450913..7bddb01365 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java @@ -42,7 +42,7 @@ public abstract class ItemRendererMixin { @Unique private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(() -> new ItemRenderContext(itemColors)); - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/resources/model/BakedModel;isCustomRenderer()Z"), method = "render", cancellable = true) + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/ItemRenderer;renderSimpleItemModel(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemDisplayContext;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/resources/model/BakedModel;Z)V"), method = "render", cancellable = true) public void hook_renderItem(ItemStack stack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int light, int overlay, BakedModel model, CallbackInfo ci) { if (!model.isVanillaAdapter()) { fabric_contexts.get().renderModel(stack, transformMode, invert, matrixStack, vertexConsumerProvider, light, overlay, model); diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java b/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java new file mode 100644 index 0000000000..e57610fc39 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java @@ -0,0 +1,111 @@ +package net.vulkanmod.mixin.render.shader; + +import com.google.gson.JsonObject; +import com.mojang.blaze3d.preprocessor.GlslPreprocessor; +import com.mojang.blaze3d.shaders.CompiledShader; +import net.minecraft.client.renderer.*; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.Initializer; +import net.vulkanmod.interfaces.shader.PipelineConfig; +import net.vulkanmod.interfaces.shader.ShaderMixed; +import net.vulkanmod.render.shader.ShaderLoadUtil; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.shader.parser.GlslConverter; +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; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Collections; +import java.util.Map; + +@Mixin(ShaderManager.CompilationCache.class) +public abstract class CompilationCacheM { + + @Shadow @Final private ShaderManager.Configs configs; + @Shadow @Final public Map shaders; + + @Inject(method = "compileProgram", at = @At("HEAD"), cancellable = true) + public void compileProgram(ShaderProgram shaderProgram, + CallbackInfoReturnable cir) throws ShaderManager.CompilationException { + ShaderProgramConfig shaderProgramConfig = this.configs.programs().get(shaderProgram.configId()); + if (shaderProgramConfig == null) { + throw new ShaderManager.CompilationException("Could not find program with id: " + shaderProgram.configId()); + } else { + cir.setReturnValue(createShaderProgram(shaderProgram, shaderProgramConfig)); + } + } + + private CompiledShaderProgram createShaderProgram(ShaderProgram shaderProgram, ShaderProgramConfig shaderProgramConfig) { + String configName = PipelineConfig.of(shaderProgramConfig).getName(); + + JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); + + if (config == null) { + GlslConverter converter = new GlslConverter(); + Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat(), configName); + + ShaderDefines shaderDefines = shaderProgramConfig.defines().withOverrides(shaderProgram.defines()); + String vshSrc = getShaderSource(shaderProgramConfig.vertex(), CompiledShader.Type.VERTEX, shaderDefines); + String fshSrc = getShaderSource(shaderProgramConfig.fragment(), CompiledShader.Type.FRAGMENT, shaderDefines); + + converter.process(vshSrc, fshSrc); + + UBO ubo = converter.createUBO(); + + builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); + builder.compileShaders(configName, converter.getVshConverted(), converter.getFshConverted()); + + GraphicsPipeline pipeline = builder.createGraphicsPipeline(); + CompiledShaderProgram compiledShaderProgram = createProgram(); + + compiledShaderProgram.setupUniforms(shaderProgramConfig.uniforms(), shaderProgramConfig.samplers()); + ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); + shaderMixed.setPipeline(pipeline); + + shaderMixed.setupUniformSuppliers(ubo); + shaderMixed.setUniformsUpdate(); + + return compiledShaderProgram; + } + + CompiledShaderProgram compiledShaderProgram = createProgram(); + compiledShaderProgram.setupUniforms(shaderProgramConfig.uniforms(), shaderProgramConfig.samplers()); + ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); + + Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat(), configName); + builder.setUniformSupplierGetter(info -> shaderMixed.getUniformSupplier(info.name)); + + builder.parseBindings(config); + + ShaderDefines shaderDefines = shaderProgramConfig.defines().withOverrides(shaderProgram.defines()); + + if (!shaderDefines.isEmpty()) { + Initializer.LOGGER.error("Shader {} is using external defines that are unsupported.", configName); + } + + ShaderLoadUtil.loadShaders(builder, config, configName, "core"); + + GraphicsPipeline pipeline = builder.createGraphicsPipeline(); + shaderMixed.setPipeline(pipeline); + + return compiledShaderProgram; + } + + private String getShaderSource(ResourceLocation resourceLocation, CompiledShader.Type type, ShaderDefines shaderDefines) { + ShaderManager.ShaderCompilationKey shaderCompilationKey = new ShaderManager.ShaderCompilationKey(resourceLocation, type, shaderDefines); + + String source = this.configs.shaderSources().get(new ShaderManager.ShaderSourceKey(shaderCompilationKey.id(), shaderCompilationKey.type())); + String processedSource = GlslPreprocessor.injectDefines(source, shaderCompilationKey.defines()); + + return processedSource; + } + + private static CompiledShaderProgram createProgram() { + return new CompiledShaderProgram(0); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java b/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java new file mode 100644 index 0000000000..4d0c65948e --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java @@ -0,0 +1,219 @@ +package net.vulkanmod.mixin.render.shader; + +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.shaders.CompiledShader; +import com.mojang.blaze3d.shaders.Uniform; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.VertexFormat; +import it.unimi.dsi.fastutil.ints.IntList; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.CompiledShaderProgram; +import net.minecraft.client.renderer.FogParameters; +import net.minecraft.client.renderer.ShaderManager; +import net.minecraft.client.renderer.ShaderProgramConfig; +import net.vulkanmod.Initializer; +import net.vulkanmod.interfaces.shader.ShaderMixed; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.util.MappedBuffer; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +@Mixin(CompiledShaderProgram.class) +public abstract class CompiledShaderProgramM implements ShaderMixed { + + @Shadow @Final private IntList samplerLocations; + @Shadow @Final private Object2IntMap samplerTextures; + @Shadow @Final private List samplers; + @Shadow @Final private Map uniformsByName; + + @Shadow @Nullable public Uniform MODEL_VIEW_MATRIX; + @Shadow @Nullable public Uniform PROJECTION_MATRIX; + @Shadow @Nullable public Uniform COLOR_MODULATOR; + @Shadow @Nullable public Uniform GLINT_ALPHA; + @Shadow @Nullable public Uniform FOG_START; + + GraphicsPipeline pipeline; + boolean updateUniforms = false; + + /** + * @author + * @reason + */ + @Overwrite + public static CompiledShaderProgram link(CompiledShader compiledShader, CompiledShader compiledShader2, VertexFormat vertexFormat) throws ShaderManager.CompilationException { + return new CompiledShaderProgram(0); + } + + @Shadow @Nullable public Uniform TEXTURE_MATRIX; + @Shadow @Nullable public Uniform SCREEN_SIZE; + @Shadow @Nullable public Uniform LIGHT0_DIRECTION; + @Shadow @Nullable public Uniform LIGHT1_DIRECTION; + @Shadow @Nullable public Uniform FOG_END; + @Shadow @Nullable public Uniform FOG_COLOR; + @Shadow @Nullable public Uniform FOG_SHAPE; + @Shadow @Nullable public Uniform LINE_WIDTH; + @Shadow @Nullable public Uniform GAME_TIME; + @Shadow @Nullable public Uniform MODEL_OFFSET; + + /** + * @author + * @reason + */ + @Overwrite + public void apply() { + if (!this.updateUniforms) { + return; + } + + for (int j = 0; j < this.samplerLocations.size(); j++) { + String string = this.samplers.get(j).name(); + int k = this.samplerTextures.getInt(string); + if (k != -1) { + int l = this.samplerLocations.getInt(j); + RenderSystem.activeTexture(33984 + j); + RenderSystem.bindTexture(k); + RenderSystem.setShaderTexture(j, k); + } + } + + if (this.MODEL_VIEW_MATRIX != null) { + this.MODEL_VIEW_MATRIX.set(RenderSystem.getModelViewMatrix()); + } + + if (this.PROJECTION_MATRIX != null) { + this.PROJECTION_MATRIX.set(RenderSystem.getProjectionMatrix()); + } + + if (this.COLOR_MODULATOR != null) { + this.COLOR_MODULATOR.set(RenderSystem.getShaderColor()); + } + + if (this.GLINT_ALPHA != null) { + this.GLINT_ALPHA.set(RenderSystem.getShaderGlintAlpha()); + } + + FogParameters fogParameters = RenderSystem.getShaderFog(); + if (this.FOG_START != null) { + this.FOG_START.set(fogParameters.start()); + } + + if (this.FOG_END != null) { + this.FOG_END.set(fogParameters.end()); + } + + if (this.FOG_COLOR != null) { + this.FOG_COLOR.set(fogParameters.red(), fogParameters.green(), fogParameters.blue(), fogParameters.alpha()); + } + + if (this.FOG_SHAPE != null) { + this.FOG_SHAPE.set(fogParameters.shape().getIndex()); + } + + if (this.TEXTURE_MATRIX != null) { + this.TEXTURE_MATRIX.set(RenderSystem.getTextureMatrix()); + } + + if (this.GAME_TIME != null) { + this.GAME_TIME.set(RenderSystem.getShaderGameTime()); + } + + if (this.SCREEN_SIZE != null) { + Window window = Minecraft.getInstance().getWindow(); + this.SCREEN_SIZE.set((float)window.getWidth(), (float)window.getHeight()); + } + + if (this.LINE_WIDTH != null) { + this.LINE_WIDTH.set(RenderSystem.getShaderLineWidth()); + } + } + + + + @Inject(method = "close", at = @At("RETURN")) + private void onClose(CallbackInfo ci) { + this.pipeline.scheduleCleanUp(); + } + + @Override + public void setPipeline(GraphicsPipeline graphicsPipeline) { + this.pipeline = graphicsPipeline; + } + + @Override + public GraphicsPipeline getPipeline() { + return pipeline; + } + + public void setupUniformSuppliers(UBO ubo) { + for (net.vulkanmod.vulkan.shader.layout.Uniform vUniform : ubo.getUniforms()) { + com.mojang.blaze3d.shaders.Uniform uniform = this.uniformsByName.get(vUniform.getName()); + + if (uniform == null) { + Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); + continue; + } + + Supplier supplier; + ByteBuffer byteBuffer; + + if (uniform.getType() <= 3) { + byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); + } else if (uniform.getType() <= 10) { + byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); + } else { + throw new RuntimeException("out of bounds value for uniform " + uniform); + } + + + MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); + supplier = () -> mappedBuffer; + + vUniform.setSupplier(supplier); + } + + } + + public Supplier getUniformSupplier(String name) { + com.mojang.blaze3d.shaders.Uniform uniform1 = this.uniformsByName.get(name); + + if (uniform1 == null) { + Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", name)); + return null; + } + + Supplier supplier; + ByteBuffer byteBuffer; + + if (uniform1.getType() <= 3) { + byteBuffer = MemoryUtil.memByteBuffer(uniform1.getIntBuffer()); + } else if (uniform1.getType() <= 10) { + byteBuffer = MemoryUtil.memByteBuffer(uniform1.getFloatBuffer()); + } else { + throw new RuntimeException("out of bounds value for uniform " + uniform1); + } + + MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); + supplier = () -> mappedBuffer; + + return supplier; + } + + @Override + public void setUniformsUpdate() { + this.updateUniforms = true; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java b/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java new file mode 100644 index 0000000000..1c5c98e234 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java @@ -0,0 +1,22 @@ +package net.vulkanmod.mixin.render.shader; + +import net.minecraft.client.renderer.ShaderProgramConfig; +import net.vulkanmod.interfaces.shader.PipelineConfig; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(ShaderProgramConfig.class) +public class ShadeProgramConfigM implements PipelineConfig { + + String name; + + + @Override + public String getName() { + return this.name; + } + + @Override + public void setName(String s) { + this.name = s; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java b/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java new file mode 100644 index 0000000000..c64e8ce156 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java @@ -0,0 +1,297 @@ +package net.vulkanmod.mixin.render.shader; + +import com.google.common.collect.ImmutableMap; +import com.google.gson.*; +import com.mojang.blaze3d.preprocessor.GlslPreprocessor; +import com.mojang.blaze3d.shaders.CompiledShader; +import com.mojang.serialization.JsonOps; +import it.unimi.dsi.fastutil.objects.ObjectArraySet; +import net.minecraft.FileUtil; +import net.minecraft.ResourceLocationException; +import net.minecraft.client.renderer.*; +import net.minecraft.resources.FileToIdConverter; +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.profiling.ProfilerFiller; +import net.vulkanmod.Initializer; +import net.vulkanmod.interfaces.shader.PipelineConfig; +import net.vulkanmod.interfaces.shader.ShaderMixed; +import net.vulkanmod.render.shader.ShaderLoadUtil; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.SPIRVUtils; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; + +@Mixin(ShaderManager.class) +public abstract class ShaderManagerM { + + @Shadow @Final private static FileToIdConverter PROGRAM_ID_CONVERTER; + + @Shadow private ShaderManager.CompilationCache compilationCache; + + @Shadow @Final private static Logger LOGGER; + @Shadow @Final private static FileToIdConverter POST_CHAIN_ID_CONVERTER; + + /** + * @author + * @reason + */ + @Overwrite + public void preloadForStartup(ResourceProvider resourceProvider, ShaderProgram... shaderPrograms) throws IOException { + for (ShaderProgram shaderProgram : shaderPrograms) { + ResourceLocation location = PROGRAM_ID_CONVERTER.idToFile(shaderProgram.configId()); + Resource resource = resourceProvider.getResourceOrThrow(location); + Reader reader = resource.openAsReader(); + + String locationPath = location.getPath(); + String configName = locationPath.split("/")[2]; + + // Remove .json suffix + configName = configName.substring(0, configName.length() - 5); + + try { + JsonElement jsonElement = JsonParser.parseReader(reader); + ShaderProgramConfig shaderProgramConfig = ShaderProgramConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow( + JsonSyntaxException::new); + + PipelineConfig.of(shaderProgramConfig).setName(configName); + + Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat()); + + JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); + builder.parseBindings(config); + + ShaderLoadUtil.loadShader(builder, configName, shaderProgramConfig.vertex().getPath(), SPIRVUtils.ShaderKind.VERTEX_SHADER); + ShaderLoadUtil.loadShader(builder, configName, shaderProgramConfig.fragment().getPath(), SPIRVUtils.ShaderKind.FRAGMENT_SHADER); + + GraphicsPipeline pipeline = builder.createGraphicsPipeline(); + CompiledShaderProgram compiledShaderProgram = createProgram(pipeline); + + this.compilationCache.programs.put(shaderProgram, Optional.of(compiledShaderProgram)); + } catch (Throwable var16) { + try { + reader.close(); + } catch (Throwable var15) { + var16.addSuppressed(var15); + } + + throw var16; + } + + reader.close(); + } + } + + /** + * @author + * @reason + */ + @Overwrite + public ShaderManager.Configs prepare(ResourceManager resourceManager, ProfilerFiller profilerFiller) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + ImmutableMap.Builder builder2 = ImmutableMap.builder(); + + Predicate filter = location -> !location.getNamespace().equals("vulkanmod") && (isProgram(location) || isShader(location)); + + Map map = resourceManager.listResources("shaders", filter); + + for (Map.Entry entry : map.entrySet()) { + ResourceLocation resourceLocation = entry.getKey(); + CompiledShader.Type type = CompiledShader.Type.byLocation(resourceLocation); + if (type != null) { + loadShader(resourceLocation, entry.getValue(), type, map, builder2); + } else if (isProgram(resourceLocation)) { + loadProgram(resourceLocation, entry.getValue(), builder); + } + } + + ImmutableMap.Builder builder3 = ImmutableMap.builder(); + + for (Map.Entry entry2 : POST_CHAIN_ID_CONVERTER.listMatchingResources(resourceManager).entrySet()) { + loadPostChain(entry2.getKey(), entry2.getValue(), builder3); + } + + return new ShaderManager.Configs(builder.build(), builder2.build(), builder3.build()); + } + + private static GlslPreprocessor createPreprocessor(Map map, ResourceLocation resourceLocation) { + final ResourceLocation resourceLocation2 = resourceLocation.withPath(FileUtil::getFullResourcePath); + return new GlslPreprocessor() { + private final Set importedLocations = new ObjectArraySet<>(); + + @Override + public String applyImport(boolean bl, String string) { + ResourceLocation resourceLocation; + try { + if (bl) { + resourceLocation = resourceLocation2.withPath( + string2 -> FileUtil.normalizeResourcePath(string2 + string)); + } else { + resourceLocation = ResourceLocation.parse(string).withPrefix("shaders/include/"); + } + } catch (ResourceLocationException var8) { + LOGGER.error("Malformed GLSL import {}: {}", string, var8.getMessage()); + return "#error " + var8.getMessage(); + } + + if (!this.importedLocations.add(resourceLocation)) { + return null; + } else { + try { + Reader reader = map.get(resourceLocation).openAsReader(); + + String var5; + try { + var5 = IOUtils.toString(reader); + } catch (Throwable var9) { + if (reader != null) { + try { + reader.close(); + } catch (Throwable var7) { + var9.addSuppressed(var7); + } + } + + throw var9; + } + + if (reader != null) { + reader.close(); + } + + return var5; + } catch (IOException var10) { + LOGGER.error("Could not open GLSL import {}: {}", resourceLocation, var10.getMessage()); + return "#error " + var10.getMessage(); + } + } + } + }; + } + + private static void loadProgram(ResourceLocation resourceLocation, Resource resource, ImmutableMap.Builder builder) { + ResourceLocation resourceLocation2 = PROGRAM_ID_CONVERTER.fileToId(resourceLocation); + + try { + Reader reader = resource.openAsReader(); + + try { + JsonElement jsonElement = JsonParser.parseReader(reader); + ShaderProgramConfig shaderProgramConfig = ShaderProgramConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow(JsonSyntaxException::new); + + String configPath = resourceLocation.getPath(); + String configName = configPath.split("/")[2]; + + // Remove .json suffix + configName = configName.substring(0, configName.length() - 5); + + PipelineConfig.of(shaderProgramConfig).setName(configName); + + builder.put(resourceLocation2, shaderProgramConfig); + } catch (Throwable var8) { + try { + reader.close(); + } catch (Throwable var7) { + var8.addSuppressed(var7); + } + + throw var8; + } + + reader.close(); + } catch (JsonParseException | IOException var9) { + LOGGER.error("Failed to parse shader config at {}", resourceLocation, var9); + } + } + + private static void loadPostChain(ResourceLocation resourceLocation, Resource resource, ImmutableMap.Builder builder) { + ResourceLocation resourceLocation2 = POST_CHAIN_ID_CONVERTER.fileToId(resourceLocation); + + try { + Reader reader = resource.openAsReader(); + + try { + JsonElement jsonElement = JsonParser.parseReader(reader); + builder.put(resourceLocation2, PostChainConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow(JsonSyntaxException::new)); + } catch (Throwable var8) { + if (reader != null) { + try { + reader.close(); + } catch (Throwable var7) { + var8.addSuppressed(var7); + } + } + + throw var8; + } + + if (reader != null) { + reader.close(); + } + } catch (JsonParseException | IOException var9) { + LOGGER.error("Failed to parse post chain at {}", resourceLocation, var9); + } + } + + private static boolean isProgram(ResourceLocation resourceLocation) { + return resourceLocation.getPath().endsWith(".json"); + } + + private static boolean isShader(ResourceLocation resourceLocation) { + return CompiledShader.Type.byLocation(resourceLocation) != null || resourceLocation.getPath().endsWith(".glsl"); + } + + private static void loadShader( + ResourceLocation resourceLocation, Resource resource, CompiledShader.Type type, Map map, ImmutableMap.Builder builder + ) { + ResourceLocation resourceLocation2 = type.idConverter().fileToId(resourceLocation); + GlslPreprocessor glslPreprocessor = createPreprocessor(map, resourceLocation); + + try { + Reader reader = resource.openAsReader(); + + try { + String string = IOUtils.toString(reader); + builder.put(new ShaderManager.ShaderSourceKey(resourceLocation2, type), String.join("", glslPreprocessor.process(string))); + } catch (Throwable var11) { + try { + reader.close(); + } catch (Throwable var10) { + var11.addSuppressed(var10); + } + + throw var11; + } + + reader.close(); + } catch (IOException var12) { + LOGGER.error("Failed to load shader source at {}", resourceLocation, var12); + } + } + + private static CompiledShaderProgram createProgram(GraphicsPipeline pipeline) { + CompiledShaderProgram compiledShaderProgram = new CompiledShaderProgram(0); + ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); + shaderMixed.setPipeline(pipeline); + + return compiledShaderProgram; + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java index 4579ba83c3..ea58c807a2 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java @@ -3,8 +3,14 @@ import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.VkGlFramebuffer; -import net.vulkanmod.gl.VkGlTexture; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.CompiledShaderProgram; +import net.minecraft.client.renderer.CoreShaders; +import net.vulkanmod.gl.GlFramebuffer; +import net.vulkanmod.gl.GlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -17,6 +23,8 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import java.util.Objects; + @Mixin(RenderTarget.class) public abstract class RenderTargetMixin { @@ -39,15 +47,15 @@ public abstract class RenderTargetMixin { * @author */ @Overwrite - public void clear(boolean getError) { + public void clear() { RenderSystem.assertOnRenderThreadOrInit(); if(!Renderer.isRecording()) return; // If the framebuffer is not bound postpone clear - VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId); - if(!bound || VkGlFramebuffer.getBoundFramebuffer() != glFramebuffer) { + GlFramebuffer glFramebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId); + if (!bound || GlFramebuffer.getBoundFramebuffer() != glFramebuffer) { needClear = true; return; } @@ -59,7 +67,7 @@ public void clear(boolean getError) { i |= 256; } - GlStateManager._clear(i, getError); + GlStateManager._clear(i); needClear = false; } @@ -72,11 +80,11 @@ public void bindRead() { applyClear(); - VkGlTexture.bindTexture(this.colorTextureId); + GlTexture.bindTexture(this.colorTextureId); try (MemoryStack stack = MemoryStack.stackPush()) { - VkGlTexture.getBoundTexture().getVulkanImage() - .readOnlyLayout(stack, Renderer.getCommandBuffer()); + GlTexture.getBoundTexture().getVulkanImage() + .readOnlyLayout(stack, Renderer.getCommandBuffer()); } } @@ -86,24 +94,24 @@ public void bindRead() { @Overwrite public void unbindRead() { RenderSystem.assertOnRenderThreadOrInit(); - VkGlTexture.bindTexture(0); + GlTexture.bindTexture(0); } /** * @author */ @Overwrite - private void _bindWrite(boolean bl) { + public void bindWrite(boolean bl) { RenderSystem.assertOnRenderThreadOrInit(); - VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); + GlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); if (bl) { GlStateManager._viewport(0, 0, this.viewWidth, this.viewHeight); } this.bound = true; if (needClear) - clear(false); + clear(); } /** @@ -122,11 +130,11 @@ public void unbindWrite() { } } - @Inject(method = "_blitToScreen", at = @At("HEAD"), cancellable = true) - private void _blitToScreen(int width, int height, boolean disableBlend, CallbackInfo ci) { + @Inject(method = "blitToScreen", at = @At("HEAD"), cancellable = true) + private void blitToScreen(int width, int height, CallbackInfo ci) { // If the target needs clear it means it has not been used, thus we can skip blit if (!this.needClear) { - Framebuffer framebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); + Framebuffer framebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); VTextureSelector.bindTexture(0, framebuffer.getColorAttachment()); DrawUtil.blitToScreen(); @@ -135,6 +143,43 @@ private void _blitToScreen(int width, int height, boolean disableBlend, Callback ci.cancel(); } + /** + * @author + * @reason + */ + @Overwrite + public void blitAndBlendToScreen(int i, int j) { + RenderSystem.assertOnRenderThread(); + + if (this.needClear) { + return; + } + + GlStateManager._colorMask(true, true, true, false); + GlStateManager._disableDepthTest(); + GlStateManager._depthMask(false); + GlStateManager._viewport(0, 0, i, j); + + CompiledShaderProgram compiledShaderProgram = Objects.requireNonNull( + RenderSystem.setShader(CoreShaders.BLIT_SCREEN), "Blit shader not loaded" + ); + + int prevTexture = RenderSystem.getShaderTexture(0); + RenderSystem.setShaderTexture(0, this.colorTextureId); + +// compiledShaderProgram.bindSampler("InSampler", this.colorTextureId); + BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN); + bufferBuilder.addVertex(0.0F, 0.0F, 0.0F); + bufferBuilder.addVertex(1.0F, 0.0F, 0.0F); + bufferBuilder.addVertex(1.0F, 1.0F, 0.0F); + bufferBuilder.addVertex(0.0F, 1.0F, 0.0F); + BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + + RenderSystem.setShaderTexture(0, prevTexture); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); + } + @Inject(method = "getColorTextureId", at = @At("HEAD")) private void injClear(CallbackInfoReturnable cir) { applyClear(); @@ -143,12 +188,12 @@ private void injClear(CallbackInfoReturnable cir) { @Unique private void applyClear() { if (this.needClear) { - VkGlFramebuffer currentFramebuffer = VkGlFramebuffer.getBoundFramebuffer(); + GlFramebuffer currentFramebuffer = GlFramebuffer.getBoundFramebuffer(); - this._bindWrite(false); + this.bindWrite(false); if (currentFramebuffer != null) { - VkGlFramebuffer.beginRendering(currentFramebuffer); + GlFramebuffer.beginRendering(currentFramebuffer); } } } diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java index e355ccadd5..a815f5a38a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java @@ -1,9 +1,12 @@ package net.vulkanmod.mixin.render.vertex; +import com.mojang.blaze3d.buffers.BufferType; +import com.mojang.blaze3d.buffers.BufferUsage; +import com.mojang.blaze3d.buffers.GpuBuffer; import com.mojang.blaze3d.vertex.ByteBufferBuilder; import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexBuffer; -import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.CompiledShaderProgram; import net.vulkanmod.render.VBO; import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; @@ -19,14 +22,14 @@ public class VertexBufferM { private VBO vbo; @Inject(method = "", at = @At("RETURN")) - private void constructor(VertexBuffer.Usage usage, CallbackInfo ci) { + private void constructor(BufferUsage usage, CallbackInfo ci) { vbo = new VBO(usage); } - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenBuffers()I")) - private int doNothing() { - return 0; - } +// @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/buffers/GpuBuffer;(Lcom/mojang/blaze3d/buffers/BufferType;Lcom/mojang/blaze3d/buffers/BufferUsage;I)V")) +// private void doNothing(GpuBuffer instance, BufferType bufferType, BufferUsage bufferUsage, int i) { +// instance = null; +// } @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenVertexArrays()I")) private int doNothing2() { @@ -65,7 +68,7 @@ public void uploadIndexBuffer(ByteBufferBuilder.Result result) { * @author */ @Overwrite - public void drawWithShader(Matrix4f viewMatrix, Matrix4f projectionMatrix, ShaderInstance shader) { + public void drawWithShader(Matrix4f viewMatrix, Matrix4f projectionMatrix, CompiledShaderProgram shader) { vbo.drawWithShader(viewMatrix, projectionMatrix, shader); } diff --git a/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java b/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java index e41785636a..49043c5d86 100644 --- a/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java +++ b/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java @@ -11,7 +11,7 @@ public class ScreenM { @Inject(method = "renderBlurredBackground", at = @At("RETURN")) - private void clearDepth(float f, CallbackInfo ci) { + private void clearDepth(CallbackInfo ci) { // Workaround to fix hardcoded z value on PostPass blit shader, // that conflicts with Vulkan depth range [0.0, 1.0] Renderer.clearAttachments(256); diff --git a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java index fa7a99ce5f..882a1b7290 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java @@ -11,11 +11,11 @@ @Mixin(AbstractTexture.class) public abstract class MAbstractTexture { - @Shadow protected boolean blur; - @Shadow protected boolean mipmap; - @Shadow protected int id; + private boolean blur; + private boolean mipmap; + /** * @author */ diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java index 6eecb8cc31..34bd443331 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java @@ -37,12 +37,6 @@ public abstract class MNativeImage { @Shadow public abstract int getHeight(); - @Shadow public abstract void setPixelRGBA(int i, int j, int k); - - @Shadow public abstract int getPixelRGBA(int i, int j); - - @Shadow protected abstract void checkAllocated(); - private ByteBuffer buffer; @Inject(method = "(Lcom/mojang/blaze3d/platform/NativeImage$Format;IIZ)V", at = @At("RETURN")) diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java index e807e35bfd..39c521afb8 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.texture.update; +import com.mojang.blaze3d.pipeline.TextureTarget; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; @@ -8,6 +9,8 @@ import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.util.Mth; +import net.minecraft.util.profiling.Profiler; +import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.LivingEntity; @@ -27,21 +30,36 @@ public class MLightTexture { @Shadow @Final private Minecraft minecraft; @Shadow @Final private GameRenderer renderer; + @Shadow @Final private TextureTarget target; @Shadow private boolean updateLightTexture; @Shadow private float blockLightRedFlicker; - @Shadow @Final private DynamicTexture lightTexture; - @Shadow @Final private NativeImage lightPixels; - + private DynamicTexture lightTexture; + private NativeImage lightPixels; private Vector3f[] tempVecs; @Inject(method = "", at = @At("RETURN")) private void onInit(GameRenderer gameRenderer, Minecraft minecraft, CallbackInfo ci) { + initLightMap(); + this.tempVecs = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; } + private void initLightMap() { + this.lightTexture = new DynamicTexture(16, 16, false); + this.lightPixels = this.lightTexture.getPixels(); + + for(int i = 0; i < 16; ++i) { + for(int j = 0; j < 16; ++j) { + this.lightPixels.setPixel(j, i, 0xFFFFFFFF); + } + } + + this.lightTexture.upload(); + } + /** * @author * @reason @@ -57,7 +75,8 @@ public void updateLightTexture(float partialTicks, CallbackInfo ci) { if (this.updateLightTexture) { this.updateLightTexture = false; - this.minecraft.getProfiler().push("lightTex"); + ProfilerFiller profilerFiller = Profiler.get(); + profilerFiller.push("lightTex"); // TODO: Other mods might be changing lightmap behaviour, we can't be aware of that here @@ -162,9 +181,7 @@ public void updateLightTexture(float partialTicks, CallbackInfo ci) { VkGlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); } - ImageUploadHelper.INSTANCE.submitCommands(); - - this.minecraft.getProfiler().pop(); + profilerFiller.pop(); } } diff --git a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java index 842c44fd2b..6a23dcf26b 100644 --- a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java +++ b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java @@ -123,7 +123,7 @@ public void vertex(float x, float y, float z, int packedColor, float u, float v, position.set(x, y , z, 1.0f); this.normalInversePose.transform(normal); - Direction direction = Direction.getNearest(normal.x(), normal.y(), normal.z()); + Direction direction = Direction.getApproximateNearest(normal.x(), normal.y(), normal.z()); this.cameraInversePose.transform(position); position.rotateY(3.1415927F); position.rotateX(-1.5707964F); diff --git a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java index 5f4c71ce83..7d06b2a6bb 100644 --- a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java +++ b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.window; +import com.mojang.blaze3d.TracyFrameCapture; import com.mojang.blaze3d.platform.*; import com.mojang.blaze3d.systems.RenderSystem; import net.vulkanmod.Initializer; @@ -12,6 +13,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.Vulkan; +import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GLCapabilities; import org.slf4j.Logger; @@ -32,8 +34,6 @@ public abstract class WindowMixin { @Shadow private boolean vsync; - @Shadow protected abstract void updateFullscreen(boolean bl); - @Shadow private boolean fullscreen; @Shadow @Final private static Logger LOGGER; @@ -54,6 +54,8 @@ public abstract class WindowMixin { @Shadow public abstract int getHeight(); + @Shadow protected abstract void updateFullscreen(boolean bl, @Nullable TracyFrameCapture tracyFrameCapture); + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwWindowHint(II)V")) private void redirect(int hint, int value) { } @@ -110,12 +112,17 @@ public void toggleFullScreen() { * @author */ @Overwrite - public void updateDisplay() { - RenderSystem.flipFrame(this.window); + public void updateDisplay(@Nullable TracyFrameCapture tracyFrameCapture) { + RenderSystem.flipFrame(this.window, tracyFrameCapture); + +// if (this.fullscreen != this.actuallyFullscreen) { +// this.actuallyFullscreen = this.fullscreen; +// this.updateFullscreen(this.vsync, tracyFrameCapture); +// } if (Options.fullscreenDirty) { Options.fullscreenDirty = false; - this.updateFullscreen(this.vsync); + this.updateFullscreen(this.vsync, tracyFrameCapture); } } diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 48f10decbd..3e981572f3 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -1,12 +1,13 @@ package net.vulkanmod.render; +import com.mojang.blaze3d.buffers.BufferUsage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexFormat; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.renderer.CompiledShaderProgram; +import net.vulkanmod.interfaces.shader.ShaderMixed; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.*; @@ -14,6 +15,7 @@ import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; import net.vulkanmod.vulkan.memory.buffer.index.AutoIndexBuffer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.joml.Matrix4f; @@ -25,13 +27,15 @@ public class VBO { private VertexBuffer vertexBuffer; private IndexBuffer indexBuffer; - private VertexFormat.Mode mode; - private boolean autoIndexed = false; private int indexCount; private int vertexCount; + private VertexFormat.Mode mode; + + AutoIndexBuffer autoIndexBuffer; + private boolean autoIndexed = false; - public VBO(com.mojang.blaze3d.vertex.VertexBuffer.Usage usage) { - this.memoryType = usage == com.mojang.blaze3d.vertex.VertexBuffer.Usage.STATIC ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; + public VBO(BufferUsage usage) { + this.memoryType = usage == BufferUsage.STATIC_WRITE ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; } public void upload(MeshData meshData) { @@ -92,50 +96,38 @@ public void uploadIndexBuffer(ByteBuffer data) { if (autoIndexBuffer != null) { autoIndexBuffer.checkCapacity(this.vertexCount); - this.indexBuffer = autoIndexBuffer.getIndexBuffer(); + this.autoIndexBuffer = autoIndexBuffer; } this.autoIndexed = true; - } - else { - if (this.indexBuffer != null && !this.autoIndexed) { + + } else { + if (this.indexBuffer != null) this.indexBuffer.scheduleFree(); - } this.indexBuffer = new IndexBuffer(data.remaining(), MemoryTypes.GPU_MEM); this.indexBuffer.copyBuffer(data, data.remaining()); } + } - public void drawWithShader(Matrix4f modelView, Matrix4f projection, ShaderInstance shaderInstance) { + public void drawWithShader(Matrix4f MV, Matrix4f P, CompiledShaderProgram shader) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); - RenderSystem.setShader(() -> shaderInstance); - - VRenderSystem.applyMVP(modelView, projection); - VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); - - shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, modelView, projection, Minecraft.getInstance().getWindow()); - shaderInstance.apply(); - - if (this.indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - } - else { - Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); - } + RenderSystem.setShader(shader); - // Reset MVP to previous state - VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); + GraphicsPipeline pipeline = ShaderMixed.of(shader).getPipeline(); + drawWithShader(MV, P, pipeline); } } - public void drawWithShader(Matrix4f modelView, Matrix4f projection, GraphicsPipeline pipeline) { + public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); - VRenderSystem.applyMVP(modelView, projection); + VRenderSystem.applyMVP(MV, P); + VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); Renderer renderer = Renderer.getInstance(); @@ -143,26 +135,34 @@ public void drawWithShader(Matrix4f modelView, Matrix4f projection, GraphicsPipe VTextureSelector.bindShaderTextures(pipeline); renderer.uploadAndBindUBOs(pipeline); - if (this.indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); + IndexBuffer indexBuffer; + if (this.autoIndexBuffer != null) { + indexBuffer = this.autoIndexBuffer.getIndexBuffer(); + } else { + indexBuffer = this.indexBuffer; + } + + if (indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, indexBuffer, this.indexCount); } else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); } - // Reset MVP to previous state VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); + } } public void draw() { if (this.indexCount != 0) { - if (this.indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - } - else { - Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); - } + RenderSystem.assertOnRenderThread(); + + Renderer renderer = Renderer.getInstance(); + Pipeline pipeline = renderer.getBoundPipeline(); + renderer.uploadAndBindUBOs(pipeline); + + Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java index b6d142b227..f7075774a8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java +++ b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java @@ -31,7 +31,7 @@ public SectionGrid(Level level, int viewDistance) { this.level = level; this.setViewDistance(viewDistance); this.createChunks(); - this.chunkAreaManager = new ChunkAreaManager(this.gridWidth, this.gridHeight, this.level.getMinBuildHeight()); + this.chunkAreaManager = new ChunkAreaManager(this.gridWidth, this.gridHeight, this.level.getMinY()); this.prevSecX = Integer.MIN_VALUE; this.prevSecZ = Integer.MIN_VALUE; @@ -180,7 +180,7 @@ private void moveSection(int xRelativeIndex, int yRel, int zRelativeIndex, CircularIntList xList, CircularIntList zList, int xCurrentIdx, int zCurrentIdx) { - int y1 = this.level.getMinBuildHeight() + (yRel << 4); + int y1 = this.level.getMinY() + (yRel << 4); RenderSection renderSection = this.sections[this.getChunkIndex(xRelativeIndex, yRel, zRelativeIndex)]; this.unsetNeighbours(renderSection); @@ -281,7 +281,7 @@ private void setChunkArea(RenderSection section, int x, int y, int z) { public void setDirty(int sectionX, int sectionY, int sectionZ, boolean playerChanged) { int i = Math.floorMod(sectionX, this.gridWidth); - int j = Math.floorMod(sectionY - this.level.getMinSection(), this.gridHeight); + int j = Math.floorMod(sectionY - this.level.getMinSectionY(), this.gridHeight); int k = Math.floorMod(sectionZ, this.gridWidth); RenderSection renderSection = this.sections[this.getChunkIndex(i, j, k)]; renderSection.setDirty(playerChanged); @@ -294,7 +294,7 @@ public RenderSection getSectionAtBlockPos(BlockPos blockPos) { public RenderSection getSectionAtBlockPos(int x, int y, int z) { int i = x >> 4; - int j = (y - this.level.getMinBuildHeight()) >> 4; + int j = (y - this.level.getMinY()) >> 4; int k = z >> 4; return this.getSectionAtSectionPos(i, j, k); diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index c8fed57c51..2fc12a79a1 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -19,6 +19,8 @@ import net.minecraft.core.SectionPos; import net.minecraft.server.level.BlockDestructionProgress; import net.minecraft.util.Mth; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.util.profiling.Zone; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; @@ -136,6 +138,8 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus Profiler profiler = Profiler.getMainProfiler(); profiler.push("Setup_Renderer"); + ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); + benchCallback(); this.cameraPos = camera.getPosition(); @@ -143,7 +147,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus this.allChanged(); } - this.level.getProfiler().push("camera"); + mcProfiler.push("camera"); float cameraX = (float) cameraPos.x(); float cameraY = (float) cameraPos.y(); float cameraZ = (float) cameraPos.z(); @@ -163,10 +167,9 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus double entityDistanceScaling = this.minecraft.options.entityDistanceScaling().get(); Entity.setViewScale(Mth.clamp((double) this.renderDistance / 8.0D, 1.0D, 2.5D) * entityDistanceScaling); - this.level.getProfiler().popPush("cull"); - this.minecraft.getProfiler().popPush("culling"); + mcProfiler.popPush("cull"); - this.minecraft.getProfiler().popPush("update"); + mcProfiler.popPush("update"); boolean cameraMoved = false; float d_xRot = Math.abs(camera.getXRot() - this.lastCamRotX); @@ -194,12 +197,13 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus this.indirectBuffers[Renderer.getCurrentFrame()].reset(); - this.minecraft.getProfiler().pop(); + mcProfiler.pop(); profiler.pop(); } public void uploadSections() { - this.minecraft.getProfiler().push("upload"); + ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); + mcProfiler.push("upload"); Profiler profiler = Profiler.getMainProfiler(); profiler.push("Uploads"); @@ -214,7 +218,7 @@ public void uploadSections() { profiler.pop(); - this.minecraft.getProfiler().pop(); + mcProfiler.pop(); } public boolean isSectionCompiled(BlockPos blockPos) { @@ -294,8 +298,8 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, this.sortTranslucentSections(camX, camY, camZ); - this.minecraft.getProfiler().push("filterempty"); - this.minecraft.getProfiler().popPush(() -> "render_" + renderType); + ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); + Zone zone = mcProfiler.zone(() -> "render_" + renderType); final boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; final boolean indirectDraw = Initializer.CONFIG.indirectDraw; @@ -347,12 +351,13 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, renderer.pushConstants(pipeline); } - this.minecraft.getProfiler().pop(); + zone.close(); renderType.clearRenderState(); } private void sortTranslucentSections(double camX, double camY, double camZ) { - this.minecraft.getProfiler().push("translucent_sort"); + ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); + mcProfiler.push("translucent_sort"); double d0 = camX - this.xTransparentOld; double d1 = camY - this.yTransparentOld; double d2 = camZ - this.zTransparentOld; @@ -374,7 +379,7 @@ private void sortTranslucentSections(double camX, double camY, double camZ) { } } - this.minecraft.getProfiler().pop(); + mcProfiler.pop(); } public void renderBlockEntities(PoseStack poseStack, double camX, double camY, double camZ, diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 94a19358b1..4d01f40c64 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -193,8 +193,8 @@ public int getBlockTint(BlockPos blockPos, ColorResolver colorResolver) { return tintCache.getColor(blockPos, colorResolver); } - public int getMinBuildHeight() { - return this.level.getMinBuildHeight(); + public int getMinY() { + return this.level.getMinY(); } public int getHeight() { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java index dc33176367..98a3ab4355 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java @@ -41,10 +41,11 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { DataLayer[][] lightData = new DataLayer[RenderRegion.SIZE][2 /* Light types */]; + final int minHeightSec = level.getMinY() >> 4; long biomeZoomSeed = BiomeManagerExtended.of(level.getBiomeManager()).getBiomeZoomSeed(); BiomeData biomeData = new BiomeData(biomeZoomSeed, minSecX, minSecY, minSecZ); - final int minHeightSec = level.getMinBuildHeight() >> 4; + final int minHeightSec = level.getMinY() >> 4; for (int x = minSecX; x <= maxSecX; ++x) { for (int z = minSecZ; z <= maxSecZ; ++z) { LevelChunk levelChunk1 = getLevelChunk(level, x, z); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java index bf6deebb70..8b8ebb1b0e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java @@ -107,7 +107,7 @@ public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { final Direction nominalFace = q.nominalFace(); if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) { - Vec3i vec = nominalFace.getNormal(); + Vec3i vec = nominalFace.getUnitVec3i(); saveTo.set(vec.getX(), vec.getY(), vec.getZ()); return; } @@ -184,7 +184,7 @@ public static int computePackedNormal(ModelQuadView q) { } public static int packedNormalFromDirection(Direction direction) { - Vec3i normal = direction.getNormal(); + Vec3i normal = direction.getUnitVec3i(); return I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 3b3fb644ef..b7120ac014 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -16,6 +16,7 @@ package net.vulkanmod.render.chunk.build.frapi.mesh; +import net.minecraft.client.renderer.LightTexture; import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import net.vulkanmod.render.model.quad.ModelQuadView; import org.jetbrains.annotations.Nullable; @@ -207,8 +208,16 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], quadView.getFlags()); this.facing = quadView.getQuadFacing(); - this.isGeometryInvalid = false; + + int lightEmission = quad.getLightEmission(); + + if (lightEmission > 0) { + for (int i = 0; i < 4; i++) { + lightmap(i, LightTexture.lightCoordsWithEmission(lightmap(i), lightEmission)); + } + } + return this; } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index 0262756128..abd7ca1962 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -63,7 +63,7 @@ public void emitDirectly() { protected BlockAndTintGetter renderRegion; - protected final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { + protected final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { protected void rehash(int i) { } }; @@ -111,12 +111,6 @@ public ItemDisplayContext itemTransformationMode() { throw new IllegalStateException("itemTransformationMode() can only be called on an item render context."); } - @SuppressWarnings("removal") - @Override - public BakedModelConsumer bakedModelConsumer() { - return null; - } - public void prepareForWorld(BlockAndTintGetter blockView, boolean enableCulling) { this.renderRegion = blockView; this.enableCulling = enableCulling; @@ -170,12 +164,12 @@ public boolean faceNotOccluded(BlockState blockState, Direction face) { } if (adjBlockState.canOcclude()) { - VoxelShape shape = blockState.getFaceOcclusionShape(blockGetter, blockPos, face); + VoxelShape shape = blockState.getFaceOcclusionShape(face); if (shape.isEmpty()) return true; - VoxelShape adjShape = adjBlockState.getFaceOcclusionShape(blockGetter, adjPos, face.getOpposite()); + VoxelShape adjShape = adjBlockState.getFaceOcclusionShape(face.getOpposite()); if (adjShape.isEmpty()) return true; @@ -184,7 +178,7 @@ public boolean faceNotOccluded(BlockState blockState, Direction face) { return false; } - Block.BlockStatePairKey blockStatePairKey = new Block.BlockStatePairKey(blockState, adjBlockState, face); + ShapePairKey blockStatePairKey = new ShapePairKey(shape, adjShape); byte b = occlusionCache.getAndMoveToFirst(blockStatePairKey); if (b != 127) { @@ -245,11 +239,13 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, if (emissive) { for (int i = 0; i < 4; i++) { quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); +// quad.lightmap(i, LightTexture.FULL_BRIGHT); data.lm[i] = LightTexture.FULL_BRIGHT; } } else { for (int i = 0; i < 4; i++) { quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); +// quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i])); data.lm[i] = ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i]); } } @@ -300,4 +296,19 @@ public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplie } + // TODO move elsewhere + record ShapePairKey(VoxelShape first, VoxelShape second) { + public boolean equals(Object object) { + if (object instanceof ShapePairKey shapePairKey && this.first == shapePairKey.first && this.second == shapePairKey.second) { + return true; + } + + return false; + } + + public int hashCode() { + return System.identityHashCode(this.first) * 31 + System.identityHashCode(this.second); + } + } + } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java index 4ea9392be7..c0376db6f8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -1,3 +1,19 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.vulkanmod.render.chunk.build.frapi.render; import com.mojang.blaze3d.vertex.PoseStack; @@ -5,6 +21,9 @@ import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.CrashReport; +import net.minecraft.CrashReportCategory; +import net.minecraft.ReportedException; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -43,7 +62,7 @@ public BlockRenderContext() { } public void render(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrixStack, VertexConsumer buffer, boolean cull, RandomSource random, long seed, int overlay) { - Vec3 offset = state.getOffset(blockView, pos); + Vec3 offset = state.getOffset(pos); matrixStack.translate(offset.x, offset.y, offset.z); this.blockPos = pos; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index 0aef4c9a87..843c71a8be 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -81,8 +81,6 @@ public void emitDirectly() { } }; - private final BakedModelConsumerImpl vanillaModelConsumer = new BakedModelConsumerImpl(); - private ItemStack itemStack; private ItemDisplayContext transformMode; private PoseStack matrixStack; @@ -120,11 +118,6 @@ public ItemDisplayContext itemTransformationMode() { return transformMode; } - @Override - public BakedModelConsumer bakedModelConsumer() { - return vanillaModelConsumer; - } - public void renderModel(ItemStack itemStack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int lightmap, int overlay, BakedModel model) { this.itemStack = itemStack; this.transformMode = transformMode; @@ -251,7 +244,7 @@ private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { /** * Caches custom blend mode / vertex consumers and mimics the logic - * in {@code RenderLayers.getEntityBlockLayer}. Layers other than + * in {@code RenderLayers.getItemLayer}. Layers other than * translucent are mapped to cutout. */ private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode) { @@ -273,13 +266,13 @@ private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode if (translucent) { if (glint) { if (translucentGlintVertexConsumer == null) { - translucentGlintVertexConsumer = createTranslucentVertexConsumer(true); + translucentGlintVertexConsumer = createVertexConsumer(Sheets.translucentItemSheet(), true); } return translucentGlintVertexConsumer; } else { if (translucentVertexConsumer == null) { - translucentVertexConsumer = createTranslucentVertexConsumer(false); + translucentVertexConsumer = createVertexConsumer(Sheets.translucentItemSheet(), false); } return translucentVertexConsumer; @@ -287,13 +280,13 @@ private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode } else { if (glint) { if (cutoutGlintVertexConsumer == null) { - cutoutGlintVertexConsumer = createCutoutVertexConsumer(true); + cutoutGlintVertexConsumer = createVertexConsumer(Sheets.cutoutBlockSheet(), true); } return cutoutGlintVertexConsumer; } else { if (cutoutVertexConsumer == null) { - cutoutVertexConsumer = createCutoutVertexConsumer(false); + cutoutVertexConsumer = createVertexConsumer(Sheets.cutoutBlockSheet(), false); } return cutoutVertexConsumer; @@ -301,51 +294,22 @@ private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode } } - private VertexConsumer createTranslucentVertexConsumer(boolean glint) { - if (glint && isGlintDynamicDisplay) { - return createDynamicDisplayGlintVertexConsumer(Minecraft.useShaderTransparency() && !isTranslucentDirect ? Sheets.translucentItemSheet() : Sheets.translucentCullBlockSheet()); - } - - if (isTranslucentDirect) { - return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); - } else if (Minecraft.useShaderTransparency()) { - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentItemSheet(), true, glint); - } else { - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); - } - } - - private VertexConsumer createCutoutVertexConsumer(boolean glint) { - if (glint && isGlintDynamicDisplay) { - return createDynamicDisplayGlintVertexConsumer(Sheets.cutoutBlockSheet()); - } - - return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.cutoutBlockSheet(), true, glint); - } - - private VertexConsumer createDynamicDisplayGlintVertexConsumer(RenderType layer) { - if (dynamicDisplayGlintEntry == null) { - dynamicDisplayGlintEntry = matrixStack.last().copy(); + private VertexConsumer createVertexConsumer(RenderType layer, boolean glint) { + if (isGlintDynamicDisplay && glint) { + if (dynamicDisplayGlintEntry == null) { + dynamicDisplayGlintEntry = matrixStack.last().copy(); - if (transformMode == ItemDisplayContext.GUI) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.5F); - } else if (transformMode.firstPerson()) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.75F); + if (transformMode == ItemDisplayContext.GUI) { + MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.5F); + } else if (transformMode.firstPerson()) { + MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.75F); + } } - } - return ItemRenderer.getCompassFoilBuffer(vertexConsumerProvider, layer, dynamicDisplayGlintEntry); - } - - private class BakedModelConsumerImpl implements BakedModelConsumer { - @Override - public void accept(BakedModel model) { - accept(model, null); + return ItemRenderer.getCompassFoilBuffer(vertexConsumerProvider, layer, dynamicDisplayGlintEntry); } - @Override - public void accept(BakedModel model, @Nullable BlockState state) { - VanillaModelEncoder.emitItemQuads(model, state, randomSupplier, ItemRenderContext.this); - } + return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint); } + } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java index 1312b46715..3152c48d1f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java @@ -88,9 +88,9 @@ protected int compute(int x, int y, int z) { if (this.subBlockLighting) op = state.canOcclude(); else - op = state.isViewBlocking(region, pos) && state.getLightBlock(region, pos) != 0; + op = state.isViewBlocking(region, pos) && state.getLightBlock() != 0; - boolean fo = state.isSolidRender(region, pos); + boolean fo = state.isSolidRender(); boolean fc = state.isCollisionShapeFullBlock(region, pos); int lu = state.getLightEmission(); @@ -217,8 +217,7 @@ public static int getLightmap(int word) { public static int getEmissiveLightmap(int word) { if (unpackEM(word)) { return LightTexture.FULL_BRIGHT; - } - else { + } else { return getLightmap(word); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index f04244f3fa..6e458a6760 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -65,7 +65,7 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); BlockAndTintGetter renderRegion = this.renderRegion; - Vec3 offset = blockState.getOffset(renderRegion, blockPos); + Vec3 offset = blockState.getOffset(blockPos); pos.add((float) offset.x, (float) offset.y, (float) offset.z); this.prepareForBlock(blockState, blockPos, model.useAmbientOcclusion()); @@ -112,7 +112,7 @@ public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadVie TerrainBufferBuilder bufferBuilder = terrainBuilder.getBufferBuilder(quadFacing.ordinal()); - Vec3i normal = quad.getFacingDirection().getNormal(); + Vec3i normal = quad.getFacingDirection().getUnitVec3i(); int packedNormal = I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); float[] brightnessArr = quadLightData.br; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java index 30c5317f88..cb19f0a8c6 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java @@ -74,10 +74,10 @@ public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos } private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Direction direction, BlockPos blockPos, BlockState blockState) { - mBlockPos.set(blockPos).offset(Direction.DOWN.getNormal()); + mBlockPos.set(blockPos).offset(Direction.DOWN.getUnitVec3i()); if (blockState.canOcclude()) { - VoxelShape occlusionShape = blockState.getOcclusionShape(blockGetter, mBlockPos); + VoxelShape occlusionShape = blockState.getOcclusionShape(); if (occlusionShape == Shapes.block()) { return direction != Direction.UP; @@ -164,14 +164,14 @@ public void render(FluidRenderHandler handler, BlockState blockState, FluidState seHeight = 1.0F; swHeight = 1.0F; } else { - float s = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()), northState); - float t = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()), southState); - float u = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.EAST.getNormal()), eastState); - float v = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.WEST.getNormal()), westState); - neHeight = this.calculateAverageHeight(region, fluid, height, s, u, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()).offset(Direction.EAST.getNormal())); - nwHeight = this.calculateAverageHeight(region, fluid, height, s, v, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()).offset(Direction.WEST.getNormal())); - seHeight = this.calculateAverageHeight(region, fluid, height, t, u, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()).offset(Direction.EAST.getNormal())); - swHeight = this.calculateAverageHeight(region, fluid, height, t, v, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()).offset(Direction.WEST.getNormal())); + float s = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.NORTH.getUnitVec3i()), northState); + float t = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.SOUTH.getUnitVec3i()), southState); + float u = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.EAST.getUnitVec3i()), eastState); + float v = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.WEST.getUnitVec3i()), westState); + neHeight = this.calculateAverageHeight(region, fluid, height, s, u, mBlockPos.set(blockPos).offset(Direction.NORTH.getUnitVec3i()).offset(Direction.EAST.getUnitVec3i())); + nwHeight = this.calculateAverageHeight(region, fluid, height, s, v, mBlockPos.set(blockPos).offset(Direction.NORTH.getUnitVec3i()).offset(Direction.WEST.getUnitVec3i())); + seHeight = this.calculateAverageHeight(region, fluid, height, t, u, mBlockPos.set(blockPos).offset(Direction.SOUTH.getUnitVec3i()).offset(Direction.EAST.getUnitVec3i())); + swHeight = this.calculateAverageHeight(region, fluid, height, t, v, mBlockPos.set(blockPos).offset(Direction.SOUTH.getUnitVec3i()).offset(Direction.WEST.getUnitVec3i())); } float x0 = (posX & 15); @@ -422,7 +422,7 @@ private float getHeight(BlockAndTintGetter blockAndTintGetter, Fluid fluid, Bloc private float getHeight(BlockAndTintGetter blockAndTintGetter, Fluid fluid, BlockPos blockPos, BlockState adjBlockState) { FluidState adjFluidState = adjBlockState.getFluidState(); if (fluid.isSame(adjFluidState.getType())) { - BlockState blockState2 = blockAndTintGetter.getBlockState(blockPos.offset(Direction.UP.getNormal())); + BlockState blockState2 = blockAndTintGetter.getBlockState(blockPos.offset(Direction.UP.getUnitVec3i())); return fluid.isSame(blockState2.getFluidState().getType()) ? 1.0F : adjFluidState.getOwnHeight(); } else { return !adjBlockState.isSolid() ? 0.0F : -1.0f; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java index 068700b6d0..a3dc33e5f8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java @@ -104,7 +104,7 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc blockPos.set(section.xOffset() + x, section.yOffset() + y, section.zOffset() + z); BlockState blockState = this.region.getBlockState(blockPos); - if (blockState.isSolidRender(this.region, blockPos)) { + if (blockState.isSolidRender()) { visGraph.setOpaque(blockPos); } diff --git a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java index 8a3d641beb..58b2d156ee 100644 --- a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java +++ b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java @@ -7,6 +7,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.util.Mth; +import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.vulkanmod.Initializer; @@ -55,13 +56,14 @@ public SectionGraph(Level level, SectionGrid sectionGrid, TaskDispatcher taskDis public void update(Camera camera, Frustum frustum, boolean spectator) { Profiler profiler = Profiler.getMainProfiler(); + ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); BlockPos blockpos = camera.getBlockPosition(); - this.minecraft.getProfiler().popPush("update"); + mcProfiler.popPush("update"); boolean flag = this.minecraft.smartCull; - if (spectator && this.level.getBlockState(blockpos).isSolidRender(this.level, blockpos)) { + if (spectator && this.level.getBlockState(blockpos).isSolidRender()) { flag = false; } @@ -70,7 +72,7 @@ public void update(Camera camera, Frustum frustum, boolean spectator) { this.sectionGrid.updateFrustumVisibility(this.frustum); profiler.pop(); - this.minecraft.getProfiler().push("partial_update"); + mcProfiler.push("partial_update"); this.initUpdate(); this.initializeQueueForFullUpdate(camera); @@ -82,7 +84,7 @@ public void update(Camera camera, Frustum frustum, boolean spectator) { this.scheduleRebuilds(); - this.minecraft.getProfiler().pop(); + mcProfiler.pop(); } private void initializeQueueForFullUpdate(Camera camera) { @@ -91,8 +93,8 @@ private void initializeQueueForFullUpdate(Camera camera) { RenderSection renderSection = this.sectionGrid.getSectionAtBlockPos(blockpos); if (renderSection == null) { - boolean flag = blockpos.getY() > this.level.getMinBuildHeight(); - int y = flag ? this.level.getMaxBuildHeight() - 8 : this.level.getMinBuildHeight() + 8; + boolean flag = blockpos.getY() > this.level.getMinY(); + int y = flag ? this.level.getMaxY() - 8 : this.level.getMinY() + 8; int x = Mth.floor(vec3.x / 16.0D) * 16; int z = Mth.floor(vec3.z / 16.0D) * 16; diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 2227c7b225..2fade3880f 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -1,12 +1,12 @@ package net.vulkanmod.render.sky; +import com.mojang.blaze3d.buffers.BufferUsage; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import net.minecraft.client.CloudStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.FogRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; @@ -57,7 +57,7 @@ public void loadTexture() { this.cloudGrid = createCloudGrid(TEXTURE_LOCATION); } - public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { + public void renderClouds(ClientLevel level, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { float cloudHeight = level.effects().getCloudHeight(); if (Float.isNaN(cloudHeight)) { @@ -110,7 +110,7 @@ else if (centerY > 0.0f) { return; } - this.cloudBuffer = new VBO(VertexBuffer.Usage.STATIC); + this.cloudBuffer = new VBO(BufferUsage.STATIC_WRITE); this.cloudBuffer.upload(cloudsMesh); } @@ -118,19 +118,15 @@ else if (centerY > 0.0f) { return; } - FogRenderer.levelFogColor(); - float xTranslation = (float) (centerX - (centerCellX * CELL_WIDTH)); float yTranslation = (float) (centerY); float zTranslation = (float) (centerZ - (centerCellZ * CELL_WIDTH)); - poseStack.pushPose(); - poseStack.mulPose(modelView); - poseStack.translate(-xTranslation, yTranslation, -zTranslation); + Matrix4f matrix4f = new Matrix4f(modelView).translate(-xTranslation, yTranslation, -zTranslation); VRenderSystem.setModelOffset(-xTranslation, 0, -zTranslation); - Vec3 cloudColor = level.getCloudColor(partialTicks); + Vec3 cloudColor = Vec3.fromRGB24(level.getCloudColor(partialTicks)); RenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); GraphicsPipeline pipeline = PipelineManager.getCloudsPipeline(); @@ -148,18 +144,16 @@ else if (centerY > 0.0f) { if (!fastClouds) { RenderSystem.colorMask(false, false, false, false); - this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); + this.cloudBuffer.drawWithShader(matrix4f, projection, pipeline); RenderSystem.colorMask(true, true, true, true); } - this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); + this.cloudBuffer.drawWithShader(matrix4f, projection, pipeline); RenderSystem.enableCull(); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); VRenderSystem.setModelOffset(0.0f, 0.0f, 0.0f); - - poseStack.popPose(); } public void resetBuffer() { @@ -285,7 +279,7 @@ private static CloudGrid createCloudGrid(ResourceLocation textureLocation) { int height = image.getHeight(); Validate.isTrue(width == height, "Image width and height must be the same"); - int[] pixels = image.getPixelsRGBA(); + int[] pixels = image.getPixelsABGR(); return new CloudGrid(pixels, width); } diff --git a/src/main/java/net/vulkanmod/render/util/DrawUtil.java b/src/main/java/net/vulkanmod/render/util/DrawUtil.java index 430194d69b..f1ba4e9235 100644 --- a/src/main/java/net/vulkanmod/render/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/render/util/DrawUtil.java @@ -1,8 +1,10 @@ package net.vulkanmod.render.util; +import com.mojang.blaze3d.ProjectionType; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -51,13 +53,14 @@ public static void drawFramebuffer(GraphicsPipeline pipeline, VulkanImage attach VTextureSelector.bindTexture(attachment); - Matrix4f matrix4f = new Matrix4f().setOrtho(0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, true); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.DISTANCE_TO_ORIGIN); - Matrix4fStack posestack = RenderSystem.getModelViewStack(); - posestack.pushMatrix(); - posestack.identity(); - RenderSystem.applyModelViewMatrix(); - posestack.popMatrix(); + Matrix4f projection = new Matrix4f().setOrtho(0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, true); + Matrix4fStack poseStack = RenderSystem.getModelViewStack(); + poseStack.pushMatrix(); + poseStack.identity(); + + VRenderSystem.applyMVP(poseStack, projection); + + poseStack.popMatrix(); Renderer.getInstance().uploadAndBindUBOs(pipeline); diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index db4996d69f..ca42ee5735 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -61,6 +61,8 @@ public abstract class VRenderSystem { public static void initRenderer() { Vulkan.initVulkan(window); + + setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); } public static MappedBuffer getScreenSize() { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java index 7ca193a650..9a30567ae3 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.util.MappedBuffer; import java.util.function.Supplier; @@ -28,11 +29,11 @@ public static void setupDefaultUniforms() { //Vec1i vec1i_uniformMap.put("EndPortalLayers", () -> 15); - vec1i_uniformMap.put("FogShape", () -> RenderSystem.getShaderFogShape().getIndex()); + vec1i_uniformMap.put("FogShape", () -> RenderSystem.getShaderFog().shape().getIndex()); //Vec1 - vec1f_uniformMap.put("FogStart", RenderSystem::getShaderFogStart); - vec1f_uniformMap.put("FogEnd", RenderSystem::getShaderFogEnd); + vec1f_uniformMap.put("FogStart", () -> RenderSystem.getShaderFog().start()); + vec1f_uniformMap.put("FogEnd", () -> RenderSystem.getShaderFog().end()); vec1f_uniformMap.put("LineWidth", RenderSystem::getShaderLineWidth); vec1f_uniformMap.put("GameTime", RenderSystem::getShaderGameTime); vec1f_uniformMap.put("GlintAlpha", RenderSystem::getShaderGlintAlpha); diff --git a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java index b5ba525811..fd2a9ece00 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java @@ -1,16 +1,10 @@ package net.vulkanmod.vulkan.util; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import org.joml.Matrix4f; -import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; import org.lwjgl.vulkan.VK11; import org.lwjgl.vulkan.VkCommandBuffer; @@ -38,33 +32,35 @@ public static void fastBlit() { VRenderSystem.enableCull(); } - public static void defualtBlit() { - Matrix4f matrix4f = new Matrix4f().setOrtho(0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); - Matrix4fStack posestack = RenderSystem.getModelViewStack(); - posestack.pushMatrix(); - posestack.identity(); - RenderSystem.applyModelViewMatrix(); - posestack.popMatrix(); - - ShaderInstance shaderInstance = Minecraft.getInstance().gameRenderer.blitShader; -// RenderSystem.setShader(() -> shaderInstance); - - Tesselator tesselator = RenderSystem.renderThreadTesselator(); - BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); - bufferBuilder.addVertex(-1.0f, -1.0f, 0.0f).setUv(0.0F, 1.0F); - bufferBuilder.addVertex(1.0f, -1.0f, 0.0f).setUv(1.0F, 1.0F); - bufferBuilder.addVertex(1.0f, 1.0f, 0.0f).setUv(1.0F, 0.0F); - bufferBuilder.addVertex(-1.0f, 1.0f, 0.0f).setUv(0.0F, 0.0F); - var meshData = bufferBuilder.buildOrThrow(); - - MeshData.DrawState parameters = meshData.drawState(); - - Renderer renderer = Renderer.getInstance(); - - GraphicsPipeline pipeline = ((ShaderMixed)(shaderInstance)).getPipeline(); - renderer.bindGraphicsPipeline(pipeline); - renderer.uploadAndBindUBOs(pipeline); - Renderer.getDrawer().draw(meshData.vertexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); - } + // TODO +// public static void defualtBlit() { +// Matrix4f matrix4f = new Matrix4f().setOrtho(0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F); +// RenderSystem.setProjectionMatrix(matrix4f, ProjectionType.ORTHOGRAPHIC); +// Matrix4fStack posestack = RenderSystem.getModelViewStack(); +// posestack.pushMatrix(); +// posestack.identity(); +// VRenderSystem.applyModelViewMatrix(); +// RenderSystem.(); +// posestack.popMatrix(); +// +// ShaderProgram shaderInstance = CoreShaders.BLIT_SCREEN; +//// RenderSystem.setShader(() -> shaderInstance); +// +// Tesselator tesselator = RenderSystem.renderThreadTesselator(); +// BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); +// bufferBuilder.addVertex(-1.0f, -1.0f, 0.0f).setUv(0.0F, 1.0F); +// bufferBuilder.addVertex(1.0f, -1.0f, 0.0f).setUv(1.0F, 1.0F); +// bufferBuilder.addVertex(1.0f, 1.0f, 0.0f).setUv(1.0F, 0.0F); +// bufferBuilder.addVertex(-1.0f, 1.0f, 0.0f).setUv(0.0F, 0.0F); +// var meshData = bufferBuilder.buildOrThrow(); +// +// MeshData.DrawState parameters = meshData.drawState(); +// +// Renderer renderer = Renderer.getInstance(); +// +// GraphicsPipeline pipeline = ((ShaderMixed)(shaderInstance)).getPipeline(); +// renderer.bindGraphicsPipeline(pipeline); +// renderer.uploadAndBindUBOs(pipeline); +// Renderer.getDrawer().draw(meshData.vertexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); +// } } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json index d36098bcfb..be8253788a 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json @@ -17,6 +17,8 @@ { "type": "vertex", "binding": 0, "fields": [ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "ModelOffset", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } ] }, { "type": "fragment", "binding": 1, "fields": [ diff --git a/src/main/resources/vulkanmod.accesswidener b/src/main/resources/vulkanmod.accesswidener index 2dd84a08c2..9a9e7fd208 100644 --- a/src/main/resources/vulkanmod.accesswidener +++ b/src/main/resources/vulkanmod.accesswidener @@ -13,5 +13,14 @@ accessible field net/minecraft/client/renderer/texture/SpriteContents$AnimatedTe accessible field net/minecraft/client/renderer/texture/SpriteContents$FrameInfo time I #1.20 -accessible field com/mojang/blaze3d/systems/RenderSystem vertexSorting Lcom/mojang/blaze3d/vertex/VertexSorting; accessible field net/minecraft/client/renderer/RenderStateShard name Ljava/lang/String; + +accessible class net/minecraft/client/renderer/ShaderManager$ShaderCompilationKey +accessible method net/minecraft/client/renderer/ShaderManager$ShaderCompilationKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/shaders/CompiledShader$Type;Lnet/minecraft/client/renderer/ShaderDefines;)V +accessible class net/minecraft/client/renderer/ShaderManager$ShaderSourceKey +accessible method net/minecraft/client/renderer/ShaderManager$ShaderSourceKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/shaders/CompiledShader$Type;)V +accessible class net/minecraft/client/renderer/ShaderManager$CompilationCache +accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache programs Ljava/util/Map; +accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache shaders Ljava/util/Map; +accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache postChains Ljava/util/Map; +accessible method net/minecraft/client/renderer/CompiledShaderProgram (I)V \ No newline at end of file diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 7ada95708d..958b0d3084 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -7,8 +7,11 @@ "mixins": [ ], "client": [ - "chunk.ClientChunkCacheM", + "window.WindowMixin", + "window.WindowAccessor", + "chunk.ClientPacketListenerM", + "chunk.ClientChunkCacheM", "chunk.DirectionMixin", "chunk.FrustumMixin", "chunk.LevelRendererMixin", @@ -16,32 +19,32 @@ "chunk.SectionRenderDispatcherM", "chunk.ViewAreaM", "chunk.VisibilitySetMixin", + "compatibility.EffectInstanceM", - "compatibility.PostChainM", - "compatibility.PostPassM", "compatibility.ProgramM", "compatibility.UniformM", "compatibility.gl.GL11M", "compatibility.gl.GL15M", "compatibility.gl.GL30M", + + "debug.crash_report.SystemReportM", "debug.DebugScreenOverlayM", "debug.GlDebugInfoM", "debug.KeyboardHandlerM", - "debug.crash_report.SystemReportM", + "matrix.Matrix4fM", "matrix.PoseAccessor", - "profiling.ClientMetricsSamplersProviderMixin", + "profiling.GuiMixin", "profiling.KeyboardHandlerM", "profiling.LevelRendererMixin", + "render.BufferUploaderM", "render.GameRendererMixin", - "render.GlProgramManagerMixin", "render.GlStateManagerM", "render.MinecraftMixin", "render.RenderSystemMixin", "render.RenderTypeM", - "render.ShaderInstanceM", "render.biome.BiomeManagerM", "render.block.BakedQuadM", "render.clouds.LevelRendererM", @@ -57,6 +60,10 @@ "render.frapi.ItemRendererMixin", "render.frapi.ModelBlockRendererM", "render.particle.SingleQuadParticleM", + "render.shader.CompilationCacheM", + "render.shader.CompiledShaderProgramM", + "render.shader.ShadeProgramConfigM", + "render.shader.ShaderManagerM", "render.target.MainTargetMixin", "render.target.RenderTargetMixin", "render.vertex.BufferBuilderM", @@ -64,28 +71,37 @@ "render.vertex.IndexTypeMixin", "render.vertex.VertexBufferM", "render.vertex.VertexFormatMixin", - "screen.OptionsScreenM", + "screen.ScreenM", - "texture.MAbstractTexture", - "texture.MTextureUtil", + "screen.OptionsScreenM", + + "texture.mip.MipmapGeneratorM", "texture.image.MNativeImage", "texture.image.NativeImageAccessor", - "texture.mip.MipmapGeneratorM", "texture.update.GameRendererM", "texture.update.MLightTexture", "texture.update.MSpriteContents", "texture.update.MTextureManager", + "texture.MAbstractTexture", + "texture.MTextureUtil", + "util.ScreenshotRecorderM", + "vertex.EntityOutlineGeneratorM", "vertex.SpriteCoordinateExpanderM", "vertex.VertexMultiConsumersM$DoubleM", "vertex.VertexMultiConsumersM$MultipleM", "vertex.VertexMultiConsumersM$SheetDecalM", - "voxel.VoxelShapeMixin", + "wayland.InputConstantsM", "wayland.MinecraftMixin", - "window.WindowAccessor", - "window.WindowMixin" + + "texture.mip.MipmapGeneratorM", + + "compatibility.PostChainM", + "compatibility.PostPassM", + + "voxel.VoxelShapeMixin" ], "injectors": { "defaultRequire": 1 From 3fa7807dab657847a6a5dc8e442915a86933073b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 10 Dec 2024 18:51:13 +0100 Subject: [PATCH 097/177] Port to 1.21.4 --- gradle.properties | 12 +- src/main/java/net/vulkanmod/Initializer.java | 4 +- .../net/vulkanmod/config/gui/GuiRenderer.java | 16 +- .../net/vulkanmod/config/gui/VOptionList.java | 2 - .../mixin/chunk/LevelRendererMixin.java | 2 +- .../mixin/profiling/LevelRendererMixin.java | 6 +- .../mixin/render/MinecraftMixin.java | 41 ---- .../mixin/render/entity/LevelRendererM.java | 4 +- .../mixin/render/frame/MinecraftMixin.java | 10 +- .../mixin/render/frapi/BakedModelM.java | 17 +- .../render/frapi/ItemRendererAccessor.java | 9 +- .../mixin/render/frapi/ItemRendererMixin.java | 27 +-- .../mixin/render/frapi/QuadEmitterM.java | 11 + .../render/shader/CompilationCacheM.java | 2 +- .../mixin/render/vertex/BufferBuilderM.java | 2 +- .../mixin/render/vertex/FaceBakeryM.java | 2 +- .../mixin/texture/image/MNativeImage.java | 2 +- .../chunk/build/RenderRegionBuilder.java | 1 - .../render/chunk/build/biome/BiomeData.java | 4 +- .../chunk/build/frapi/VulkanModRenderer.java | 15 +- .../build/frapi/helper/GeometryHelper.java | 6 +- .../frapi/material/MaterialFinderImpl.java | 34 +-- .../frapi/material/MaterialViewImpl.java | 36 ++- .../build/frapi/mesh/EncodingFormat.java | 4 +- .../build/frapi/mesh/ExtendedQuadEmitter.java | 29 +++ .../build/frapi/mesh/MeshBuilderImpl.java | 84 ------- .../chunk/build/frapi/mesh/MeshImpl.java | 60 +++-- .../build/frapi/mesh/MutableMeshImpl.java | 93 +++++++ .../build/frapi/mesh/MutableQuadViewImpl.java | 113 +++++++-- .../chunk/build/frapi/mesh/QuadViewImpl.java | 29 +-- .../render/AbstractBlockRenderContext.java | 97 +++----- .../frapi/render/AbstractRenderContext.java | 75 +----- .../frapi/render/BlockRenderContext.java | 9 +- .../build/frapi/render/ItemRenderContext.java | 227 ++++++------------ .../chunk/build/renderer/BlockRenderer.java | 5 +- .../vulkan/texture/VTextureSelector.java | 34 ++- src/main/resources/fabric.mod.json | 2 +- src/main/resources/vulkanmod.mixins.json | 1 + 38 files changed, 514 insertions(+), 613 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableMeshImpl.java diff --git a/gradle.properties b/gradle.properties index ff41672eec..089871c791 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,14 +4,14 @@ org.gradle.parallel=true # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.21.3 -yarn_mappings=1.21.3+build.2 -loader_version=0.16.7 +minecraft_version=1.21.4 +yarn_mappings=1.21.4+build.2 +loader_version=0.16.9 # Fabric API -fabric_version=0.106.1+1.21.3 +fabric_version=0.114.0+1.21.4 # Mod Properties -mod_version = 0.5.0-dev +mod_version = 0.5.3-dev.3 maven_group = net.vulkanmod -archives_base_name = VulkanMod_1.21.3 +archives_base_name = VulkanMod_1.21.4 diff --git a/src/main/java/net/vulkanmod/Initializer.java b/src/main/java/net/vulkanmod/Initializer.java index ea9360265c..198d7153a6 100644 --- a/src/main/java/net/vulkanmod/Initializer.java +++ b/src/main/java/net/vulkanmod/Initializer.java @@ -1,7 +1,7 @@ package net.vulkanmod; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.fabric.api.renderer.v1.RendererAccess; +import net.fabricmc.fabric.api.renderer.v1.Renderer; import net.fabricmc.loader.api.FabricLoader; import net.vulkanmod.config.Config; import net.vulkanmod.config.Platform; @@ -38,7 +38,7 @@ public void onInitializeClient() { CONFIG = loadConfig(configPath); - RendererAccess.INSTANCE.registerRenderer(VulkanModRenderer.INSTANCE); + Renderer.register(VulkanModRenderer.INSTANCE); } private static Config loadConfig(Path path) { diff --git a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java index a446d71b24..2a4ab41789 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java @@ -7,7 +7,6 @@ import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.util.FormattedCharSequence; import org.joml.Matrix4f; @@ -55,8 +54,6 @@ public static void fill(float x0, float y0, float x1, float y1, int color) { public static void fill(float x0, float y0, float x1, float y1, float z, int color) { Matrix4f matrix4f = pose.last().pose(); - RenderSystem.setShader(CoreShaders.POSITION_COLOR); - setupBufferBuilder(); bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color); @@ -74,10 +71,6 @@ public static void fillGradient(float x0, float y0, float x1, float y1, int colo public static void fillGradient(float x0, float y0, float x1, float y1, float z, int color1, int color2) { Matrix4f matrix4f = pose.last().pose(); - RenderSystem.setShader(CoreShaders.POSITION_COLOR); - - if (!batching) - bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); setupBufferBuilder(); bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color1); @@ -137,12 +130,7 @@ public static void beginBatch() { } public static void endBatch() { - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - batching = false; - } - - public static void endBatch() { - RenderSystem.setShader(GameRenderer::getPositionColorShader); + RenderSystem.setShader(CoreShaders.POSITION_COLOR); MeshData meshData = bufferBuilder.build(); if (meshData != null) { @@ -171,7 +159,7 @@ private static void setupBufferBuilder() { private static void submitIfNeeded() { if (!batching) { - RenderSystem.setShader(GameRenderer::getPositionColorShader); + RenderSystem.setShader(CoreShaders.POSITION_COLOR); BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); drawing = false; } diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index a3d99a4776..d2c3fe3cdb 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -274,8 +274,6 @@ protected void renderList(int mouseX, int mouseY) { rowTop += entry.getTotalHeight(); } - - GuiRenderer.flush(); } private Entry getEntry(int j) { diff --git a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java index b282665aa1..d4cb6f866f 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java @@ -90,7 +90,7 @@ private void renderSectionLayer(RenderType renderType, double camX, double camY, * @reason */ @Overwrite - public void onChunkLoaded(ChunkPos chunkPos) { + public void onChunkReadyToRender(ChunkPos chunkPos) { } /** diff --git a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java index 8fc36fbc4d..b67d076026 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java @@ -40,16 +40,14 @@ private void popProfiler(ResourceHandle resourceHandle, int i, CloudStatus cloud // TODO: fix @Inject(method = "method_62213", at = @At(value = "HEAD")) private void pushProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, - ResourceHandle resourceHandle2, LightTexture lightTexture, Camera camera, float f, - CallbackInfo ci) { + ResourceHandle resourceHandle2, Camera camera, float f, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Particles"); } @Inject(method = "method_62213", at = @At(value = "RETURN")) private void popProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, - ResourceHandle resourceHandle2, LightTexture lightTexture, Camera camera, float f, - CallbackInfo ci) { + ResourceHandle resourceHandle2, Camera camera, float f, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 3e36b6ff8a..8823d7ad47 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -40,47 +40,6 @@ private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { } } - @Inject(method = "runTick", at = @At(value = "HEAD")) - private void preFrameOps(boolean bl, CallbackInfo ci) { - Renderer.getInstance().preInitFrame(); - } - - //Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(I)V")) - private void beginRender(int i, boolean bl) { - Renderer.getInstance().beginFrame(); -// RenderSystem.clear(i); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;updateDisplay(Lcom/mojang/blaze3d/TracyFrameCapture;)V", shift = At.Shift.BEFORE)) - private void submitRender(boolean tick, CallbackInfo ci) { - Renderer.getInstance().endFrame(); - } - - @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) - private void beginRender2(CallbackInfo ci) { - Renderer.getInstance().beginFrame(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) - private void redirectMainTarget1(RenderTarget instance, boolean bl) { - Renderer.getInstance().getMainPass().mainTargetBindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) - private void redirectMainTarget2(RenderTarget instance) { - Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) - private void removeBlit(RenderTarget instance, int i, int j) { - } - - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Ljava/lang/Thread;yield()V")) - private void removeThreadYield() { - } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) private Optional removeTimer() { return Optional.empty(); diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java index 99c37ded09..e482555b7f 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java @@ -41,7 +41,9 @@ public class LevelRendererM { target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V", shift = At.Shift.AFTER) ) - private void clearMap(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { + private void clearMap(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, boolean bl, + Camera camera, GameRenderer gameRenderer, Matrix4f matrix4f, Matrix4f matrix4f2, + CallbackInfo ci) { for (var bufferSource : this.bufferSourceMap.keySet()) { var entityMap = this.bufferSourceMap.get(bufferSource); entityMap.clear(); diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java index 6184f79028..66b4dde112 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java @@ -22,10 +22,9 @@ private void preFrameOps(boolean bl, CallbackInfo ci) { Renderer.getInstance().preInitFrame(); } - // Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V")) + //Main target (framebuffer) ops + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(I)V")) private void beginRender(int i, boolean bl) { - RenderSystem.clear(i, bl); Renderer.getInstance().beginFrame(); } @@ -53,9 +52,4 @@ private void removeBlit(RenderTarget instance, int i, int j) { private void removeThreadYield() { } - @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) - private void limitWhenMinimized(CallbackInfoReturnable cir) { - if (this.noRender) - cir.setReturnValue(10); - } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java index b8decdc335..0e45b706bb 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java @@ -1,29 +1,30 @@ package net.vulkanmod.mixin.render.frapi; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; -import net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext; -import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; +import net.vulkanmod.render.chunk.build.frapi.mesh.ExtendedQuadEmitter; +import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; +import java.util.function.Predicate; import java.util.function.Supplier; @Mixin(BakedModel.class) public interface BakedModelM extends FabricBakedModel { @Override - default void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { - ((AbstractBlockRenderContext) context).emitBlockQuads((BakedModel) this, state, randomSupplier, context); + default void emitBlockQuads(QuadEmitter emitter, BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { + ExtendedQuadEmitter.of(emitter).emitBlockQuads(emitter, (BakedModel) this, state, randomSupplier, cullTest); } @Override - default void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { - ((ItemRenderContext) context).emitItemQuads((BakedModel) this, null, randomSupplier); + default void emitItemQuads(QuadEmitter emitter, Supplier randomSupplier) { + ExtendedQuadEmitter.of(emitter).emitItemQuads(emitter, (BakedModel) this, null, randomSupplier); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java index 1eca3abcfc..d21bd994e2 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java @@ -1,14 +1,17 @@ package net.vulkanmod.mixin.render.frapi; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(ItemRenderer.class) public interface ItemRendererAccessor { - @Invoker("hasAnimatedTexture") - static boolean hasAnimatedTexture(ItemStack stack) { + @Invoker("getCompassFoilBuffer") + static VertexConsumer getCompassFoilBuffer(MultiBufferSource provider, RenderType layer, PoseStack.Pose entry) { throw new AssertionError(); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java index 7bddb01365..d727b36ee0 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java @@ -16,37 +16,30 @@ package net.vulkanmod.mixin.render.frapi; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -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.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.vertex.PoseStack; @Mixin(ItemRenderer.class) -public abstract class ItemRendererMixin { - @Final - @Shadow - private ItemColors itemColors; - +abstract class ItemRendererMixin { @Unique - private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(() -> new ItemRenderContext(itemColors)); + private static final ThreadLocal CONTEXTS = ThreadLocal.withInitial(ItemRenderContext::new); - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/ItemRenderer;renderSimpleItemModel(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemDisplayContext;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/resources/model/BakedModel;Z)V"), method = "render", cancellable = true) - public void hook_renderItem(ItemStack stack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int light, int overlay, BakedModel model, CallbackInfo ci) { + @Inject(method = "renderItem", at = @At(value = "HEAD"), cancellable = true) + private static void hookRenderItem(ItemDisplayContext itemDisplayContext, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j, int[] is, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType, CallbackInfo ci) { if (!model.isVanillaAdapter()) { - fabric_contexts.get().renderModel(stack, transformMode, invert, matrixStack, vertexConsumerProvider, light, overlay, model); - matrixStack.popPose(); + CONTEXTS.get().renderModel(itemDisplayContext, poseStack, multiBufferSource, i, j, is, model, renderType, foilType); ci.cancel(); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java new file mode 100644 index 0000000000..8e8119d760 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java @@ -0,0 +1,11 @@ +package net.vulkanmod.mixin.render.frapi; + +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.vulkanmod.render.chunk.build.frapi.mesh.ExtendedQuadEmitter; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(QuadEmitter.class) +public interface QuadEmitterM extends ExtendedQuadEmitter { + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java b/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java index e57610fc39..9e3b66eda1 100644 --- a/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java +++ b/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java @@ -12,7 +12,7 @@ import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.parser.GlslConverter; +import net.vulkanmod.vulkan.shader.converter.GlslConverter; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java index a7e5c696e4..9dfd918a9f 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java @@ -163,7 +163,7 @@ public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brig @Unique private void putQuadData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { int[] quadData = quad.getVertices(); - Vec3i vec3i = quad.getDirection().getNormal(); + Vec3i vec3i = quad.getDirection().getUnitVec3i(); Matrix4f matrix4f = matrixEntry.pose(); boolean trustedNormals = ((PoseAccessor)(Object)matrixEntry).trustedNormals(); diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java index b3262bb898..855e7f7503 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java @@ -24,7 +24,7 @@ public class FaceBakeryM { * @author */ @Overwrite - private float[] setupShape(Vector3f vector3f, Vector3f vector3f2) { + private static float[] setupShape(Vector3f vector3f, Vector3f vector3f2) { float[] fs = new float[Direction.values().length]; fs[FaceInfo.Constants.MIN_X] = vector3f.x() * DIV; fs[FaceInfo.Constants.MIN_Y] = vector3f.y() * DIV; diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java index 34bd443331..76317df8d4 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java @@ -57,7 +57,7 @@ private void constr(NativeImage.Format format, int width, int height, boolean us * @author */ @Overwrite - private void _upload(int level, int xOffset, int yOffset, int unpackSkipPixels, int unpackSkipRows, int widthIn, int heightIn, boolean blur, boolean clamp, boolean mipmap, boolean autoClose) { + private void _upload(int level, int xOffset, int yOffset, int unpackSkipPixels, int unpackSkipRows, int widthIn, int heightIn, boolean autoClose) { RenderSystem.assertOnRenderThreadOrInit(); VTextureSelector.uploadSubTexture(level, widthIn, heightIn, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, this.getWidth(), this.buffer); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java index 98a3ab4355..b3148e219e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java @@ -41,7 +41,6 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { DataLayer[][] lightData = new DataLayer[RenderRegion.SIZE][2 /* Light types */]; - final int minHeightSec = level.getMinY() >> 4; long biomeZoomSeed = BiomeManagerExtended.of(level.getBiomeManager()).getBiomeZoomSeed(); BiomeData biomeData = new BiomeData(biomeZoomSeed, minSecX, minSecY, minSecZ); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java index 166f4b3a8a..fe701cbe63 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java @@ -32,8 +32,8 @@ public BiomeData(long biomeZoomSeed, int secX, int secY, int secZ) { public void getBiomeData(Level level, LevelChunkSection chunkSection, int secX, int secY, int secZ) { Biome defaultValue = level.registryAccess() - .registryOrThrow(Registries.BIOME) - .getHolderOrThrow(Biomes.PLAINS) + .lookupOrThrow(Registries.BIOME) + .getOrThrow(Biomes.PLAINS) .value(); int baseIdx = getRelativeSectionIdx(secX, secY, secZ); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java index e2a3351097..c61e9b064c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java @@ -2,15 +2,14 @@ import java.util.HashMap; +import net.fabricmc.fabric.api.renderer.v1.mesh.MutableMesh; import net.minecraft.resources.ResourceLocation; import net.fabricmc.fabric.api.renderer.v1.Renderer; import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; import net.vulkanmod.render.chunk.build.frapi.material.MaterialFinderImpl; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; -import net.vulkanmod.render.chunk.build.frapi.mesh.MeshBuilderImpl; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; /** * The Fabric default renderer implementation. Supports all @@ -19,10 +18,10 @@ public class VulkanModRenderer implements Renderer { public static final VulkanModRenderer INSTANCE = new VulkanModRenderer(); - public static final RenderMaterial MATERIAL_STANDARD = INSTANCE.materialFinder().find(); + public static final RenderMaterial STANDARD_MATERIAL = INSTANCE.materialFinder().find(); static { - INSTANCE.registerMaterial(RenderMaterial.MATERIAL_STANDARD, MATERIAL_STANDARD); + INSTANCE.registerMaterial(RenderMaterial.STANDARD_ID, STANDARD_MATERIAL); } private final HashMap materialMap = new HashMap<>(); @@ -30,8 +29,8 @@ public class VulkanModRenderer implements Renderer { private VulkanModRenderer() {} @Override - public MeshBuilder meshBuilder() { - return new MeshBuilderImpl(); + public MutableMesh mutableMesh() { + return new MutableMeshImpl(); } @Override @@ -49,7 +48,7 @@ public boolean registerMaterial(ResourceLocation id, RenderMaterial material) { if (materialMap.containsKey(id)) return false; // cast to prevent acceptance of impostor implementations - materialMap.put(id, (RenderMaterialImpl) material); + materialMap.put(id, material); return true; } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java index 66e8a805e4..fc68442cda 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java @@ -18,12 +18,12 @@ import static net.minecraft.util.Mth.equal; -import org.joml.Vector3f; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; +import org.joml.Vector3fc; /** * Static routines of general utility for renderer implementations. @@ -178,7 +178,7 @@ private static boolean confirmSquareCorners(int aCoordinate, int bCoordinate, Qu *

Derived from the quad face normal and expects convex quads with all points co-planar. */ public static Direction lightFace(QuadView quad) { - final Vector3f normal = quad.faceNormal(); + final Vector3fc normal = quad.faceNormal(); switch (GeometryHelper.longestAxis(normal)) { case X: return normal.x() > 0 ? Direction.EAST : Direction.WEST; @@ -216,7 +216,7 @@ public static float max(float a, float b, float c, float d) { /** * @see #longestAxis(float, float, float) */ - public static Axis longestAxis(Vector3f vec) { + public static Axis longestAxis(Vector3fc vec) { return longestAxis(vec.x(), vec.y(), vec.z()); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java index 91b510452e..ed75223ebd 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java @@ -19,6 +19,7 @@ import java.util.Objects; import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; @@ -26,21 +27,26 @@ import net.fabricmc.fabric.api.util.TriState; public class MaterialFinderImpl extends MaterialViewImpl implements MaterialFinder { - private static int defaultBits = 0; + private static final int DEFAULT_BITS; static { - MaterialFinderImpl finder = new MaterialFinderImpl(); + // Start with all zeroes + MaterialFinderImpl finder = new MaterialFinderImpl(0); + // Apply non-zero defaults finder.ambientOcclusion(TriState.DEFAULT); - finder.glint(TriState.DEFAULT); - defaultBits = finder.bits; + DEFAULT_BITS = finder.bits; - if (!areBitsValid(defaultBits)) { + if (!areBitsValid(DEFAULT_BITS)) { throw new AssertionError("Default MaterialFinder bits are not valid!"); } } + protected MaterialFinderImpl(int bits) { + super(bits); + } + public MaterialFinderImpl() { - super(defaultBits); + this(DEFAULT_BITS); } @Override @@ -51,12 +57,6 @@ public MaterialFinder blendMode(BlendMode blendMode) { return this; } - @Override - public MaterialFinder disableColorIndex(boolean disable) { - bits = disable ? (bits | COLOR_DISABLE_FLAG) : (bits & ~COLOR_DISABLE_FLAG); - return this; - } - @Override public MaterialFinder emissive(boolean isEmissive) { bits = isEmissive ? (bits | EMISSIVE_FLAG) : (bits & ~EMISSIVE_FLAG); @@ -78,10 +78,10 @@ public MaterialFinder ambientOcclusion(TriState mode) { } @Override - public MaterialFinder glint(TriState mode) { - Objects.requireNonNull(mode, "glint TriState may not be null"); + public MaterialFinder glintMode(GlintMode mode) { + Objects.requireNonNull(mode, "GlintMode may not be null"); - bits = (bits & ~GLINT_MASK) | (mode.ordinal() << GLINT_BIT_OFFSET); + bits = (bits & ~GLINT_MODE_MASK) | (mode.ordinal() << GLINT_MODE_BIT_OFFSET); return this; } @@ -101,7 +101,7 @@ public MaterialFinder copyFrom(MaterialView material) { @Override public MaterialFinder clear() { - bits = defaultBits; + bits = DEFAULT_BITS; return this; } @@ -109,4 +109,4 @@ public MaterialFinder clear() { public RenderMaterial find() { return RenderMaterialImpl.byIndex(bits); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java index 0ae0705742..3733f6da74 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java @@ -16,13 +16,15 @@ package net.vulkanmod.render.chunk.build.frapi.material; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.bitMask; +import net.minecraft.util.Mth; import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; import net.fabricmc.fabric.api.util.TriState; -import net.minecraft.util.Mth; + +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.bitMask; /** * Default implementation of the standard render materials. @@ -35,43 +37,42 @@ public class MaterialViewImpl implements MaterialView { private static final int BLEND_MODE_COUNT = BLEND_MODES.length; private static final TriState[] TRI_STATES = TriState.values(); private static final int TRI_STATE_COUNT = TRI_STATES.length; + private static final GlintMode[] GLINT_MODES = GlintMode.values(); + private static final int GLINT_MODE_COUNT = GLINT_MODES.length; private static final ShadeMode[] SHADE_MODES = ShadeMode.values(); private static final int SHADE_MODE_COUNT = SHADE_MODES.length; protected static final int BLEND_MODE_BIT_LENGTH = Mth.ceillog2(BLEND_MODE_COUNT); - protected static final int COLOR_DISABLE_BIT_LENGTH = 1; protected static final int EMISSIVE_BIT_LENGTH = 1; protected static final int DIFFUSE_BIT_LENGTH = 1; protected static final int AO_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); - protected static final int GLINT_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); + protected static final int GLINT_MODE_BIT_LENGTH = Mth.ceillog2(GLINT_MODE_COUNT); protected static final int SHADE_MODE_BIT_LENGTH = Mth.ceillog2(SHADE_MODE_COUNT); protected static final int BLEND_MODE_BIT_OFFSET = 0; - protected static final int COLOR_DISABLE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; - protected static final int EMISSIVE_BIT_OFFSET = COLOR_DISABLE_BIT_OFFSET + COLOR_DISABLE_BIT_LENGTH; + protected static final int EMISSIVE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; protected static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; protected static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; - protected static final int GLINT_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; - protected static final int SHADE_MODE_BIT_OFFSET = GLINT_BIT_OFFSET + GLINT_BIT_LENGTH; + protected static final int GLINT_MODE_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; + protected static final int SHADE_MODE_BIT_OFFSET = GLINT_MODE_BIT_OFFSET + GLINT_MODE_BIT_LENGTH; public static final int TOTAL_BIT_LENGTH = SHADE_MODE_BIT_OFFSET + SHADE_MODE_BIT_LENGTH; protected static final int BLEND_MODE_MASK = bitMask(BLEND_MODE_BIT_LENGTH, BLEND_MODE_BIT_OFFSET); - protected static final int COLOR_DISABLE_FLAG = bitMask(COLOR_DISABLE_BIT_LENGTH, COLOR_DISABLE_BIT_OFFSET); protected static final int EMISSIVE_FLAG = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); protected static final int DIFFUSE_FLAG = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); protected static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); - protected static final int GLINT_MASK = bitMask(GLINT_BIT_LENGTH, GLINT_BIT_OFFSET); + protected static final int GLINT_MODE_MASK = bitMask(GLINT_MODE_BIT_LENGTH, GLINT_MODE_BIT_OFFSET); protected static final int SHADE_MODE_MASK = bitMask(SHADE_MODE_BIT_LENGTH, SHADE_MODE_BIT_OFFSET); protected static boolean areBitsValid(int bits) { int blendMode = (bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET; int ao = (bits & AO_MASK) >>> AO_BIT_OFFSET; - int glint = (bits & GLINT_MASK) >>> GLINT_BIT_OFFSET; + int glintMode = (bits & GLINT_MODE_MASK) >>> GLINT_MODE_BIT_OFFSET; int shadeMode = (bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET; return blendMode < BLEND_MODE_COUNT && ao < TRI_STATE_COUNT - && glint < TRI_STATE_COUNT + && glintMode < GLINT_MODE_COUNT && shadeMode < SHADE_MODE_COUNT; } @@ -86,11 +87,6 @@ public BlendMode blendMode() { return BLEND_MODES[(bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET]; } - @Override - public boolean disableColorIndex() { - return (bits & COLOR_DISABLE_FLAG) != 0; - } - @Override public boolean emissive() { return (bits & EMISSIVE_FLAG) != 0; @@ -107,12 +103,12 @@ public TriState ambientOcclusion() { } @Override - public TriState glint() { - return TRI_STATES[(bits & GLINT_MASK) >>> GLINT_BIT_OFFSET]; + public GlintMode glintMode() { + return GLINT_MODES[(bits & GLINT_MODE_MASK) >>> GLINT_MODE_BIT_OFFSET]; } @Override public ShadeMode shadeMode() { return SHADE_MODES[(bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET]; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java index f1cf763cce..259c4186bc 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java @@ -33,12 +33,12 @@ * packing/unpacking quad data in an array of integers. * All of this is implementation-specific - that's why it isn't a "helper" class. */ -public abstract class EncodingFormat { +public final class EncodingFormat { private EncodingFormat() { } static final int HEADER_BITS = 0; static final int HEADER_FACE_NORMAL = 1; - static final int HEADER_COLOR_INDEX = 2; + static final int HEADER_TINT_INDEX = 2; static final int HEADER_TAG = 3; public static final int HEADER_STRIDE = 4; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java new file mode 100644 index 0000000000..38ac8c8a1d --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java @@ -0,0 +1,29 @@ +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.impl.renderer.VanillaModelEncoder; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Predicate; +import java.util.function.Supplier; + +public interface ExtendedQuadEmitter { + + static ExtendedQuadEmitter of(QuadEmitter quadEmitter) { + return (ExtendedQuadEmitter) quadEmitter; + } + + default void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { + VanillaModelEncoder.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); + } + + default void emitItemQuads(QuadEmitter emitter,BakedModel model, BlockState state, Supplier randomSupplier) { + VanillaModelEncoder.emitItemQuads(emitter, model, state, randomSupplier); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java deleted file mode 100644 index b5119de51b..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; -import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; - -/** - * Our implementation of {@link MeshBuilder}, used for static mesh creation and baking. - * Not much to it - mainly it just needs to grow the int[] array as quads are appended - * and maintain/provide a properly-configured {@link net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView} instance. - * All the encoding and other work is handled in the quad base classes. - * The one interesting bit is in {@link Maker#emitDirectly()}. - */ -public class MeshBuilderImpl implements MeshBuilder { - private int[] data = new int[256]; - private int index = 0; - private int limit = data.length; - private final Maker maker = new Maker(); - - public MeshBuilderImpl() { - ensureCapacity(EncodingFormat.TOTAL_STRIDE); - maker.data = data; - maker.baseIndex = index; - maker.clear(); - } - - protected void ensureCapacity(int stride) { - if (stride > limit - index) { - limit *= 2; - final int[] bigger = new int[limit]; - System.arraycopy(data, 0, bigger, 0, index); - data = bigger; - maker.data = data; - } - } - - @Override - public QuadEmitter getEmitter() { - maker.clear(); - return maker; - } - - @Override - public Mesh build() { - final int[] packed = new int[index]; - System.arraycopy(data, 0, packed, 0, index); - index = 0; - maker.baseIndex = index; - maker.clear(); - return new MeshImpl(packed); - } - - /** - * Our base classes are used differently so we define final - * encoding steps in subtypes. This will be a static mesh used - * at render time so we want to capture all geometry now and - * apply non-location-dependent lighting. - */ - private class Maker extends MutableQuadViewImpl { - @Override - public void emitDirectly() { - computeGeometry(); - index += EncodingFormat.TOTAL_STRIDE; - ensureCapacity(EncodingFormat.TOTAL_STRIDE); - baseIndex = index; - } - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java index ff23f44f77..834f867b82 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java @@ -18,61 +18,85 @@ import java.util.function.Consumer; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.Range; + import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -/** - * Implementation of {@link Mesh}. - * The way we encode meshes makes it very simple. - */ public class MeshImpl implements Mesh { /** Used to satisfy external calls to {@link #forEach(Consumer)}. */ - private final ThreadLocal cursorPool = ThreadLocal.withInitial(QuadViewImpl::new); + private static final ThreadLocal> CURSOR_POOLS = ThreadLocal.withInitial(ObjectArrayList::new); - final int[] data; + int[] data; + int limit; MeshImpl(int[] data) { this.data = data; + limit = data.length; + } + + MeshImpl() { + } + + @Override + @Range(from = 0, to = Integer.MAX_VALUE) + public int size() { + return limit / EncodingFormat.TOTAL_STRIDE; } @Override - public void forEach(Consumer consumer) { - forEach(consumer, cursorPool.get()); + public void forEach(Consumer action) { + ObjectArrayList pool = CURSOR_POOLS.get(); + QuadViewImpl cursor; + + if (pool.isEmpty()) { + cursor = new QuadViewImpl(); + } else { + cursor = pool.pop(); + } + + forEach(action, cursor); + + pool.push(cursor); } /** - * The renderer can call this with its own cursor - * to avoid the performance hit of a thread-local lookup. - * Also means renderer can hold final references to quad buffers. + * The renderer can call this with its own cursor to avoid the performance hit of a + * thread-local lookup or to use a mutable cursor. */ - void forEach(Consumer consumer, QuadViewImpl cursor) { - final int limit = data.length; + void forEach(Consumer action, C cursor) { + final int limit = this.limit; int index = 0; - cursor.data = this.data; + cursor.data = data; while (index < limit) { cursor.baseIndex = index; cursor.load(); - consumer.accept(cursor); + action.accept(cursor); index += EncodingFormat.TOTAL_STRIDE; } + + cursor.data = null; } + // TODO: This could be optimized by checking if the emitter is that of a MutableMeshImpl and if + // it has no transforms, in which case the entire data array can be copied in bulk. @Override public void outputTo(QuadEmitter emitter) { MutableQuadViewImpl e = (MutableQuadViewImpl) emitter; final int[] data = this.data; - final int limit = data.length; + final int limit = this.limit; int index = 0; while (index < limit) { System.arraycopy(data, index, e.data, e.baseIndex, EncodingFormat.TOTAL_STRIDE); e.load(); - e.emitDirectly(); + e.transformAndEmit(); index += EncodingFormat.TOTAL_STRIDE; } e.clear(); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableMeshImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableMeshImpl.java new file mode 100644 index 0000000000..79ab94df64 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableMeshImpl.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.mesh; + +import java.util.function.Consumer; + +import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; +import net.fabricmc.fabric.api.renderer.v1.mesh.MutableMesh; +import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; + +/** + * Our implementation of {@link MutableMesh}, mainly used for optimized mesh creation. + * Not much to it - mainly it just needs to grow the int[] array as quads are appended + * and maintain/provide a properly-configured {@link MutableQuadView} instance. + * All the encoding and other work is handled in the quad base classes. + * The one interesting bit is in {@link #emitter}. + */ +public class MutableMeshImpl extends MeshImpl implements MutableMesh { + private final MutableQuadViewImpl emitter = new MutableQuadViewImpl() { + @Override + protected void emitDirectly() { + // Necessary because the validity of geometry is not encoded; reading mesh data always + // uses QuadViewImpl#load(), which assumes valid geometry. Built immutable meshes + // should also have valid geometry for better performance. + computeGeometry(); + limit += EncodingFormat.TOTAL_STRIDE; + ensureCapacity(EncodingFormat.TOTAL_STRIDE); + baseIndex = limit; + } + }; + + public MutableMeshImpl() { + data = new int[8 * EncodingFormat.TOTAL_STRIDE]; + limit = 0; + + ensureCapacity(EncodingFormat.TOTAL_STRIDE); + emitter.data = data; + emitter.baseIndex = limit; + emitter.clear(); + } + + private void ensureCapacity(int stride) { + if (stride > data.length - limit) { + final int[] bigger = new int[data.length * 2]; + System.arraycopy(data, 0, bigger, 0, limit); + data = bigger; + emitter.data = data; + } + } + + @Override + public QuadEmitter emitter() { + emitter.clear(); + return emitter; + } + + @Override + public void forEachMutable(Consumer action) { + // emitDirectly will not be called by forEach, so just reuse the main emitter. + forEach(action, emitter); + emitter.data = data; + emitter.baseIndex = limit; + } + + @Override + public Mesh immutableCopy() { + final int[] packed = new int[limit]; + System.arraycopy(data, 0, packed, 0, limit); + return new MeshImpl(packed); + } + + @Override + public void clear() { + limit = 0; + emitter.baseIndex = limit; + emitter.clear(); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index b7120ac014..3ab5d27275 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -16,19 +16,21 @@ package net.vulkanmod.render.chunk.build.frapi.mesh; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import net.vulkanmod.render.model.quad.ModelQuadView; import org.jetbrains.annotations.Nullable; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadTransform; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; import net.vulkanmod.render.chunk.build.frapi.helper.TextureHelper; import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.*; @@ -43,16 +45,46 @@ * render - the editor is serving mainly as a way to access vertex data without magical * numbers. It also allows for a consistent interface for those transformations. */ -public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter { - public void clear() { - System.arraycopy(EMPTY, 0, data, baseIndex, EncodingFormat.TOTAL_STRIDE); +public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter, ExtendedQuadEmitter { + private static final QuadTransform NO_TRANSFORM = q -> true; + + private static final int[] DEFAULT_QUAD_DATA = new int[EncodingFormat.TOTAL_STRIDE]; + + static { + MutableQuadViewImpl quad = new MutableQuadViewImpl() { + @Override + protected void emitDirectly() { + // This quad won't be emitted. It's only used to configure the default quad data. + } + }; + + // Start with all zeroes + quad.data = DEFAULT_QUAD_DATA; + // Apply non-zero defaults + quad.color(-1, -1, -1, -1); + quad.cullFace(null); + quad.material(VulkanModRenderer.STANDARD_MATERIAL); + quad.tintIndex(-1); + } + + private QuadTransform activeTransform = NO_TRANSFORM; + private final ObjectArrayList transformStack = new ObjectArrayList<>(); + private final QuadTransform stackTransform = q -> { + int i = transformStack.size() - 1; + + while (i >= 0) { + if (!transformStack.get(i--).transform(q)) { + return false; + } + } + + return true; + }; + + public final void clear() { + System.arraycopy(DEFAULT_QUAD_DATA, 0, data, baseIndex, EncodingFormat.TOTAL_STRIDE); isGeometryInvalid = true; nominalFace = null; - normalFlags(0); - tag(0); - colorIndex(-1); - cullFace(null); - material(VulkanModRenderer.MATERIAL_STANDARD); } @Override @@ -136,17 +168,13 @@ public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { @Override public final MutableQuadViewImpl material(RenderMaterial material) { - if (material == null) { - material = VulkanModRenderer.MATERIAL_STANDARD; - } - data[baseIndex + HEADER_BITS] = EncodingFormat.material(data[baseIndex + HEADER_BITS], (RenderMaterialImpl) material); return this; } @Override - public final MutableQuadViewImpl colorIndex(int colorIndex) { - data[baseIndex + HEADER_COLOR_INDEX] = colorIndex; + public final MutableQuadViewImpl tintIndex(int tintIndex) { + data[baseIndex + HEADER_TINT_INDEX] = tintIndex; return this; } @@ -159,12 +187,14 @@ public final MutableQuadViewImpl tag(int tag) { @Override public MutableQuadViewImpl copyFrom(QuadView quad) { final QuadViewImpl q = (QuadViewImpl) quad; - q.computeGeometry(); - System.arraycopy(q.data, q.baseIndex, data, baseIndex, EncodingFormat.TOTAL_STRIDE); - faceNormal.set(q.faceNormal); nominalFace = q.nominalFace; - isGeometryInvalid = false; + isGeometryInvalid = q.isGeometryInvalid; + + if (!isGeometryInvalid) { + faceNormal.set(q.faceNormal); + } + return this; } @@ -188,7 +218,7 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate fromVanilla(quad.getVertices(), 0); data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); nominalFace(quad.getDirection()); - colorIndex(quad.getTintIndex()); + tintIndex(quad.getTintIndex()); if (!quad.isShade()) { material = RenderMaterialImpl.setDisableDiffuse((RenderMaterialImpl) material, true); @@ -221,16 +251,51 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate return this; } + @Override + public void pushTransform(QuadTransform transform) { + if (transform == null) { + throw new NullPointerException("QuadTransform cannot be null!"); + } + + transformStack.push(transform); + + if (transformStack.size() == 1) { + activeTransform = transform; + } else if (transformStack.size() == 2) { + activeTransform = stackTransform; + } + } + + @Override + public void popTransform() { + transformStack.pop(); + + if (transformStack.size() == 0) { + activeTransform = NO_TRANSFORM; + } else if (transformStack.size() == 1) { + activeTransform = transformStack.get(0); + } + } + /** - * Emit the quad without clearing the underlying data. + * Emit the quad without applying transforms and without clearing the underlying data. * Geometry is not guaranteed to be valid when called, but can be computed by calling {@link #computeGeometry()}. */ - public abstract void emitDirectly(); + protected abstract void emitDirectly(); + + /** + * Apply transforms and then if transforms return true, emit the quad without clearing the underlying data. + */ + public final void transformAndEmit() { + if (activeTransform.transform(this)) { + emitDirectly(); + } + } @Override public final MutableQuadViewImpl emit() { - emitDirectly(); + transformAndEmit(); clear(); return this; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java index 526e45b615..d6e63b13ba 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java @@ -17,7 +17,7 @@ package net.vulkanmod.render.chunk.build.frapi.mesh; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_BITS; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_COLOR_INDEX; +import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_TINT_INDEX; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_FACE_NORMAL; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_STRIDE; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_TAG; @@ -166,22 +166,22 @@ public int lightmap(int vertexIndex) { return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP]; } - public int normalFlags() { + public final int normalFlags() { return EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS]); } @Override - public boolean hasNormal(int vertexIndex) { + public final boolean hasNormal(int vertexIndex) { return (normalFlags() & (1 << vertexIndex)) != 0; } /** True if any vertex normal has been set. */ - public boolean hasVertexNormals() { + public final boolean hasVertexNormals() { return normalFlags() != 0; } /** True if all vertex normals have been set. */ - public boolean hasAllVertexNormals() { + public final boolean hasAllVertexNormals() { return (normalFlags() & 0b1111) == 0b1111; } @@ -190,23 +190,23 @@ protected final int normalIndex(int vertexIndex) { } @Override - public float normalX(int vertexIndex) { + public final float normalX(int vertexIndex) { return hasNormal(vertexIndex) ? NormalHelper.unpackNormalX(data[normalIndex(vertexIndex)]) : Float.NaN; } @Override - public float normalY(int vertexIndex) { + public final float normalY(int vertexIndex) { return hasNormal(vertexIndex) ? NormalHelper.unpackNormalY(data[normalIndex(vertexIndex)]) : Float.NaN; } @Override - public float normalZ(int vertexIndex) { + public final float normalZ(int vertexIndex) { return hasNormal(vertexIndex) ? NormalHelper.unpackNormalZ(data[normalIndex(vertexIndex)]) : Float.NaN; } @Override @Nullable - public Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { + public final Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { if (hasNormal(vertexIndex)) { if (target == null) { target = new Vector3f(); @@ -256,8 +256,8 @@ public final RenderMaterialImpl material() { } @Override - public final int colorIndex() { - return data[baseIndex + HEADER_COLOR_INDEX]; + public final int tintIndex() { + return data[baseIndex + HEADER_TINT_INDEX]; } @Override @@ -269,10 +269,7 @@ public final int tag() { public final void toVanilla(int[] target, int targetIndex) { System.arraycopy(data, baseIndex + HEADER_STRIDE, target, targetIndex, QUAD_STRIDE); - // The color is the fourth integer in each vertex. - // EncodingFormat.VERTEX_COLOR is not used because it also - // contains the header size; vanilla quads do not have a header. - int colorIndex = targetIndex + 3; + int colorIndex = targetIndex + VERTEX_COLOR - HEADER_STRIDE; for (int i = 0; i < 4; i++) { target[colorIndex] = ColorHelper.toVanillaColor(target[colorIndex]); @@ -317,7 +314,7 @@ public float getV(int idx) { @Override public int getColorIndex() { - return this.colorIndex(); + return this.tintIndex(); } @Override diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index abd7ca1962..5399f7e423 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -2,44 +2,42 @@ import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; import net.fabricmc.fabric.api.renderer.v1.Renderer; -import net.fabricmc.fabric.api.renderer.v1.RendererAccess; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.resources.model.BakedModel; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.vulkanmod.interfaces.color.BlockColorsExtended; import net.vulkanmod.render.chunk.build.color.BlockColorRegistry; +import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import org.jetbrains.annotations.Nullable; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.util.TriState; import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.level.block.state.BlockState; import java.util.List; +import java.util.function.Predicate; import java.util.function.Supplier; public abstract class AbstractBlockRenderContext extends AbstractRenderContext { - private static final Renderer RENDERER = RendererAccess.INSTANCE.getRenderer(); + private static final Renderer RENDERER = VulkanModRenderer.INSTANCE; protected static final RenderMaterial STANDARD_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).find(); protected static final RenderMaterial NO_AO_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).ambientOcclusion(TriState.FALSE).find(); @@ -55,6 +53,12 @@ public abstract class AbstractBlockRenderContext extends AbstractRenderContext { public void emitDirectly() { renderQuad(this); } + + @Override + public void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, + Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { + AbstractBlockRenderContext.this.emitBlockQuads(model, state, randomSupplier, cullTest); + } }; protected BlockState blockState; @@ -100,17 +104,6 @@ protected void setupLightPipelines(LightPipeline flatLightPipeline, LightPipelin this.smoothLightPipeline = smoothLightPipeline; } - @Override - public QuadEmitter getEmitter() { - editorQuad.clear(); - return editorQuad; - } - - @Override - public ItemDisplayContext itemTransformationMode() { - throw new IllegalStateException("itemTransformationMode() can only be called on an item render context."); - } - public void prepareForWorld(BlockAndTintGetter blockView, boolean enableCulling) { this.renderRegion = blockView; this.enableCulling = enableCulling; @@ -127,7 +120,6 @@ public void prepareForBlock(BlockState blockState, BlockPos blockPos, boolean mo this.cullResultFlags = 0; } - @Override public boolean isFaceCulled(@Nullable Direction face) { return !this.shouldRenderFace(face); } @@ -198,11 +190,17 @@ public boolean faceNotOccluded(BlockState blockState, Direction face) { return true; } - private void renderQuad(MutableQuadViewImpl quad) { - if (!transform(quad)) { - return; - } + public QuadEmitter getEmitter() { + editorQuad.clear(); + return editorQuad; + } + + @Override + protected void bufferQuad(MutableQuadViewImpl quadView) { + this.renderQuad(quadView); + } + private void renderQuad(MutableQuadViewImpl quad) { if (isFaceCulled(quad.cullFace())) { return; } @@ -213,9 +211,11 @@ private void renderQuad(MutableQuadViewImpl quad) { protected void endRenderQuad(MutableQuadViewImpl quad) {} /** handles block color, common to all renders. */ - protected void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { - if (colorIndex != -1) { - final int blockColor = getBlockColor(this.renderRegion, colorIndex); + protected void tintQuad(MutableQuadViewImpl quad) { + int tintIndex = quad.tintIndex(); + + if (tintIndex != -1) { + final int blockColor = getBlockColor(this.renderRegion, tintIndex); for (int i = 0; i < 4; i++) { quad.color(i, ColorHelper.multiplyColor(blockColor, quad.color(i))); @@ -251,46 +251,27 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, } } - public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, RenderContext context) { + public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, Predicate cullTest) { MutableQuadViewImpl quad = this.editorQuad; final RenderMaterial defaultMaterial = model.useAmbientOcclusion() ? STANDARD_MATERIAL : NO_AO_MATERIAL; - boolean noTransform = !this.hasTransform(); - - if (noTransform) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - - if (context.isFaceCulled(cullFace)) { - // Skip entire quad list if possible. - continue; - } - - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - quad.fromVanilla(q, defaultMaterial, cullFace); - - this.endRenderQuad(quad); - } + if (cullTest.test(cullFace)) { + // Skip entire quad list if possible. + continue; } - } else { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - quad.fromVanilla(q, defaultMaterial, cullFace); + //noinspection ForLoopReplaceableByForEach + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + quad.fromVanilla(q, defaultMaterial, cullFace); - this.renderQuad(quad); - } + this.endRenderQuad(quad); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java index 5048e0874b..c3d47270f8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java @@ -16,85 +16,26 @@ package net.vulkanmod.render.chunk.build.frapi.render; -import java.util.function.Consumer; import com.mojang.blaze3d.vertex.VertexConsumer; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; import org.joml.Vector4f; -import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; -import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; - -abstract class AbstractRenderContext implements RenderContext { - private static final QuadTransform NO_TRANSFORM = q -> true; - - private QuadTransform activeTransform = NO_TRANSFORM; - private final ObjectArrayList transformStack = new ObjectArrayList<>(); - private final QuadTransform stackTransform = q -> { - int i = transformStack.size() - 1; - - while (i >= 0) { - if (!transformStack.get(i--).transform(q)) { - return false; - } - } - return true; - }; - @Deprecated - private final Consumer meshConsumer = mesh -> mesh.outputTo(getEmitter()); +public abstract class AbstractRenderContext { + private final Vector4f posVec = new Vector4f(); + private final Vector3f normalVec = new Vector3f(); protected Matrix4f matrix; protected Matrix3f normalMatrix; protected int overlay; - private final Vector4f posVec = new Vector4f(); - private final Vector3f normalVec = new Vector3f(); - protected final boolean transform(MutableQuadView q) { - return activeTransform.transform(q); - } + protected abstract QuadEmitter getEmitter(); - @Override - public boolean hasTransform() { - return activeTransform != NO_TRANSFORM; - } - - @Override - public void pushTransform(QuadTransform transform) { - if (transform == null) { - throw new NullPointerException("Renderer received null QuadTransform."); - } - - transformStack.push(transform); - - if (transformStack.size() == 1) { - activeTransform = transform; - } else if (transformStack.size() == 2) { - activeTransform = stackTransform; - } - } - - @Override - public void popTransform() { - transformStack.pop(); - - if (transformStack.size() == 0) { - activeTransform = NO_TRANSFORM; - } else if (transformStack.size() == 1) { - activeTransform = transformStack.get(0); - } - } - - // Overridden to prevent allocating a lambda every time this method is called. - @Deprecated - @Override - public Consumer meshConsumer() { - return meshConsumer; - } + protected abstract void bufferQuad(MutableQuadViewImpl quadView); /** final output step, common to all renders. */ protected void bufferQuad(MutableQuadViewImpl quad, VertexConsumer vertexConsumer) { @@ -128,4 +69,4 @@ protected void bufferQuad(MutableQuadViewImpl quad, VertexConsumer vertexConsume vertexConsumer.setNormal(normalVec.x(), normalVec.y(), normalVec.z()); } } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java index c0376db6f8..c8016d4b63 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -86,7 +86,6 @@ public void render(BlockAndTintGetter blockView, BakedModel model, BlockState st protected void endRenderQuad(MutableQuadViewImpl quad) { final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); final TriState aoMode = mat.ambientOcclusion(); final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); final boolean emissive = mat.emissive(); @@ -94,16 +93,10 @@ protected void endRenderQuad(MutableQuadViewImpl quad) { LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; - colorizeQuad(quad, colorIndex); + tintQuad(quad); shadeQuad(quad, lightPipeline, emissive, vanillaShade); copyLightData(quad); bufferQuad(quad, vertexConsumer); } - private void copyLightData(MutableQuadViewImpl quad) { - for (int i = 0; i < 4; i++) { - quad.lightmap(i, this.quadLightData.lm[i]); - } - } - } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index 843c71a8be..5f934c7ec1 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -20,15 +20,16 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.math.MatrixUtil; +import java.util.Arrays; import java.util.List; import java.util.function.Supplier; +import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; import org.jetbrains.annotations.Nullable; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.item.ItemColors; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; @@ -50,7 +51,6 @@ import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -import net.fabricmc.fabric.impl.renderer.VanillaModelEncoder; import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; @@ -59,10 +59,10 @@ */ @SuppressWarnings("removal") public class ItemRenderContext extends AbstractRenderContext { - /** Value vanilla uses for item rendering. The only sensible choice, of course. */ + /** Value vanilla uses for item rendering. The only sensible choice, of course. */ private static final long ITEM_RANDOM_SEED = 42L; + private static final int GLINT_COUNT = ItemStackRenderState.FoilType.values().length; - private final ItemColors itemColors; private final RandomSource random = RandomSource.create(); private final Supplier randomSupplier = () -> { random.setSeed(ITEM_RANDOM_SEED); @@ -77,153 +77,95 @@ public class ItemRenderContext extends AbstractRenderContext { @Override public void emitDirectly() { - renderQuad(this); + bufferQuad(this); + } + + @Override + public void emitItemQuads(QuadEmitter emitter, BakedModel model, BlockState state, + Supplier randomSupplier) { +// super.emitItemQuads(emitter, model, state, randomSupplier); + ItemRenderContext.this.emitItemQuads(model, state, randomSupplier); } }; - private ItemStack itemStack; private ItemDisplayContext transformMode; private PoseStack matrixStack; private MultiBufferSource vertexConsumerProvider; private int lightmap; + private int[] tints; - private boolean isDefaultTranslucent; - private boolean isTranslucentDirect; - private boolean isDefaultGlint; - private boolean isGlintDynamicDisplay; + private RenderType defaultLayer; + private ItemStackRenderState.FoilType defaultGlint; - private PoseStack.Pose dynamicDisplayGlintEntry; - private VertexConsumer translucentVertexConsumer; - private VertexConsumer cutoutVertexConsumer; - private VertexConsumer translucentGlintVertexConsumer; - private VertexConsumer cutoutGlintVertexConsumer; + private PoseStack.Pose specialGlintEntry; + private final VertexConsumer[] vertexConsumerCache = new VertexConsumer[3 * GLINT_COUNT]; - public ItemRenderContext(ItemColors itemColors) { - this.itemColors = itemColors; + public ItemRenderContext() { } - @Override public QuadEmitter getEmitter() { editorQuad.clear(); return editorQuad; } - @Override - public boolean isFaceCulled(@Nullable Direction face) { - throw new IllegalStateException("isFaceCulled can only be called on a block render context."); - } - - @Override - public ItemDisplayContext itemTransformationMode() { - return transformMode; - } - - public void renderModel(ItemStack itemStack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int lightmap, int overlay, BakedModel model) { - this.itemStack = itemStack; + public void renderModel(ItemDisplayContext transformMode, PoseStack matrixStack, MultiBufferSource bufferSource, int lightmap, int overlay, int[] tints, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType) { this.transformMode = transformMode; this.matrixStack = matrixStack; - this.vertexConsumerProvider = vertexConsumerProvider; + this.vertexConsumerProvider = bufferSource; this.lightmap = lightmap; this.overlay = overlay; - computeOutputInfo(); + this.tints = tints; + + defaultLayer = renderType; + defaultGlint = foilType; matrix = matrixStack.last().pose(); normalMatrix = matrixStack.last().normal(); - model.emitItemQuads(itemStack, randomSupplier, this); + model.emitItemQuads(getEmitter(), randomSupplier); - this.itemStack = null; this.matrixStack = null; this.vertexConsumerProvider = null; + this.tints = null; - dynamicDisplayGlintEntry = null; - translucentVertexConsumer = null; - cutoutVertexConsumer = null; - translucentGlintVertexConsumer = null; - cutoutGlintVertexConsumer = null; + specialGlintEntry = null; + Arrays.fill(vertexConsumerCache, null); } public void emitItemQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier) { - if (!this.hasTransform()) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - endRenderQuad(editorQuad); - } - } - } - else { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - this.renderQuad(editorQuad); - } - } - } - } - - private void computeOutputInfo() { - isDefaultTranslucent = true; - isTranslucentDirect = true; + for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { + final Direction cullFace = ModelHelper.faceFromIndex(i); + final List quads = model.getQuads(state, cullFace, randomSupplier.get()); + final int count = quads.size(); - Item item = itemStack.getItem(); + for (int j = 0; j < count; j++) { + final BakedQuad q = quads.get(j); + editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - if (item instanceof BlockItem blockItem) { - BlockState state = blockItem.getBlock().defaultBlockState(); - RenderType renderLayer = ItemBlockRenderTypes.getChunkRenderType(state); - - if (renderLayer != RenderType.translucent()) { - isDefaultTranslucent = false; - } - - if (transformMode != ItemDisplayContext.GUI && !transformMode.firstPerson()) { - isTranslucentDirect = false; + bufferQuad(editorQuad); } } - - isDefaultGlint = itemStack.hasFoil(); - isGlintDynamicDisplay = ItemRendererAccessor.hasAnimatedTexture(itemStack); - } - - private void renderQuad(MutableQuadViewImpl quad) { - if (!transform(quad)) { - return; - } - - endRenderQuad(quad); } - private void endRenderQuad(MutableQuadViewImpl quad) { + @Override + protected void bufferQuad(MutableQuadViewImpl quad) { final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); final boolean emissive = mat.emissive(); - final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glint()); + final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glintMode()); - colorizeQuad(quad, colorIndex); + tintQuad(quad); shadeQuad(quad, emissive); bufferQuad(quad, vertexConsumer); } - private void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { - if (colorIndex != -1) { - final int itemColor = itemColors.getColor(itemStack, colorIndex); + private void tintQuad(MutableQuadViewImpl quad) { + int tintIndex = quad.tintIndex(); + + if (tintIndex != -1 && tintIndex < tints.length) { + final int tint = tints[tintIndex]; for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyColor(itemColor, quad.color(i))); + quad.color(i, ColorHelper.multiplyColor(tint, quad.color(i))); } } } @@ -242,74 +184,59 @@ private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { } } - /** - * Caches custom blend mode / vertex consumers and mimics the logic - * in {@code RenderLayers.getItemLayer}. Layers other than - * translucent are mapped to cutout. - */ - private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode) { - boolean translucent; - boolean glint; + private VertexConsumer getVertexConsumer(BlendMode blendMode, GlintMode glintMode) { + RenderType layer; + ItemStackRenderState.FoilType glint; if (blendMode == BlendMode.DEFAULT) { - translucent = isDefaultTranslucent; + layer = defaultLayer; } else { - translucent = blendMode == BlendMode.TRANSLUCENT; + layer = blendMode == BlendMode.TRANSLUCENT ? Sheets.translucentItemSheet() : Sheets.cutoutBlockSheet(); } - if (glintMode == TriState.DEFAULT) { - glint = isDefaultGlint; + if (glintMode == GlintMode.DEFAULT) { + glint = defaultGlint; } else { - glint = glintMode == TriState.TRUE; + glint = glintMode.glint; } - if (translucent) { - if (glint) { - if (translucentGlintVertexConsumer == null) { - translucentGlintVertexConsumer = createVertexConsumer(Sheets.translucentItemSheet(), true); - } - - return translucentGlintVertexConsumer; - } else { - if (translucentVertexConsumer == null) { - translucentVertexConsumer = createVertexConsumer(Sheets.translucentItemSheet(), false); - } + int cacheIndex; - return translucentVertexConsumer; - } + if (layer == Sheets.translucentItemSheet()) { + cacheIndex = 0; + } else if (layer == Sheets.cutoutBlockSheet()) { + cacheIndex = GLINT_COUNT; } else { - if (glint) { - if (cutoutGlintVertexConsumer == null) { - cutoutGlintVertexConsumer = createVertexConsumer(Sheets.cutoutBlockSheet(), true); - } + cacheIndex = 2 * GLINT_COUNT; + } - return cutoutGlintVertexConsumer; - } else { - if (cutoutVertexConsumer == null) { - cutoutVertexConsumer = createVertexConsumer(Sheets.cutoutBlockSheet(), false); - } + cacheIndex += glint.ordinal(); + VertexConsumer vertexConsumer = vertexConsumerCache[cacheIndex]; - return cutoutVertexConsumer; - } + if (vertexConsumer == null) { + vertexConsumer = createVertexConsumer(layer, glint); + vertexConsumerCache[cacheIndex] = vertexConsumer; } + + return vertexConsumer; } - private VertexConsumer createVertexConsumer(RenderType layer, boolean glint) { - if (isGlintDynamicDisplay && glint) { - if (dynamicDisplayGlintEntry == null) { - dynamicDisplayGlintEntry = matrixStack.last().copy(); + private VertexConsumer createVertexConsumer(RenderType layer, ItemStackRenderState.FoilType glint) { + if (glint == ItemStackRenderState.FoilType.SPECIAL) { + if (specialGlintEntry == null) { + specialGlintEntry = matrixStack.last().copy(); if (transformMode == ItemDisplayContext.GUI) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.5F); + MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.5F); } else if (transformMode.firstPerson()) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.75F); + MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.75F); } } - return ItemRenderer.getCompassFoilBuffer(vertexConsumerProvider, layer, dynamicDisplayGlintEntry); + return ItemRendererAccessor.getCompassFoilBuffer(vertexConsumerProvider, layer, specialGlintEntry); } - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint); + return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint != ItemStackRenderState.FoilType.NONE); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index 6e458a6760..06c27945a6 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -70,12 +70,11 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) this.prepareForBlock(blockState, blockPos, model.useAmbientOcclusion()); - model.emitBlockQuads(renderRegion, blockState, blockPos, this.randomSupplier, this); + model.emitBlockQuads(this.getEmitter(), renderRegion, blockState, blockPos, this.randomSupplier, this::isFaceCulled); } protected void endRenderQuad(MutableQuadViewImpl quad) { final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); final TriState aoMode = mat.ambientOcclusion(); final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); final boolean emissive = mat.emissive(); @@ -85,7 +84,7 @@ protected void endRenderQuad(MutableQuadViewImpl quad) { LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; - colorizeQuad(quad, colorIndex); + tintQuad(quad); shadeQuad(quad, lightPipeline, emissive, vanillaShade); bufferQuad(terrainBuilder, this.pos, quad, this.quadLightData); } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index dfc85ec77c..f312a5ae10 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -3,7 +3,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.VkGlTexture; +import net.vulkanmod.gl.GlTexture; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; @@ -25,7 +25,7 @@ public static void bindTexture(VulkanImage texture) { } public static void bindTexture(int i, VulkanImage texture) { - if (i < 0 || i >= SIZE) { + if(i < 0 || i >= SIZE) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -35,7 +35,7 @@ public static void bindTexture(int i, VulkanImage texture) { } public static void bindImage(int i, VulkanImage texture, int level) { - if (i < 0 || i > 7) { + if(i < 0 || i > 7) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -73,15 +73,16 @@ public static void bindShaderTextures(Pipeline pipeline) { for (ImageDescriptor state : imageDescriptors) { final int shaderTexture = RenderSystem.getShaderTexture(state.imageIdx); - VkGlTexture texture = VkGlTexture.getTexture(shaderTexture); + GlTexture texture = GlTexture.getTexture(shaderTexture); if (texture != null && texture.getVulkanImage() != null) { VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); } - else { - texture = VkGlTexture.getTexture(MissingTextureAtlasSprite.getTexture().getId()); - VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); - } + // TODO +// else { +// texture = GlTexture.getTexture(MissingTextureAtlasSprite.getTexture().getId()); +// VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); +// } } } @@ -98,23 +99,16 @@ public static void setOverlayTexture(VulkanImage texture) { } public static void setActiveTexture(int activeTexture) { - if (activeTexture < 0 || activeTexture >= SIZE) { - Initializer.LOGGER.error( - String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); + if(activeTexture < 0 || activeTexture >= SIZE) { + Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); } VTextureSelector.activeTexture = activeTexture; } - public static VulkanImage getBoundTexture() { - return boundTextures[activeTexture]; - } + public static VulkanImage getBoundTexture() { return boundTextures[activeTexture]; } - public static VulkanImage getBoundTexture(int i) { - return boundTextures[i]; - } + public static VulkanImage getBoundTexture(int i) { return boundTextures[i]; } - public static VulkanImage getWhiteTexture() { - return whiteTexture; - } + public static VulkanImage getWhiteTexture() { return whiteTexture; } } diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index b70e87d78a..c1ee1dcd01 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,7 @@ "depends": { "fabricloader": ">=0.14.14", - "minecraft": ["1.21", "1.21.1"] + "minecraft": ">=1.21.4" }, "custom": { "fabric-renderer-api-v1:contains_renderer": true diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 958b0d3084..3949dd9129 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -59,6 +59,7 @@ "render.frapi.ItemRendererAccessor", "render.frapi.ItemRendererMixin", "render.frapi.ModelBlockRendererM", + "render.frapi.QuadEmitterM", "render.particle.SingleQuadParticleM", "render.shader.CompilationCacheM", "render.shader.CompiledShaderProgramM", From 281d1297efe51b8028f6411e7c297ef32ddfc62e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 9 Feb 2025 14:55:37 +0100 Subject: [PATCH 098/177] Update FRAPI implementation --- .../build/frapi/mesh/MutableQuadViewImpl.java | 3 ++ .../render/AbstractBlockRenderContext.java | 8 ++++-- .../frapi/render/BlockRenderContext.java | 12 +++++++- .../build/frapi/render/ItemRenderContext.java | 28 +------------------ 4 files changed, 21 insertions(+), 30 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 3ab5d27275..7b27594839 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -67,6 +67,7 @@ protected void emitDirectly() { quad.tintIndex(-1); } + protected boolean hasTransform = false; private QuadTransform activeTransform = NO_TRANSFORM; private final ObjectArrayList transformStack = new ObjectArrayList<>(); private final QuadTransform stackTransform = q -> { @@ -258,6 +259,7 @@ public void pushTransform(QuadTransform transform) { } transformStack.push(transform); + hasTransform = true; if (transformStack.size() == 1) { activeTransform = transform; @@ -272,6 +274,7 @@ public void popTransform() { if (transformStack.size() == 0) { activeTransform = NO_TRANSFORM; + hasTransform = false; } else if (transformStack.size() == 1) { activeTransform = transformStack.get(0); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index 5399f7e423..5fc917a3dd 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -57,7 +57,11 @@ public void emitDirectly() { @Override public void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { - AbstractBlockRenderContext.this.emitBlockQuads(model, state, randomSupplier, cullTest); + if (this.hasTransform) { + super.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); + } else { + AbstractBlockRenderContext.this.emitVanillaBlockQuads(model, state, randomSupplier, cullTest); + } } }; @@ -251,7 +255,7 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, } } - public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, Predicate cullTest) { + public void emitVanillaBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, Predicate cullTest) { MutableQuadViewImpl quad = this.editorQuad; final RenderMaterial defaultMaterial = model.useAmbientOcclusion() ? STANDARD_MATERIAL : NO_AO_MATERIAL; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java index c8016d4b63..1f75c1f437 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -31,13 +31,17 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.vulkanmod.Initializer; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; import net.vulkanmod.render.chunk.build.light.LightMode; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.ArrayLightDataCache; +import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import net.vulkanmod.render.chunk.build.light.flat.FlatLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.NewSmoothLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.SmoothLightPipeline; +import org.joml.Vector3f; +import org.joml.Vector4f; /** * Context for non-terrain block rendering. @@ -79,7 +83,7 @@ public void render(BlockAndTintGetter blockView, BakedModel model, BlockState st this.prepareForWorld(blockView, cull); this.prepareForBlock(state, pos, model.useAmbientOcclusion()); - model.emitBlockQuads(blockView, state, pos, this.randomSupplier, this); + model.emitBlockQuads(getEmitter(), blockView, state, pos, this.randomSupplier, this::isFaceCulled); this.vertexConsumer = null; } @@ -99,4 +103,10 @@ protected void endRenderQuad(MutableQuadViewImpl quad) { bufferQuad(quad, vertexConsumer); } + private void copyLightData(MutableQuadViewImpl quad) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, this.quadLightData.lm[i]); + } + } + } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index 5f934c7ec1..b063874df0 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -21,33 +21,23 @@ import com.mojang.math.MatrixUtil; import java.util.Arrays; -import java.util.List; import java.util.function.Supplier; import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; -import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; -import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.item.ItemStackRenderState; import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; -import org.jetbrains.annotations.Nullable; -import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.Sheets; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.util.TriState; import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; @@ -83,8 +73,7 @@ public void emitDirectly() { @Override public void emitItemQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier) { -// super.emitItemQuads(emitter, model, state, randomSupplier); - ItemRenderContext.this.emitItemQuads(model, state, randomSupplier); + super.emitItemQuads(emitter, model, state, randomSupplier); } }; @@ -132,21 +121,6 @@ public void renderModel(ItemDisplayContext transformMode, PoseStack matrixStack, Arrays.fill(vertexConsumerCache, null); } - public void emitItemQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - bufferQuad(editorQuad); - } - } - } - @Override protected void bufferQuad(MutableQuadViewImpl quad) { final RenderMaterial mat = quad.material(); From 02f72f5c55175e8c96e0fd9b56aa2ffe28c34776 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 13 Nov 2025 23:49:09 +0100 Subject: [PATCH 099/177] Rename and refactor gl emulation classes --- .../java/net/vulkanmod/gl/VkGlBuffer.java | 6 +- .../net/vulkanmod/gl/VkGlFramebuffer.java | 68 ++++++++++--------- .../gl/{GlShader.java => VkGlShader.java} | 13 ++-- .../java/net/vulkanmod/gl/VkGlTexture.java | 4 ++ 4 files changed, 49 insertions(+), 42 deletions(-) rename src/main/java/net/vulkanmod/gl/{GlShader.java => VkGlShader.java} (66%) diff --git a/src/main/java/net/vulkanmod/gl/VkGlBuffer.java b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java index 05cc59be17..1a2d6b4d59 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlBuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java @@ -7,14 +7,15 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; -// TODO: This class is only used to emulate a CPU buffer for texture copying purposes -// any other use is not supported +// TODO: Implement missing features. +// This class is only used to emulate a CPU buffer for texture copying purposes public class VkGlBuffer { private static int ID_COUNTER = 1; private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundId = 0; private static VkGlBuffer boundBuffer; + private static VkGlBuffer arrayBufferBound; private static VkGlBuffer pixelPackBufferBound; private static VkGlBuffer pixelUnpackBufferBound; @@ -39,6 +40,7 @@ public static void glBindBuffer(int target, int buffer) { switch (target) { case GL32.GL_PIXEL_PACK_BUFFER -> pixelPackBufferBound = glBuffer; case GL32.GL_PIXEL_UNPACK_BUFFER -> pixelUnpackBufferBound = glBuffer; + case GL32.GL_ARRAY_BUFFER -> arrayBufferBound = glBuffer; default -> throw new IllegalStateException("Unexpected value: " + target); } } diff --git a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java index 9981da56f6..fffacde972 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java @@ -51,13 +51,10 @@ public static int genFramebufferId() { public static void bindFramebuffer(int target, int id) { if (id == 0) { - Renderer.getInstance() - .endRenderPass(); + Renderer.getInstance().endRenderPass(); if (Renderer.isRecording()) { - Renderer.getInstance() - .getMainPass() - .rebindMainTarget(); + Renderer.getInstance().getMainPass().rebindMainTarget(); } boundFramebuffer = null; @@ -69,6 +66,10 @@ public static void bindFramebuffer(int target, int id) { if (glFramebuffer == null) throw new NullPointerException("No Framebuffer with ID: %d ".formatted(id)); + if (glFramebuffer.needsUpdate) { + glFramebuffer.create(); + } + switch (target) { case GL30.GL_DRAW_FRAMEBUFFER, GL30.GL_FRAMEBUFFER -> { if (glFramebuffer.framebuffer != null) { @@ -110,6 +111,8 @@ public static void framebufferTexture2D(int target, int attachment, int texTarge } boundFramebuffer.setAttachmentTexture(attachment, texture); + boundFramebuffer.create(); + VkGlFramebuffer.beginRendering(boundFramebuffer); } public static void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer) { @@ -117,6 +120,8 @@ public static void framebufferRenderbuffer(int target, int attachment, int rende return; boundFramebuffer.setAttachmentRenderbuffer(attachment, renderbuffer); + boundFramebuffer.create(); + VkGlFramebuffer.beginRendering(boundFramebuffer); } public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, @@ -145,6 +150,8 @@ public static VkGlFramebuffer getFramebuffer(int id) { VulkanImage colorAttachment; VulkanImage depthAttachment; + boolean needsUpdate; + VkGlFramebuffer(int i) { this.id = i; } @@ -153,52 +160,48 @@ boolean beginRendering() { return Renderer.getInstance().beginRendering(this.renderPass, this.framebuffer); } - void setAttachmentTexture(int attachment, int texture) { - VkGlTexture glTexture = VkGlTexture.getTexture(texture); - - if (glTexture == null) - throw new NullPointerException(String.format("Texture %d is null", texture)); + public void setAttachmentTexture(int attachment, int id) { + VkGlTexture vkGlTexture = VkGlTexture.getTexture(id); - if (glTexture.vulkanImage == null) - return; - - switch (attachment) { - case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(glTexture.getVulkanImage()); - case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(glTexture.getVulkanImage()); + if (vkGlTexture == null) + throw new NullPointerException(String.format("Texture %d is null", id)); - default -> throw new IllegalStateException("Unexpected value: " + attachment); - } + setAttachmentImage(attachment, vkGlTexture.getVulkanImage()); } - void setAttachmentRenderbuffer(int attachment, int texture) { - VkGlRenderbuffer renderbuffer = VkGlRenderbuffer.getRenderbuffer(texture); + public void setAttachmentRenderbuffer(int attachment, int id) { + VkGlRenderbuffer renderbuffer = VkGlRenderbuffer.getRenderbuffer(id); if (renderbuffer == null) - throw new NullPointerException(String.format("Texture %d is null", texture)); + throw new NullPointerException(String.format("Texture %d is null", id)); - if (renderbuffer.vulkanImage == null) - return; + setAttachmentImage(attachment, renderbuffer.getVulkanImage()); + } + + public void setAttachmentImage(int attachment, VulkanImage image) { + if (image == null) + throw new NullPointerException("Image is null"); switch (attachment) { - case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(renderbuffer.getVulkanImage()); - case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(renderbuffer.getVulkanImage()); + case (GL30.GL_COLOR_ATTACHMENT0) -> this.setColorAttachment(image); + case (GL30.GL_DEPTH_ATTACHMENT) -> this.setDepthAttachment(image); default -> throw new IllegalStateException("Unexpected value: " + attachment); } + + this.needsUpdate = true; } void setColorAttachment(VulkanImage image) { this.colorAttachment = image; - createAndBind(); } void setDepthAttachment(VulkanImage image) { //TODO check if texture is in depth format this.depthAttachment = image; - createAndBind(); } - void createAndBind() { + public void create() { // Cannot create without color attachment if (this.colorAttachment == null) return; @@ -224,8 +227,7 @@ void createAndBind() { } this.renderPass = builder.build(); - - VkGlFramebuffer.beginRendering(this); + this.needsUpdate = false; } public Framebuffer getFramebuffer() { @@ -237,8 +239,10 @@ public RenderPass getRenderPass() { } void cleanUp(boolean freeAttachments) { - this.framebuffer.cleanUp(freeAttachments); - this.renderPass.cleanUp(); + if (framebuffer != null) { + this.framebuffer.cleanUp(freeAttachments); + this.renderPass.cleanUp(); + } this.framebuffer = null; this.renderPass = null; diff --git a/src/main/java/net/vulkanmod/gl/GlShader.java b/src/main/java/net/vulkanmod/gl/VkGlShader.java similarity index 66% rename from src/main/java/net/vulkanmod/gl/GlShader.java rename to src/main/java/net/vulkanmod/gl/VkGlShader.java index 0585f62725..95b70bff0b 100644 --- a/src/main/java/net/vulkanmod/gl/GlShader.java +++ b/src/main/java/net/vulkanmod/gl/VkGlShader.java @@ -1,18 +1,15 @@ package net.vulkanmod.gl; -import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; -import org.lwjgl.opengl.GL20; -import org.spongepowered.asm.mixin.Overwrite; -public class GlShader { +public class VkGlShader { private static int ID_COUNTER = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); private static int boundTextureId = 0; public static int glCreateShader(int type) { int id = ID_COUNTER++; - GlShader shader = new GlShader(id, type); + VkGlShader shader = new VkGlShader(id, type); map.put(id, shader); return id; @@ -23,7 +20,7 @@ public static void glDeleteShader(int i) { } public static void glShaderSource(int i, String string) { - GlShader shader = map.get(i); + VkGlShader shader = map.get(i); shader.source = string; } @@ -40,7 +37,7 @@ public static int glGetShaderi(int i, int j) { String source; - GlShader(int id, int type) { + VkGlShader(int id, int type) { this.id = id; this.type = type; } diff --git a/src/main/java/net/vulkanmod/gl/VkGlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java index 7f01144a24..8d39e536e4 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -437,6 +437,10 @@ public VulkanImage getVulkanImage() { public void setVulkanImage(VulkanImage vulkanImage) { this.vulkanImage = vulkanImage; + this.width = vulkanImage.width; + this.height = vulkanImage.height; + this.maxLevel = vulkanImage.mipLevels; + this.vkFormat = vulkanImage.format; } } From ff6a1d8868d280586ca592dffaa713f98f223db6 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Fri, 14 Nov 2025 18:19:06 +0100 Subject: [PATCH 100/177] Port to 1.21.10 - Refactor Port to 1.21.10 - Add a simple GLSL parser to convert vanilla shader on the fly - Add array layers on VulkanImage for cubemaps - Refactor --- build.gradle | 8 +- gradle.properties | 12 +- gradle/wrapper/gradle-wrapper.properties | 2 +- .../net/vulkanmod/config/gui/GuiElement.java | 41 +- .../net/vulkanmod/config/gui/GuiRenderer.java | 167 ---- .../net/vulkanmod/config/gui/VOptionList.java | 61 +- .../vulkanmod/config/gui/VOptionScreen.java | 40 +- .../config/gui/render/GuiRenderer.java | 101 ++ .../config/gui/render/PolygonRenderState.java | 73 ++ .../gui/widget/CyclingOptionWidget.java | 82 +- .../config/gui/widget/OptionWidget.java | 43 +- .../config/gui/widget/RangeOptionWidget.java | 23 +- .../config/gui/widget/SwitchOptionWidget.java | 18 +- .../config/gui/widget/VAbstractWidget.java | 25 +- .../config/gui/widget/VButtonWidget.java | 16 +- .../net/vulkanmod/config/option/Options.java | 4 + .../shader/ExtendedRenderPipeline.java | 21 + .../interfaces/shader/PipelineConfig.java | 14 - .../interfaces/shader/ShaderMixed.java | 25 - .../mixin/chunk/ClientChunkCacheM.java | 6 +- .../vulkanmod/mixin/chunk/FrustumMixin.java | 13 +- .../mixin/chunk/LevelRendererMixin.java | 92 +- .../mixin/compatibility/PostChainM.java | 83 -- .../mixin/compatibility/PostPassM.java | 125 +-- .../mixin/compatibility/UniformM.java | 55 -- .../mixin/debug/DebugEntryMemoryM.java | 55 ++ .../mixin/debug/DebugScreenOverlayM.java | 80 -- .../vulkanmod/mixin/debug/GlDebugInfoM.java | 44 - .../mixin/debug/KeyboardHandlerM.java | 11 +- .../vulkanmod/mixin/profiling/GuiMixin.java | 2 +- .../mixin/profiling/KeyboardHandlerM.java | 13 +- .../mixin/profiling/LevelRendererMixin.java | 67 +- .../mixin/profiling/TimerQueryM.java | 18 + .../mixin/render/BufferUploaderM.java | 93 -- .../mixin/render/CompositeRenderTypeM.java | 123 +++ .../mixin/render/CompositeStateAccessor.java | 23 + .../mixin/render/FogRendererMixin.java | 26 + .../mixin/render/GlStateManagerM.java | 191 ++-- .../mixin/render/GuiRendererMixin.java | 74 ++ .../mixin/render/MinecraftMixin.java | 7 +- .../render/PictureInPictureRendererM.java | 42 + .../mixin/render/RenderSystemMixin.java | 391 +------- .../vulkanmod/mixin/render/RenderTypeM.java | 8 +- .../mixin/render/clouds/LevelRendererM.java | 13 +- .../mixin/render/entity/LevelRendererM.java | 143 +-- .../render/entity/model/ModelPartCubeM.java | 22 +- .../mixin/render/entity/model/ModelPartM.java | 34 +- .../mixin/render/frame/MinecraftMixin.java | 24 +- .../mixin/render/frapi/BakedModelM.java | 30 - .../frapi/BlockRenderDispatcherAccessor.java | 19 + .../render/frapi/ItemRendererAccessor.java | 4 +- .../mixin/render/frapi/ItemRendererMixin.java | 33 +- .../render/frapi/LayerRenderStateMixin.java | 55 ++ .../render/frapi/ModelBlockRendererM.java | 29 +- .../OrderedRenderCommandQueueImplMixin.java | 41 + .../render/particle/QuadParticleGroupM.java | 25 + .../particle/QuadParticleRenderStateM.java | 45 + .../render/particle/SingleQuadParticleM.java | 118 --- .../render/shader/CompilationCacheM.java | 111 --- .../render/shader/CompiledShaderProgramM.java | 219 ----- .../mixin/render/shader/RenderPipelineM.java | 35 + .../render/shader/ShadeProgramConfigM.java | 22 - .../mixin/render/shader/ShaderManagerM.java | 305 +----- .../mixin/render/target/MainTargetMixin.java | 49 +- .../render/target/RenderTargetMixin.java | 215 +---- .../mixin/render/vertex/BufferBuilderM.java | 4 +- .../mixin/render/vertex/FaceBakeryM.java | 80 -- .../mixin/render/vertex/VertexBufferM.java | 90 -- .../mixin/texture/MAbstractTexture.java | 50 - .../vulkanmod/mixin/texture/MTextureUtil.java | 73 -- .../mixin/texture/image/MNativeImage.java | 103 -- .../mixin/texture/update/MLightTexture.java | 322 ++++--- .../mixin/texture/update/MSpriteContents.java | 3 +- .../vulkanmod/mixin/util/ScreenshotMixin.java | 94 ++ .../mixin/util/ScreenshotRecorderM.java | 32 - .../mixin/vertex/EntityOutlineGeneratorM.java | 2 +- .../mixin/wayland/MinecraftMixin.java | 4 +- .../vulkanmod/mixin/window/WindowMixin.java | 42 +- .../net/vulkanmod/render/PipelineManager.java | 8 +- src/main/java/net/vulkanmod/render/VBO.java | 80 +- .../vulkanmod/render/chunk/RenderSection.java | 3 +- .../vulkanmod/render/chunk/WorldRenderer.java | 201 ++-- .../render/chunk/build/RenderRegion.java | 3 +- .../chunk/build/frapi/VulkanModRenderer.java | 70 +- .../AccessBatchingRenderCommandQueue.java | 9 + .../accessor/AccessChunkRendererRegion.java | 29 + .../accessor/AccessLayerRenderState.java | 23 + .../accessor/AccessRenderCommandQueue.java | 15 + .../chunk/build/frapi/helper/ColorHelper.java | 10 + .../frapi/material/MaterialFinderImpl.java | 112 --- .../frapi/material/MaterialViewImpl.java | 114 --- .../frapi/material/RenderMaterialImpl.java | 52 -- .../build/frapi/mesh/EncodingFormat.java | 99 +- .../build/frapi/mesh/ExtendedQuadEmitter.java | 25 +- .../build/frapi/mesh/MutableQuadViewImpl.java | 87 +- .../chunk/build/frapi/mesh/QuadViewImpl.java | 52 +- .../render/AbstractBlockRenderContext.java | 64 +- .../frapi/render/AbstractRenderContext.java | 40 +- .../frapi/render/BlockRenderContext.java | 71 +- .../build/frapi/render/ItemRenderContext.java | 432 ++++----- .../render/SimpleBlockRenderContext.java | 119 +++ .../build/light/data/LightDataAccess.java | 2 +- .../chunk/build/renderer/BlockRenderer.java | 46 +- .../chunk/build/renderer/FluidRenderer.java | 2 +- .../render/chunk/build/task/BuildTask.java | 5 +- .../chunk/build/thread/ThreadBuilderPack.java | 2 +- .../vulkanmod/render/engine/EGlProgram.java | 87 ++ .../render/engine/VkCommandEncoder.java | 878 ++++++++++++++++++ .../vulkanmod/render/engine/VkDebugLabel.java | 40 + .../net/vulkanmod/render/engine/VkFbo.java | 67 ++ .../vulkanmod/render/engine/VkGpuBuffer.java | 111 +++ .../vulkanmod/render/engine/VkGpuDevice.java | 398 ++++++++ .../vulkanmod/render/engine/VkGpuTexture.java | 157 ++++ .../vulkanmod/render/engine/VkRenderPass.java | 212 +++++ .../render/engine/VkTextureView.java | 29 + .../render/gui/GuiBatchRenderer.java | 0 .../net/vulkanmod/render/model/CubeModel.java | 204 ++-- .../render/profiling/ProfilerOverlay.java | 13 +- .../render/shader/CustomRenderPipelines.java | 31 + .../render/shader/ShaderLoadUtil.java | 58 ++ .../vulkanmod/render/sky/CloudRenderer.java | 64 +- .../net/vulkanmod/render/util/DrawUtil.java | 8 +- .../render/vertex/TerrainRenderType.java | 23 +- .../java/net/vulkanmod/vulkan/Renderer.java | 44 +- .../net/vulkanmod/vulkan/VRenderSystem.java | 16 + .../java/net/vulkanmod/vulkan/Vulkan.java | 2 - .../vulkan/framebuffer/RenderPass.java | 19 +- .../vulkan/framebuffer/SwapChain.java | 2 +- .../vulkan/memory/MemoryManager.java | 11 +- .../vulkan/memory/buffer/BufferSlice.java | 25 + .../memory/buffer/index/AutoIndexBuffer.java | 20 +- .../vulkan/pass/DefaultMainPass.java | 39 +- .../net/vulkanmod/vulkan/pass/MainPass.java | 11 +- .../vulkan/shader/DescriptorSets.java | 288 ++++++ .../vulkan/shader/GraphicsPipeline.java | 25 +- .../net/vulkanmod/vulkan/shader/Pipeline.java | 298 +----- .../vulkan/shader/PipelineState.java | 16 - .../vulkanmod/vulkan/shader/SPIRVUtils.java | 9 +- .../net/vulkanmod/vulkan/shader/Uniforms.java | 14 +- .../vulkan/shader/converter/Attribute.java | 29 + .../vulkan/shader/converter/CodeParser.java | 82 -- .../vulkan/shader/converter/GLSLParser.java | 483 ++++++++++ .../shader/converter/GlslConverter.java | 203 ---- .../shader/converter/InputOutputParser.java | 120 --- .../vulkan/shader/converter/Lexer.java | 258 +++++ .../vulkan/shader/converter/Sampler.java | 32 + .../vulkan/shader/converter/Token.java | 49 + .../vulkan/shader/converter/UniformBlock.java | 61 ++ .../shader/converter/UniformParser.java | 158 ---- .../shader/descriptor/ImageDescriptor.java | 22 +- .../vulkan/shader/descriptor/ManualUBO.java | 2 +- .../vulkan/shader/descriptor/UBO.java | 38 +- .../vulkan/shader/layout/AlignedStruct.java | 10 +- .../vulkanmod/vulkan/texture/ImageUtil.java | 5 +- .../vulkan/texture/VTextureSelector.java | 57 +- .../vulkanmod/vulkan/texture/VulkanImage.java | 84 +- .../vulkanmod/shaders/basic/clouds/clouds.fsh | 15 +- .../shaders/basic/clouds/clouds.json | 6 +- .../vulkanmod/shaders/basic/clouds/clouds.vsh | 7 +- .../shaders/basic/terrain/terrain.fsh | 13 +- .../shaders/basic/terrain/terrain.json | 8 +- .../shaders/basic/terrain/terrain.vsh | 17 +- .../basic/terrain_earlyZ/terrain_earlyZ.fsh | 13 +- .../basic/terrain_earlyZ/terrain_earlyZ.json | 8 +- .../shaders/core/blit_screen/blit_screen.fsh | 12 - .../shaders/core/blit_screen/blit_screen.json | 9 - .../shaders/core/blit_screen/blit_screen.vsh | 11 - .../vulkanmod/shaders/core/entity/entity.fsh | 30 - .../vulkanmod/shaders/core/entity/entity.vsh | 36 - .../vulkanmod/shaders/core/glint/glint.fsh | 25 - .../vulkanmod/shaders/core/glint/glint.vsh | 21 - .../assets/vulkanmod/shaders/core/gui/gui.fsh | 17 - .../assets/vulkanmod/shaders/core/gui/gui.vsh | 16 - .../shaders/core/lightmap/lightmap.fsh | 70 -- .../shaders/core/lightmap/lightmap.json | 30 - .../shaders/core/particle/particle.fsh | 25 - .../shaders/core/particle/particle.json | 19 - .../shaders/core/particle/particle.vsh | 26 - .../shaders/core/position/position.fsh | 17 - .../shaders/core/position/position.json | 28 - .../shaders/core/position/position.vsh | 17 - .../core/position_color/position_color.fsh | 17 - .../core/position_color/position_color.json | 24 - .../core/position_color/position_color.vsh | 16 - .../position_color_lightmap.fsh | 17 - .../position_color_lightmap.json | 28 - .../position_color_lightmap.vsh | 19 - .../position_color_normal.fsh | 49 - .../position_color_normal.json | 29 - .../position_color_normal.vsh | 23 - .../position_color_tex/position_color_tex.fsh | 20 - .../position_color_tex.json | 28 - .../position_color_tex/position_color_tex.vsh | 19 - .../position_color_tex_lightmap.fsh | 20 - .../position_color_tex_lightmap.json | 28 - .../position_color_tex_lightmap.vsh | 19 - .../core/position_tex/position_tex.fsh | 19 - .../core/position_tex/position_tex.json | 27 - .../core/position_tex/position_tex.vsh | 16 - .../position_tex_color/position_tex_color.fsh | 20 - .../position_tex_color.json | 20 - .../position_tex_color/position_tex_color.vsh | 19 - .../position_tex_color_normal.fsh | 27 - .../position_tex_color_normal.json | 34 - .../position_tex_color_normal.vsh | 25 - .../rendertype_armor_cutout_no_cull.fsh | 25 - .../rendertype_armor_cutout_no_cull.json | 41 - .../rendertype_armor_cutout_no_cull.vsh | 30 - .../rendertype_armor_entity_glint.fsh | 25 - .../rendertype_armor_entity_glint.json | 34 - .../rendertype_armor_entity_glint.vsh | 21 - .../rendertype_armor_glint.json | 19 - .../rendertype_armor_translucent.json | 29 - .../rendertype_beacon_beam.fsh | 28 - .../rendertype_beacon_beam.json | 36 - .../rendertype_beacon_beam.vsh | 20 - .../rendertype_breeze_wind.fsh | 24 - .../rendertype_breeze_wind.json | 21 - .../rendertype_breeze_wind.vsh | 32 - .../rendertype_clouds/rendertype_clouds.fsh | 43 - .../rendertype_clouds/rendertype_clouds.json | 30 - .../rendertype_clouds/rendertype_clouds.vsh | 28 - .../rendertype_crumbling.fsh | 20 - .../rendertype_crumbling.json | 29 - .../rendertype_crumbling.vsh | 20 - .../rendertype_cutout/rendertype_cutout.fsh | 25 - .../rendertype_cutout/rendertype_cutout.json | 38 - .../rendertype_cutout/rendertype_cutout.vsh | 30 - .../rendertype_cutout_mipped.fsh | 25 - .../rendertype_cutout_mipped.json | 38 - .../rendertype_cutout_mipped.vsh | 30 - .../rendertype_end_gateway.json | 17 - .../rendertype_end_portal.fsh | 69 -- .../rendertype_end_portal.json | 17 - .../rendertype_end_portal.vsh | 23 - .../rendertype_energy_swirl.fsh | 24 - .../rendertype_energy_swirl.json | 34 - .../rendertype_energy_swirl.vsh | 24 - .../rendertype_entity_alpha.fsh | 16 - .../rendertype_entity_alpha.json | 13 - .../rendertype_entity_alpha.vsh | 21 - .../rendertype_entity_cutout.json | 27 - .../rendertype_entity_cutout_no_cull.json | 27 - ...ertype_entity_cutout_no_cull_z_offset.json | 27 - .../rendertype_entity_decal.fsh | 28 - .../rendertype_entity_decal.json | 43 - .../rendertype_entity_decal.vsh | 34 - .../rendertype_entity_glint.fsh | 25 - .../rendertype_entity_glint.json | 34 - .../rendertype_entity_glint.vsh | 21 - .../rendertype_entity_glint_direct.fsh | 25 - .../rendertype_entity_glint_direct.json | 34 - .../rendertype_entity_glint_direct.vsh | 21 - .../rendertype_entity_no_outline.fsh | 22 - .../rendertype_entity_no_outline.json | 41 - .../rendertype_entity_no_outline.vsh | 30 - .../rendertype_entity_shadow.fsh | 18 - .../rendertype_entity_shadow.json | 28 - .../rendertype_entity_shadow.vsh | 19 - .../rendertype_entity_smooth_cutout.json | 27 - .../rendertype_entity_solid.fsh | 26 - .../rendertype_entity_solid.json | 22 - .../rendertype_entity_solid.vsh | 36 - .../rendertype_entity_translucent.json | 27 - .../rendertype_entity_translucent_cull.fsh | 25 - .../rendertype_entity_translucent_cull.json | 37 - .../rendertype_entity_translucent_cull.vsh | 31 - ...rendertype_entity_translucent_emissive.fsh | 27 - ...endertype_entity_translucent_emissive.json | 40 - ...rendertype_entity_translucent_emissive.vsh | 33 - .../core/rendertype_eyes/rendertype_eyes.fsh | 21 - .../core/rendertype_eyes/rendertype_eyes.json | 32 - .../core/rendertype_eyes/rendertype_eyes.vsh | 23 - .../rendertype_glint/rendertype_glint.json | 19 - .../rendertype_glint_direct.json | 19 - .../rendertype_glint_translucent.json | 19 - .../core/rendertype_gui/rendertype_gui.json | 19 - .../rendertype_gui_ghost_recipe_overlay.json | 19 - .../rendertype_gui_overlay.json | 19 - .../core/rendertype_gui_text_highlight.json | 19 - ...endertype_item_entity_translucent_cull.fsh | 25 - ...ndertype_item_entity_translucent_cull.json | 41 - ...endertype_item_entity_translucent_cull.vsh | 101 +- .../rendertype_leash/rendertype_leash.fsh | 17 - .../rendertype_leash/rendertype_leash.json | 34 - .../rendertype_leash/rendertype_leash.vsh | 24 - .../rendertype_lightning.fsh | 17 - .../rendertype_lightning.json | 28 - .../rendertype_lightning.vsh | 20 - .../rendertype_lines/rendertype_lines.fsh | 19 - .../rendertype_lines/rendertype_lines.json | 36 - .../rendertype_lines/rendertype_lines.vsh | 47 - .../rendertype_outline/rendertype_outline.fsh | 20 - .../rendertype_outline.json | 28 - .../rendertype_outline/rendertype_outline.vsh | 20 - .../rendertype_solid/rendertype_solid.fsh | 22 - .../rendertype_solid/rendertype_solid.json | 38 - .../rendertype_solid/rendertype_solid.vsh | 30 - .../core/rendertype_text/rendertype_text.fsh | 25 - .../core/rendertype_text/rendertype_text.json | 36 - .../core/rendertype_text/rendertype_text.vsh | 26 - .../rendertype_text_background.fsh | 22 - .../rendertype_text_background.json | 35 - .../rendertype_text_background.vsh | 23 - ...rendertype_text_background_see_through.fsh | 17 - ...endertype_text_background_see_through.json | 25 - ...rendertype_text_background_see_through.vsh | 16 - .../rendertype_text_intensity.fsh | 25 - .../rendertype_text_intensity.json | 36 - .../rendertype_text_intensity.vsh | 26 - .../rendertype_text_intensity_see_through.fsh | 20 - ...rendertype_text_intensity_see_through.json | 28 - .../rendertype_text_intensity_see_through.vsh | 19 - .../rendertype_text_see_through.fsh | 21 - .../rendertype_text_see_through.json | 28 - .../rendertype_text_see_through.vsh | 20 - .../rendertype_translucent.fsh | 22 - .../rendertype_translucent.json | 38 - .../rendertype_translucent.vsh | 30 - .../rendertype_translucent_moving_block.fsh | 17 - .../rendertype_translucent_moving_block.json | 31 - .../rendertype_translucent_moving_block.vsh | 23 - .../rendertype_translucent_no_crumbling.fsh | 17 - .../rendertype_translucent_no_crumbling.json | 29 - .../rendertype_translucent_no_crumbling.vsh | 22 - .../rendertype_tripwire.fsh | 25 - .../rendertype_tripwire.json | 38 - .../rendertype_tripwire.vsh | 30 - .../rendertype_water_mask.fsh | 11 - .../rendertype_water_mask.json | 22 - .../rendertype_water_mask.vsh | 11 - .../shaders/core/screenquad/screenquad.vsh | 11 + .../assets/vulkanmod/shaders/include/fog.glsl | 29 + .../vulkanmod/shaders/include/light.glsl | 24 +- .../vulkanmod/shaders/post/blit/blit.vsh | 15 + .../vulkanmod/shaders/post/blit/blur.vsh | 21 + src/main/resources/fabric.mod.json | 2 +- src/main/resources/vulkanmod.accesswidener | 10 +- src/main/resources/vulkanmod.mixins.json | 42 +- 339 files changed, 6773 insertions(+), 9459 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/config/gui/GuiRenderer.java create mode 100644 src/main/java/net/vulkanmod/config/gui/render/GuiRenderer.java create mode 100644 src/main/java/net/vulkanmod/config/gui/render/PolygonRenderState.java create mode 100644 src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java delete mode 100644 src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java delete mode 100644 src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java delete mode 100644 src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java create mode 100644 src/main/java/net/vulkanmod/mixin/debug/DebugEntryMemoryM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java create mode 100644 src/main/java/net/vulkanmod/mixin/profiling/TimerQueryM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/CompositeStateAccessor.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/GuiRendererMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/PictureInPictureRendererM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderDispatcherAccessor.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleGroupM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleRenderStateM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java delete mode 100644 src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java delete mode 100644 src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java create mode 100644 src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java delete mode 100644 src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessChunkRendererRegion.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/SimpleBlockRenderContext.java create mode 100644 src/main/java/net/vulkanmod/render/engine/EGlProgram.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkDebugLabel.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkFbo.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkGpuBuffer.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkRenderPass.java create mode 100644 src/main/java/net/vulkanmod/render/engine/VkTextureView.java delete mode 100644 src/main/java/net/vulkanmod/render/gui/GuiBatchRenderer.java create mode 100644 src/main/java/net/vulkanmod/render/shader/CustomRenderPipelines.java create mode 100644 src/main/java/net/vulkanmod/vulkan/memory/buffer/BufferSlice.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/Attribute.java delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/Sampler.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/Token.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/UniformBlock.java delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position/position.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json delete mode 100644 src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/core/screenquad/screenquad.vsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/post/blit/blit.vsh create mode 100644 src/main/resources/assets/vulkanmod/shaders/post/blit/blur.vsh diff --git a/build.gradle b/build.gradle index 3f9e6b94dc..5bcdbd2918 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'fabric-loom' version '1.9.2' + id 'fabric-loom' version '1.12-SNAPSHOT' id 'maven-publish' } @@ -20,7 +20,7 @@ dependencies { mappings loom.officialMojangMappings() modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - // Fabric API. This is technically optional, but you probably want it anyway. + // Fabric API. modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" ext.includeModule = { name -> @@ -31,11 +31,13 @@ dependencies { includeModule("fabric-api-base") includeModule("fabric-resource-loader-v0") + includeModule("fabric-resource-loader-v1") includeModule("fabric-rendering-v1") includeModule("fabric-renderer-api-v1") includeModule("fabric-rendering-fluids-v1") - includeModule("fabric-rendering-data-attachment-v1") includeModule("fabric-block-view-api-v2") + includeModule("fabric-lifecycle-events-v1") + includeModule("fabric-transitive-access-wideners-v1") } project.ext.lwjglVersion = "3.3.3" diff --git a/gradle.properties b/gradle.properties index 089871c791..ba55088d98 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,14 +4,14 @@ org.gradle.parallel=true # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.21.4 -yarn_mappings=1.21.4+build.2 -loader_version=0.16.9 +minecraft_version = 1.21.10 +yarn_mappings = 1.21.10+build.2 +loader_version = 0.17.3 # Fabric API -fabric_version=0.114.0+1.21.4 +fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.5.3-dev.3 +mod_version = 0.5.7-dev maven_group = net.vulkanmod -archives_base_name = VulkanMod_1.21.4 +archives_base_name = VulkanMod_1.21.10 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index cea7a793a8..d4081da476 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/src/main/java/net/vulkanmod/config/gui/GuiElement.java b/src/main/java/net/vulkanmod/config/gui/GuiElement.java index ee4305de12..04b85d2a1b 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiElement.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiElement.java @@ -7,6 +7,7 @@ import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.input.MouseButtonEvent; import org.jetbrains.annotations.Nullable; public abstract class GuiElement implements GuiEventListener, NarratableEntry { @@ -82,46 +83,6 @@ public float getHoverMultiplier(float time) { } } - @Override - public void mouseMoved(double d, double e) { - GuiEventListener.super.mouseMoved(d, e); - } - - @Override - public boolean mouseClicked(double d, double e, int i) { - return GuiEventListener.super.mouseClicked(d, e, i); - } - - @Override - public boolean mouseReleased(double d, double e, int i) { - return GuiEventListener.super.mouseReleased(d, e, i); - } - - @Override - public boolean mouseDragged(double d, double e, int i, double f, double g) { - return GuiEventListener.super.mouseDragged(d, e, i, f, g); - } - - @Override - public boolean mouseScrolled(double d, double e, double f, double g) { - return GuiEventListener.super.mouseScrolled(d, e, f, g); - } - - @Override - public boolean keyPressed(int i, int j, int k) { - return GuiEventListener.super.keyPressed(i, j, k); - } - - @Override - public boolean keyReleased(int i, int j, int k) { - return GuiEventListener.super.keyReleased(i, j, k); - } - - @Override - public boolean charTyped(char c, int i) { - return GuiEventListener.super.charTyped(c, i); - } - @Nullable @Override public ComponentPath nextFocusPath(FocusNavigationEvent focusNavigationEvent) { diff --git a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java deleted file mode 100644 index 2a4ab41789..0000000000 --- a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java +++ /dev/null @@ -1,167 +0,0 @@ -package net.vulkanmod.config.gui; - -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.network.chat.Component; -import net.minecraft.util.FormattedCharSequence; -import org.joml.Matrix4f; - -import java.util.List; - -public abstract class GuiRenderer { - - public static Minecraft minecraft; - public static Font font; - public static GuiGraphics guiGraphics; - public static PoseStack pose; - public static BufferBuilder bufferBuilder; - - private static boolean batching = false; - private static boolean drawing = false; - - public static void setPoseStack(PoseStack poseStack) { - pose = poseStack; - } - - public static void disableScissor() { - RenderSystem.disableScissor(); - } - - public static void enableScissor(int x, int y, int width, int height) { - Window window = Minecraft.getInstance().getWindow(); - int wHeight = window.getHeight(); - double scale = window.getGuiScale(); - int xScaled = (int) (x * scale); - int yScaled = (int) (wHeight - (y + height) * scale); - int widthScaled = (int) (width * scale); - int heightScaled = (int) (height * scale); - RenderSystem.enableScissor(xScaled, yScaled, Math.max(0, widthScaled), Math.max(0, heightScaled)); - } - - public static void fillBox(float x0, float y0, float width, float height, int color) { - fill(x0, y0, x0 + width, y0 + height, 0, color); - } - - public static void fill(float x0, float y0, float x1, float y1, int color) { - fill(x0, y0, x1, y1, 0, color); - } - - public static void fill(float x0, float y0, float x1, float y1, float z, int color) { - Matrix4f matrix4f = pose.last().pose(); - - setupBufferBuilder(); - - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(color); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(color); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(color); - - submitIfNeeded(); - } - - public static void fillGradient(float x0, float y0, float x1, float y1, int color1, int color2) { - fillGradient(x0, y0, x1, y1, 0, color1, color2); - } - - public static void fillGradient(float x0, float y0, float x1, float y1, float z, int color1, int color2) { - Matrix4f matrix4f = pose.last().pose(); - - setupBufferBuilder(); - - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(color1); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(color2); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(color2); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(color1); - - submitIfNeeded(); - } - - public static void renderBoxBorder(float x0, float y0, float width, float height, float borderWidth, int color) { - renderBorder(x0, y0, x0 + width, y0 + height, borderWidth, color); - } - - public static void renderBorder(float x0, float y0, float x1, float y1, float width, int color) { - GuiRenderer.fill(x0, y0, x1, y0 + width, color); - GuiRenderer.fill(x0, y1 - width, x1, y1, color); - - GuiRenderer.fill(x0, y0 + width, x0 + width, y1 - width, color); - GuiRenderer.fill(x1 - width, y0 + width, x1, y1 - width, color); - } - - public static void drawString(Font font, Component component, int x, int y, int color) { - drawString(font, component.getVisualOrderText(), x, y, color); - } - - public static void drawString(Font font, FormattedCharSequence formattedCharSequence, int x, int y, int color) { - guiGraphics.drawString(font, formattedCharSequence, x, y, color); - } - - public static void drawString(Font font, Component component, int x, int y, int color, boolean shadow) { - drawString(font, component.getVisualOrderText(), x, y, color, shadow); - } - - public static void drawString(Font font, FormattedCharSequence formattedCharSequence, int x, int y, int color, boolean shadow) { - guiGraphics.drawString(font, formattedCharSequence, x, y, color, shadow); - } - - public static void drawCenteredString(Font font, Component component, int x, int y, int color) { - FormattedCharSequence formattedCharSequence = component.getVisualOrderText(); - guiGraphics.drawString(font, formattedCharSequence, x - font.width(formattedCharSequence) / 2, y, color); - } - - public static int getMaxTextWidth(Font font, List list) { - int maxWidth = 0; - for (var text : list) { - int width = font.width(text); - if (width > maxWidth) { - maxWidth = width; - } - } - return maxWidth; - } - - public static void beginBatch() { - batching = true; - } - - public static void endBatch() { - RenderSystem.setShader(CoreShaders.POSITION_COLOR); - MeshData meshData = bufferBuilder.build(); - - if (meshData != null) { - BufferUploader.drawWithShader(meshData); - meshData.close(); - } - - batching = false; - drawing = false; - } - - public static void flush() { - guiGraphics.flush(); - - if (batching) { - endBatch(); - } - } - - private static void setupBufferBuilder() { - if (!batching || !drawing) { - bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - drawing = true; - } - } - - private static void submitIfNeeded() { - if (!batching) { - RenderSystem.setShader(CoreShaders.POSITION_COLOR); - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - drawing = false; - } - } -} diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index d2c3fe3cdb..6e353f2f46 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -1,11 +1,11 @@ package net.vulkanmod.config.gui; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.opengl.GlStateManager; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.util.Mth; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.gui.widget.OptionWidget; import net.vulkanmod.config.gui.widget.VAbstractWidget; import net.vulkanmod.config.option.Option; @@ -105,27 +105,29 @@ void setFocused(Entry focussed) { this.focused = focussed; } - public boolean mouseClicked(double mouseX, double mouseY, int button) { - this.updateScrollingState(mouseX, button); - if (this.isMouseOver(mouseX, mouseY)) { - Entry entry = this.getEntryAtPos(mouseX, mouseY); - if (entry != null && entry.mouseClicked(mouseX, mouseY, button)) { + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean bl) { + this.updateScrollingState(event.x(), event.button()); + if (this.isMouseOver(event.x(), event.y())) { + Entry entry = this.getEntryAtPos(event.x(), event.y()); + if (entry != null && entry.mouseClicked(event, bl)) { setFocused(entry); entry.setFocused(true); return true; } - return button == 0; + return event.button() == 0; } return false; } - public boolean mouseReleased(double mouseX, double mouseY, int button) { - if (this.isValidClickButton(button)) { - Entry entry = this.getEntryAtPos(mouseX, mouseY); + @Override + public boolean mouseReleased(MouseButtonEvent event) { + if (this.isValidClickButton(event.button())) { + Entry entry = this.getEntryAtPos(event.x(), event.y()); if (entry != null) { - if (entry.mouseReleased(mouseX, mouseY, button)) { + if (entry.mouseReleased(event)) { entry.setFocused(false); setFocused(null); return true; @@ -135,13 +137,14 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { return false; } - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - if (button != 0) { + @Override + public boolean mouseDragged(MouseButtonEvent event, double deltaX, double deltaY) { + if (event.button() != 0) { return false; } if (this.getFocused() != null) { - return this.getFocused().mouseDragged(mouseX, mouseY, button, deltaX, deltaY); + return this.getFocused().mouseDragged(event, deltaX, deltaY); } if (!this.scrolling) { @@ -149,9 +152,9 @@ public boolean mouseDragged(double mouseX, double mouseY, int button, double del } double maxScroll = this.getMaxScroll(); - if (mouseY < this.y) { + if (event.y() < this.y) { this.setScrollAmount(0.0); - } else if (mouseY > this.getBottom()) { + } else if (event.y() > this.getBottom()) { this.setScrollAmount(maxScroll); } else if (maxScroll > 0.0) { double barHeight = (double) this.height * this.height / this.getTotalLength(); @@ -204,18 +207,15 @@ public void updateState(double mX, double mY) { } public void renderWidget(int mouseX, int mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - GuiRenderer.enableScissor(x, y, width, height); + GuiRenderer.enableScissor(x, y, x + width, y + height); this.renderList(mouseX, mouseY); - GuiRenderer.flush(); GuiRenderer.disableScissor(); // Scroll bar int maxScroll = this.getMaxScroll(); if (maxScroll > 0) { - RenderSystem.enableBlend(); - RenderSystem.setShader(CoreShaders.POSITION_COLOR); + GlStateManager._enableBlend(); int height = this.getHeight(); int totalLength = this.getTotalLength(); @@ -312,16 +312,19 @@ public int getTotalHeight() { return margin; } - public boolean mouseClicked(double mouseX, double mouseY, int button) { - return widget.mouseClicked(mouseX, mouseY, button); + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean bl) { + return widget.mouseClicked(event, bl); } - public boolean mouseReleased(double mouseX, double mouseY, int button) { - return widget.mouseReleased(mouseX, mouseY, button); + @Override + public boolean mouseReleased(MouseButtonEvent event) { + return widget.mouseReleased(event); } - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - return widget.mouseDragged(mouseX, mouseY, button, deltaX, deltaY); + @Override + public boolean mouseDragged(MouseButtonEvent event, double deltaX, double deltaY) { + return widget.mouseDragged(event, deltaX, deltaY); } @Override diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java index c53775ae18..fcf879d71e 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java @@ -1,21 +1,23 @@ package net.vulkanmod.config.gui; import com.google.common.collect.Lists; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.client.renderer.RenderPipelines; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; import net.vulkanmod.Initializer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.gui.widget.VAbstractWidget; import net.vulkanmod.config.gui.widget.VButtonWidget; import net.vulkanmod.config.option.OptionPage; import net.vulkanmod.config.option.Options; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import java.util.ArrayList; @@ -196,11 +198,12 @@ private void addButtons() { this.addWidget(this.supportButton); } - public boolean mouseClicked(double mouseX, double mouseY, int button) { + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean bl) { for (GuiEventListener element : this.children()) { - if (element.mouseClicked(mouseX, mouseY, button)) { + if (element.mouseClicked(event, bl)) { this.setFocused(element); - if (button == 0) { + if (event.button() == 0) { this.setDragging(true); } @@ -213,11 +216,11 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { + public boolean mouseReleased(MouseButtonEvent event) { this.setDragging(false); this.updateState(); - return this.getChildAt(mouseX, mouseY) - .filter(guiEventListener -> guiEventListener.mouseReleased(mouseX, mouseY, button)) + return this.getChildAt(event.x(), event.y()) + .filter(guiEventListener -> guiEventListener.mouseReleased(event)) .isPresent(); } @@ -226,29 +229,14 @@ public void onClose() { this.minecraft.setScreen(this.parent); } - @Override - public void renderBackground(GuiGraphics guiGraphics, int i, int j, float f) { - if (this.minecraft.level == null) { - this.renderPanorama(guiGraphics, f); - } - - this.renderBlurredBackground(); - this.renderMenuBackground(guiGraphics); - - } - @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) { - this.renderBackground(guiGraphics, 0, 0, delta); - GuiRenderer.guiGraphics = guiGraphics; - GuiRenderer.setPoseStack(guiGraphics.pose()); - - RenderSystem.enableBlend(); + VRenderSystem.enableBlend(); int size = minecraft.font.lineHeight * 4; - guiGraphics.blit(RenderType::guiTextured, ICON, 30, 4, 0f, 0f, size, size, size, size); + guiGraphics.blit(RenderPipelines.GUI_TEXTURED, ICON, 30, 4, 0f, 0f, size, size, size, size); VOptionList currentList = this.optionPages.get(this.currentListIdx).getOptionList(); currentList.updateState(mouseX, mouseY); @@ -275,8 +263,6 @@ private void renderTooltip(List list, int x, int y) { int color = ColorUtil.ARGB.pack(intensity, intensity, intensity, 0.6f); GuiRenderer.fill(x - padding, y - padding, x + width + padding, y + height + padding, color); -// intensity = 0.4f; -// color = ColorUtil.ARGB.pack(intensity, intensity, intensity, 0.9f); color = RED; GuiRenderer.renderBorder(x - padding, y - padding, x + width + padding, y + height + padding, 1, color); diff --git a/src/main/java/net/vulkanmod/config/gui/render/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/render/GuiRenderer.java new file mode 100644 index 0000000000..e268dab921 --- /dev/null +++ b/src/main/java/net/vulkanmod/config/gui/render/GuiRenderer.java @@ -0,0 +1,101 @@ +package net.vulkanmod.config.gui.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; +import org.joml.Matrix3x2f; + +import java.util.List; + +public abstract class GuiRenderer { + + public static Minecraft minecraft; + public static GuiGraphics guiGraphics; + public static PoseStack pose; + public static BufferBuilder bufferBuilder; + + public static void enableScissor(int i, int j, int k, int l) { + guiGraphics.enableScissor(i, j, k, l); + } + + public static void disableScissor() { + guiGraphics.disableScissor(); + } + + public static void fillBox(int x0, int y0, int width, int height, int color) { + fill(x0, y0, x0 + width, y0 + height, 0, color); + } + + public static void fill(int x0, int y0, int x1, int y1, int color) { + fill(x0, y0, x1, y1, 0, color); + } + + public static void fill(int x0, int y0, int x1, int y1, int z, int color) { + guiGraphics.fill(x0, y0, x1, y1, color); + } + + public static void fillGradient(int x0, int y0, int x1, int y1, int color1, int color2) { + fillGradient(x0, y0, x1, y1, 0, color1, color2); + } + + public static void fillGradient(int x0, int y0, int x1, int y1, int z, int color1, int color2) { + guiGraphics.fillGradient(x0, y0, x1, y1, color1, color2); + } + + public static void renderBoxBorder(int x0, int y0, int width, int height, int borderWidth, int color) { + renderBorder(x0, y0, x0 + width, y0 + height, borderWidth, color); + } + + public static void renderBorder(int x0, int y0, int x1, int y1, int width, int color) { + GuiRenderer.fill(x0, y0, x1, y0 + width, color); + GuiRenderer.fill(x0, y1 - width, x1, y1, color); + + GuiRenderer.fill(x0, y0 + width, x0 + width, y1 - width, color); + GuiRenderer.fill(x1 - width, y0 + width, x1, y1 - width, color); + } + + public static void drawString(Font font, Component component, int x, int y, int color) { + drawString(font, component.getVisualOrderText(), x, y, color); + } + + public static void drawString(Font font, FormattedCharSequence formattedCharSequence, int x, int y, int color) { + guiGraphics.drawString(font, formattedCharSequence, x, y, color); + } + + public static void drawString(Font font, Component component, int x, int y, int color, boolean shadow) { + drawString(font, component.getVisualOrderText(), x, y, color, shadow); + } + + public static void drawString(Font font, FormattedCharSequence formattedCharSequence, int x, int y, int color, boolean shadow) { + guiGraphics.drawString(font, formattedCharSequence, x, y, color, shadow); + } + + public static void drawCenteredString(Font font, Component component, int x, int y, int color) { + FormattedCharSequence formattedCharSequence = component.getVisualOrderText(); + guiGraphics.drawString(font, formattedCharSequence, x - font.width(formattedCharSequence) / 2, y, color); + } + + public static int getMaxTextWidth(Font font, List list) { + int maxWidth = 0; + for (var text : list) { + int width = font.width(text); + if (width > maxWidth) { + maxWidth = width; + } + } + return maxWidth; + } + + public static void submitPolygon(RenderPipeline renderPipeline, TextureSetup textureSetup, float[][] vertices, int color) { + guiGraphics.guiRenderState.submitGuiElement( + new PolygonRenderState( + renderPipeline, textureSetup, new Matrix3x2f(), vertices, color, guiGraphics.scissorStack.peek() + ) + ); + } +} diff --git a/src/main/java/net/vulkanmod/config/gui/render/PolygonRenderState.java b/src/main/java/net/vulkanmod/config/gui/render/PolygonRenderState.java new file mode 100644 index 0000000000..ff4b2b03df --- /dev/null +++ b/src/main/java/net/vulkanmod/config/gui/render/PolygonRenderState.java @@ -0,0 +1,73 @@ +package net.vulkanmod.config.gui.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.GuiElementRenderState; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3x2f; + +public record PolygonRenderState ( + RenderPipeline pipeline, + TextureSetup textureSetup, + Matrix3x2f pose, + float[][] vertices, + int col, + @Nullable ScreenRectangle scissorArea, + @Nullable ScreenRectangle bounds +) implements GuiElementRenderState { + + public PolygonRenderState( + RenderPipeline renderPipeline, + TextureSetup textureSetup, + Matrix3x2f pose, + float[][] vertices, + int color, + @Nullable ScreenRectangle screenRectangle + ) { + this(renderPipeline, textureSetup, pose, vertices, color, screenRectangle, + getBounds(vertices, pose, screenRectangle)); + } + + @Override + public void buildVertices(VertexConsumer vertexConsumer) { + for (float[] vertex : vertices) { + float x = vertex[0]; + float y = vertex[1]; + vertexConsumer.addVertexWith2DPose(this.pose(), x, y) + .setColor(this.col); + } + } + + @Nullable + private static ScreenRectangle getBounds(float[][] vertices, Matrix3x2f matrix3x2f, @Nullable ScreenRectangle screenRectangle) { + float x0 = vertices[0][0]; + float x1 = vertices[0][0]; + float y0 = vertices[0][1]; + float y1 = vertices[0][1]; + + for (float[] vertex : vertices) { + float x = vertex[0]; + float y = vertex[1]; + + if (x < x0) { + x0 = x; + } + if (x > x1) { + x1 = x; + } + + if (y < y0) { + y0 = y; + } + if (y > y1) { + y1 = y; + } + } + + ScreenRectangle screenRectangle2 = new ScreenRectangle((int) x0, (int) y0, (int) (x1 - x0), (int) (y1 - y0)).transformMaxBounds(matrix3x2f); + return screenRectangle != null ? screenRectangle.intersection(screenRectangle2) : screenRectangle2; + } +} + diff --git a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java index 415db96459..6ec5157d2b 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java @@ -1,16 +1,13 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.gui.render.TextureSetup; import net.minecraft.network.chat.Component; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.option.CyclingOption; +import net.vulkanmod.render.shader.CustomRenderPipelines; import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Matrix4f; public class CyclingOptionWidget extends OptionWidget> { private Button leftButton; @@ -29,25 +26,23 @@ public CyclingOptionWidget(CyclingOption option, int x, int y, int width, int @Override protected int getYImage(boolean hovered) { - return 0; + return 0; } public void renderControls(double mouseX, double mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - this.renderBars(); this.leftButton.setStatus(option.index() > 0); this.rightButton.setStatus(option.index() < option.getValues().length - 1); - int color = this.active ? 0xFFFFFF : 0xA0A0A0; + int color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; Font textRenderer = Minecraft.getInstance().font; int x = this.controlX + this.controlWidth / 2; int y = this.y + (this.height - 9) / 2; GuiRenderer.drawCenteredString(textRenderer, this.getDisplayedValue(), x, y, color); - this.leftButton.renderButton(GuiRenderer.guiGraphics.pose(), mouseX, mouseY); - this.rightButton.renderButton(GuiRenderer.guiGraphics.pose(), mouseX, mouseY); + this.leftButton.renderButton(mouseX, mouseY); + this.rightButton.renderButton(mouseX, mouseY); } public void renderBars() { @@ -65,11 +60,11 @@ public void renderBars() { return; for (int i = 0; i < count; i++) { - float x0 = this.controlX + margin + i * (barWidth + padding); - float y0 = this.y + this.height - 5.0f; + int x0 = this.controlX + margin + i * (barWidth + padding); + int y0 = this.y + this.height - 5; int c = i == current ? activeColor : color; - GuiRenderer.fill(x0, y0, x0 + barWidth, y0 + 1.5f, c); + GuiRenderer.fill(x0, y0, x0 + barWidth, (int) (y0 + 1.5f), c); } } @@ -104,6 +99,10 @@ public boolean isFocused() { } class Button { + final int ACTIVE_COLOR = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.8f); + final int HOVERED_COLOR = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 1.0f); + final int INACTIVE_COLOR = ColorUtil.ARGB.pack(0.3f, 0.3f, 0.3f, 0.8f); + int x; int width; boolean active; @@ -124,44 +123,43 @@ void setStatus(boolean status) { this.active = status; } - void renderButton(PoseStack matrices, double mouseX, double mouseY) { - Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.TRIANGLE_STRIP, DefaultVertexFormat.POSITION); - - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - + void renderButton(double mouseX, double mouseY) { float f = this.isHovered(mouseX, mouseY) && this.active ? 5.0f : 4.5f; - Matrix4f matrix4f = matrices.last().pose(); - - RenderSystem.setShader(CoreShaders.POSITION); - RenderSystem.enableBlend(); - - if(this.isHovered(mouseX, mouseY) && this.active) - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - else if(this.active) - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 0.8f); - else - RenderSystem.setShaderColor(0.3f, 0.3f, 0.3f, 0.8f); + int color; + if (this.isHovered(mouseX, mouseY) && this.active) { + color = HOVERED_COLOR; + } + else if (this.active) { + color = ACTIVE_COLOR; + } + else { + color = INACTIVE_COLOR; + } float h = f; float w = f - 1.0f; float yC = y + height * 0.5f; float xC = x + width * 0.5f; + + float[][] vertices; if (this.direction == Direction.LEFT) { - bufferBuilder.addVertex(matrix4f, xC - w, yC, 0); - bufferBuilder.addVertex(matrix4f, xC + w, yC + h, 0); - bufferBuilder.addVertex(matrix4f, xC + w, yC - h, 0); - } else { - bufferBuilder.addVertex(matrix4f, xC + w, yC, 0); - bufferBuilder.addVertex(matrix4f, xC - w, yC - h, 0); - bufferBuilder.addVertex(matrix4f, xC - w, yC + h, 0); + vertices = new float[][]{ + {xC - w, yC}, + {xC + w, yC + h}, + {xC + w, yC - h}, + }; + } + else { + vertices = new float[][]{ + {xC + w, yC}, + {xC - w, yC - h}, + {xC - w, yC + h}, + }; } - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - RenderSystem.setShader(CoreShaders.POSITION); + GuiRenderer.submitPolygon(CustomRenderPipelines.GUI_TRIANGLES, TextureSetup.noTexture(), vertices, color); } enum Direction { diff --git a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java index a5210a01b7..b3ee793459 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java @@ -1,29 +1,18 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.client.sounds.SoundManager; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; -import net.minecraft.util.Mth; -import net.vulkanmod.config.gui.GuiElement; -import net.vulkanmod.config.gui.GuiRenderer; -import net.vulkanmod.config.option.CyclingOption; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.option.Option; -import net.vulkanmod.render.util.MathUtil; import net.vulkanmod.vulkan.util.ColorUtil; -import java.util.Objects; - public abstract class OptionWidget> extends VAbstractWidget implements NarratableEntry { @@ -70,12 +59,7 @@ public void updateState() { public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); - RenderSystem.setShader(CoreShaders.POSITION_TEX); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); int i = this.getYImage(this.isHovered()); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - RenderSystem.enableDepthTest(); int xPadding = 0; int yPadding = 0; @@ -85,14 +69,11 @@ public void renderWidget(double mouseX, double mouseY) { this.renderHovering(0, 0); - color = this.active ? 0xFFFFFF : 0xA0A0A0; -// j = 0xB0f0d0a0; + color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; Font textRenderer = minecraftClient.font; GuiRenderer.drawString(textRenderer, this.getName().getVisualOrderText(), this.x + 8, this.y + (this.height - 8) / 2, color); - RenderSystem.enableBlend(); - this.renderControls(mouseX, mouseY); } @@ -123,32 +104,32 @@ protected boolean isValidClickButton(int button) { } @Override - public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - if (this.isValidClickButton(button)) { - this.onDrag(mouseX, mouseY, deltaX, deltaY); + public boolean mouseDragged(MouseButtonEvent event, double deltaX, double deltaY) { + if (this.isValidClickButton(event.button())) { + this.onDrag(event.x(), event.y(), deltaX, deltaY); return true; } return false; } @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { + public boolean mouseClicked(MouseButtonEvent event, boolean bl) { if (!this.active || !this.visible) { return false; } - if (this.isValidClickButton(button) && this.clicked(mouseX, mouseY)) { + if (this.isValidClickButton(event.button()) && this.clicked(event.x(), event.y())) { this.playDownSound(Minecraft.getInstance().getSoundManager()); - this.onClick(mouseX, mouseY); + this.onClick(event.x(), event.y()); return true; } return false; } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { - if (this.isValidClickButton(button)) { - this.onRelease(mouseX, mouseY); + public boolean mouseReleased(MouseButtonEvent event) { + if (this.isValidClickButton(event.button())) { + this.onRelease(event.x(), event.y()); return true; } return false; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java index 7cef7e1071..277386177b 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java @@ -1,13 +1,14 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.input.KeyEvent; import net.minecraft.client.sounds.SoundManager; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.option.RangeOption; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.glfw.GLFW; @@ -30,16 +31,14 @@ protected int getYImage(boolean hovered) { @Override protected void renderControls(double mouseX, double mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - int valueX = this.controlX + (int) (this.value * (this.controlWidth)); if (this.controlHovered) { int halfWidth = 2; int halfHeight = 4; - float y0 = this.y + this.height * 0.5f - 1.0f; - float y1 = y0 + 2.0f; + int y0 = (int) (this.y + this.height * 0.5f - 1.0f); + int y1 = (int) (y0 + 2.0f); GuiRenderer.fill(this.controlX, y0, this.controlX + this.controlWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.1f)); GuiRenderer.fill(this.controlX, y0, valueX - halfWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f)); @@ -48,13 +47,13 @@ protected void renderControls(double mouseX, double mouseY) { // GuiRenderer.fill(valueX - halfWidth, y0 - 3.0f, valueX + halfWidth, y1 + 3.0f, color); } else { - float y0 = this.y + this.height - 5.0f; - float y1 = y0 + 1.5f; + int y0 = (int) (this.y + this.height - 5.0f); + int y1 = (int) (y0 + 1.5f); GuiRenderer.fill(this.controlX, y0, this.controlX + this.controlWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f)); GuiRenderer.fill(this.controlX, y0, valueX, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.8f)); } - int color = this.active ? 0xFFFFFF : 0xA0A0A0; + int color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; Font font = Minecraft.getInstance().font; var text = this.getDisplayedValue(); int width = font.width(text); @@ -70,9 +69,9 @@ public void onClick(double mouseX, double mouseY) { } @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - boolean isLeft = keyCode == GLFW.GLFW_KEY_LEFT; - boolean isRight = keyCode == GLFW.GLFW_KEY_RIGHT; + public boolean keyPressed(KeyEvent event) { + boolean isLeft = event.key() == GLFW.GLFW_KEY_LEFT; + boolean isRight = event.key() == GLFW.GLFW_KEY_RIGHT; if (isLeft || isRight) { float direction = isLeft ? -1.0f : 1.0f; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java index 340902f3ce..f4b0b5f9f0 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java @@ -3,7 +3,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.network.chat.Component; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.option.SwitchOption; import net.vulkanmod.vulkan.util.ColorUtil; @@ -19,16 +19,16 @@ public SwitchOptionWidget(SwitchOption option, int x, int y, int width, int heig @Override protected void renderControls(double mouseX, double mouseY) { int center = controlX + controlWidth / 2; - float halfWidth = 12; - float x0 = center - halfWidth; - float y0 = y + 4; - float height = this.height - 8; + int halfWidth = 12; + int x0 = center - halfWidth; + int y0 = y + 4; + int height = this.height - 8; int color; - float w1 = halfWidth - 4; - float h1 = height - 4; + int w1 = halfWidth - 4; + int h1 = height - 4; if (this.option.getNewValue()) { - float x1 = x0 + halfWidth + 2; + int x1 = x0 + halfWidth + 2; color = ColorUtil.ARGB.pack(0.4f, 0.4f, 0.4f, 1.0f); GuiRenderer.fillBox(x0 + 2, y0 + 2, x1 - (x0 + 2) - 1, h1, color); @@ -43,7 +43,7 @@ protected void renderControls(double mouseX, double mouseY) { color = ColorUtil.ARGB.pack(0.6f, 0.6f, 0.6f, 1.0f); GuiRenderer.renderBoxBorder(x0, y0, halfWidth * 2, height, 1, color); - color = this.active ? 0xFFFFFF : 0xA0A0A0; + color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; Font textRenderer = Minecraft.getInstance().font; int margin = Math.max( textRenderer.width(Component.translatable("options.on").getString()) / 3, diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java index 58bbd0d0ed..0a76bd6ff3 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java @@ -1,12 +1,13 @@ package net.vulkanmod.config.gui.widget; import net.minecraft.client.Minecraft; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.client.sounds.SoundManager; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.vulkanmod.config.gui.GuiElement; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.vulkan.util.ColorUtil; public abstract class VAbstractWidget extends GuiElement { @@ -56,13 +57,13 @@ protected void renderHovering(int xPadding, int yPadding) { } @Override - public boolean mouseClicked(double mX, double mY, int button) { + public boolean mouseClicked(MouseButtonEvent event, boolean bl) { if (this.active && this.visible) { - if (this.isValidClickButton(button)) { - boolean bl = this.clicked(mX, mY); - if (bl) { + if (this.isValidClickButton(event.button())) { + boolean clicked = this.clicked(event.x(), event.y()); + if (clicked) { this.playDownSound(Minecraft.getInstance().getSoundManager()); - this.onClick(mX, mY); + this.onClick(event.x(), event.y()); return true; } } @@ -81,9 +82,9 @@ protected boolean clicked(double mX, double mY) { } @Override - public boolean mouseReleased(double mX, double mY, int button) { - if (this.isValidClickButton(button)) { - this.onRelease(mX, mY); + public boolean mouseReleased(MouseButtonEvent event) { + if (this.isValidClickButton(event.button())) { + this.onRelease(event.x(), event.y()); return true; } else { return false; @@ -95,9 +96,9 @@ protected boolean isValidClickButton(int button) { } @Override - public boolean mouseDragged(double mX, double mY, int button, double f, double g) { - if (this.isValidClickButton(button)) { - this.onDrag(mX, mY, f, g); + public boolean mouseDragged(MouseButtonEvent event, double d, double e) { + if (this.isValidClickButton(event.button())) { + this.onDrag(event.x(), event.y(), d, e); return true; } else { return false; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java index 64269c6b67..3055259d60 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java @@ -1,13 +1,11 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.renderer.CoreShaders; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import java.util.function.Consumer; @@ -28,10 +26,6 @@ public VButtonWidget(int x, int y, int width, int height, Component message, Con public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); Font textRenderer = minecraftClient.font; - RenderSystem.setShader(CoreShaders.POSITION_TEX); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha); - - RenderSystem.enableBlend(); int xPadding = 0; int yPadding = 0; @@ -46,15 +40,11 @@ public void renderWidget(double mouseX, double mouseY) { int j = this.active ? 0xFFFFFF : 0xA0A0A0; GuiRenderer.drawCenteredString(textRenderer, this.message, this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0f) << 24); - RenderSystem.enableBlend(); if(this.selected) { -// color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 1.0f); color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 1.0f); -// GuiRenderer.fillBox(this.x, this.y + this.height - 1, this.width, 1, color); - GuiRenderer.fillBox(this.x, this.y, 1.5f, this.height, color); + GuiRenderer.fillBox(this.x, this.y, (int) 1.5f, this.height, color); -// color = ColorUtil.ARGB.pack(0.5f, 0.5f, 0.5f, 0.2f); color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 0.2f); GuiRenderer.fillBox(this.x, this.y, this.width, this.height, color); } diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index ffe471b7e1..702b3b754a 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -187,6 +187,10 @@ public static OptionBlock[] getGraphicsOpts() { value -> minecraftOptions.cloudStatus().set(value), () -> minecraftOptions.cloudStatus().get()) .setTranslator(value -> Component.translatable(value.getKey())), + new RangeOption(Component.translatable("options.renderCloudsDistance"), + 2, 128, 1, + (value) -> minecraftOptions.cloudRange().set(value), + () -> minecraftOptions.cloudRange().get()), new CyclingOption<>(Component.translatable("options.ao"), new Integer[]{LightMode.FLAT, LightMode.SMOOTH, LightMode.SUB_BLOCK}, (value) -> { diff --git a/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java b/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java new file mode 100644 index 0000000000..dc927f0f09 --- /dev/null +++ b/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java @@ -0,0 +1,21 @@ +package net.vulkanmod.interfaces.shader; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import net.vulkanmod.render.engine.EGlProgram; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; + +public interface ExtendedRenderPipeline { + + static ExtendedRenderPipeline of(RenderPipeline renderPipeline) { + return (ExtendedRenderPipeline) renderPipeline; + } + + void setPipeline(GraphicsPipeline pipeline); + + void setProgram(EGlProgram program); + + Pipeline getPipeline(); + + EGlProgram getProgram(); +} diff --git a/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java b/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java deleted file mode 100644 index 34910ea47b..0000000000 --- a/src/main/java/net/vulkanmod/interfaces/shader/PipelineConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.vulkanmod.interfaces.shader; - -import net.minecraft.client.renderer.ShaderProgramConfig; - -public interface PipelineConfig { - - static PipelineConfig of(ShaderProgramConfig shaderProgramConfig) { - return (PipelineConfig) (Object) shaderProgramConfig; - } - - String getName(); - - void setName(String s); -} diff --git a/src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java b/src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java deleted file mode 100644 index f158141dee..0000000000 --- a/src/main/java/net/vulkanmod/interfaces/shader/ShaderMixed.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.vulkanmod.interfaces.shader; - -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.util.MappedBuffer; - -import java.util.function.Supplier; - -public interface ShaderMixed { - - static ShaderMixed of(CompiledShaderProgram compiledShaderProgram) { - return (ShaderMixed) compiledShaderProgram; - } - - void setPipeline(GraphicsPipeline graphicsPipeline); - - GraphicsPipeline getPipeline(); - - void setupUniformSuppliers(UBO ubo); - - Supplier getUniformSupplier(String name); - - void setUniformsUpdate(); -} diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java index 0acf28529f..0f5e9d392f 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java @@ -6,6 +6,7 @@ import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.levelgen.Heightmap; import net.vulkanmod.render.chunk.ChunkStatusMap; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; @@ -14,6 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import java.util.Map; import java.util.function.Consumer; @Mixin(ClientChunkCache.class) @@ -21,7 +23,9 @@ public class ClientChunkCacheM { @Inject(method = "replaceWithPacketData", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/ClientLevel;onChunkLoaded(Lnet/minecraft/world/level/ChunkPos;)V")) - private void setChunkStatus(int x, int z, FriendlyByteBuf friendlyByteBuf, CompoundTag compoundTag, Consumer consumer, CallbackInfoReturnable<@Nullable LevelChunk> cir) { + private void setChunkStatus(int x, int z, FriendlyByteBuf friendlyByteBuf, Map map, + Consumer consumer, + CallbackInfoReturnable cir) { ChunkStatusMap.INSTANCE.setChunkStatus(x, z, ChunkStatusMap.DATA_READY); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java index 4959c34d2d..7fdfcc70e4 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java @@ -4,8 +4,11 @@ import net.vulkanmod.interfaces.FrustumMixed; import net.vulkanmod.render.chunk.frustum.VFrustum; import org.joml.Matrix4f; +import org.joml.Vector4f; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; 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.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -16,13 +19,15 @@ public class FrustumMixin implements FrustumMixed { @Shadow private double camX; @Shadow private double camY; @Shadow private double camZ; - private final VFrustum vFrustum = new VFrustum(); + @Shadow @Final private Matrix4f matrix; + @Shadow private Vector4f viewVector; - @Inject(method = "calculateFrustum", at = @At("HEAD"), cancellable = true) + @Unique private final VFrustum vFrustum = new VFrustum(); + + @Inject(method = "calculateFrustum", at = @At("HEAD")) private void calculateFrustum(Matrix4f modelView, Matrix4f projection, CallbackInfo ci) { -// this.vFrustum = new VFrustum(modelView, projection); this.vFrustum.calculateFrustum(modelView, projection); - ci.cancel(); + this.viewVector = this.matrix.transformTranspose(new Vector4f(0.0F, 0.0F, 1.0F, 0.0F)); } @Inject(method = "prepare", at = @At("RETURN")) diff --git a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java index d4cb6f866f..c4471218b9 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java @@ -1,5 +1,7 @@ package net.vulkanmod.mixin.chunk; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.resource.GraphicsResourceAllocator; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.client.Camera; @@ -8,14 +10,22 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.client.renderer.chunk.ChunkSectionLayerGroup; +import net.minecraft.client.renderer.chunk.ChunkSectionsToRender; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.client.renderer.feature.FeatureRenderDispatcher; +import net.minecraft.client.renderer.state.LevelRenderState; import net.minecraft.core.BlockPos; import net.minecraft.server.level.BlockDestructionProgress; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.chunk.WorldRenderer; +import net.vulkanmod.render.profiling.Profiler; +import net.vulkanmod.render.vertex.TerrainRenderType; import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector4f; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -26,18 +36,19 @@ @Mixin(LevelRenderer.class) public abstract class LevelRendererMixin { + @Shadow @Final private Long2ObjectMap> destructionProgress; - @Shadow @Final - private RenderBuffers renderBuffers; + @Unique private WorldRenderer worldRenderer; - @Shadow @Final - private Long2ObjectMap> destructionProgress; - - private WorldRenderer worldRenderer; + @Unique double camX, camY, camZ; + @Unique Matrix4f modelView, projection; @Inject(method = "", at = @At("RETURN")) - private void init(Minecraft minecraft, EntityRenderDispatcher entityRenderDispatcher, BlockEntityRenderDispatcher blockEntityRenderDispatcher, RenderBuffers renderBuffers, CallbackInfo ci) { - this.worldRenderer = WorldRenderer.init(this.renderBuffers); + private void init(Minecraft minecraft, EntityRenderDispatcher entityRenderDispatcher, + BlockEntityRenderDispatcher blockEntityRenderDispatcher, RenderBuffers renderBuffers, + LevelRenderState levelRenderState, FeatureRenderDispatcher featureRenderDispatcher, + CallbackInfo ci) { + this.worldRenderer = WorldRenderer.init(entityRenderDispatcher, blockEntityRenderDispatcher, renderBuffers, levelRenderState, featureRenderDispatcher); } @Inject(method = "setLevel", at = @At("RETURN")) @@ -50,12 +61,20 @@ private void onAllChanged(CallbackInfo ci) { this.worldRenderer.allChanged(); } - @Inject(method = "renderBlockEntities", at = @At(value = "RETURN")) - private void renderBlockEntities(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, MultiBufferSource.BufferSource bufferSource2, Camera camera, float partialTicks, CallbackInfo ci) { - Vec3 pos = camera.getPosition(); -// PoseStack poseStack = new PoseStack(); + @Inject(method = "extractVisibleBlockEntities", at = @At("HEAD"), cancellable = true) + private void onExtractVisibleBlockEntities(Camera camera, float partialTick, LevelRenderState levelRenderState, + CallbackInfo ci) { + this.worldRenderer.setPartialTick(partialTick); - this.worldRenderer.renderBlockEntities(poseStack, pos.x(), pos.y(), pos.z(), this.destructionProgress, partialTicks); + ci.cancel(); + } + + @Inject(method = "submitBlockEntities", at = @At(value = "RETURN"), cancellable = true) + private void onSubmitBlockEntities(PoseStack poseStack, LevelRenderState levelRenderState, + SubmitNodeStorage submitNodeStorage, CallbackInfo ci) { + this.worldRenderer.renderBlockEntities(poseStack, levelRenderState, submitNodeStorage, this.destructionProgress); + + ci.cancel(); } /** @@ -63,8 +82,9 @@ private void renderBlockEntities(PoseStack poseStack, MultiBufferSource.BufferSo * @reason */ @Overwrite - private void setupRender(Camera camera, Frustum frustum, boolean isCapturedFrustum, boolean spectator) { - this.worldRenderer.setupRenderer(camera, frustum, isCapturedFrustum, spectator); + private void cullTerrain(Camera camera, Frustum frustum, boolean spectator) { + // TODO: port capture frustum + this.worldRenderer.setupRenderer(camera, frustum, false, spectator); } /** @@ -76,13 +96,43 @@ public boolean isSectionCompiled(BlockPos blockPos) { return this.worldRenderer.isSectionCompiled(blockPos); } - /** - * @author - * @reason - */ + @Inject(method = "renderLevel", at = @At("HEAD")) + private void updateMatrices(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, + boolean bl, Camera camera, Matrix4f modelView, Matrix4f projection, Matrix4f matrix4f, + GpuBufferSlice gpuBufferSlice, Vector4f vector4f, boolean bl2, CallbackInfo ci) { + this.modelView = modelView; + this.projection = projection; + } + @Overwrite - private void renderSectionLayer(RenderType renderType, double camX, double camY, double camZ, Matrix4f modelView, Matrix4f projectionMatrix) { - this.worldRenderer.renderSectionLayer(renderType, camX, camY, camZ, modelView, projectionMatrix); + private ChunkSectionsToRender prepareChunkRenders(Matrix4fc matrix4fc, double camX, double camY, double camZ) { + this.camX = camX; + this.camY = camY; + this.camZ = camZ; + + return null; + } + + @Redirect(method = "method_62214", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/chunk/ChunkSectionsToRender;renderGroup(Lnet/minecraft/client/renderer/chunk/ChunkSectionLayerGroup;)V")) + private void renderSectionLayer(ChunkSectionsToRender instance, ChunkSectionLayerGroup chunkSectionLayerGroup) { + if (chunkSectionLayerGroup == ChunkSectionLayerGroup.OPAQUE) { + Profiler profiler = Profiler.getMainProfiler(); + profiler.push("Opaque_terrain"); + + this.worldRenderer.renderSectionLayer(TerrainRenderType.SOLID, camX, camY, camZ, modelView, projection); + this.worldRenderer.renderSectionLayer(TerrainRenderType.CUTOUT, camX, camY, camZ, modelView, projection); + this.worldRenderer.renderSectionLayer(TerrainRenderType.CUTOUT_MIPPED, camX, camY, camZ, modelView, projection); + } + else if (chunkSectionLayerGroup == ChunkSectionLayerGroup.TRANSLUCENT) { + Profiler profiler = Profiler.getMainProfiler(); + profiler.pop(); + profiler.push("Translucent_terrain"); + + this.worldRenderer.renderSectionLayer(TerrainRenderType.TRANSLUCENT, camX, camY, camZ, modelView, projection); + + profiler.pop(); + } + } /** diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java deleted file mode 100644 index ee24f81304..0000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.PostChain; -import net.minecraft.client.renderer.PostPass; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ChainedJsonException; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.GsonHelper; -import net.vulkanmod.vulkan.Renderer; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -@Mixin(PostChain.class) -public abstract class PostChainM { - - // TODO: port -// @Shadow private int screenWidth; -// @Shadow private int screenHeight; -// -// @Shadow @Final private Map customRenderTargets; -// @Shadow @Final private RenderTarget screenTarget; -// @Shadow @Final private List passes; -// -// @Shadow private float lastStamp; -// @Shadow private float time; -// -// @Shadow public abstract void addTempTarget(String string, int i, int j); -// @Shadow protected abstract void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException; -// @Shadow protected abstract void parseUniformNode(JsonElement jsonElement) throws ChainedJsonException; -// -// /** -// * @author -// * @reason -// */ -// @Overwrite -// public void process(float f) { -// if (f < this.lastStamp) { -// this.time += 1.0F - this.lastStamp; -// this.time += f; -// } else { -// this.time += f - this.lastStamp; -// } -// -// this.lastStamp = f; -// -// while(this.time > 20.0F) { -// this.time -= 20.0F; -// } -// -// int filterMode = 9728; -// -// for(PostPass postPass : this.passes) { -// int passFilterMode = postPass.getFilterMode(); -// if (filterMode != passFilterMode) { -// this.setFilterMode(passFilterMode); -// filterMode = passFilterMode; -// } -// -// postPass.process(this.time / 20.0F); -// } -// -// this.setFilterMode(9728); -// -// Renderer.resetViewport(); -// } - -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java index f81d9e23b2..99580bb1dd 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java @@ -1,20 +1,25 @@ package net.vulkanmod.mixin.compatibility; import com.mojang.blaze3d.ProjectionType; +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.buffers.Std140Builder; import com.mojang.blaze3d.framegraph.FrameGraphBuilder; import com.mojang.blaze3d.framegraph.FramePass; -import com.mojang.blaze3d.pipeline.MainTarget; +import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.resource.ResourceHandle; -import com.mojang.blaze3d.shaders.Uniform; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.RenderPass; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.GpuTextureView; import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.minecraft.client.renderer.PostChainConfig; +import com.mojang.datafixers.util.Pair; +import net.minecraft.client.renderer.MappableRingBuffer; import net.minecraft.client.renderer.PostPass; import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.render.engine.*; import net.vulkanmod.vulkan.Renderer; -import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -22,92 +27,90 @@ import java.util.List; import java.util.Map; +import java.util.OptionalDouble; +import java.util.OptionalInt; @Mixin(PostPass.class) public abstract class PostPassM { @Shadow @Final private String name; - @Shadow @Final private List inputs; @Shadow @Final private ResourceLocation outputTargetId; - @Shadow @Final private CompiledShaderProgram shader; - @Shadow @Final private List uniforms; - - @Shadow protected abstract void restoreDefaultUniforms(); + @Shadow @Final private RenderPipeline pipeline; + @Shadow @Final private MappableRingBuffer infoUbo; + @Shadow @Final private Map customUniforms; /** * @author * @reason */ @Overwrite - public void addToFrame(FrameGraphBuilder frameGraphBuilder, Map> map, Matrix4f matrix4f) { + public void addToFrame(FrameGraphBuilder frameGraphBuilder, Map> map, GpuBufferSlice gpuBufferSlice) { FramePass framePass = frameGraphBuilder.addPass(this.name); for (PostPass.Input input : this.inputs) { input.addToPass(framePass, map); } - ResourceHandle resourceHandle = map.computeIfPresent( + ResourceHandle resourceHandle = (ResourceHandle)map.computeIfPresent( this.outputTargetId, (resourceLocation, resourceHandlex) -> framePass.readsAndWrites(resourceHandlex) ); if (resourceHandle == null) { throw new IllegalStateException("Missing handle for target " + this.outputTargetId); } else { - framePass.executes(() -> { - RenderTarget renderTarget = resourceHandle.get(); - RenderSystem.viewport(0, 0, renderTarget.width, renderTarget.height); + framePass.executes( + () -> { + RenderTarget renderTarget = resourceHandle.get(); + RenderSystem.backupProjectionMatrix(); + RenderSystem.setProjectionMatrix(gpuBufferSlice, ProjectionType.ORTHOGRAPHIC); + CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); + List> list = this.inputs.stream().map(inputxx -> Pair.of(inputxx.samplerName(), inputxx.texture(map))).toList(); + + try (GpuBuffer.MappedView mappedView = commandEncoder.mapBuffer(this.infoUbo.currentBuffer(), false, true)) { + Std140Builder std140Builder = Std140Builder.intoBuffer(mappedView.data()); + std140Builder.putVec2(renderTarget.width, renderTarget.height); + + for (Pair pair : list) { + std140Builder.putVec2(pair.getSecond().getWidth(0), pair.getSecond().getHeight(0)); + } + } - for (PostPass.Input inputx : this.inputs) { - if (inputx instanceof PostPass.TargetInput) { - var targetId = ((PostPass.TargetInput) inputx).targetId(); - var inTarget = map.get(targetId).get(); + Renderer.getInstance().endRenderPass(); - if (inTarget instanceof MainTarget) { - inTarget.bindRead(); + for (var input : this.inputs) { + VkGpuTexture gpuTexture = (VkGpuTexture) input.texture(map).texture(); + gpuTexture.getVulkanImage().readOnlyLayout(); } - } - inputx.bindTo(this.shader, map); - } + try (RenderPass renderPass = commandEncoder.createRenderPass( + () -> "Post pass " + this.name, + renderTarget.getColorTextureView(), + OptionalInt.empty(), + renderTarget.useDepth ? renderTarget.getDepthTextureView() : null, + OptionalDouble.empty() + )) { + renderPass.setPipeline(this.pipeline); + RenderSystem.bindDefaultUniforms(renderPass); + renderPass.setUniform("SamplerInfo", this.infoUbo.currentBuffer()); + + for (Map.Entry entry : this.customUniforms.entrySet()) { + renderPass.setUniform((String)entry.getKey(), (GpuBuffer)entry.getValue()); + } + + for (Pair pair2 : list) { + renderPass.bindSampler(pair2.getFirst() + "Sampler", pair2.getSecond()); + } + + renderPass.draw(0, 3); + } - this.shader.safeGetUniform("OutSize").set((float)renderTarget.width, (float)renderTarget.height); + this.infoUbo.rotate(); + RenderSystem.restoreProjectionMatrix(); - for (PostChainConfig.Uniform uniform : this.uniforms) { - Uniform uniform2 = this.shader.getUniform(uniform.name()); - if (uniform2 != null) { - uniform2.setFromConfig(uniform.values(), uniform.values().size()); + for (PostPass.Input inputx : this.inputs) { + inputx.cleanup(map); + } } - } - - renderTarget.setClearColor(0.0F, 0.0F, 0.0F, 0.0F); - renderTarget.clear(); - renderTarget.bindWrite(false); - RenderSystem.depthFunc(519); - RenderSystem.setShader(this.shader); - RenderSystem.backupProjectionMatrix(); - RenderSystem.setProjectionMatrix(matrix4f, ProjectionType.ORTHOGRAPHIC); - - Renderer.setInvertedViewport(0, 0, renderTarget.width, renderTarget.height); - Renderer.resetScissor(); - - BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); - bufferBuilder.addVertex(0.0F, 0.0F, 500.0F); - bufferBuilder.addVertex((float)renderTarget.width, 0.0F, 500.0F); - bufferBuilder.addVertex((float)renderTarget.width, (float)renderTarget.height, 500.0F); - bufferBuilder.addVertex(0.0F, (float)renderTarget.height, 500.0F); - - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - RenderSystem.depthFunc(515); - RenderSystem.restoreProjectionMatrix(); - renderTarget.unbindWrite(); - - Renderer.resetViewport(); - - for (PostPass.Input input2 : this.inputs) { - input2.cleanup(map); - } - - this.restoreDefaultUniforms(); - }); + ); } } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java deleted file mode 100644 index d8a4289135..0000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.mojang.blaze3d.shaders.Shader; -import com.mojang.blaze3d.shaders.Uniform; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.Pipeline; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(Uniform.class) -public class UniformM { - - @Shadow @Final private Shader parent; - - /** - * @author - * @reason - */ - @Overwrite - public static int glGetUniformLocation(int i, CharSequence charSequence) { - //TODO - return 1; - } - - @Inject(method = "upload", at = @At("HEAD"), cancellable = true) - public void redirectUpload(CallbackInfo ci) { - Renderer renderer = Renderer.getInstance(); - Pipeline boundPipeline = renderer.getBoundPipeline(); - - ci.cancel(); - - VkGlProgram program = VkGlProgram.getBoundProgram(); - - if (program == null) { - return; - } - - // Update descriptors only if the pipeline has already been bound - Pipeline pipeline = program.getPipeline(); - if (boundPipeline == pipeline) { - renderer.uploadAndBindUBOs(boundPipeline); - } - } - - @Inject(method = "uploadInteger", at = @At("HEAD"), cancellable = true) - private static void cancelUploadInteger(int i, int j, CallbackInfo ci) { - ci.cancel(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/debug/DebugEntryMemoryM.java b/src/main/java/net/vulkanmod/mixin/debug/DebugEntryMemoryM.java new file mode 100644 index 0000000000..cd6e90fd6c --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/debug/DebugEntryMemoryM.java @@ -0,0 +1,55 @@ +package net.vulkanmod.mixin.debug; + +import net.minecraft.client.gui.components.debug.DebugEntryMemory; +import net.minecraft.client.gui.components.debug.DebugScreenDisplayer; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.LevelChunk; +import net.vulkanmod.vulkan.memory.MemoryManager; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.lang.management.ManagementFactory; +import java.util.List; +import java.util.Locale; + +@Mixin(DebugEntryMemory.class) +public abstract class DebugEntryMemoryM { + + @Shadow @Final private static ResourceLocation GROUP; + + @Shadow + protected static long bytesToMegabytes(long l) { + return 0; + } + + // TODO +// @Shadow @Final private DebugEntryMemory.AllocationRateCalculator allocationRateCalculator; + + @Overwrite + public void display(DebugScreenDisplayer debugScreenDisplayer, @Nullable Level level, @Nullable LevelChunk levelChunk, @Nullable LevelChunk levelChunk2) { + long l = Runtime.getRuntime().maxMemory(); + long m = Runtime.getRuntime().totalMemory(); + long n = Runtime.getRuntime().freeMemory(); + long o = m - n; + debugScreenDisplayer.addToGroup( + GROUP, + List.of( + String.format(Locale.ROOT, "Mem: %2d%% %03d/%03dMB", o * 100L / l, bytesToMegabytes(o), bytesToMegabytes(l)), +// String.format(Locale.ROOT, "Allocation rate: %03dMB/s", bytesToMegabytes(this.allocationRateCalculator.bytesAllocatedPerSecond(o))), + String.format(Locale.ROOT, "Allocated: %2d%% %03dMB", m * 100L / l, bytesToMegabytes(m)), + String.format("Off-heap: " + getOffHeapMemory() + "MB"), + "NativeMemory: %dMB".formatted(MemoryManager.getInstance().getNativeMemoryMB()), + "DeviceMemory: %dMB".formatted(MemoryManager.getInstance().getAllocatedDeviceMemoryMB()) + ) + ); + + } + + private long getOffHeapMemory() { + return bytesToMegabytes(ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed()); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java b/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java deleted file mode 100644 index da44e8b84a..0000000000 --- a/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.vulkanmod.mixin.debug; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.components.DebugScreenOverlay; -import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.vulkan.SystemInfo; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.device.Device; -import net.vulkanmod.vulkan.memory.MemoryManager; -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; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static net.vulkanmod.Initializer.getVersion; - -@Mixin(DebugScreenOverlay.class) -public abstract class DebugScreenOverlayM { - - @Shadow - @Final - private Minecraft minecraft; - - @Shadow - private static long bytesToMegabytes(long bytes) { - return 0; - } - - @Shadow - @Final - private Font font; - - @Shadow - protected abstract List getGameInformation(); - - @Shadow - protected abstract List getSystemInformation(); - - @Redirect(method = "getSystemInformation", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Lists;newArrayList([Ljava/lang/Object;)Ljava/util/ArrayList;")) - private ArrayList redirectList(Object[] elements) { - ArrayList strings = new ArrayList<>(); - - long maxMemory = Runtime.getRuntime().maxMemory(); - long totalMemory = Runtime.getRuntime().totalMemory(); - long freeMemory = Runtime.getRuntime().freeMemory(); - long usedMemory = totalMemory - freeMemory; - - Device device = Vulkan.getDevice(); - - strings.add(String.format("Java: %s", System.getProperty("java.version"))); - strings.add(String.format("Mem: % 2d%% %03d/%03dMB", usedMemory * 100L / maxMemory, bytesToMegabytes(usedMemory), bytesToMegabytes(maxMemory))); - strings.add(String.format("Allocated: % 2d%% %03dMB", totalMemory * 100L / maxMemory, bytesToMegabytes(totalMemory))); - strings.add(String.format("Off-heap: " + getOffHeapMemory() + "MB")); - strings.add("NativeMemory: %dMB".formatted(MemoryManager.getInstance().getNativeMemoryMB())); - strings.add("DeviceMemory: %dMB".formatted(MemoryManager.getInstance().getAllocatedDeviceMemoryMB())); - strings.add(""); - strings.add("VulkanMod " + getVersion()); - strings.add("CPU: " + SystemInfo.cpuInfo); - strings.add("GPU: " + device.deviceName); - strings.add("Driver: " + device.driverVersion); - strings.add("Vulkan: " + device.vkVersion); - strings.add(""); - strings.add(""); - - Collections.addAll(strings, WorldRenderer.getInstance().getChunkAreaManager().getStats()); - - return strings; - } - - private long getOffHeapMemory() { - return bytesToMegabytes(ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed()); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java b/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java deleted file mode 100644 index 10986a42aa..0000000000 --- a/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.vulkanmod.mixin.debug; - -import com.mojang.blaze3d.platform.GlUtil; -import net.vulkanmod.vulkan.SystemInfo; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.device.Device; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(GlUtil.class) -public class GlDebugInfoM { - - /** - * @author - */ - @Overwrite - public static String getVendor() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().vendorIdString : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getRenderer() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().deviceName : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getOpenGLVersion() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().driverVersion : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getCpuInfo() { - return SystemInfo.cpuInfo; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java b/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java index 67330cece5..e01a76c911 100644 --- a/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java +++ b/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyboardHandler; import net.minecraft.client.Minecraft; +import net.minecraft.client.input.KeyEvent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -12,15 +13,15 @@ @Mixin(KeyboardHandler.class) public abstract class KeyboardHandlerM { - @Shadow protected abstract boolean handleChunkDebugKeys(int i); + @Shadow protected abstract boolean handleChunkDebugKeys(KeyEvent keyEvent); @Shadow private boolean handledDebugKey; - @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/InputConstants;isKeyDown(JI)Z", ordinal = 0, shift = At.Shift.AFTER)) - private void chunkDebug(long window, int key, int scancode, int action, int mods, CallbackInfo ci) { + @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/KeyMapping;set(Lcom/mojang/blaze3d/platform/InputConstants$Key;Z)V", ordinal = 1)) + private void chunkDebug(long l, int i, KeyEvent keyEvent, CallbackInfo ci) { // GLFW key 296 -> F7 // U -> Capture frustum - this.handledDebugKey |= InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 296) - && this.handleChunkDebugKeys(key); + this.handledDebugKey |= InputConstants.isKeyDown(Minecraft.getInstance().getWindow(), 296) + && this.handleChunkDebugKeys(keyEvent); } } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java index 1fd1ede71c..26563f60a7 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java @@ -26,7 +26,7 @@ private void createProfilerOverlay(Minecraft minecraft, CallbackInfo ci) { @Inject(method = "render", at = @At(value = "RETURN")) private void renderProfilerOverlay(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if(ProfilerOverlay.shouldRender && !this.debugOverlay.showDebugScreen()) + if (ProfilerOverlay.shouldRender && !this.debugOverlay.showDebugScreen()) ProfilerOverlay.INSTANCE.render(guiGraphics); } } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java b/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java index 242ce30601..467ec1a73e 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyboardHandler; import net.minecraft.client.Minecraft; +import net.minecraft.client.input.KeyEvent; import net.vulkanmod.render.profiling.BuildTimeProfiler; import net.vulkanmod.render.profiling.ProfilerOverlay; import org.lwjgl.glfw.GLFW; @@ -16,16 +17,16 @@ public class KeyboardHandlerM { @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/KeyMapping;set(Lcom/mojang/blaze3d/platform/InputConstants$Key;Z)V", - ordinal = 0, shift = At.Shift.AFTER)) - private void injOverlayToggle(long window, int key, int scancode, int action, int mods, CallbackInfo ci) { - if(InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { - switch (key) { + ordinal = 1, shift = At.Shift.AFTER)) + private void injOverlayToggle(long l, int i, KeyEvent keyEvent, CallbackInfo ci) { + if (InputConstants.isKeyDown(Minecraft.getInstance().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { + switch (keyEvent.key()) { case GLFW.GLFW_KEY_F8 -> ProfilerOverlay.toggle(); case GLFW.GLFW_KEY_F10 -> BuildTimeProfiler.startBench(); } } - else if(ProfilerOverlay.shouldRender) { - ProfilerOverlay.onKeyPress(key); + else if (ProfilerOverlay.shouldRender) { + ProfilerOverlay.onKeyPress(keyEvent.key()); } } } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java index b67d076026..b0061a2611 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java @@ -1,16 +1,13 @@ package net.vulkanmod.mixin.profiling; -import com.mojang.blaze3d.framegraph.FrameGraphBuilder; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.resource.ResourceHandle; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Camera; import net.minecraft.client.CloudStatus; import net.minecraft.client.DeltaTracker; -import net.minecraft.client.renderer.FogParameters; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.client.renderer.state.LevelRenderState; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.profiling.Profiler; @@ -24,81 +21,43 @@ public class LevelRendererMixin { @Inject(method = "method_62205", at = @At("HEAD")) - private void pushProfiler(ResourceHandle resourceHandle, int i, CloudStatus cloudStatus, float f, Matrix4f matrix4f, - Matrix4f matrix4f2, Vec3 vec3, float g, CallbackInfo ci) { + private void pushProfiler(int i, CloudStatus cloudStatus, float f, Vec3 vec3, float g, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Clouds"); } @Inject(method = "method_62205", at = @At("RETURN")) - private void popProfiler(ResourceHandle resourceHandle, int i, CloudStatus cloudStatus, float f, Matrix4f matrix4f, - Matrix4f matrix4f2, Vec3 vec3, float g, CallbackInfo ci) { + private void popProfiler(int i, CloudStatus cloudStatus, float f, Vec3 vec3, float g, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } // TODO: fix @Inject(method = "method_62213", at = @At(value = "HEAD")) - private void pushProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, - ResourceHandle resourceHandle2, Camera camera, float f, CallbackInfo ci) { + private void pushProfiler3(GpuBufferSlice gpuBufferSlice, ResourceHandle resourceHandle, + ResourceHandle resourceHandle2, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Particles"); } @Inject(method = "method_62213", at = @At(value = "RETURN")) - private void popProfiler3(FogParameters fogParameters, ResourceHandle resourceHandle, - ResourceHandle resourceHandle2, Camera camera, float f, CallbackInfo ci) { + private void popProfiler3(GpuBufferSlice gpuBufferSlice, ResourceHandle resourceHandle, + ResourceHandle resourceHandle2, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } @Inject(method = "method_62214", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 0, - shift = At.Shift.BEFORE)) - private void profilerTerrain1(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, - ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, - boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.push("Opaque_terrain"); - } - - @Inject(method = "method_62214", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/Camera;Lnet/minecraft/client/DeltaTracker;Ljava/util/List;)V")) - private void profilerTerrain2(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, - ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, - boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { + target = "Lnet/minecraft/client/renderer/LevelRenderer;submitEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/state/LevelRenderState;Lnet/minecraft/client/renderer/SubmitNodeCollector;)V")) + private void profilerTerrain2(GpuBufferSlice gpuBufferSlice, LevelRenderState levelRenderState, + ProfilerFiller profilerFiller, Matrix4f matrix4f, ResourceHandle resourceHandle, + ResourceHandle resourceHandle2, boolean bl, Frustum frustum, + ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, CallbackInfo ci) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); profiler.push("entities"); } - @Inject(method = "method_62214", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 3, - shift = At.Shift.BEFORE)) - private void profilerTerrain3(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, - ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, - boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.pop(); - profiler.push("Translucent_terrain"); - } - - @Inject(method = "method_62214", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", - ordinal = 4, - shift = At.Shift.AFTER)) - private void profilerTerrain4(FogParameters fogParameters, DeltaTracker deltaTracker, Camera camera, ProfilerFiller profilerFiller, Matrix4f matrix4f, Matrix4f matrix4f2, - ResourceHandle resourceHandle, ResourceHandle resourceHandle2, ResourceHandle resourceHandle3, ResourceHandle resourceHandle4, - boolean bl, Frustum frustum, ResourceHandle resourceHandle5, CallbackInfo ci) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.pop(); - } - } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/TimerQueryM.java b/src/main/java/net/vulkanmod/mixin/profiling/TimerQueryM.java new file mode 100644 index 0000000000..71836fd9f8 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/profiling/TimerQueryM.java @@ -0,0 +1,18 @@ +package net.vulkanmod.mixin.profiling; + +import com.mojang.blaze3d.systems.TimerQuery; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@Mixin(TimerQuery.class) +public class TimerQueryM { + + @Overwrite + public void beginProfile() { + } + + @Overwrite + public TimerQuery.FrameProfile endProfile() { + return null; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java deleted file mode 100644 index 9268a925e2..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ /dev/null @@ -1,93 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferUploader; -import com.mojang.blaze3d.vertex.MeshData; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.vulkanmod.interfaces.shader.ShaderMixed; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; - -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(BufferUploader.class) -public class BufferUploaderM { - - /** - * @author - */ - @Overwrite - public static void reset() {} - - /** - * @author - */ - @Overwrite - public static void drawWithShader(MeshData meshData) { - RenderSystem.assertOnRenderThread(); - - MeshData.DrawState parameters = meshData.drawState(); - - Renderer renderer = Renderer.getInstance(); - - Matrix4f projection = RenderSystem.getProjectionMatrix(); - Matrix4f modelView = RenderSystem.getModelViewStack(); - - VRenderSystem.applyMVP(modelView, projection); - - if (parameters.vertexCount() > 0) { - CompiledShaderProgram shaderProgram = RenderSystem.getShader(); - - // Prevent drawing if formats don't match to avoid disturbing visual bugs -// if (shaderProgram.getVertexFormat() != parameters.format()) { -// meshData.close(); -// return; -// } - - // Used to update legacy shader uniforms - // TODO it would be faster to allocate a buffer from stack and set all values - shaderProgram.apply(); -// shaderProgram.setDefaultUniforms(parameters.mode(), modelView, projection, Minecraft.getInstance().getWindow()); - - GraphicsPipeline pipeline = ((ShaderMixed)(shaderProgram)).getPipeline(); - - if (pipeline == null) { -// throw new NullPointerException("Shader %s has no initialized pipeline".formatted(shaderProgram.getName())); - throw new NullPointerException("Shader %d has no initialized pipeline".formatted(shaderProgram.getProgramId())); - } - - VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); - renderer.bindGraphicsPipeline(pipeline); - VTextureSelector.bindShaderTextures(pipeline); - renderer.uploadAndBindUBOs(pipeline); - - Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); - } - - meshData.close(); - } - - /** - * @author - */ - @Overwrite - public static void draw(MeshData meshData) { - MeshData.DrawState parameters = meshData.drawState(); - - if (parameters.vertexCount() > 0) { - Renderer renderer = Renderer.getInstance(); - Pipeline pipeline = renderer.getBoundPipeline(); - renderer.uploadAndBindUBOs(pipeline); - - Renderer.getDrawer().draw(meshData.vertexBuffer(), null, parameters.mode(), parameters.format(), parameters.vertexCount()); - } - - meshData.close(); - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java b/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java new file mode 100644 index 0000000000..c701142d79 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java @@ -0,0 +1,123 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.ScissorState; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderType; +import net.vulkanmod.render.engine.*; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.joml.Vector3f; +import org.joml.Vector4f; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.OptionalDouble; +import java.util.OptionalInt; + +@Mixin(RenderType.CompositeRenderType.class) +public abstract class CompositeRenderTypeM { + + @Shadow @Final private RenderType.CompositeState state; + @Shadow @Final private RenderPipeline renderPipeline; + + // TODO + /** + * @author + * @reason + */ + @Overwrite + public void draw(MeshData meshData) { + ((RenderType.CompositeRenderType)(Object)(this)).setupRenderState(); + GpuBufferSlice gpuBufferSlice = RenderSystem.getDynamicUniforms() + .writeTransform( + RenderSystem.getModelViewMatrix(), + new Vector4f(1.0F, 1.0F, 1.0F, 1.0F), + new Vector3f(), + RenderSystem.getTextureMatrix(), + RenderSystem.getShaderLineWidth() + ); + MeshData var3 = meshData; + + try { + GpuBuffer gpuBuffer = this.renderPipeline.getVertexFormat().uploadImmediateVertexBuffer(meshData.vertexBuffer()); + GpuBuffer gpuBuffer2; + VertexFormat.IndexType indexType; + if (meshData.indexBuffer() == null) { + RenderSystem.AutoStorageIndexBuffer autoStorageIndexBuffer = RenderSystem.getSequentialBuffer(meshData.drawState().mode()); + gpuBuffer2 = autoStorageIndexBuffer.getBuffer(meshData.drawState().indexCount()); + indexType = autoStorageIndexBuffer.type(); + } else { + gpuBuffer2 = this.renderPipeline.getVertexFormat().uploadImmediateIndexBuffer(meshData.indexBuffer()); + indexType = meshData.drawState().indexType(); + } + + RenderTarget renderTarget = ((CompositeStateAccessor)(Object)this.state).getOutputState().getRenderTarget(); + GpuTextureView gpuTextureView = RenderSystem.outputColorTextureOverride != null + ? RenderSystem.outputColorTextureOverride + : renderTarget.getColorTextureView(); + GpuTextureView gpuTextureView2 = renderTarget.useDepth + ? (RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : renderTarget.getDepthTextureView()) + : null; + + try (RenderPass renderPass = RenderSystem.getDevice() + .createCommandEncoder() + .createRenderPass(() -> "Immediate draw for " + + ((RenderType.CompositeRenderType) (Object) (this)).getName(), + gpuTextureView, OptionalInt.empty(), gpuTextureView2, OptionalDouble.empty())) { + renderPass.setPipeline(this.renderPipeline); + ScissorState scissorState = RenderSystem.getScissorStateForRenderTypeDraws(); + if (scissorState.enabled()) { + renderPass.enableScissor(scissorState.x(), scissorState.y(), scissorState.width(), scissorState.height()); + } + + RenderSystem.bindDefaultUniforms(renderPass); + renderPass.setUniform("DynamicTransforms", gpuBufferSlice); + renderPass.setVertexBuffer(0, gpuBuffer); + + for (int i = 0; i < 12; i++) { + GpuTextureView gpuTextureView3 = RenderSystem.getShaderTexture(i); + if (gpuTextureView3 != null) { + renderPass.bindSampler("Sampler" + i, gpuTextureView3); + + VkGpuTexture vkGpuTexture = (VkGpuTexture) gpuTextureView3.texture(); + VTextureSelector.bindTexture(i, vkGpuTexture.getVulkanImage()); + } + } + + renderPass.setIndexBuffer(gpuBuffer2, indexType); + + VkCommandEncoder commandEncoder = (VkCommandEncoder) RenderSystem.getDevice().createCommandEncoder(); + commandEncoder.trySetup((VkRenderPass) renderPass); + + Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), meshData.drawState().mode(), meshData.drawState().format(), meshData.drawState().vertexCount()); + } + } catch (Throwable var17) { + if (meshData != null) { + try { + var3.close(); + } catch (Throwable var14) { + var17.addSuppressed(var14); + } + } + + throw var17; + } + + if (meshData != null) { + meshData.close(); + } + + ((RenderType.CompositeRenderType)(Object)(this)).clearRenderState(); + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/CompositeStateAccessor.java b/src/main/java/net/vulkanmod/mixin/render/CompositeStateAccessor.java new file mode 100644 index 0000000000..1f3abc805c --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/CompositeStateAccessor.java @@ -0,0 +1,23 @@ +package net.vulkanmod.mixin.render; + +import com.google.common.collect.ImmutableList; +import net.minecraft.client.renderer.RenderStateShard; +import net.minecraft.client.renderer.RenderType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(RenderType.CompositeState.class) +public interface CompositeStateAccessor { + + @Accessor("textureState") + RenderStateShard.EmptyTextureStateShard getTextureState(); + + @Accessor("outputState") + RenderStateShard.OutputStateShard getOutputState(); + + @Accessor("outlineProperty") + RenderType.OutlineProperty getOutlineProperty(); + + @Accessor("states") + ImmutableList getStates(); +} diff --git a/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java new file mode 100644 index 0000000000..d8fb71eb8e --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java @@ -0,0 +1,26 @@ +package net.vulkanmod.mixin.render; + +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.client.Camera; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.fog.FogData; +import net.minecraft.client.renderer.fog.FogRenderer; +import net.vulkanmod.vulkan.VRenderSystem; +import org.joml.Vector4f; +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.CallbackInfoReturnable; + +@Mixin(FogRenderer.class) +public class FogRendererMixin { + + @Inject(method = "setupFog", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Mth;clamp(FFF)F")) + private void onSetupFog(Camera camera, int i, boolean bl, DeltaTracker deltaTracker, float f, + ClientLevel clientLevel, CallbackInfoReturnable cir, + @Local FogData fogData, @Local Vector4f fogColor) { + VRenderSystem.fogData = fogData; + VRenderSystem.setShaderFogColor(fogColor.x(), fogColor.y(), fogColor.z(), fogColor.w()); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index f538baa813..8006d35f61 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -1,19 +1,12 @@ package net.vulkanmod.mixin.render; -import com.google.common.base.Charsets; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.opengl.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.jtracy.Plot; import net.vulkanmod.gl.*; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; -import org.lwjgl.PointerBuffer; -import org.lwjgl.opengl.GL15; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL20C; -import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -22,7 +15,6 @@ import org.spongepowered.asm.mixin.Shadow; import java.nio.ByteBuffer; -import java.nio.IntBuffer; @Mixin(GlStateManager.class) public class GlStateManagerM { @@ -36,7 +28,7 @@ public class GlStateManagerM { */ @Overwrite(remap = false) public static void _bindTexture(int i) { - GlTexture.bindTexture(i); + VkGlTexture.bindTexture(i); } /** @@ -57,16 +49,6 @@ public static void _enableBlend() { VRenderSystem.enableBlend(); } - /** - * @author - */ - @Overwrite(remap = false) - public static void _blendFunc(int i, int j) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.blendFunc(i, j); - - } - /** * @author */ @@ -136,9 +118,9 @@ public static int _getError() { * @author */ @Overwrite(remap = false) - public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { - RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); + public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) { + RenderSystem.assertOnRenderThread(); + VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } /** @@ -146,8 +128,8 @@ public static void _texImage2D(int target, int level, int internalFormat, int wi */ @Overwrite(remap = false) public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { - RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); + RenderSystem.assertOnRenderThread(); + VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** @@ -155,7 +137,7 @@ public static void _texSubImage2D(int target, int level, int offsetX, int offset */ @Overwrite(remap = false) public static void _activeTexture(int i) { - GlTexture.activeTexture(i); + VkGlTexture.activeTexture(i); } /** @@ -163,15 +145,7 @@ public static void _activeTexture(int i) { */ @Overwrite(remap = false) public static void _texParameter(int i, int j, int k) { - GlTexture.texParameteri(i, j, k); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _texParameter(int i, int j, float k) { - //TODO + VkGlTexture.texParameteri(i, j, k); } /** @@ -179,7 +153,7 @@ public static void _texParameter(int i, int j, float k) { */ @Overwrite(remap = false) public static int _getTexLevelParameter(int i, int j, int k) { - return GlTexture.getTexLevelParameter(i, j, k); + return VkGlTexture.getTexLevelParameter(i, j, k); } /** @@ -188,8 +162,8 @@ public static int _getTexLevelParameter(int i, int j, int k) { @Overwrite(remap = false) public static void _pixelStore(int pname, int param) { //Used during upload to set copy offsets - RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.pixelStoreI(pname, param); + RenderSystem.assertOnRenderThread(); + VkGlTexture.pixelStoreI(pname, param); } /** @@ -197,8 +171,8 @@ public static void _pixelStore(int pname, int param) { */ @Overwrite(remap = false) public static int _genTexture() { - RenderSystem.assertOnRenderThreadOrInit(); - return GlTexture.genTextureId(); + RenderSystem.assertOnRenderThread(); + return VkGlTexture.genTextureId(); } /** @@ -206,8 +180,8 @@ public static int _genTexture() { */ @Overwrite(remap = false) public static void _deleteTexture(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.glDeleteTextures(i); + RenderSystem.assertOnRenderThread(); + VkGlTexture.glDeleteTextures(i); } /** @@ -224,7 +198,7 @@ public static void _colorMask(boolean red, boolean green, boolean blue, boolean */ @Overwrite(remap = false) public static void _depthFunc(int i) { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); VRenderSystem.depthFunc(i); } @@ -232,124 +206,127 @@ public static void _depthFunc(int i) { * @author */ @Overwrite(remap = false) - public static void _clearColor(float f, float g, float h, float i) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.setClearColor(f, g, h, i); + public static void _polygonMode(int face, int mode) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.setPolygonModeGL(mode); } /** * @author */ @Overwrite(remap = false) - public static void _clearDepth(double d) {} + public static void _enablePolygonOffset() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.enablePolygonOffset(); + } /** * @author */ @Overwrite(remap = false) - public static void _clear(int mask) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.clear(mask); + public static void _disablePolygonOffset() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.disablePolygonOffset(); } /** * @author */ @Overwrite(remap = false) - public static void _disableDepthTest() { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.disableDepthTest(); + public static void _polygonOffset(float f, float g) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.polygonOffset(g, f); } /** * @author */ @Overwrite(remap = false) - public static void _enableDepthTest() { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.enableDepthTest(); + public static void _enableColorLogicOp() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.enableColorLogicOp(); } /** * @author */ @Overwrite(remap = false) - public static void _depthMask(boolean bl) { + public static void _disableColorLogicOp() { RenderSystem.assertOnRenderThread(); - VRenderSystem.depthMask(bl); - + VRenderSystem.disableColorLogicOp(); } /** * @author */ @Overwrite(remap = false) - public static int glGenFramebuffers() { - RenderSystem.assertOnRenderThreadOrInit(); - return GlFramebuffer.genFramebufferId(); + public static void _logicOp(int i) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.logicOp(i); } /** * @author */ @Overwrite(remap = false) - public static int glGenRenderbuffers() { - RenderSystem.assertOnRenderThreadOrInit(); - return GlRenderbuffer.genId(); + public static void _clear(int mask) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.clear(mask); } /** * @author */ @Overwrite(remap = false) - public static void _glBindFramebuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.bindFramebuffer(i, j); + public static void _disableDepthTest() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.disableDepthTest(); } /** * @author */ @Overwrite(remap = false) - public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { - RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.framebufferTexture2D(i, j, k, l, m); + public static void _enableDepthTest() { + RenderSystem.assertOnRenderThread(); + VRenderSystem.enableDepthTest(); } /** * @author */ @Overwrite(remap = false) - public static void _glBindRenderbuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - GlRenderbuffer.bindRenderbuffer(i, j); + public static void _depthMask(boolean bl) { + RenderSystem.assertOnRenderThread(); + VRenderSystem.depthMask(bl); + } /** * @author */ @Overwrite(remap = false) - public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { - RenderSystem.assertOnRenderThreadOrInit(); - GlFramebuffer.framebufferRenderbuffer(i, j, k, l); + public static int glGenFramebuffers() { + RenderSystem.assertOnRenderThread(); + return VkGlFramebuffer.genFramebufferId(); } /** * @author */ @Overwrite(remap = false) - public static void _glRenderbufferStorage(int i, int j, int k, int l) { - RenderSystem.assertOnRenderThreadOrInit(); - GlRenderbuffer.renderbufferStorage(i, j, k, l); + public static void _glBindFramebuffer(int i, int j) { + RenderSystem.assertOnRenderThread(); + VkGlFramebuffer.bindFramebuffer(i, j); } /** * @author */ @Overwrite(remap = false) - public static int glCheckFramebufferStatus(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - return GlFramebuffer.glCheckFramebufferStatus(i); + public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { + RenderSystem.assertOnRenderThread(); + VkGlFramebuffer.framebufferTexture2D(i, j, k, l, m); } /** @@ -357,12 +334,12 @@ public static int glCheckFramebufferStatus(int i) { */ @Overwrite(remap = false) public static int _glGenBuffers() { - RenderSystem.assertOnRenderThreadOrInit(); + RenderSystem.assertOnRenderThread(); numBuffers++; PLOT_BUFFERS.setValue(numBuffers); - return GlBuffer.glGenBuffers(); + return VkGlBuffer.glGenBuffers(); } /** @@ -370,8 +347,8 @@ public static int _glGenBuffers() { */ @Overwrite(remap = false) public static void _glBindBuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBindBuffer(i, j); + RenderSystem.assertOnRenderThread(); + VkGlBuffer.glBindBuffer(i, j); } /** @@ -379,8 +356,8 @@ public static void _glBindBuffer(int i, int j) { */ @Overwrite(remap = false) public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBufferData(i, byteBuffer, j); + RenderSystem.assertOnRenderThread(); + VkGlBuffer.glBufferData(i, byteBuffer, j); } /** @@ -388,18 +365,8 @@ public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { */ @Overwrite(remap = false) public static void _glBufferData(int i, long l, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glBufferData(i, l, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - @Nullable - public static ByteBuffer _glMapBuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - return GlBuffer.glMapBuffer(i, j); + RenderSystem.assertOnRenderThread(); + VkGlBuffer.glBufferData(i, l, j); } /** @@ -407,8 +374,8 @@ public static ByteBuffer _glMapBuffer(int i, int j) { */ @Overwrite(remap = false) public static void _glUnmapBuffer(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - GlBuffer.glUnmapBuffer(i); + RenderSystem.assertOnRenderThread(); + VkGlBuffer.glUnmapBuffer(i); } /** @@ -417,22 +384,16 @@ public static void _glUnmapBuffer(int i) { @Overwrite(remap = false) public static void _glDeleteBuffers(int i) { RenderSystem.assertOnRenderThread(); - GlBuffer.glDeleteBuffers(i); + VkGlBuffer.glDeleteBuffers(i); } - /** - * @author - */ - @Overwrite(remap = false) - public static void _disableVertexAttribArray(int i) {} - /** * @author */ @Overwrite(remap = false) public static void glDeleteShader(int i) { RenderSystem.assertOnRenderThread(); - GlShader.glDeleteShader(i); + VkGlShader.glDeleteShader(i); } /** @@ -441,7 +402,7 @@ public static void glDeleteShader(int i) { @Overwrite(remap = false) public static int glCreateShader(int i) { RenderSystem.assertOnRenderThread(); - return GlShader.glCreateShader(i); + return VkGlShader.glCreateShader(i); } /** @@ -450,7 +411,7 @@ public static int glCreateShader(int i) { @Overwrite(remap = false) public static void glShaderSource(int i, String string) { RenderSystem.assertOnRenderThread(); - GlShader.glShaderSource(i, string); + VkGlShader.glShaderSource(i, string); } /** @@ -459,7 +420,7 @@ public static void glShaderSource(int i, String string) { @Overwrite(remap = false) public static void glCompileShader(int i) { RenderSystem.assertOnRenderThread(); - GlShader.glCompileShader(i); + VkGlShader.glCompileShader(i); } /** @@ -468,7 +429,7 @@ public static void glCompileShader(int i) { @Overwrite(remap = false) public static int glGetShaderi(int i, int j) { RenderSystem.assertOnRenderThread(); - return GlShader.glGetShaderi(i, j); + return VkGlShader.glGetShaderi(i, j); } /** diff --git a/src/main/java/net/vulkanmod/mixin/render/GuiRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/GuiRendererMixin.java new file mode 100644 index 0000000000..09e25216ef --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/GuiRendererMixin.java @@ -0,0 +1,74 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.gui.render.GuiRenderer; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.BlitRenderState; +import net.minecraft.client.gui.render.state.GuiItemRenderState; +import net.minecraft.client.gui.render.state.GuiRenderState; +import net.minecraft.client.renderer.RenderPipelines; +import net.vulkanmod.render.engine.VkRenderPass; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(GuiRenderer.class) +public abstract class GuiRendererMixin { + + @Shadow @Final private GuiRenderState renderState; + @Shadow private @Nullable GpuTextureView itemsAtlasView; + + @Overwrite + private void submitBlitFromItemAtlas(GuiItemRenderState guiItemRenderState, float u, float v, int size, int atlasSize) { + v = 1.0f - v; + float u1 = u + (float)size / atlasSize; + float v1 = v + (float)(size) / atlasSize; + this.renderState + .submitBlitToCurrentLayer( + new BlitRenderState( + RenderPipelines.GUI_TEXTURED_PREMULTIPLIED_ALPHA, + TextureSetup.singleTexture(this.itemsAtlasView), + guiItemRenderState.pose(), + guiItemRenderState.x(), + guiItemRenderState.y(), + guiItemRenderState.x() + 16, + guiItemRenderState.y() + 16, + u, + u1, + v, + v1, + -1, + guiItemRenderState.scissorArea(), + null + ) + ); + } + + @Redirect(method = "executeDraw", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderPass;setIndexBuffer(Lcom/mojang/blaze3d/buffers/GpuBuffer;Lcom/mojang/blaze3d/vertex/VertexFormat$IndexType;)V")) + private void removeIndexBuffer(RenderPass instance, GpuBuffer gpuBuffer, VertexFormat.IndexType indexType) { + // This draw method forces quad index buffer, not allowing other draw modes + // Not binding it here will allow for a proper index selection in lower level methods + } + + @Redirect(method = "executeDraw", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderPass;drawIndexed(IIII)V")) + private void useVertexCount(RenderPass renderPass, int baseVertex, int firstIndex, int indexCount, int instanceCount) { + // For the same reason here we need to use vertexCount instead of indexCount + + VkRenderPass vkRenderPass = (VkRenderPass) renderPass; + if (vkRenderPass.getPipeline().getVertexFormatMode() != VertexFormat.Mode.TRIANGLES) { + int vertexCount = indexCount * 2 / 3; + renderPass.drawIndexed(baseVertex, 0, vertexCount, 1); + } + else { + renderPass.drawIndexed(baseVertex, 0, indexCount, 1); + } + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 8823d7ad47..d39d1cd183 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -40,14 +40,9 @@ private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { } } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) - private Optional removeTimer() { - return Optional.empty(); - } - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;tick()V"), locals = LocalCapture.CAPTURE_FAILHARD) - private void redirectResourceTick(boolean bl, CallbackInfo ci, Runnable runnable, int i, ProfilerFiller profilerFiller, int j) { + private void redirectResourceTick(boolean bl, CallbackInfo ci, int i, ProfilerFiller profilerFiller, int j) { int n = Math.min(10, i) - 1; boolean doUpload = j == n; SpriteUpdateUtil.setDoUpload(doUpload); diff --git a/src/main/java/net/vulkanmod/mixin/render/PictureInPictureRendererM.java b/src/main/java/net/vulkanmod/mixin/render/PictureInPictureRendererM.java new file mode 100644 index 0000000000..6ed06dc333 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/PictureInPictureRendererM.java @@ -0,0 +1,42 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.textures.GpuTextureView; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.pip.PictureInPictureRenderer; +import net.minecraft.client.gui.render.state.BlitRenderState; +import net.minecraft.client.gui.render.state.GuiRenderState; +import net.minecraft.client.gui.render.state.pip.PictureInPictureRenderState; +import net.minecraft.client.renderer.RenderPipelines; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(PictureInPictureRenderer.class) +public class PictureInPictureRendererM { + + @Shadow + private @Nullable GpuTextureView textureView; + + @Overwrite + public void blitTexture(T pictureInPictureRenderState, GuiRenderState guiRenderState) { + guiRenderState.submitBlitToCurrentLayer( + new BlitRenderState( + RenderPipelines.GUI_TEXTURED_PREMULTIPLIED_ALPHA, + TextureSetup.singleTexture(this.textureView), + pictureInPictureRenderState.pose(), + pictureInPictureRenderState.x0(), + pictureInPictureRenderState.y0(), + pictureInPictureRenderState.x1(), + pictureInPictureRenderState.y1(), + 0.0F, + 1.0F, + 0.0F, + 1.0F, + -1, + pictureInPictureRenderState.scissorArea(), + null + ) + ); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 0b3a39ba76..74ef4eb5ba 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -1,406 +1,63 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.ProjectionType; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.shaders.ShaderType; +import com.mojang.blaze3d.systems.GpuDevice; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.VertexSorting; -import net.minecraft.client.renderer.FogParameters; -import net.vulkanmod.gl.GlTexture; +import com.mojang.blaze3d.vertex.*; +import net.minecraft.client.renderer.DynamicUniforms; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.render.engine.VkGpuDevice; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; -import org.joml.Matrix4fStack; -import org.joml.Vector3f; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import java.util.function.Consumer; +import java.util.function.BiFunction; import static com.mojang.blaze3d.systems.RenderSystem.*; @Mixin(RenderSystem.class) public abstract class RenderSystemMixin { - - @Shadow private static Matrix4f projectionMatrix; - @Shadow private static Matrix4f savedProjectionMatrix; - @Shadow @Final private static Matrix4fStack modelViewStack; @Shadow private static Matrix4f textureMatrix; - - @Shadow @Final private static float[] shaderColor; - @Shadow @Final private static Vector3f[] shaderLightDirections; - @Shadow private static @Nullable Thread renderThread; - @Shadow - public static void assertOnRenderThread() { - } + @Shadow private static @Nullable GpuDevice DEVICE; + @Shadow private static @Nullable DynamicUniforms dynamicUniforms; - @Shadow private static ProjectionType projectionType; + @Shadow private static String apiDescription; - @Shadow private static ProjectionType savedProjectionType; - - @Shadow private static FogParameters shaderFog; + @Shadow + public static void assertOnRenderThread() {} - /** - * @author - */ @Overwrite(remap = false) - public static void initRenderer(int debugVerbosity, boolean debugSync) { - VRenderSystem.initRenderer(); - + public static void initRenderer(long l, int i, boolean bl, BiFunction shaderSource, boolean bl2) { renderThread.setPriority(Thread.NORM_PRIORITY + 2); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void setupDefaultState(int x, int y, int width, int height) { } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableColorLogicOp() { - assertOnRenderThread(); - VRenderSystem.enableColorLogicOp(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableColorLogicOp() { - assertOnRenderThread(); - VRenderSystem.disableColorLogicOp(); - } - - /** - * @author - */ - @Overwrite - public static void logicOp(GlStateManager.LogicOp op) { - assertOnRenderThread(); - VRenderSystem.logicOp(op); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void activeTexture(int texture) { - GlTexture.activeTexture(texture); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static int maxSupportedTextureSize() { - return VRenderSystem.maxSupportedTextureSize(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void clear(int mask) { - VRenderSystem.clear(mask); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void clearColor(float r, float g, float b, float a) { - VRenderSystem.setClearColor(r, g, b, a); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void clearDepth(double d) { - VRenderSystem.clearDepth(d); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableScissor(int x, int y, int width, int height) { - Renderer.setScissor(x, y, width, height); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableScissor() { - Renderer.resetScissor(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableDepthTest() { - assertOnRenderThread(); - //GlStateManager._disableDepthTest(); - VRenderSystem.disableDepthTest(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableDepthTest() { - assertOnRenderThreadOrInit(); - VRenderSystem.enableDepthTest(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void depthFunc(int i) { - assertOnRenderThread(); - VRenderSystem.depthFunc(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void depthMask(boolean b) { - assertOnRenderThread(); - VRenderSystem.depthMask(b); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - VRenderSystem.colorMask(red, green, blue, alpha); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendEquation(int i) { - assertOnRenderThread(); - //TODO - } - /** - * @author - */ - @Overwrite(remap = false) - public static void enableBlend() { - VRenderSystem.enableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableBlend() { - VRenderSystem.disableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFunc(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - VRenderSystem.blendFunc(sourceFactor, destFactor); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFunc(int srcFactor, int dstFactor) { - VRenderSystem.blendFunc(srcFactor, dstFactor); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFuncSeparate(GlStateManager.SourceFactor p_69417_, GlStateManager.DestFactor p_69418_, GlStateManager.SourceFactor p_69419_, GlStateManager.DestFactor p_69420_) { - VRenderSystem.blendFuncSeparate(p_69417_, p_69418_, p_69419_, p_69420_); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void blendFuncSeparate(int srcFactorRGB, int dstFactorRGB, int srcFactorAlpha, int dstFactorAlpha) { - VRenderSystem.blendFuncSeparate(srcFactorRGB, dstFactorRGB, srcFactorAlpha, dstFactorAlpha); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enableCull() { - assertOnRenderThread(); - VRenderSystem.enableCull(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disableCull() { - assertOnRenderThread(); - VRenderSystem.disableCull(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void polygonMode(final int face, final int mode) { - assertOnRenderThread(); - VRenderSystem.setPolygonModeGL(mode); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void enablePolygonOffset() { - assertOnRenderThread(); - VRenderSystem.enablePolygonOffset(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void disablePolygonOffset() { - assertOnRenderThread(); - VRenderSystem.disablePolygonOffset(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void polygonOffset(float factor, float units) { - assertOnRenderThread(); - VRenderSystem.polygonOffset(factor, units); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void setShaderLights(Vector3f dir0, Vector3f dir1) { - shaderLightDirections[0] = dir0; - shaderLightDirections[1] = dir1; - - VRenderSystem.lightDirection0.buffer.putFloat(0, dir0.x()); - VRenderSystem.lightDirection0.buffer.putFloat(4, dir0.y()); - VRenderSystem.lightDirection0.buffer.putFloat(8, dir0.z()); - - VRenderSystem.lightDirection1.buffer.putFloat(0, dir1.x()); - VRenderSystem.lightDirection1.buffer.putFloat(4, dir1.y()); - VRenderSystem.lightDirection1.buffer.putFloat(8, dir1.z()); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void setShaderColor(float r, float g, float b, float a) { - shaderColor[0] = r; - shaderColor[1] = g; - shaderColor[2] = b; - shaderColor[3] = a; - - VRenderSystem.setShaderColor(r, g, b, a); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void setShaderFog(FogParameters fogParameters) { - assertOnRenderThread(); - shaderFog = fogParameters; + VRenderSystem.initRenderer(); - VRenderSystem.setShaderFogColor(fogParameters.red(), fogParameters.green(), fogParameters.blue(), fogParameters.alpha()); - } + DEVICE = new VkGpuDevice(l, i, bl, shaderSource, bl2); + apiDescription = getDevice().getImplementationInformation(); - /** - * @author - */ - @Overwrite(remap = false) - public static void setProjectionMatrix(Matrix4f projectionMatrix, ProjectionType projectionType) { - Matrix4f matrix4f = new Matrix4f(projectionMatrix); - RenderSystemMixin.projectionMatrix = matrix4f; - RenderSystemMixin.projectionType = projectionType; + Renderer.initRenderer(); - VRenderSystem.applyProjectionMatrix(matrix4f); - VRenderSystem.calculateMVP(); + dynamicUniforms = new DynamicUniforms(); } - /** - * @author - */ @Overwrite(remap = false) public static void setTextureMatrix(Matrix4f matrix4f) { - Matrix4f matrix4f2 = new Matrix4f(matrix4f); - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> { - textureMatrix = matrix4f2; - VRenderSystem.setTextureMatrix(matrix4f); - }); - } else { - textureMatrix = matrix4f2; - VRenderSystem.setTextureMatrix(matrix4f); - } + assertOnRenderThread(); + textureMatrix.set(matrix4f); + VRenderSystem.setTextureMatrix(matrix4f); } - /** - * @author - */ @Overwrite(remap = false) public static void resetTextureMatrix() { - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> textureMatrix.identity()); - } else { - textureMatrix.identity(); - VRenderSystem.setTextureMatrix(textureMatrix); - } - } - - - /** - * @author - */ - @Overwrite(remap = false) - public static void restoreProjectionMatrix() { - projectionMatrix = savedProjectionMatrix; - projectionType = savedProjectionType; - - VRenderSystem.applyProjectionMatrix(projectionMatrix); - VRenderSystem.calculateMVP(); + assertOnRenderThread(); + textureMatrix.identity(); + VRenderSystem.setTextureMatrix(textureMatrix); } - /** - * @author - */ - @Overwrite(remap = false) - public static void texParameter(int target, int pname, int param) { - GlTexture.texParameteri(target, pname, param); - } } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java b/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java index adae96e46d..2c65c43077 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java @@ -1,6 +1,5 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.RenderType; import net.vulkanmod.interfaces.ExtendedRenderType; import net.vulkanmod.render.vertex.TerrainRenderType; @@ -12,9 +11,10 @@ @Mixin(RenderType.class) public class RenderTypeM implements ExtendedRenderType { TerrainRenderType terrainRenderType; - + @Inject(method = "", at = @At("RETURN")) - private void inj(String string, VertexFormat vertexFormat, VertexFormat.Mode mode, int i, boolean bl, boolean bl2, Runnable runnable, Runnable runnable2, CallbackInfo ci) { + private void inj(String string, int i, boolean bl, boolean bl2, Runnable runnable, Runnable runnable2, + CallbackInfo ci) { terrainRenderType = switch (string) { case "solid" -> TerrainRenderType.SOLID; case "cutout" -> TerrainRenderType.CUTOUT; @@ -24,7 +24,7 @@ private void inj(String string, VertexFormat vertexFormat, VertexFormat.Mode mod default -> null; }; } - + @Override public TerrainRenderType getTerrainRenderType() { return terrainRenderType; diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index 186d6ebd88..10231841c7 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -2,8 +2,6 @@ import com.mojang.blaze3d.framegraph.FrameGraphBuilder; import com.mojang.blaze3d.framegraph.FramePass; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.resource.ResourceHandle; import net.minecraft.client.CloudStatus; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.*; @@ -12,7 +10,6 @@ import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.sky.CloudRenderer; import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -28,7 +25,7 @@ public abstract class LevelRendererM { @Unique private CloudRenderer cloudRenderer; @Inject(method = "addCloudsPass", at = @At("HEAD"), cancellable = true) - public void addCloudsPass(FrameGraphBuilder frameGraphBuilder, Matrix4f modelView, Matrix4f projection, CloudStatus cloudStatus, Vec3 camPos, float partialTicks, int i, float g, CallbackInfo ci) { + public void addCloudsPass(FrameGraphBuilder frameGraphBuilder, CloudStatus cloudStatus, Vec3 camPos, float partialTicks, int i, float g, CallbackInfo ci) { if (this.cloudRenderer == null) { this.cloudRenderer = new CloudRenderer(); } @@ -40,17 +37,11 @@ public void addCloudsPass(FrameGraphBuilder frameGraphBuilder, Matrix4f modelVie this.targets.main = framePass.readsAndWrites(this.targets.main); } - ResourceHandle resourceHandle = this.targets.clouds; framePass.executes(() -> { Profiler profiler = Profiler.getMainProfiler(); profiler.push("Clouds"); - if (resourceHandle != null) { - resourceHandle.get().setClearColor(0.0F, 0.0F, 0.0F, 0.0F); - resourceHandle.get().clear(); - } - - this.cloudRenderer.renderClouds(this.level, modelView, projection, this.ticks, partialTicks, + this.cloudRenderer.renderClouds(this.level, this.ticks, partialTicks, camPos.x(), camPos.y(), camPos.z()); profiler.pop(); diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java index e482555b7f..2fda4e46da 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.render.entity; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.resource.GraphicsResourceAllocator; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; @@ -19,6 +20,7 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.WorldRenderer; import org.joml.Matrix4f; +import org.joml.Vector4f; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -30,74 +32,75 @@ @Mixin(LevelRenderer.class) public class LevelRendererM { - @Shadow @Final private EntityRenderDispatcher entityRenderDispatcher; - @Shadow @Final private Minecraft minecraft; - - @Unique private Object2ReferenceOpenHashMap, ObjectArrayList>> bufferSourceMap = new Object2ReferenceOpenHashMap<>(); - @Unique boolean managed; - - @Inject(method = "renderLevel", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V", - shift = At.Shift.AFTER) - ) - private void clearMap(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, boolean bl, - Camera camera, GameRenderer gameRenderer, Matrix4f matrix4f, Matrix4f matrix4f2, - CallbackInfo ci) { - for (var bufferSource : this.bufferSourceMap.keySet()) { - var entityMap = this.bufferSourceMap.get(bufferSource); - entityMap.clear(); - } - - this.managed = true; - } - - /** - * @author - * @reason - */ - @Overwrite - private void renderEntity(Entity entity, double d, double e, double f, float partialTicks, PoseStack poseStack, MultiBufferSource multiBufferSource) { - if (!Initializer.CONFIG.entityCulling || !this.managed) { - double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); - double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); - double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, partialTicks, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); - return; - } - - var entityClass = entity.getClass(); - - var entityMap = this.bufferSourceMap.computeIfAbsent(multiBufferSource, bufferSource -> new Object2ReferenceOpenHashMap<>()); - var list = entityMap.computeIfAbsent(entityClass, k -> new ObjectArrayList<>()); - list.add(entity); - } - - @Inject(method = "renderEntities", at = @At("RETURN")) - private void renderEntities(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource1, Camera camera, DeltaTracker deltaTracker, List entityList, CallbackInfo ci) { - if (!Initializer.CONFIG.entityCulling) - return; - - Vec3 cameraPos = WorldRenderer.getCameraPos(); - TickRateManager tickRateManager = this.minecraft.level.tickRateManager(); - -// PoseStack poseStack = new PoseStack(); - - for (var bufferSource : this.bufferSourceMap.keySet()) { - var entityMap = this.bufferSourceMap.get(bufferSource); - - for (var list : entityMap.values()) { - for (Entity entity : list) { - float partialTicks = deltaTracker.getGameTimeDeltaPartialTick(!tickRateManager.isEntityFrozen(entity)); - - double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); - double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); - double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - this.entityRenderDispatcher.render(entity, h - cameraPos.x, i - cameraPos.y, j - cameraPos.z, partialTicks, poseStack, bufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); - } - } - } - - this.managed = false; - } + // TODO +// @Shadow @Final private EntityRenderDispatcher entityRenderDispatcher; +// @Shadow @Final private Minecraft minecraft; +// +// @Unique private Object2ReferenceOpenHashMap, ObjectArrayList>> bufferSourceMap = new Object2ReferenceOpenHashMap<>(); +// @Unique boolean managed; +// +// @Inject(method = "renderLevel", +// at = @At(value = "INVOKE", +// target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V", +// shift = At.Shift.AFTER) +// ) +// private void clearMap(GraphicsResourceAllocator graphicsResourceAllocator, DeltaTracker deltaTracker, boolean bl, +// Camera camera, Matrix4f matrix4f, Matrix4f matrix4f2, Matrix4f matrix4f3, +// GpuBufferSlice gpuBufferSlice, Vector4f vector4f, boolean bl2, CallbackInfo ci) { +// for (var bufferSource : this.bufferSourceMap.keySet()) { +// var entityMap = this.bufferSourceMap.get(bufferSource); +// entityMap.clear(); +// } +// +// this.managed = true; +// } +// +// /** +// * @author +// * @reason +// */ +// @Overwrite +// private void renderEntity(Entity entity, double d, double e, double f, float partialTicks, PoseStack poseStack, MultiBufferSource multiBufferSource) { +// if (!Initializer.CONFIG.entityCulling || !this.managed) { +// double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); +// double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); +// double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); +// this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, partialTicks, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); +// return; +// } +// +// var entityClass = entity.getClass(); +// +// var entityMap = this.bufferSourceMap.computeIfAbsent(multiBufferSource, bufferSource -> new Object2ReferenceOpenHashMap<>()); +// var list = entityMap.computeIfAbsent(entityClass, k -> new ObjectArrayList<>()); +// list.add(entity); +// } +// +// @Inject(method = "renderEntities", at = @At("RETURN")) +// private void renderEntities(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource1, Camera camera, DeltaTracker deltaTracker, List entityList, CallbackInfo ci) { +// if (!Initializer.CONFIG.entityCulling) +// return; +// +// Vec3 cameraPos = WorldRenderer.getCameraPos(); +// TickRateManager tickRateManager = this.minecraft.level.tickRateManager(); +// +//// PoseStack poseStack = new PoseStack(); +// +// for (var bufferSource : this.bufferSourceMap.keySet()) { +// var entityMap = this.bufferSourceMap.get(bufferSource); +// +// for (var list : entityMap.values()) { +// for (Entity entity : list) { +// float partialTicks = deltaTracker.getGameTimeDeltaPartialTick(!tickRateManager.isEntityFrozen(entity)); +// +// double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); +// double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); +// double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); +// this.entityRenderDispatcher.render(entity, h - cameraPos.x, i - cameraPos.y, j - cameraPos.z, partialTicks, poseStack, bufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); +// } +// } +// } +// +// this.managed = false; +// } } diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java index fdc8fe213c..9fdf1ac151 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java @@ -4,7 +4,9 @@ import net.minecraft.core.Direction; import net.vulkanmod.interfaces.ModelPartCubeMixed; import net.vulkanmod.render.model.CubeModel; +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; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -14,18 +16,36 @@ @Mixin(ModelPart.Cube.class) public class ModelPartCubeM implements ModelPartCubeMixed { + @Shadow + @Final + public ModelPart.Polygon[] polygons; CubeModel cube; @Inject(method = "", at = @At(value = "FIELD", target = "Lnet/minecraft/client/model/geom/ModelPart$Cube;polygons:[Lnet/minecraft/client/model/geom/ModelPart$Polygon;", ordinal = 0, shift = At.Shift.AFTER)) private void getVertices(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set, CallbackInfo ci) { - //TODO check if set is needed CubeModel cube = new CubeModel(); cube.setVertices(i, j, f, g, h, k, l, m, n, o, p, bl, q, r, set); this.cube = cube; } + @Inject(method = "", at = @At("RETURN")) + private void debug(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set, CallbackInfo ci) { + // Debug + CubeModel.Polygon[] polygons = cube.getPolygons(); + for (int i1 = 0; i1 < polygons.length; i1++) { + var v = polygons[i1].vertices(); + var v2 = this.polygons[i1].vertices(); + + for (int s = 0; s < v.length; s++) { + if (v[s].u() != v2[s].u() || v[s].v() != v2[s].v()) { + System.nanoTime(); + } + } + } + } + @Override public CubeModel getCubeModel() { diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java index 871f7d1ae8..514dc06816 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java @@ -22,7 +22,7 @@ public abstract class ModelPartM { @Shadow @Final private List cubes; - Vector3f normal = new Vector3f(); + @Unique Vector3f normal = new Vector3f(); @Inject(method = "compile", at = @At("HEAD"), cancellable = true) private void injCompile(PoseStack.Pose pose, VertexConsumer vertexConsumer, int light, int overlay, int color, CallbackInfo ci) { @@ -37,28 +37,33 @@ public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int ExtendedVertexBuilder vertexBuilder = ExtendedVertexBuilder.of(vertexConsumer); - if (vertexBuilder != null && vertexBuilder.canUseFastVertex()) { + boolean useFastFormat = vertexBuilder != null && vertexBuilder.canUseFastVertex(); + + if (useFastFormat) { color = ColorUtil.RGBA.fromArgb32(color); for (ModelPart.Cube cube : this.cubes) { ModelPartCubeMixed cubeMixed = (ModelPartCubeMixed)(cube); CubeModel cubeModel = cubeMixed.getCubeModel(); - ModelPart.Polygon[] polygons = cubeModel.getPolygons(); + CubeModel.Polygon[] polygons = cubeModel.getPolygons(); cubeModel.transformVertices(matrix4f); - for (ModelPart.Polygon polygon : polygons) { + for (CubeModel.Polygon polygon : polygons) { matrix3f.transform(this.normal.set(polygon.normal())); this.normal.normalize(); int packedNormal = I32_SNorm.packNormal(normal.x(), normal.y(), normal.z()); - ModelPart.Vertex[] vertices = polygon.vertices(); + CubeModel.Vertex[] vertices = polygon.vertices(); - for (ModelPart.Vertex vertex : vertices) { + for (CubeModel.Vertex vertex : vertices) { Vector3f pos = vertex.pos(); - vertexBuilder.vertex(pos.x(), pos.y(), pos.z(), color, vertex.u(), vertex.v(), overlay, light, packedNormal); + vertexBuilder.vertex(pos.x(), pos.y(), pos.z(), + color, + vertex.u(), vertex.v(), + overlay, light, packedNormal); } } } @@ -68,20 +73,23 @@ public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int ModelPartCubeMixed cubeMixed = (ModelPartCubeMixed)(cube); CubeModel cubeModel = cubeMixed.getCubeModel(); - ModelPart.Polygon[] polygons = cubeModel.getPolygons(); + CubeModel.Polygon[] polygons = cubeModel.getPolygons(); cubeModel.transformVertices(matrix4f); - for (ModelPart.Polygon polygon : polygons) { + for (CubeModel.Polygon polygon : polygons) { matrix3f.transform(this.normal.set(polygon.normal())); this.normal.normalize(); - ModelPart.Vertex[] vertices = polygon.vertices(); + CubeModel.Vertex[] vertices = polygon.vertices(); - for (ModelPart.Vertex vertex : vertices) { + for (CubeModel.Vertex vertex : vertices) { Vector3f pos = vertex.pos(); - vertexConsumer.addVertex(pos.x(), pos.y(), pos.z(), color, vertex.u(), vertex.v(), overlay, light, - normal.x(), normal.y(), normal.z()); + vertexConsumer.addVertex(pos.x(), pos.y(), pos.z(), + color, + vertex.u(), vertex.v(), + overlay, light, + normal.x(), normal.y(), normal.z()); } } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java index 66b4dde112..1298815bf9 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java @@ -1,16 +1,17 @@ package net.vulkanmod.mixin.render.frame; import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.textures.GpuTexture; import net.minecraft.client.Minecraft; import net.vulkanmod.vulkan.Renderer; +import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Minecraft.class) public class MinecraftMixin { @@ -23,9 +24,10 @@ private void preFrameOps(boolean bl, CallbackInfo ci) { } //Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(I)V")) - private void beginRender(int i, boolean bl) { + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/CommandEncoder;clearColorAndDepthTextures(Lcom/mojang/blaze3d/textures/GpuTexture;ILcom/mojang/blaze3d/textures/GpuTexture;D)V")) + private void beginRender(CommandEncoder instance, GpuTexture gpuTexture, int i, GpuTexture gpuTexture2, double v) { Renderer.getInstance().beginFrame(); + Renderer.clearAttachments(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_COLOR_BUFFER_BIT); } @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) @@ -33,18 +35,8 @@ private void beginRender2(CallbackInfo ci) { Renderer.getInstance().beginFrame(); } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) - private void redirectMainTarget1(RenderTarget instance, boolean bl) { - Renderer.getInstance().getMainPass().mainTargetBindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) - private void redirectMainTarget2(RenderTarget instance) { - Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) - private void removeBlit(RenderTarget instance, int i, int j) { + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen()V")) + private void removeBlit(RenderTarget instance) { } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java deleted file mode 100644 index 0e45b706bb..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.vulkanmod.mixin.render.frapi; - -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.vulkanmod.render.chunk.build.frapi.mesh.ExtendedQuadEmitter; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Predicate; -import java.util.function.Supplier; - -@Mixin(BakedModel.class) -public interface BakedModelM extends FabricBakedModel { - - @Override - default void emitBlockQuads(QuadEmitter emitter, BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { - ExtendedQuadEmitter.of(emitter).emitBlockQuads(emitter, (BakedModel) this, state, randomSupplier, cullTest); - } - - @Override - default void emitItemQuads(QuadEmitter emitter, Supplier randomSupplier) { - ExtendedQuadEmitter.of(emitter).emitItemQuads(emitter, (BakedModel) this, null, randomSupplier); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderDispatcherAccessor.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderDispatcherAccessor.java new file mode 100644 index 0000000000..3ded983673 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderDispatcherAccessor.java @@ -0,0 +1,19 @@ +package net.vulkanmod.mixin.render.frapi; + +import java.util.function.Supplier; + +import net.minecraft.client.renderer.SpecialBlockModelRenderer; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import net.minecraft.client.color.block.BlockColors; + +@Mixin(BlockRenderDispatcher.class) +public interface BlockRenderDispatcherAccessor { + @Accessor("specialBlockModelRenderer") + Supplier getBlockEntityModelsGetter(); + + @Accessor("blockColors") + BlockColors getBlockColors(); +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java index d21bd994e2..06ca19723d 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java @@ -10,8 +10,8 @@ @Mixin(ItemRenderer.class) public interface ItemRendererAccessor { - @Invoker("getCompassFoilBuffer") - static VertexConsumer getCompassFoilBuffer(MultiBufferSource provider, RenderType layer, PoseStack.Pose entry) { + @Invoker("getSpecialFoilBuffer") + static VertexConsumer getSpecialFoilBuffer(MultiBufferSource provider, RenderType layer, PoseStack.Pose entry) { throw new AssertionError(); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java index d727b36ee0..f3f9278b87 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java @@ -16,31 +16,24 @@ package net.vulkanmod.mixin.render.frapi; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.item.ItemStackRenderState; -import net.minecraft.world.item.ItemDisplayContext; -import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; @Mixin(ItemRenderer.class) abstract class ItemRendererMixin { - @Unique - private static final ThreadLocal CONTEXTS = ThreadLocal.withInitial(ItemRenderContext::new); +// @Unique +// private static final ThreadLocal CONTEXTS = ThreadLocal.withInitial(ItemRenderContext::new); - @Inject(method = "renderItem", at = @At(value = "HEAD"), cancellable = true) - private static void hookRenderItem(ItemDisplayContext itemDisplayContext, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j, int[] is, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType, CallbackInfo ci) { - if (!model.isVanillaAdapter()) { - CONTEXTS.get().renderModel(itemDisplayContext, poseStack, multiBufferSource, i, j, is, model, renderType, foilType); - ci.cancel(); - } - } + // TODO: frapi +// @Inject(method = "renderItem", at = @At(value = "HEAD"), cancellable = true) +// private static void hookRenderItem(ItemDisplayContext itemDisplayContext, PoseStack poseStack, +// MultiBufferSource multiBufferSource, int i, int j, int[] is, +// List list, RenderType renderType, +// ItemStackRenderState.FoilType foilType, CallbackInfo ci) { +// if (!model.isVanillaAdapter()) { +// CONTEXTS.get().renderModel(itemDisplayContext, poseStack, multiBufferSource, i, j, is, model, renderType, foilType); +// ci.cancel(); +// } +// } } \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java new file mode 100644 index 0000000000..c7515f2161 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.mixin.render.frapi; + +import net.fabricmc.fabric.api.renderer.v1.render.FabricLayerRenderState; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(value = ItemStackRenderState.LayerRenderState.class) +abstract class LayerRenderStateMixin implements FabricLayerRenderState { +//abstract class LayerRenderStateMixin implements FabricLayerRenderState, AccessLayerRenderState { +// @Unique +// private final MutableMeshImpl mutableMesh = new MutableMeshImpl(); +// +// @Inject(method = "clear()V", at = @At("RETURN")) +// private void onReturnClear(CallbackInfo ci) { +// mutableMesh.clear(); +// } + + // TODO: frapi +// @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/ItemRenderer;renderItem(Lnet/minecraft/world/item/ItemDisplayContext;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;II[ILjava/util/List;Lnet/minecraft/client/renderer/RenderType;Lnet/minecraft/client/renderer/item/ItemStackRenderState$FoilType;)V")) +// private void renderItemProxy(net.minecraft.world.item.ItemDisplayContext itemDisplayContext, PoseStack poseStack, +// MultiBufferSource multiBufferSource, int i, int j, int[] is, +// List list, RenderType renderType, +// ItemStackRenderState.FoilType foilType) { +// if (mutableMesh.size() > 0) { +// ItemRenderContext.POOL.get().renderItem(displayContext, matrices, vertexConsumers, light, overlay, tints, quads, mutableMesh, layer, glint); +// } else { +// ItemRenderer.renderItem(displayContext, matrices, vertexConsumers, light, overlay, tints, quads, layer, glint); +// } +// } + +// @Override +// public MutableMeshImpl fabric_getMutableMesh() { +// return mutableMesh; +// } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java index d89759594f..d032bbf3a5 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java @@ -19,17 +19,7 @@ import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.client.renderer.block.ModelBlockRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; @Mixin(ModelBlockRenderer.class) public abstract class ModelBlockRendererM { @@ -38,13 +28,16 @@ public abstract class ModelBlockRendererM { @Unique private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(BlockRenderContext::new); - @Inject(at = @At("HEAD"), method = "tesselateBlock", cancellable = true) - private void hookRender(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrix, VertexConsumer buffer, boolean cull, RandomSource rand, long seed, int overlay, CallbackInfo ci) { - if (!model.isVanillaAdapter()) { - BlockRenderContext context = fabric_contexts.get(); - context.render(blockView, model, state, pos, matrix, buffer, cull, rand, seed, overlay); - ci.cancel(); - } - } + // TODO: frapi +// @Inject(at = @At("HEAD"), method = "tesselateBlock", cancellable = true) +// private void hookRender(BlockAndTintGetter blockAndTintGetter, List list, BlockState blockState, +// BlockPos blockPos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean bl, int i, +// CallbackInfo ci) { +// if (!model.isVanillaAdapter()) { +// BlockRenderContext context = fabric_contexts.get(); +// context.render(blockView, model, state, pos, matrix, buffer, cull, rand, seed, overlay); +// ci.cancel(); +// } +// } } diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java new file mode 100644 index 0000000000..f7187bf15e --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.mixin.render.frapi; + +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; +import net.fabricmc.fabric.impl.client.indigo.renderer.accessor.AccessRenderCommandQueue; + +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.SubmitNodeStorage; + +import org.spongepowered.asm.mixin.Mixin; + +import java.util.List; + +@Mixin(SubmitNodeStorage.class) +abstract class OrderedRenderCommandQueueImplMixin implements SubmitNodeCollector, AccessRenderCommandQueue { +// @Override +// public void fabric_submitItem(MatrixStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderLayer renderLayer, ItemRenderState.Glint glintType, MeshView mesh) { +// RenderCommandQueue queue = getBatchingQueue(0); +// +// if (queue instanceof AccessRenderCommandQueue access) { +// access.fabric_submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType, mesh); +// } else { +// queue.submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType); +// } +// } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleGroupM.java b/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleGroupM.java new file mode 100644 index 0000000000..807c85b931 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleGroupM.java @@ -0,0 +1,25 @@ +package net.vulkanmod.mixin.render.particle; + +import net.minecraft.client.particle.QuadParticleGroup; +import net.minecraft.client.renderer.culling.Frustum; +import net.vulkanmod.render.chunk.RenderSection; +import net.vulkanmod.render.chunk.WorldRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(QuadParticleGroup.class) +public class QuadParticleGroupM { + + @Redirect(method = "extractRenderState", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/culling/Frustum;pointInFrustum(DDD)Z")) + private boolean particleWithinSections(Frustum instance, double x, double y, double z) { + return !cull(WorldRenderer.getInstance(), x, y, z) && instance.pointInFrustum(x,y, z); + } + + @Unique + private static boolean cull(WorldRenderer worldRenderer, double x, double y, double z) { + RenderSection section = worldRenderer.getSectionGrid().getSectionAtBlockPos((int) x, (int) y, (int) z); + return section != null && section.getLastFrame() != worldRenderer.getLastFrame(); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleRenderStateM.java b/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleRenderStateM.java new file mode 100644 index 0000000000..b893f08358 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/particle/QuadParticleRenderStateM.java @@ -0,0 +1,45 @@ +package net.vulkanmod.mixin.render.particle; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.state.QuadParticleRenderState; +import net.vulkanmod.interfaces.ExtendedVertexBuilder; +import net.vulkanmod.vulkan.util.ColorUtil; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(QuadParticleRenderState.class) +public class QuadParticleRenderStateM { + + @Unique private final Quaternionf quaternionf = new Quaternionf(); + @Unique private final Vector3f vector3f = new Vector3f(); + + @Overwrite + public void renderRotatedQuad( + VertexConsumer vertexConsumer, float x, float y, float z, float xr, float yr, float zr, float wr, float m, float u0, float u1, float v0, float v1, int color, int light + ) { + quaternionf.set(xr, yr, zr, wr); + + ExtendedVertexBuilder vertexBuilder = (ExtendedVertexBuilder)vertexConsumer; + + color = ColorUtil.BGRAtoRGBA(color); + + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, -1.0F, m, u1, v1, color, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, 1.0F, m, u1, v0, color, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, 1.0F, m, u0, v0, color, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, -1.0F, m, u0, v1, color, light); + } + + private void renderVertex( + ExtendedVertexBuilder vertexConsumer, Quaternionf quaternionf, float x, float y, float z, float i, float j, float k, float u, float v, int color, int light + ) { + vector3f.set(i, j, 0.0f) + .rotate(quaternionf) + .mul(k) + .add(x, y, z); + + vertexConsumer.vertex(vector3f.x(), vector3f.y(), vector3f.z(), u, v, color, light); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java b/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java deleted file mode 100644 index 220b9235d8..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.vulkanmod.mixin.render.particle; - -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.Camera; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.particle.Particle; -import net.minecraft.client.particle.ParticleRenderType; -import net.minecraft.client.particle.SingleQuadParticle; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.core.BlockPos; -import net.minecraft.util.Mth; -import net.minecraft.world.phys.Vec3; -import net.vulkanmod.interfaces.ExtendedVertexBuilder; -import net.vulkanmod.render.chunk.RenderSection; -import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Quaternionf; -import org.joml.Vector3f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(SingleQuadParticle.class) -public abstract class SingleQuadParticleM extends Particle { - - @Shadow protected float quadSize; - - @Unique private final Quaternionf quaternionf = new Quaternionf(); - @Unique private final Vector3f vector3f = new Vector3f(); - - @Shadow protected abstract float getU0(); - @Shadow protected abstract float getU1(); - @Shadow protected abstract float getV0(); - @Shadow protected abstract float getV1(); - - @Shadow public abstract float getQuadSize(float f); - - @Shadow public abstract SingleQuadParticle.FacingCameraMode getFacingCameraMode(); - - protected SingleQuadParticleM(ClientLevel clientLevel, double d, double e, double f, double g, double h, double i) { - super(clientLevel, d, e, f, g, h, i); - this.quadSize = 0.1F * (this.random.nextFloat() * 0.5F + 0.5F) * 2.0F; - } - - /** - * @author - * @reason - */ - @Overwrite - public void render(VertexConsumer vertexConsumer, Camera camera, float f) { - double lx = (Mth.lerp(f, this.xo, this.x)); - double ly = (Mth.lerp(f, this.yo, this.y)); - double lz = (Mth.lerp(f, this.zo, this.z)); - - if (cull(WorldRenderer.getInstance(), lx, ly, lz)) - return; - - Vec3 vec3 = camera.getPosition(); - float offsetX = (float) (lx - vec3.x()); - float offsetY = (float) (ly - vec3.y()); - float offsetZ = (float) (lz - vec3.z()); - - quaternionf.identity(); - this.getFacingCameraMode().setRotation(quaternionf, camera, f); - if (this.roll != 0.0F) { - quaternionf.rotateZ(Mth.lerp(f, this.oRoll, this.roll)); - } - - this.renderRotatedQuad(vertexConsumer, quaternionf, offsetX, offsetY, offsetZ, f); - } - - @Unique - private void renderRotatedQuad(VertexConsumer vertexConsumer, Quaternionf quaternionf, float x, float y, float z, float f) { - float j = this.getQuadSize(f); - float u0 = this.getU0(); - float u1 = this.getU1(); - float v0 = this.getV0(); - float v1 = this.getV1(); - int light = this.getLightColor(f); - - ExtendedVertexBuilder vertexBuilder = (ExtendedVertexBuilder)vertexConsumer; - int packedColor = ColorUtil.RGBA.pack(this.rCol, this.gCol, this.bCol, this.alpha); - - this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, -1.0F, j, u1, v1, packedColor, light); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, 1.0F, j, u1, v0, packedColor, light); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, 1.0F, j, u0, v0, packedColor, light); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, -1.0F, j, u0, v1, packedColor, light); - } - - @Unique - private void renderVertex( - ExtendedVertexBuilder vertexConsumer, Quaternionf quaternionf, float x, float y, float z, float i, float j, float k, float u, float v, int color, int light - ) { - vector3f.set(i, j, 0.0f) - .rotate(quaternionf) - .mul(k) - .add(x, y, z); - - vertexConsumer.vertex(vector3f.x(), vector3f.y(), vector3f.z(), u, v, color, light); - } - - protected int getLightColor(float f) { - BlockPos blockPos = BlockPos.containing(this.x, this.y, this.z); - return this.level.hasChunkAt(blockPos) ? LevelRenderer.getLightColor(this.level, blockPos) : 0; - } - - private boolean cull(WorldRenderer worldRenderer, double x, double y, double z) { - RenderSection section = worldRenderer.getSectionGrid().getSectionAtBlockPos((int) x, (int) y, (int) z); - return section != null && section.getLastFrame() != worldRenderer.getLastFrame(); - } - - @Override - public ParticleRenderType getRenderType() { - return null; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java b/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java deleted file mode 100644 index 9e3b66eda1..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/shader/CompilationCacheM.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.vulkanmod.mixin.render.shader; - -import com.google.gson.JsonObject; -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import com.mojang.blaze3d.shaders.CompiledShader; -import net.minecraft.client.renderer.*; -import net.minecraft.resources.ResourceLocation; -import net.vulkanmod.Initializer; -import net.vulkanmod.interfaces.shader.PipelineConfig; -import net.vulkanmod.interfaces.shader.ShaderMixed; -import net.vulkanmod.render.shader.ShaderLoadUtil; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.converter.GlslConverter; -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; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Collections; -import java.util.Map; - -@Mixin(ShaderManager.CompilationCache.class) -public abstract class CompilationCacheM { - - @Shadow @Final private ShaderManager.Configs configs; - @Shadow @Final public Map shaders; - - @Inject(method = "compileProgram", at = @At("HEAD"), cancellable = true) - public void compileProgram(ShaderProgram shaderProgram, - CallbackInfoReturnable cir) throws ShaderManager.CompilationException { - ShaderProgramConfig shaderProgramConfig = this.configs.programs().get(shaderProgram.configId()); - if (shaderProgramConfig == null) { - throw new ShaderManager.CompilationException("Could not find program with id: " + shaderProgram.configId()); - } else { - cir.setReturnValue(createShaderProgram(shaderProgram, shaderProgramConfig)); - } - } - - private CompiledShaderProgram createShaderProgram(ShaderProgram shaderProgram, ShaderProgramConfig shaderProgramConfig) { - String configName = PipelineConfig.of(shaderProgramConfig).getName(); - - JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); - - if (config == null) { - GlslConverter converter = new GlslConverter(); - Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat(), configName); - - ShaderDefines shaderDefines = shaderProgramConfig.defines().withOverrides(shaderProgram.defines()); - String vshSrc = getShaderSource(shaderProgramConfig.vertex(), CompiledShader.Type.VERTEX, shaderDefines); - String fshSrc = getShaderSource(shaderProgramConfig.fragment(), CompiledShader.Type.FRAGMENT, shaderDefines); - - converter.process(vshSrc, fshSrc); - - UBO ubo = converter.createUBO(); - - builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); - builder.compileShaders(configName, converter.getVshConverted(), converter.getFshConverted()); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - CompiledShaderProgram compiledShaderProgram = createProgram(); - - compiledShaderProgram.setupUniforms(shaderProgramConfig.uniforms(), shaderProgramConfig.samplers()); - ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); - shaderMixed.setPipeline(pipeline); - - shaderMixed.setupUniformSuppliers(ubo); - shaderMixed.setUniformsUpdate(); - - return compiledShaderProgram; - } - - CompiledShaderProgram compiledShaderProgram = createProgram(); - compiledShaderProgram.setupUniforms(shaderProgramConfig.uniforms(), shaderProgramConfig.samplers()); - ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); - - Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat(), configName); - builder.setUniformSupplierGetter(info -> shaderMixed.getUniformSupplier(info.name)); - - builder.parseBindings(config); - - ShaderDefines shaderDefines = shaderProgramConfig.defines().withOverrides(shaderProgram.defines()); - - if (!shaderDefines.isEmpty()) { - Initializer.LOGGER.error("Shader {} is using external defines that are unsupported.", configName); - } - - ShaderLoadUtil.loadShaders(builder, config, configName, "core"); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - shaderMixed.setPipeline(pipeline); - - return compiledShaderProgram; - } - - private String getShaderSource(ResourceLocation resourceLocation, CompiledShader.Type type, ShaderDefines shaderDefines) { - ShaderManager.ShaderCompilationKey shaderCompilationKey = new ShaderManager.ShaderCompilationKey(resourceLocation, type, shaderDefines); - - String source = this.configs.shaderSources().get(new ShaderManager.ShaderSourceKey(shaderCompilationKey.id(), shaderCompilationKey.type())); - String processedSource = GlslPreprocessor.injectDefines(source, shaderCompilationKey.defines()); - - return processedSource; - } - - private static CompiledShaderProgram createProgram() { - return new CompiledShaderProgram(0); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java b/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java deleted file mode 100644 index 4d0c65948e..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/shader/CompiledShaderProgramM.java +++ /dev/null @@ -1,219 +0,0 @@ -package net.vulkanmod.mixin.render.shader; - -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.shaders.CompiledShader; -import com.mojang.blaze3d.shaders.Uniform; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.VertexFormat; -import it.unimi.dsi.fastutil.ints.IntList; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.minecraft.client.renderer.FogParameters; -import net.minecraft.client.renderer.ShaderManager; -import net.minecraft.client.renderer.ShaderProgramConfig; -import net.vulkanmod.Initializer; -import net.vulkanmod.interfaces.shader.ShaderMixed; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.util.MappedBuffer; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.nio.ByteBuffer; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -@Mixin(CompiledShaderProgram.class) -public abstract class CompiledShaderProgramM implements ShaderMixed { - - @Shadow @Final private IntList samplerLocations; - @Shadow @Final private Object2IntMap samplerTextures; - @Shadow @Final private List samplers; - @Shadow @Final private Map uniformsByName; - - @Shadow @Nullable public Uniform MODEL_VIEW_MATRIX; - @Shadow @Nullable public Uniform PROJECTION_MATRIX; - @Shadow @Nullable public Uniform COLOR_MODULATOR; - @Shadow @Nullable public Uniform GLINT_ALPHA; - @Shadow @Nullable public Uniform FOG_START; - - GraphicsPipeline pipeline; - boolean updateUniforms = false; - - /** - * @author - * @reason - */ - @Overwrite - public static CompiledShaderProgram link(CompiledShader compiledShader, CompiledShader compiledShader2, VertexFormat vertexFormat) throws ShaderManager.CompilationException { - return new CompiledShaderProgram(0); - } - - @Shadow @Nullable public Uniform TEXTURE_MATRIX; - @Shadow @Nullable public Uniform SCREEN_SIZE; - @Shadow @Nullable public Uniform LIGHT0_DIRECTION; - @Shadow @Nullable public Uniform LIGHT1_DIRECTION; - @Shadow @Nullable public Uniform FOG_END; - @Shadow @Nullable public Uniform FOG_COLOR; - @Shadow @Nullable public Uniform FOG_SHAPE; - @Shadow @Nullable public Uniform LINE_WIDTH; - @Shadow @Nullable public Uniform GAME_TIME; - @Shadow @Nullable public Uniform MODEL_OFFSET; - - /** - * @author - * @reason - */ - @Overwrite - public void apply() { - if (!this.updateUniforms) { - return; - } - - for (int j = 0; j < this.samplerLocations.size(); j++) { - String string = this.samplers.get(j).name(); - int k = this.samplerTextures.getInt(string); - if (k != -1) { - int l = this.samplerLocations.getInt(j); - RenderSystem.activeTexture(33984 + j); - RenderSystem.bindTexture(k); - RenderSystem.setShaderTexture(j, k); - } - } - - if (this.MODEL_VIEW_MATRIX != null) { - this.MODEL_VIEW_MATRIX.set(RenderSystem.getModelViewMatrix()); - } - - if (this.PROJECTION_MATRIX != null) { - this.PROJECTION_MATRIX.set(RenderSystem.getProjectionMatrix()); - } - - if (this.COLOR_MODULATOR != null) { - this.COLOR_MODULATOR.set(RenderSystem.getShaderColor()); - } - - if (this.GLINT_ALPHA != null) { - this.GLINT_ALPHA.set(RenderSystem.getShaderGlintAlpha()); - } - - FogParameters fogParameters = RenderSystem.getShaderFog(); - if (this.FOG_START != null) { - this.FOG_START.set(fogParameters.start()); - } - - if (this.FOG_END != null) { - this.FOG_END.set(fogParameters.end()); - } - - if (this.FOG_COLOR != null) { - this.FOG_COLOR.set(fogParameters.red(), fogParameters.green(), fogParameters.blue(), fogParameters.alpha()); - } - - if (this.FOG_SHAPE != null) { - this.FOG_SHAPE.set(fogParameters.shape().getIndex()); - } - - if (this.TEXTURE_MATRIX != null) { - this.TEXTURE_MATRIX.set(RenderSystem.getTextureMatrix()); - } - - if (this.GAME_TIME != null) { - this.GAME_TIME.set(RenderSystem.getShaderGameTime()); - } - - if (this.SCREEN_SIZE != null) { - Window window = Minecraft.getInstance().getWindow(); - this.SCREEN_SIZE.set((float)window.getWidth(), (float)window.getHeight()); - } - - if (this.LINE_WIDTH != null) { - this.LINE_WIDTH.set(RenderSystem.getShaderLineWidth()); - } - } - - - - @Inject(method = "close", at = @At("RETURN")) - private void onClose(CallbackInfo ci) { - this.pipeline.scheduleCleanUp(); - } - - @Override - public void setPipeline(GraphicsPipeline graphicsPipeline) { - this.pipeline = graphicsPipeline; - } - - @Override - public GraphicsPipeline getPipeline() { - return pipeline; - } - - public void setupUniformSuppliers(UBO ubo) { - for (net.vulkanmod.vulkan.shader.layout.Uniform vUniform : ubo.getUniforms()) { - com.mojang.blaze3d.shaders.Uniform uniform = this.uniformsByName.get(vUniform.getName()); - - if (uniform == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); - continue; - } - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); - } else if (uniform.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform); - } - - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - vUniform.setSupplier(supplier); - } - - } - - public Supplier getUniformSupplier(String name) { - com.mojang.blaze3d.shaders.Uniform uniform1 = this.uniformsByName.get(name); - - if (uniform1 == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", name)); - return null; - } - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform1.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getIntBuffer()); - } else if (uniform1.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform1); - } - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - return supplier; - } - - @Override - public void setUniformsUpdate() { - this.updateUniforms = true; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java b/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java new file mode 100644 index 0000000000..465ae4a925 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java @@ -0,0 +1,35 @@ +package net.vulkanmod.mixin.render.shader; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import net.vulkanmod.interfaces.shader.ExtendedRenderPipeline; +import net.vulkanmod.render.engine.EGlProgram; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(RenderPipeline.class) +public abstract class RenderPipelineM implements ExtendedRenderPipeline { + @Unique GraphicsPipeline pipeline; + @Unique EGlProgram eGlProgram; + + @Override + public void setPipeline(GraphicsPipeline pipeline) { + this.pipeline = pipeline; + } + + @Override + public void setProgram(EGlProgram program) { + this.eGlProgram = program; + } + + @Override + public EGlProgram getProgram() { + return this.eGlProgram; + } + + @Override + public Pipeline getPipeline() { + return this.pipeline; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java b/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java deleted file mode 100644 index 1c5c98e234..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/shader/ShadeProgramConfigM.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.vulkanmod.mixin.render.shader; - -import net.minecraft.client.renderer.ShaderProgramConfig; -import net.vulkanmod.interfaces.shader.PipelineConfig; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(ShaderProgramConfig.class) -public class ShadeProgramConfigM implements PipelineConfig { - - String name; - - - @Override - public String getName() { - return this.name; - } - - @Override - public void setName(String s) { - this.name = s; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java b/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java index c64e8ce156..4294266e72 100644 --- a/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/shader/ShaderManagerM.java @@ -1,297 +1,32 @@ package net.vulkanmod.mixin.render.shader; -import com.google.common.collect.ImmutableMap; -import com.google.gson.*; -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import com.mojang.blaze3d.shaders.CompiledShader; -import com.mojang.serialization.JsonOps; -import it.unimi.dsi.fastutil.objects.ObjectArraySet; -import net.minecraft.FileUtil; -import net.minecraft.ResourceLocationException; -import net.minecraft.client.renderer.*; -import net.minecraft.resources.FileToIdConverter; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.blaze3d.pipeline.CompiledRenderPipeline; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.systems.GpuDevice; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.ShaderManager; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceProvider; import net.minecraft.util.profiling.ProfilerFiller; -import net.vulkanmod.Initializer; -import net.vulkanmod.interfaces.shader.PipelineConfig; -import net.vulkanmod.interfaces.shader.ShaderMixed; -import net.vulkanmod.render.shader.ShaderLoadUtil; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.SPIRVUtils; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Final; +import net.vulkanmod.render.shader.CustomRenderPipelines; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ShaderManager.class) -public abstract class ShaderManagerM { - - @Shadow @Final private static FileToIdConverter PROGRAM_ID_CONVERTER; - - @Shadow private ShaderManager.CompilationCache compilationCache; - - @Shadow @Final private static Logger LOGGER; - @Shadow @Final private static FileToIdConverter POST_CHAIN_ID_CONVERTER; - - /** - * @author - * @reason - */ - @Overwrite - public void preloadForStartup(ResourceProvider resourceProvider, ShaderProgram... shaderPrograms) throws IOException { - for (ShaderProgram shaderProgram : shaderPrograms) { - ResourceLocation location = PROGRAM_ID_CONVERTER.idToFile(shaderProgram.configId()); - Resource resource = resourceProvider.getResourceOrThrow(location); - Reader reader = resource.openAsReader(); - - String locationPath = location.getPath(); - String configName = locationPath.split("/")[2]; - - // Remove .json suffix - configName = configName.substring(0, configName.length() - 5); - - try { - JsonElement jsonElement = JsonParser.parseReader(reader); - ShaderProgramConfig shaderProgramConfig = ShaderProgramConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow( - JsonSyntaxException::new); - - PipelineConfig.of(shaderProgramConfig).setName(configName); +public class ShaderManagerM { - Pipeline.Builder builder = new Pipeline.Builder(shaderProgram.vertexFormat()); + @Inject(method = "apply(Lnet/minecraft/client/renderer/ShaderManager$Configs;Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/util/profiling/ProfilerFiller;)V", + at = @At(value = "INVOKE", target = "Ljava/util/List;isEmpty()Z")) + private void onApply(ShaderManager.Configs configs, ResourceManager resourceManager, ProfilerFiller profilerFiller, + CallbackInfo ci, @Local ShaderManager.CompilationCache compilationCache) { + GpuDevice gpuDevice = RenderSystem.getDevice(); + var pipelines = CustomRenderPipelines.pipelines; - JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); - builder.parseBindings(config); - - ShaderLoadUtil.loadShader(builder, configName, shaderProgramConfig.vertex().getPath(), SPIRVUtils.ShaderKind.VERTEX_SHADER); - ShaderLoadUtil.loadShader(builder, configName, shaderProgramConfig.fragment().getPath(), SPIRVUtils.ShaderKind.FRAGMENT_SHADER); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - CompiledShaderProgram compiledShaderProgram = createProgram(pipeline); - - this.compilationCache.programs.put(shaderProgram, Optional.of(compiledShaderProgram)); - } catch (Throwable var16) { - try { - reader.close(); - } catch (Throwable var15) { - var16.addSuppressed(var15); - } - - throw var16; - } - - reader.close(); + for (RenderPipeline renderPipeline : pipelines) { + CompiledRenderPipeline compiledRenderPipeline = gpuDevice.precompilePipeline(renderPipeline, compilationCache::getShaderSource); } } - - /** - * @author - * @reason - */ - @Overwrite - public ShaderManager.Configs prepare(ResourceManager resourceManager, ProfilerFiller profilerFiller) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - ImmutableMap.Builder builder2 = ImmutableMap.builder(); - - Predicate filter = location -> !location.getNamespace().equals("vulkanmod") && (isProgram(location) || isShader(location)); - - Map map = resourceManager.listResources("shaders", filter); - - for (Map.Entry entry : map.entrySet()) { - ResourceLocation resourceLocation = entry.getKey(); - CompiledShader.Type type = CompiledShader.Type.byLocation(resourceLocation); - if (type != null) { - loadShader(resourceLocation, entry.getValue(), type, map, builder2); - } else if (isProgram(resourceLocation)) { - loadProgram(resourceLocation, entry.getValue(), builder); - } - } - - ImmutableMap.Builder builder3 = ImmutableMap.builder(); - - for (Map.Entry entry2 : POST_CHAIN_ID_CONVERTER.listMatchingResources(resourceManager).entrySet()) { - loadPostChain(entry2.getKey(), entry2.getValue(), builder3); - } - - return new ShaderManager.Configs(builder.build(), builder2.build(), builder3.build()); - } - - private static GlslPreprocessor createPreprocessor(Map map, ResourceLocation resourceLocation) { - final ResourceLocation resourceLocation2 = resourceLocation.withPath(FileUtil::getFullResourcePath); - return new GlslPreprocessor() { - private final Set importedLocations = new ObjectArraySet<>(); - - @Override - public String applyImport(boolean bl, String string) { - ResourceLocation resourceLocation; - try { - if (bl) { - resourceLocation = resourceLocation2.withPath( - string2 -> FileUtil.normalizeResourcePath(string2 + string)); - } else { - resourceLocation = ResourceLocation.parse(string).withPrefix("shaders/include/"); - } - } catch (ResourceLocationException var8) { - LOGGER.error("Malformed GLSL import {}: {}", string, var8.getMessage()); - return "#error " + var8.getMessage(); - } - - if (!this.importedLocations.add(resourceLocation)) { - return null; - } else { - try { - Reader reader = map.get(resourceLocation).openAsReader(); - - String var5; - try { - var5 = IOUtils.toString(reader); - } catch (Throwable var9) { - if (reader != null) { - try { - reader.close(); - } catch (Throwable var7) { - var9.addSuppressed(var7); - } - } - - throw var9; - } - - if (reader != null) { - reader.close(); - } - - return var5; - } catch (IOException var10) { - LOGGER.error("Could not open GLSL import {}: {}", resourceLocation, var10.getMessage()); - return "#error " + var10.getMessage(); - } - } - } - }; - } - - private static void loadProgram(ResourceLocation resourceLocation, Resource resource, ImmutableMap.Builder builder) { - ResourceLocation resourceLocation2 = PROGRAM_ID_CONVERTER.fileToId(resourceLocation); - - try { - Reader reader = resource.openAsReader(); - - try { - JsonElement jsonElement = JsonParser.parseReader(reader); - ShaderProgramConfig shaderProgramConfig = ShaderProgramConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow(JsonSyntaxException::new); - - String configPath = resourceLocation.getPath(); - String configName = configPath.split("/")[2]; - - // Remove .json suffix - configName = configName.substring(0, configName.length() - 5); - - PipelineConfig.of(shaderProgramConfig).setName(configName); - - builder.put(resourceLocation2, shaderProgramConfig); - } catch (Throwable var8) { - try { - reader.close(); - } catch (Throwable var7) { - var8.addSuppressed(var7); - } - - throw var8; - } - - reader.close(); - } catch (JsonParseException | IOException var9) { - LOGGER.error("Failed to parse shader config at {}", resourceLocation, var9); - } - } - - private static void loadPostChain(ResourceLocation resourceLocation, Resource resource, ImmutableMap.Builder builder) { - ResourceLocation resourceLocation2 = POST_CHAIN_ID_CONVERTER.fileToId(resourceLocation); - - try { - Reader reader = resource.openAsReader(); - - try { - JsonElement jsonElement = JsonParser.parseReader(reader); - builder.put(resourceLocation2, PostChainConfig.CODEC.parse(JsonOps.INSTANCE, jsonElement).getOrThrow(JsonSyntaxException::new)); - } catch (Throwable var8) { - if (reader != null) { - try { - reader.close(); - } catch (Throwable var7) { - var8.addSuppressed(var7); - } - } - - throw var8; - } - - if (reader != null) { - reader.close(); - } - } catch (JsonParseException | IOException var9) { - LOGGER.error("Failed to parse post chain at {}", resourceLocation, var9); - } - } - - private static boolean isProgram(ResourceLocation resourceLocation) { - return resourceLocation.getPath().endsWith(".json"); - } - - private static boolean isShader(ResourceLocation resourceLocation) { - return CompiledShader.Type.byLocation(resourceLocation) != null || resourceLocation.getPath().endsWith(".glsl"); - } - - private static void loadShader( - ResourceLocation resourceLocation, Resource resource, CompiledShader.Type type, Map map, ImmutableMap.Builder builder - ) { - ResourceLocation resourceLocation2 = type.idConverter().fileToId(resourceLocation); - GlslPreprocessor glslPreprocessor = createPreprocessor(map, resourceLocation); - - try { - Reader reader = resource.openAsReader(); - - try { - String string = IOUtils.toString(reader); - builder.put(new ShaderManager.ShaderSourceKey(resourceLocation2, type), String.join("", glslPreprocessor.process(string))); - } catch (Throwable var11) { - try { - reader.close(); - } catch (Throwable var10) { - var11.addSuppressed(var10); - } - - throw var11; - } - - reader.close(); - } catch (IOException var12) { - LOGGER.error("Failed to load shader source at {}", resourceLocation, var12); - } - } - - private static CompiledShaderProgram createProgram(GraphicsPipeline pipeline) { - CompiledShaderProgram compiledShaderProgram = new CompiledShaderProgram(0); - ShaderMixed shaderMixed = ShaderMixed.of(compiledShaderProgram); - shaderMixed.setPipeline(pipeline); - - return compiledShaderProgram; - } - } diff --git a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java index 61adacc7cc..9eb4a00cf1 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java @@ -2,9 +2,9 @@ import com.mojang.blaze3d.pipeline.MainTarget; import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.*; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.framebuffer.SwapChain; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -12,7 +12,7 @@ public class MainTargetMixin extends RenderTarget { public MainTargetMixin(boolean useDepth) { - super(useDepth); + super("Main", useDepth); } /** @@ -21,26 +21,49 @@ public MainTargetMixin(boolean useDepth) { */ @Overwrite private void createFrameBuffer(int width, int height) { - this.frameBufferId = 0; - - this.viewWidth = width; - this.viewHeight = height; this.width = width; this.height = height; } @Override - public void bindWrite(boolean updateScissor) { - Renderer.getInstance().getMainPass().rebindMainTarget(); + public void createBuffers(int i, int j) { + RenderSystem.assertOnRenderThread(); + int k = RenderSystem.getDevice().getMaxTextureSize(); + if (i > 0 && i <= k && j > 0 && j <= k) { + this.width = i; + this.height = j; + if (this.useDepth) { + this.depthTexture = RenderSystem.getDevice().createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, i, j, 1, 1); + this.depthTexture.setTextureFilter(FilterMode.NEAREST, false); + this.depthTexture.setAddressMode(AddressMode.CLAMP_TO_EDGE); + } + + this.colorTexture = RenderSystem.getDevice().createTexture(() -> this.label + " / Color", 15, TextureFormat.RGBA8, i, j, 1, 1); + this.colorTexture.setAddressMode(AddressMode.CLAMP_TO_EDGE); + this.setFilterMode(FilterMode.NEAREST, true); + } else { + throw new IllegalArgumentException("Window " + i + "x" + j + " size out of bounds (max. size: " + k + ")"); + } + } + + private void setFilterMode(FilterMode filterMode, boolean bl) { + if (this.colorTexture == null) { + throw new IllegalStateException("Can't change filter mode, color texture doesn't exist yet"); + } else { + if (bl || filterMode != this.filterMode) { + this.filterMode = filterMode; + this.colorTexture.setTextureFilter(filterMode, false); + } + } } @Override - public void bindRead() { - Renderer.getInstance().getMainPass().bindAsTexture(); + public GpuTexture getColorTexture() { + return Renderer.getInstance().getMainPass().getColorAttachment(); } @Override - public int getColorTextureId() { - return Renderer.getInstance().getMainPass().getColorAttachment().id; + public GpuTextureView getColorTextureView() { + return Renderer.getInstance().getMainPass().getColorAttachmentView(); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java index ea58c807a2..310d641580 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java @@ -1,200 +1,57 @@ package net.vulkanmod.mixin.render.target; import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderPass; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.BufferUploader; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.minecraft.client.renderer.CoreShaders; -import net.vulkanmod.gl.GlFramebuffer; -import net.vulkanmod.gl.GlTexture; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.framebuffer.Framebuffer; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.DrawUtil; -import org.lwjgl.opengl.GL30; -import org.lwjgl.system.MemoryStack; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import net.minecraft.client.renderer.RenderPipelines; +import net.vulkanmod.render.engine.VkFbo; +import net.vulkanmod.render.engine.VkGpuTexture; +import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.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.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import java.util.Objects; +import java.util.OptionalInt; @Mixin(RenderTarget.class) public abstract class RenderTargetMixin { - @Shadow public int viewWidth; - @Shadow public int viewHeight; @Shadow public int width; @Shadow public int height; - @Shadow protected int depthBufferId; - @Shadow protected int colorTextureId; - @Shadow public int frameBufferId; + @Shadow @Nullable protected GpuTexture colorTexture; + @Shadow @Nullable protected GpuTexture depthTexture; + @Shadow @Nullable protected GpuTextureView colorTextureView; - @Shadow @Final private float[] clearChannels; - @Shadow @Final public boolean useDepth; - - boolean needClear = false; - boolean bound = false; - - /** - * @author - */ - @Overwrite - public void clear() { - RenderSystem.assertOnRenderThreadOrInit(); - - if(!Renderer.isRecording()) - return; - - // If the framebuffer is not bound postpone clear - GlFramebuffer glFramebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId); - if (!bound || GlFramebuffer.getBoundFramebuffer() != glFramebuffer) { - needClear = true; - return; - } - - GlStateManager._clearColor(this.clearChannels[0], this.clearChannels[1], this.clearChannels[2], this.clearChannels[3]); - int i = 16384; - if (this.useDepth) { - GlStateManager._clearDepth(1.0); - i |= 256; - } - - GlStateManager._clear(i); - needClear = false; - } - - /** - * @author - */ @Overwrite - public void bindRead() { + public void blitAndBlendToTexture(GpuTextureView gpuTextureView) { RenderSystem.assertOnRenderThread(); - applyClear(); - - GlTexture.bindTexture(this.colorTextureId); - - try (MemoryStack stack = MemoryStack.stackPush()) { - GlTexture.getBoundTexture().getVulkanImage() - .readOnlyLayout(stack, Renderer.getCommandBuffer()); - } - } - - /** - * @author - */ - @Overwrite - public void unbindRead() { - RenderSystem.assertOnRenderThreadOrInit(); - GlTexture.bindTexture(0); - } - - /** - * @author - */ - @Overwrite - public void bindWrite(boolean bl) { - RenderSystem.assertOnRenderThreadOrInit(); - - GlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); - if (bl) { - GlStateManager._viewport(0, 0, this.viewWidth, this.viewHeight); - } - - this.bound = true; - if (needClear) - clear(); - } - - /** - * @author - */ - @Overwrite - public void unbindWrite() { - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> { - GlStateManager._glBindFramebuffer(36160, 0); - this.bound = false; - }); - } else { - GlStateManager._glBindFramebuffer(36160, 0); - this.bound = false; - } - } - - @Inject(method = "blitToScreen", at = @At("HEAD"), cancellable = true) - private void blitToScreen(int width, int height, CallbackInfo ci) { - // If the target needs clear it means it has not been used, thus we can skip blit - if (!this.needClear) { - Framebuffer framebuffer = GlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); - VTextureSelector.bindTexture(0, framebuffer.getColorAttachment()); - - DrawUtil.blitToScreen(); - } - - ci.cancel(); - } - - /** - * @author - * @reason - */ - @Overwrite - public void blitAndBlendToScreen(int i, int j) { - RenderSystem.assertOnRenderThread(); - - if (this.needClear) { + VkFbo fbo = ((VkGpuTexture) this.colorTexture).getFbo(this.depthTexture); + if (fbo.needsClear()) { return; } - GlStateManager._colorMask(true, true, true, false); - GlStateManager._disableDepthTest(); - GlStateManager._depthMask(false); - GlStateManager._viewport(0, 0, i, j); - - CompiledShaderProgram compiledShaderProgram = Objects.requireNonNull( - RenderSystem.setShader(CoreShaders.BLIT_SCREEN), "Blit shader not loaded" - ); - - int prevTexture = RenderSystem.getShaderTexture(0); - RenderSystem.setShaderTexture(0, this.colorTextureId); - -// compiledShaderProgram.bindSampler("InSampler", this.colorTextureId); - BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN); - bufferBuilder.addVertex(0.0F, 0.0F, 0.0F); - bufferBuilder.addVertex(1.0F, 0.0F, 0.0F); - bufferBuilder.addVertex(1.0F, 1.0F, 0.0F); - bufferBuilder.addVertex(0.0F, 1.0F, 0.0F); - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - - RenderSystem.setShaderTexture(0, prevTexture); - GlStateManager._depthMask(true); - GlStateManager._colorMask(true, true, true, true); - } - - @Inject(method = "getColorTextureId", at = @At("HEAD")) - private void injClear(CallbackInfoReturnable cir) { - applyClear(); - } - - @Unique - private void applyClear() { - if (this.needClear) { - GlFramebuffer currentFramebuffer = GlFramebuffer.getBoundFramebuffer(); - - this.bindWrite(false); - - if (currentFramebuffer != null) { - GlFramebuffer.beginRendering(currentFramebuffer); - } - } - } + try (RenderPass renderPass = RenderSystem.getDevice() + .createCommandEncoder() + .createRenderPass(() -> "Blit render target", gpuTextureView, OptionalInt.empty())) { + renderPass.setPipeline(RenderPipelines.ENTITY_OUTLINE_BLIT); + RenderSystem.bindDefaultUniforms(renderPass); + renderPass.bindSampler("InSampler", this.colorTextureView); + renderPass.draw(0, 3); + } + } + +// @Inject(method = "getColorTextureView", at = @At("HEAD")) +// private void injClear(CallbackInfoReturnable cir) { +// applyClear(); +// } +// +// @Unique +// private void applyClear() { +// VkFbo fbo = ((VkGpuTexture) this.colorTexture).getFbo(this.depthTexture); +// if (fbo.needsClear()) { +// fbo.bind(); +// } +// } } diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java index 9dfd918a9f..9bb93a8932 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java @@ -162,8 +162,8 @@ public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brig @SuppressWarnings("UnreachableCode") @Unique private void putQuadData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { - int[] quadData = quad.getVertices(); - Vec3i vec3i = quad.getDirection().getUnitVec3i(); + int[] quadData = quad.vertices(); + Vec3i vec3i = quad.direction().getUnitVec3i(); Matrix4f matrix4f = matrixEntry.pose(); boolean trustedNormals = ((PoseAccessor)(Object)matrixEntry).trustedNormals(); diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java deleted file mode 100644 index 855e7f7503..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.vulkanmod.mixin.render.vertex; - -import com.mojang.math.*; -import net.minecraft.client.renderer.FaceInfo; -import net.minecraft.client.renderer.block.model.BlockFaceUV; -import net.minecraft.client.renderer.block.model.FaceBakery; -import net.minecraft.core.BlockMath; -import net.minecraft.core.Direction; -import net.minecraft.util.Mth; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(FaceBakery.class) -public class FaceBakeryM { - - private static final float DIV = 1.0f / 16.0f; - private static final double DIV_2 = 1.0 / 90.0; - - /** - * @author - */ - @Overwrite - private static float[] setupShape(Vector3f vector3f, Vector3f vector3f2) { - float[] fs = new float[Direction.values().length]; - fs[FaceInfo.Constants.MIN_X] = vector3f.x() * DIV; - fs[FaceInfo.Constants.MIN_Y] = vector3f.y() * DIV; - fs[FaceInfo.Constants.MIN_Z] = vector3f.z() * DIV; - fs[FaceInfo.Constants.MAX_X] = vector3f2.x() * DIV; - fs[FaceInfo.Constants.MAX_Y] = vector3f2.y() * DIV; - fs[FaceInfo.Constants.MAX_Z] = vector3f2.z() * DIV; - return fs; - } - - /** - * @author - */ - @Overwrite - public static BlockFaceUV recomputeUVs(BlockFaceUV blockFaceUV, Direction direction, Transformation transformation) { - Matrix4f matrix4f = BlockMath.getUVLockTransform(transformation, direction).getMatrix(); - float f = blockFaceUV.getU(blockFaceUV.getReverseIndex(0)); - float g = blockFaceUV.getV(blockFaceUV.getReverseIndex(0)); - Vector4f vector4f = matrix4f.transform(new Vector4f(f * DIV, g * DIV, 0.0F, 1.0F)); - float h = 16.0F * vector4f.x(); - float i = 16.0F * vector4f.y(); - float j = blockFaceUV.getU(blockFaceUV.getReverseIndex(2)); - float k = blockFaceUV.getV(blockFaceUV.getReverseIndex(2)); - Vector4f vector4f2 = matrix4f.transform(new Vector4f(j * DIV, k * DIV, 0.0F, 1.0F)); - float l = 16.0F * vector4f2.x(); - float m = 16.0F * vector4f2.y(); - float n; - float o; - if (Math.signum(j - f) == Math.signum(l - h)) { - n = h; - o = l; - } else { - n = l; - o = h; - } - - float p; - float q; - if (Math.signum(k - g) == Math.signum(m - i)) { - p = i; - q = m; - } else { - p = m; - q = i; - } - - float r = (float)Math.toRadians(blockFaceUV.rotation); - Matrix3f matrix3f = new Matrix3f(matrix4f); - Vector3f vector3f = matrix3f.transform(new Vector3f(Mth.cos(r), Mth.sin(r), 0.0F)); - int s = Math.floorMod(-((int)Math.round(Math.toDegrees(Math.atan2(vector3f.y(), vector3f.x())) * DIV_2)) * 90, 360); - return new BlockFaceUV(new float[]{n, p, o, q}, s); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java deleted file mode 100644 index a815f5a38a..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.vulkanmod.mixin.render.vertex; - -import com.mojang.blaze3d.buffers.BufferType; -import com.mojang.blaze3d.buffers.BufferUsage; -import com.mojang.blaze3d.buffers.GpuBuffer; -import com.mojang.blaze3d.vertex.ByteBufferBuilder; -import com.mojang.blaze3d.vertex.MeshData; -import com.mojang.blaze3d.vertex.VertexBuffer; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.vulkanmod.render.VBO; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(VertexBuffer.class) -public class VertexBufferM { - - private VBO vbo; - - @Inject(method = "", at = @At("RETURN")) - private void constructor(BufferUsage usage, CallbackInfo ci) { - vbo = new VBO(usage); - } - -// @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/buffers/GpuBuffer;(Lcom/mojang/blaze3d/buffers/BufferType;Lcom/mojang/blaze3d/buffers/BufferUsage;I)V")) -// private void doNothing(GpuBuffer instance, BufferType bufferType, BufferUsage bufferUsage, int i) { -// instance = null; -// } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenVertexArrays()I")) - private int doNothing2() { - return 0; - } - - /** - * @author - */ - @Overwrite - public void bind() {} - - /** - * @author - */ - @Overwrite - public static void unbind() {} - - /** - * @author - */ - @Overwrite - public void upload(MeshData meshData) { - vbo.upload(meshData); - } - - /** - * @author - */ - @Overwrite - public void uploadIndexBuffer(ByteBufferBuilder.Result result) { - vbo.uploadIndexBuffer(result.byteBuffer()); - } - - /** - * @author - */ - @Overwrite - public void drawWithShader(Matrix4f viewMatrix, Matrix4f projectionMatrix, CompiledShaderProgram shader) { - vbo.drawWithShader(viewMatrix, projectionMatrix, shader); - } - - /** - * @author - */ - @Overwrite - public void draw() { - vbo.draw(); - } - - /** - * @author - */ - @Overwrite - public void close() { - vbo.close(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java deleted file mode 100644 index 882a1b7290..0000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.vulkanmod.mixin.texture; - -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.texture.VulkanImage; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(AbstractTexture.class) -public abstract class MAbstractTexture { - @Shadow protected int id; - - private boolean blur; - private boolean mipmap; - - /** - * @author - */ - @Overwrite - public void bind() { - if (!RenderSystem.isOnRenderThreadOrInit()) { - RenderSystem.recordRenderCall(this::bindTexture); - } else { - this.bindTexture(); - } - } - - /** - * @author - */ - @Overwrite - public void setFilter(boolean blur, boolean mipmap) { - this.blur = blur; - this.mipmap = mipmap; - - VkGlTexture glTexture = VkGlTexture.getTexture(this.id); - VulkanImage vulkanImage = glTexture.getVulkanImage(); - - if (vulkanImage != null) - vulkanImage.updateTextureSampler(this.blur, false, this.mipmap); - } - - @Unique - private void bindTexture() { - VkGlTexture.bindTexture(this.id); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java deleted file mode 100644 index d04bc43ef6..0000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.vulkanmod.mixin.texture; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.platform.TextureUtil; -import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.texture.VulkanImage; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL30; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Unique; - -import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8G8B8A8_UNORM; -import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8_UNORM; - -@Mixin(TextureUtil.class) -public class MTextureUtil { - - /** - * @author - */ - @Overwrite(remap = false) - public static int generateTextureId() { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlTexture.genTextureId(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, int id, int mipLevels, int width, int height) { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlTexture.bindTexture(id); - VkGlTexture glTexture = VkGlTexture.getBoundTexture(); - VulkanImage image = glTexture.getVulkanImage(); - - if (mipLevels > 0) { - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MAX_LEVEL, mipLevels); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MIN_LOD, 0); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MAX_LOD, mipLevels); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_LOD_BIAS, 0.0F); - } - - if (image == null || image.mipLevels != mipLevels || image.width != width || image.height != height) { - if (image != null) - image.free(); - - image = new VulkanImage.Builder(width, height) - .setName(String.format("Texture %d", id)) - .setMipLevels(mipLevels + 1) - .setFormat(convertFormat(internalGlFormat)) - .setLinearFiltering(false) - .setClamp(false) - .createVulkanImage(); - - glTexture.setVulkanImage(image); - VTextureSelector.bindTexture(image); - } - } - - @Unique - private static int convertFormat(NativeImage.InternalGlFormat format) { - return switch (format) { - case RGBA -> VK_FORMAT_R8G8B8A8_UNORM; - case RED -> VK_FORMAT_R8_UNORM; - default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); - }; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java deleted file mode 100644 index 76317df8d4..0000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.vulkanmod.mixin.texture.image; - -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.texture.ImageUtil; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.lwjgl.system.MemoryUtil; -import org.lwjgl.vulkan.VK10; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.nio.ByteBuffer; -import java.util.Locale; - -@Mixin(NativeImage.class) -public abstract class MNativeImage { - - @Shadow private long pixels; - @Shadow private long size; - - @Shadow public abstract void close(); - - - @Shadow @Final private NativeImage.Format format; - - @Shadow public abstract int getWidth(); - - @Shadow @Final private int width; - @Shadow @Final private int height; - - @Shadow public abstract int getHeight(); - - private ByteBuffer buffer; - - @Inject(method = "(Lcom/mojang/blaze3d/platform/NativeImage$Format;IIZ)V", at = @At("RETURN")) - private void constr(NativeImage.Format format, int width, int height, boolean useStb, CallbackInfo ci) { - if(this.pixels != 0) { - buffer = MemoryUtil.memByteBuffer(this.pixels, (int)this.size); - } - } - - @Inject(method = "(Lcom/mojang/blaze3d/platform/NativeImage$Format;IIZJ)V", at = @At("RETURN")) - private void constr(NativeImage.Format format, int width, int height, boolean useStb, long pixels, CallbackInfo ci) { - if(this.pixels != 0) { - buffer = MemoryUtil.memByteBuffer(this.pixels, (int)this.size); - } - } - - /** - * @author - */ - @Overwrite - private void _upload(int level, int xOffset, int yOffset, int unpackSkipPixels, int unpackSkipRows, int widthIn, int heightIn, boolean autoClose) { - RenderSystem.assertOnRenderThreadOrInit(); - - VTextureSelector.uploadSubTexture(level, widthIn, heightIn, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, this.getWidth(), this.buffer); - VTextureSelector.getBoundTexture().updateTextureSampler(blur, clamp, mipmap); - - if (autoClose) { - this.close(); - } - } - - /** - * @author - */ - @Overwrite - public void downloadTexture(int level, boolean removeAlpha) { - RenderSystem.assertOnRenderThread(); - - ImageUtil.downloadTexture(VTextureSelector.getBoundTexture(0), this.pixels); - - if (removeAlpha && this.format.hasAlpha()) { - if (this.format != NativeImage.Format.RGBA) { - throw new IllegalArgumentException(String.format(Locale.ROOT, "getPixelRGBA only works on RGBA images; have %s", this.format)); - } - - var colorAttachment = ( Renderer.getInstance() - .getMainPass() - .getColorAttachment()); - boolean isBGRAFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); - - for (long l = 0; l < this.width * this.height * 4L; l+=4) { - int v = MemoryUtil.memGetInt(this.pixels + l); - - if (isBGRAFormat) - v = ColorUtil.BGRAtoRGBA(v); - - v = v | 255 << this.format.alphaOffset(); - MemoryUtil.memPutInt(this.pixels + l, v); - } - } - - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java index 39c521afb8..6cd8617975 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java @@ -1,8 +1,10 @@ package net.vulkanmod.mixin.texture.update; -import com.mojang.blaze3d.pipeline.TextureTarget; import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.GpuDevice; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.GpuTextureView; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.GameRenderer; @@ -16,6 +18,7 @@ import net.minecraft.world.entity.LivingEntity; import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.mixin.texture.image.NativeImageAccessor; +import net.vulkanmod.render.engine.VkGpuTexture; import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.queue.CommandPool; import org.joml.Vector3f; @@ -28,165 +31,182 @@ @Mixin(LightTexture.class) public class MLightTexture { + @Unique private static final Vector3f END_FLASH_SKY_LIGHT_COLOR = new Vector3f(0.9F, 0.5F, 1.0F); + @Shadow @Final private Minecraft minecraft; @Shadow @Final private GameRenderer renderer; - @Shadow @Final private TextureTarget target; @Shadow private boolean updateLightTexture; @Shadow private float blockLightRedFlicker; - private DynamicTexture lightTexture; - private NativeImage lightPixels; + @Unique private DynamicTexture lightTexture; + @Unique private GpuTextureView textureView; + @Unique private NativeImage lightPixels; private Vector3f[] tempVecs; - @Inject(method = "", at = @At("RETURN")) - private void onInit(GameRenderer gameRenderer, Minecraft minecraft, CallbackInfo ci) { - initLightMap(); - - this.tempVecs = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; - } - - private void initLightMap() { - this.lightTexture = new DynamicTexture(16, 16, false); - this.lightPixels = this.lightTexture.getPixels(); - - for(int i = 0; i < 16; ++i) { - for(int j = 0; j < 16; ++j) { - this.lightPixels.setPixel(j, i, 0xFFFFFFFF); - } - } - - this.lightTexture.upload(); - } - - /** - * @author - * @reason - */ - @Overwrite - public void turnOnLightLayer() { - RenderSystem.setShaderTexture(2, this.lightTexture.getId()); - } - - @SuppressWarnings("UnreachableCode") - @Inject(method = "updateLightTexture", at = @At("HEAD"), cancellable = true) - public void updateLightTexture(float partialTicks, CallbackInfo ci) { - if (this.updateLightTexture) { - this.updateLightTexture = false; - - ProfilerFiller profilerFiller = Profiler.get(); - profilerFiller.push("lightTex"); - - // TODO: Other mods might be changing lightmap behaviour, we can't be aware of that here - - ClientLevel clientLevel = this.minecraft.level; - if (clientLevel != null) { - float skyDarken = clientLevel.getSkyDarken(1.0F); - float skyFlashTime; - if (clientLevel.getSkyFlashTime() > 0) { - skyFlashTime = 1.0F; - } else { - skyFlashTime = skyDarken * 0.95F + 0.05F; - } - - float darknessEffectScale = this.minecraft.options.darknessEffectScale().get().floatValue(); - float darknessGamma = this.getDarknessGamma(partialTicks) * darknessEffectScale; - float darknessScale = this.calculateDarknessScale(this.minecraft.player, darknessGamma, partialTicks) * darknessEffectScale; - float waterVision = this.minecraft.player.getWaterVision(); - float nightVisionFactor; - if (this.minecraft.player.hasEffect(MobEffects.NIGHT_VISION)) { - nightVisionFactor = GameRenderer.getNightVisionScale(this.minecraft.player, partialTicks); - } else if (waterVision > 0.0F && this.minecraft.player.hasEffect(MobEffects.CONDUIT_POWER)) { - nightVisionFactor = waterVision; - } else { - nightVisionFactor = 0.0F; - } - -// Vector3f skyLightColor = new Vector3f(skyDarken, skyDarken, 1.0F).lerp(new Vector3f(1.0F, 1.0F, 1.0F), 0.35F); - skyDarken = lerp(skyDarken, 1.0f, 0.35f); - Vector3f skyLightColor = this.tempVecs[0].set(skyDarken, skyDarken, 1.0F); - float redFlicker = this.blockLightRedFlicker + 1.5F; - Vector3f lightColor = this.tempVecs[1]; - - float gamma = this.minecraft.options.gamma().get().floatValue(); - float darkenWorldAmount = this.renderer.getDarkenWorldAmount(partialTicks); - boolean forceBrightLightmap = clientLevel.effects().forceBrightLightmap(); - float ambientLight = clientLevel.dimensionType().ambientLight(); - - long ptr = ((NativeImageAccessor)(Object)this.lightPixels).getPixels(); - int width = this.lightPixels.getWidth(); - - Vector3f tVec3f = this.tempVecs[2]; - - for(int y = 0; y < 16; ++y) { - float brY = getBrightness(ambientLight, y) * skyFlashTime; - - for(int x = 0; x < 16; ++x) { - float brX = getBrightness(ambientLight, x) * redFlicker; - float t = brX * ((brX * 0.6F + 0.4F) * 0.6F + 0.4F); - float u = brX * (brX * brX * 0.6F + 0.4F); - lightColor.set(brX, t, u); - - if (forceBrightLightmap) { - lightColor.lerp(tVec3f.set(0.99F, 1.12F, 1.0F), 0.25F); - clampColor(lightColor); - } else { - tVec3f.set(skyLightColor).mul(brY); - lightColor.add(tVec3f); - - tVec3f.set(0.75F, 0.75F, 0.75F); - lightColor.lerp(tVec3f, 0.04F); - - if (darkenWorldAmount > 0.0F) { - tVec3f.set(lightColor).mul(0.7F, 0.6F, 0.6F); - lightColor.lerp(tVec3f, darkenWorldAmount); - } - } - - if (nightVisionFactor > 0.0F) { - // scale up uniformly until 1.0 is hit by one of the colors - float maxComponent = Math.max(lightColor.x(), Math.max(lightColor.y(), lightColor.z())); - if (maxComponent < 1.0F) { - float brightColor = 1.0F / maxComponent; - tVec3f.set(lightColor).mul(brightColor); - lightColor.lerp(tVec3f, nightVisionFactor); - } - } - - if (!forceBrightLightmap) { - lightColor.add(-darknessScale, -darknessScale, -darknessScale); - clampColor(lightColor); - } - - tVec3f.set(this.notGamma(lightColor.x), this.notGamma(lightColor.y), this.notGamma(lightColor.z)); - lightColor.lerp(tVec3f, Math.max(0.0F, gamma - darknessGamma)); - - lightColor.lerp(tVec3f.set(0.75F, 0.75F, 0.75F), 0.04F); - clampColor(lightColor); - - lightColor.mul(255.0F); - int r = (int)lightColor.x(); - int g = (int)lightColor.y(); - int b = (int)lightColor.z(); - - MemoryUtil.memPutInt(ptr + (((long) y * width + x) * 4L), 0xFF000000 | b << 16 | g << 8 | r); - } - } - - CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); - this.lightTexture.upload(); - - try (MemoryStack stack = MemoryStack.stackPush()) { - VkGlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); - } - - profilerFiller.pop(); - } - } - - ci.cancel(); - } +// @Inject(method = "", at = @At("RETURN")) +// private void onInit(GameRenderer gameRenderer, Minecraft minecraft, CallbackInfo ci) { +// initLightMap(); +// +// this.tempVecs = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; +// } +// +// private void initLightMap() { +// GpuDevice gpuDevice = RenderSystem.getDevice(); +// this.lightTexture = new DynamicTexture("Light Texture", 16, 16, false); +// this.textureView = gpuDevice.createTextureView(this.lightTexture.getTexture()); +// this.lightPixels = this.lightTexture.getPixels(); +// +// for(int i = 0; i < 16; ++i) { +// for(int j = 0; j < 16; ++j) { +// this.lightPixels.setPixel(j, i, 0xFFFFFFFF); +// } +// } +// +// this.lightTexture.upload(); +// } +// +// /** +// * @author +// * @reason +// */ +// @Overwrite +// public void turnOnLightLayer() { +// RenderSystem.setShaderTexture(2, this.textureView); +// } + + // TODO +// @SuppressWarnings("UnreachableCode") +// @Inject(method = "updateLightTexture", at = @At("HEAD"), cancellable = true) +// public void updateLightTexture(float partialTicks, CallbackInfo ci) { +// if (this.updateLightTexture) { +// this.updateLightTexture = false; +// +// ProfilerFiller profilerFiller = Profiler.get(); +// profilerFiller.push("lightTex"); +// +// // TODO: Other mods might be changing lightmap behaviour, we can't be aware of that here +// +// ClientLevel clientLevel = this.minecraft.level; +// if (clientLevel != null) { +// float skyDarken = clientLevel.getSkyDarken(1.0F); +// float skyFlashTime; +// if (clientLevel.getSkyFlashTime() > 0) { +// skyFlashTime = 1.0F; +// } else { +// skyFlashTime = skyDarken * 0.95F + 0.05F; +// } +// +// float darknessEffectScale = this.minecraft.options.darknessEffectScale().get().floatValue(); +// float darknessGamma = this.getDarknessGamma(partialTicks) * darknessEffectScale; +// float darknessScale = this.calculateDarknessScale(this.minecraft.player, darknessGamma, partialTicks) * darknessEffectScale; +// float waterVision = this.minecraft.player.getWaterVision(); +// float nightVisionFactor; +// if (this.minecraft.player.hasEffect(MobEffects.NIGHT_VISION)) { +// nightVisionFactor = GameRenderer.getNightVisionScale(this.minecraft.player, partialTicks); +// } else if (waterVision > 0.0F && this.minecraft.player.hasEffect(MobEffects.CONDUIT_POWER)) { +// nightVisionFactor = waterVision; +// } else { +// nightVisionFactor = 0.0F; +// } +// +//// Vector3f skyLightColor = new Vector3f(skyDarken, skyDarken, 1.0F).lerp(new Vector3f(1.0F, 1.0F, 1.0F), 0.35F); +// skyDarken = lerp(skyDarken, 1.0f, 0.35f); +// Vector3f skyLightColor = this.tempVecs[0].set(skyDarken, skyDarken, 1.0F); +// float redFlicker = this.blockLightRedFlicker + 1.5F; +// Vector3f lightColor = this.tempVecs[1]; +// +// float gamma = this.minecraft.options.gamma().get().floatValue(); +// float darkenWorldAmount = this.renderer.getDarkenWorldAmount(partialTicks); +//// boolean forceBrightLightmap = clientLevel.effects().forceBrightLightmap(); +// float ambientLight = clientLevel.dimensionType().ambientLight(); +// +// Vector3f vector3f2; +// if (clientLevel.effects().hasEndFlashes()) { +// vector3f2 = END_FLASH_SKY_LIGHT_COLOR; +// } else { +// vector3f2 = (new Vector3f(g, g, 1.0F)).lerp(new Vector3f(1.0F, 1.0F, 1.0F), 0.35F); +// } +// +// float n = this.blockLightRedFlicker + 1.5F; +// float o = clientLevel.dimensionType().ambientLight(); +// float p = ((Double)this.minecraft.options.gamma().get()).floatValue(); +// CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); +// +// long ptr = ((NativeImageAccessor)(Object)this.lightPixels).getPixels(); +// int width = this.lightPixels.getWidth(); +// +// Vector3f tVec3f = this.tempVecs[2]; +// +// for(int y = 0; y < 16; ++y) { +// float brY = getBrightness(ambientLight, y) * skyFlashTime; +// +// for(int x = 0; x < 16; ++x) { +// float brX = getBrightness(ambientLight, x) * redFlicker; +// float t = brX * ((brX * 0.6F + 0.4F) * 0.6F + 0.4F); +// float u = brX * (brX * brX * 0.6F + 0.4F); +// lightColor.set(brX, t, u); +// +// if (forceBrightLightmap) { +// lightColor.lerp(tVec3f.set(0.99F, 1.12F, 1.0F), 0.25F); +// clampColor(lightColor); +// } else { +// tVec3f.set(skyLightColor).mul(brY); +// lightColor.add(tVec3f); +// +// tVec3f.set(0.75F, 0.75F, 0.75F); +// lightColor.lerp(tVec3f, 0.04F); +// +// if (darkenWorldAmount > 0.0F) { +// tVec3f.set(lightColor).mul(0.7F, 0.6F, 0.6F); +// lightColor.lerp(tVec3f, darkenWorldAmount); +// } +// } +// +// if (nightVisionFactor > 0.0F) { +// // scale up uniformly until 1.0 is hit by one of the colors +// float maxComponent = Math.max(lightColor.x(), Math.max(lightColor.y(), lightColor.z())); +// if (maxComponent < 1.0F) { +// float brightColor = 1.0F / maxComponent; +// tVec3f.set(lightColor).mul(brightColor); +// lightColor.lerp(tVec3f, nightVisionFactor); +// } +// } +// +// if (!forceBrightLightmap) { +// lightColor.add(-darknessScale, -darknessScale, -darknessScale); +// clampColor(lightColor); +// } +// +// tVec3f.set(this.notGamma(lightColor.x), this.notGamma(lightColor.y), this.notGamma(lightColor.z)); +// lightColor.lerp(tVec3f, Math.max(0.0F, gamma - darknessGamma)); +// +// lightColor.lerp(tVec3f.set(0.75F, 0.75F, 0.75F), 0.04F); +// clampColor(lightColor); +// +// lightColor.mul(255.0F); +// int r = (int)lightColor.x(); +// int g = (int)lightColor.y(); +// int b = (int)lightColor.z(); +// +// MemoryUtil.memPutInt(ptr + (((long) y * width + x) * 4L), 0xFF000000 | b << 16 | g << 8 | r); +// } +// } +// +// CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); +// this.lightTexture.upload(); +// +// try (MemoryStack stack = MemoryStack.stackPush()) { +// VkGlTexture.getTexture(((VkGpuTexture)this.lightTexture.getTexture()).glId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); +// } +// +// profilerFiller.pop(); +// } +// } +// +// ci.cancel(); +// } @Unique private float getDarknessGamma(float f) { diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java index ea6603d66e..f61bf5539f 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.texture.update; +import com.mojang.blaze3d.textures.GpuTexture; import net.minecraft.client.renderer.texture.SpriteContents; import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.texture.VTextureSelector; @@ -18,7 +19,7 @@ public class MSpriteContents { @Shadow @Final SpriteContents.AnimatedTexture animationInfo; @Inject(method = "tickAndUpload", at = @At("HEAD"), cancellable = true) - private void checkUpload(int i, int j, CallbackInfo ci) { + private void checkUpload(int i, int j, GpuTexture gpuTexture, CallbackInfo ci) { if (!SpriteUpdateUtil.doUploadFrame()) { // Update animations frames even if no upload is scheduled ++this.subFrame; diff --git a/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java b/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java new file mode 100644 index 0000000000..04075bab5a --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java @@ -0,0 +1,94 @@ +package net.vulkanmod.mixin.util; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.TextureFormat; +import net.minecraft.client.Screenshot; +import net.minecraft.util.ARGB; +import net.vulkanmod.render.engine.VkGpuTexture; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.util.ColorUtil; +import org.lwjgl.vulkan.VK10; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +import java.util.function.Consumer; + +@Mixin(Screenshot.class) +public class ScreenshotMixin { + + @Overwrite + public static void takeScreenshot(RenderTarget renderTarget, int mipLevel, Consumer consumer) { + int width = renderTarget.width; + int height = renderTarget.height; + GpuTexture gpuTexture = renderTarget.getColorTexture(); + if (gpuTexture == null) { + throw new IllegalStateException("Tried to capture screenshot of an incomplete framebuffer"); + } else { + // Need to submit and wait cmds if screenshot was requested + // before the end of the frame + Renderer.getInstance().flushCmds(); + + int pixelSize = TextureFormat.RGBA8.pixelSize(); + GpuBuffer gpuBuffer = RenderSystem.getDevice() + .createBuffer(() -> "Screenshot buffer", 9, width * height * pixelSize); + CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); + RenderSystem.getDevice().createCommandEncoder().copyTextureToBuffer(gpuTexture, gpuBuffer, 0, () -> { + try (GpuBuffer.MappedView readView = commandEncoder.mapBuffer(gpuBuffer, true, false)) { + NativeImage nativeImage = new NativeImage(width, height, false); + + var colorAttachment = ((VkGpuTexture) Renderer.getInstance() + .getMainPass() + .getColorAttachment()); + boolean isBgraFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); + + int size = mipLevel * mipLevel; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + if (mipLevel == 1) { + int color = readView.data().getInt((x + y * width) * pixelSize); + + if (isBgraFormat) { + color = ColorUtil.BGRAtoRGBA(color); + } + + nativeImage.setPixelABGR(x, y, color | 0xFF000000); + } else { + int red = 0; + int green = 0; + int blue = 0; + + for (int x1 = 0; x1 < mipLevel; x1++) { + for (int y1 = 0; y1 < mipLevel; y1++) { + int color = readView.data().getInt(((x + x1) + (y + y1) * width) * pixelSize); + + if (isBgraFormat) { + color = ColorUtil.BGRAtoRGBA(color); + } + + red += ARGB.red(color); + green += ARGB.green(color); + blue += ARGB.blue(color); + } + } + + nativeImage.setPixelABGR(x, y, ARGB.color(255, red / size, green / size, blue / size)); + } + } + } + + consumer.accept(nativeImage); + } + + gpuBuffer.close(); + }, 0); + } + } + +} diff --git a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java b/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java deleted file mode 100644 index 703a79b77d..0000000000 --- a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.vulkanmod.mixin.util; - -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.client.Screenshot; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.Renderer; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(Screenshot.class) -public class ScreenshotRecorderM { - - /** - * @author - */ - @Overwrite - public static NativeImage takeScreenshot(RenderTarget target) { - int width = target.width; - int height = target.height; - - NativeImage nativeimage = new NativeImage(width, height, false); - VkGlTexture.bindTexture(target.getColorTextureId()); - - // Need to submit and wait cmds if screenshot was requested - // before the end of the frame - Renderer.getInstance().flushCmds(); - - nativeimage.downloadTexture(0, true); - return nativeimage; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/vertex/EntityOutlineGeneratorM.java b/src/main/java/net/vulkanmod/mixin/vertex/EntityOutlineGeneratorM.java index 1c6095267b..b9be40061e 100644 --- a/src/main/java/net/vulkanmod/mixin/vertex/EntityOutlineGeneratorM.java +++ b/src/main/java/net/vulkanmod/mixin/vertex/EntityOutlineGeneratorM.java @@ -15,7 +15,7 @@ public class EntityOutlineGeneratorM implements ExtendedVertexBuilder { private boolean canUseFastVertex = false; @Inject(method = "*", at = @At("RETURN")) - private void getExtBuilder(VertexConsumer vertexConsumer, int i, int j, int k, int l, CallbackInfo ci) { + private void getExtBuilder(VertexConsumer vertexConsumer, int i, CallbackInfo ci) { if (vertexConsumer instanceof ExtendedVertexBuilder) { this.extDelegate = (ExtendedVertexBuilder) vertexConsumer; this.canUseFastVertex = true; diff --git a/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java index a80b32c0b3..19d93d508e 100644 --- a/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java @@ -31,9 +31,9 @@ public class MinecraftMixin { */ @Redirect(method="", at=@At(value="INVOKE", target="Lcom/mojang/blaze3d/platform/Window;setIcon(Lnet/minecraft/server/packs/PackResources;Lcom/mojang/blaze3d/platform/IconSet;)V")) private void bypassWaylandIcon(Window instance, PackResources packResources, IconSet iconSet) throws IOException { - if(!Platform.isWayLand()) + if (!Platform.isWayLand()) { - this.window.setIcon(this.vanillaPackResources, SharedConstants.getCurrentVersion().isStable() ? IconSet.RELEASE : IconSet.SNAPSHOT); + this.window.setIcon(this.vanillaPackResources, SharedConstants.getCurrentVersion().stable() ? IconSet.RELEASE : IconSet.SNAPSHOT); } } } diff --git a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java index 7d06b2a6bb..4827f90431 100644 --- a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java +++ b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java @@ -15,7 +15,6 @@ import net.vulkanmod.vulkan.Vulkan; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; -import org.lwjgl.opengl.GLCapabilities; import org.slf4j.Logger; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -30,10 +29,9 @@ @Mixin(Window.class) public abstract class WindowMixin { - @Final @Shadow private long window; + @Final @Shadow private long handle; @Shadow private boolean vsync; - @Shadow private boolean fullscreen; @Shadow @Final private static Logger LOGGER; @@ -59,23 +57,6 @@ public abstract class WindowMixin { @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwWindowHint(II)V")) private void redirect(int hint, int value) { } - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwMakeContextCurrent(J)V")) - private void redirect2(long window) { } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL;createCapabilities()Lorg/lwjgl/opengl/GLCapabilities;")) - private GLCapabilities redirect2() { - return null; - } - - // Vulkan device not initialized yet - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;maxSupportedTextureSize()I")) - private int redirect3() { - return 0; - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwSetWindowSizeLimits(JIIII)V")) - private void redirect4(long window, int minwidth, int minheight, int maxwidth, int maxheight) { } - @Inject(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwCreateWindow(IILjava/lang/CharSequence;JJ)J")) private void vulkanHint(WindowEventHandler windowEventHandler, ScreenManager screenManager, DisplayData displayData, String string, String string2, CallbackInfo ci) { GLFW.glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); @@ -87,7 +68,7 @@ private void vulkanHint(WindowEventHandler windowEventHandler, ScreenManager scr @Inject(method = "", at = @At(value = "RETURN")) private void getHandle(WindowEventHandler windowEventHandler, ScreenManager screenManager, DisplayData displayData, String string, String string2, CallbackInfo ci) { - VRenderSystem.setWindow(this.window); + VRenderSystem.setWindow(this.handle); } /** @@ -113,12 +94,7 @@ public void toggleFullScreen() { */ @Overwrite public void updateDisplay(@Nullable TracyFrameCapture tracyFrameCapture) { - RenderSystem.flipFrame(this.window, tracyFrameCapture); - -// if (this.fullscreen != this.actuallyFullscreen) { -// this.actuallyFullscreen = this.fullscreen; -// this.updateFullscreen(this.vsync, tracyFrameCapture); -// } + RenderSystem.flipFrame((Window) ((Object)this), tracyFrameCapture); if (Options.fullscreenDirty) { Options.fullscreenDirty = false; @@ -166,7 +142,7 @@ private void setMode() { this.y = 0; this.width = videoMode.width; this.height = videoMode.height; - GLFW.glfwSetWindowMonitor(this.window, monitor, this.x, this.y, this.width, this.height, videoMode.refreshRate); + GLFW.glfwSetWindowMonitor(this.handle, monitor, this.x, this.y, this.width, this.height, videoMode.refreshRate); this.wasOnFullscreen = true; } @@ -184,8 +160,8 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { int width = videoMode.width; int height = videoMode.height; - GLFW.glfwSetWindowAttrib(this.window, GLFW_DECORATED, GLFW_FALSE); - GLFW.glfwSetWindowMonitor(this.window, 0L, 0, 0, width, height, -1); + GLFW.glfwSetWindowAttrib(this.handle, GLFW_DECORATED, GLFW_FALSE); + GLFW.glfwSetWindowMonitor(this.handle, 0L, 0, 0, width, height, -1); this.width = width; this.height = height; @@ -196,8 +172,8 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { this.width = this.windowedWidth; this.height = this.windowedHeight; - GLFW.glfwSetWindowMonitor(this.window, 0L, this.x, this.y, this.width, this.height, -1); - GLFW.glfwSetWindowAttrib(this.window, GLFW_DECORATED, GLFW_TRUE); + GLFW.glfwSetWindowMonitor(this.handle, 0L, this.x, this.y, this.width, this.height, -1); + GLFW.glfwSetWindowAttrib(this.handle, GLFW_DECORATED, GLFW_TRUE); this.wasOnFullscreen = false; } @@ -209,7 +185,7 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { */ @Overwrite private void onFramebufferResize(long window, int width, int height) { - if (window == this.window) { + if (window == this.handle) { int prevWidth = this.getWidth(); int prevHeight = this.getHeight(); diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 97bca6f339..9368e5ad1a 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -53,7 +53,13 @@ private static GraphicsPipeline createPipeline(String configName, VertexFormat v ShaderLoadUtil.loadShaders(pipelineBuilder, config, configName, "basic"); - return pipelineBuilder.createGraphicsPipeline(); + var pipeline = pipelineBuilder.createGraphicsPipeline(); + + for (var buffer : pipeline.getBuffers()) { + buffer.setUseGlobalBuffer(true); + } + + return pipeline; } public static GraphicsPipeline getTerrainShader(TerrainRenderType renderType) { diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 3e981572f3..e3c4153ece 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -1,15 +1,8 @@ package net.vulkanmod.render; -import com.mojang.blaze3d.buffers.BufferUsage; -import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexFormat; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.renderer.CompiledShaderProgram; -import net.vulkanmod.interfaces.shader.ShaderMixed; import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.*; import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; @@ -17,25 +10,21 @@ import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; -import org.joml.Matrix4f; import java.nio.ByteBuffer; -@Environment(EnvType.CLIENT) public class VBO { private final MemoryType memoryType; private VertexBuffer vertexBuffer; private IndexBuffer indexBuffer; - private int indexCount; - private int vertexCount; private VertexFormat.Mode mode; - - AutoIndexBuffer autoIndexBuffer; private boolean autoIndexed = false; + private int indexCount; + private int vertexCount; - public VBO(BufferUsage usage) { - this.memoryType = usage == BufferUsage.STATIC_WRITE ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; + public VBO(boolean useGpuMem) { + this.memoryType = useGpuMem ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; } public void upload(MeshData meshData) { @@ -96,73 +85,40 @@ public void uploadIndexBuffer(ByteBuffer data) { if (autoIndexBuffer != null) { autoIndexBuffer.checkCapacity(this.vertexCount); - this.autoIndexBuffer = autoIndexBuffer; + this.indexBuffer = autoIndexBuffer.getIndexBuffer(); } this.autoIndexed = true; - - } else { - if (this.indexBuffer != null) + } + else { + if (this.indexBuffer != null && !this.autoIndexed) { this.indexBuffer.scheduleFree(); + } this.indexBuffer = new IndexBuffer(data.remaining(), MemoryTypes.GPU_MEM); this.indexBuffer.copyBuffer(data, data.remaining()); } - } - public void drawWithShader(Matrix4f MV, Matrix4f P, CompiledShaderProgram shader) { - if (this.indexCount != 0) { - RenderSystem.assertOnRenderThread(); - - RenderSystem.setShader(shader); - - GraphicsPipeline pipeline = ShaderMixed.of(shader).getPipeline(); - drawWithShader(MV, P, pipeline); - } + public void bind(GraphicsPipeline pipeline) { + Renderer renderer = Renderer.getInstance(); + renderer.bindGraphicsPipeline(pipeline); + VTextureSelector.bindShaderTextures(pipeline); + renderer.uploadAndBindUBOs(pipeline); } - public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { + public void draw() { if (this.indexCount != 0) { - RenderSystem.assertOnRenderThread(); - - VRenderSystem.applyMVP(MV, P); - - VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); - Renderer renderer = Renderer.getInstance(); - renderer.bindGraphicsPipeline(pipeline); - VTextureSelector.bindShaderTextures(pipeline); + Pipeline pipeline = renderer.getBoundPipeline(); renderer.uploadAndBindUBOs(pipeline); - IndexBuffer indexBuffer; - if (this.autoIndexBuffer != null) { - indexBuffer = this.autoIndexBuffer.getIndexBuffer(); - } else { - indexBuffer = this.indexBuffer; - } - - if (indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, indexBuffer, this.indexCount); + if (this.indexBuffer != null) { + Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); } else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); } - - VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); - - } - } - - public void draw() { - if (this.indexCount != 0) { - RenderSystem.assertOnRenderThread(); - - Renderer renderer = Renderer.getInstance(); - Pipeline pipeline = renderer.getBoundPipeline(); - renderer.uploadAndBindUBOs(pipeline); - - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index 7e4d790466..0ec0365c52 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -368,7 +368,8 @@ public void updateGlobalBlockEntities(Collection fullSet) { sectionSet.clear(); sectionSet.addAll(fullSet); - Minecraft.getInstance().levelRenderer.updateGlobalBlockEntities(toRemove, toAdd); + // TODO +// Minecraft.getInstance().levelRenderer.updateGlobalBlockEntities(toRemove, toAdd); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 2fc12a79a1..9d64bc902c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -1,20 +1,26 @@ package net.vulkanmod.render.chunk; import com.google.common.collect.Sets; +import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.SheetedDecalTextureGenerator; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexMultiConsumer; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderBuffers; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.SubmitNodeStorage; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; import net.minecraft.client.renderer.culling.Frustum; -import net.minecraft.client.resources.model.ModelBakery; +import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.client.renderer.feature.FeatureRenderDispatcher; +import net.minecraft.client.renderer.feature.ModelFeatureRenderer; +import net.minecraft.client.renderer.state.LevelRenderState; +import net.minecraft.client.renderer.texture.AbstractTexture; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.server.level.BlockDestructionProgress; @@ -51,11 +57,30 @@ public class WorldRenderer { private static WorldRenderer INSTANCE; + public static WorldRenderer init(EntityRenderDispatcher entityRenderDispatcher, + BlockEntityRenderDispatcher blockEntityRenderDispatcher, + RenderBuffers renderBuffers, + LevelRenderState levelRenderState, + FeatureRenderDispatcher featureRenderDispatcher) { + if (INSTANCE != null) { + return INSTANCE; + } + else { + return INSTANCE = new WorldRenderer(entityRenderDispatcher, blockEntityRenderDispatcher, renderBuffers, levelRenderState, featureRenderDispatcher); + } + } + private final Minecraft minecraft; private ClientLevel level; private int renderDistance; private final RenderBuffers renderBuffers; + private final EntityRenderDispatcher entityRenderDispatcher; + private final BlockEntityRenderDispatcher blockEntityRenderDispatcher; + private final LevelRenderState levelRenderState; + private final FeatureRenderDispatcher featureRenderDispatcher; + + private float partialTick; private Vec3 cameraPos; private int lastCameraSectionX; private int lastCameraSectionY; @@ -85,11 +110,22 @@ public class WorldRenderer { private final List onAllChangedCallbacks = new ObjectArrayList<>(); - private WorldRenderer(RenderBuffers renderBuffers) { + private WorldRenderer(EntityRenderDispatcher entityRenderDispatcher, + BlockEntityRenderDispatcher blockEntityRenderDispatcher, + RenderBuffers renderBuffers, + LevelRenderState levelRenderState, + FeatureRenderDispatcher featureRenderDispatcher) + { this.minecraft = Minecraft.getInstance(); this.renderBuffers = renderBuffers; + this.entityRenderDispatcher = entityRenderDispatcher; + this.blockEntityRenderDispatcher = blockEntityRenderDispatcher; + this.levelRenderState = levelRenderState; + this.featureRenderDispatcher = featureRenderDispatcher; + this.renderRegionCache = new RenderRegionBuilder(); this.taskDispatcher = new TaskDispatcher(); + ChunkTask.setTaskDispatcher(this.taskDispatcher); allocateIndirectBuffers(); TerrainRenderType.updateMapping(); @@ -111,25 +147,6 @@ private void allocateIndirectBuffers() { } } - public static WorldRenderer init(RenderBuffers renderBuffers) { - if (INSTANCE != null) - return INSTANCE; - else - return INSTANCE = new WorldRenderer(renderBuffers); - } - - public static WorldRenderer getInstance() { - return INSTANCE; - } - - public static ClientLevel getLevel() { - return INSTANCE.level; - } - - public static Vec3 getCameraPos() { - return INSTANCE.cameraPos; - } - private void benchCallback() { BuildTimeProfiler.runBench(this.graphNeedsUpdate || !this.taskDispatcher.isIdle()); } @@ -292,25 +309,47 @@ public void clearOnAllChangedCallbacks() { this.onAllChangedCallbacks.clear(); } - public void renderSectionLayer(RenderType renderType, double camX, double camY, double camZ, Matrix4f modelView, Matrix4f projection) { - TerrainRenderType terrainRenderType = TerrainRenderType.get(renderType); - renderType.setupRenderState(); + public void renderSectionLayer(TerrainRenderType renderType, double camX, double camY, double camZ, Matrix4f modelView, Matrix4f projection) { + Renderer.getInstance().getMainPass().rebindMainTarget(); this.sortTranslucentSections(camX, camY, camZ); ProfilerFiller mcProfiler = net.minecraft.util.profiling.Profiler.get(); Zone zone = mcProfiler.zone(() -> "render_" + renderType); - final boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; + final boolean isTranslucent = renderType == TerrainRenderType.TRANSLUCENT; final boolean indirectDraw = Initializer.CONFIG.indirectDraw; + if (!isTranslucent) { + GlStateManager._disableBlend(); + } else { + GlStateManager._enableBlend(); + VRenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); + } + + VRenderSystem.enableCull(); + VRenderSystem.depthFunc(GL11.GL_LEQUAL); + + GlStateManager._enableDepthTest(); + GlStateManager._depthMask(true); + + GlStateManager._colorMask(true, true, true, true); + GlStateManager._disablePolygonOffset(); + VRenderSystem.setPolygonModeGL(GL11.GL_FILL); + VRenderSystem.applyMVP(modelView, projection); VRenderSystem.setPrimitiveTopologyGL(GL11.GL_TRIANGLES); Renderer renderer = Renderer.getInstance(); - GraphicsPipeline pipeline = PipelineManager.getTerrainShader(terrainRenderType); + GraphicsPipeline pipeline = PipelineManager.getTerrainShader(renderType); renderer.bindGraphicsPipeline(pipeline); + TextureManager textureManager = Minecraft.getInstance().getTextureManager(); + AbstractTexture abstractTexture = textureManager.getTexture(TextureAtlas.LOCATION_BLOCKS); + abstractTexture.setUseMipmaps(true); + var texView = abstractTexture.getTextureView(); + RenderSystem.setShaderTexture(0, texView); + VTextureSelector.bindShaderTextures(pipeline); IndexBuffer indexBuffer = Renderer.getDrawer().getQuadsIndexBuffer().getIndexBuffer(); @@ -318,8 +357,8 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, int currentFrame = Renderer.getCurrentFrame(); Set allowedRenderTypes = Initializer.CONFIG.uniqueOpaqueLayer ? TerrainRenderType.COMPACT_RENDER_TYPES : TerrainRenderType.SEMI_COMPACT_RENDER_TYPES; - if (allowedRenderTypes.contains(terrainRenderType)) { - terrainRenderType.setCutoutUniform(); + if (allowedRenderTypes.contains(renderType)) { + renderType.setCutoutUniform(); for (Iterator iterator = this.sectionGraph.getChunkAreaQueue().iterator(isTranslucent); iterator.hasNext(); ) { ChunkArea chunkArea = iterator.next(); @@ -327,32 +366,31 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, DrawBuffers drawBuffers = chunkArea.drawBuffers; renderer.uploadAndBindUBOs(pipeline); - if (drawBuffers.getAreaBuffer(terrainRenderType) != null && queue.size() > 0) { + if (drawBuffers.getAreaBuffer(renderType) != null && queue.size() > 0) { - drawBuffers.bindBuffers(Renderer.getCommandBuffer(), pipeline, terrainRenderType, camX, camY, camZ); + drawBuffers.bindBuffers(Renderer.getCommandBuffer(), pipeline, renderType, camX, camY, camZ); renderer.uploadAndBindUBOs(pipeline); if (indirectDraw) - drawBuffers.buildDrawBatchesIndirect(cameraPos, indirectBuffers[currentFrame], queue, terrainRenderType); + drawBuffers.buildDrawBatchesIndirect(cameraPos, indirectBuffers[currentFrame], queue, renderType); else - drawBuffers.buildDrawBatchesDirect(cameraPos, queue, terrainRenderType); + drawBuffers.buildDrawBatchesDirect(cameraPos, queue, renderType); } } } - if (terrainRenderType == TerrainRenderType.CUTOUT || terrainRenderType == TerrainRenderType.TRIPWIRE) { + if (renderType == TerrainRenderType.CUTOUT || renderType == TerrainRenderType.TRIPWIRE) { indirectBuffers[currentFrame].submitUploads(); // uniformBuffers.submitUploads(); } - //Need to reset push constants in case the pipeline will still be used for rendering + // Need to reset push constants in case the pipeline will still be used for rendering if (!indirectDraw) { VRenderSystem.setModelOffset(0, 0, 0); renderer.pushConstants(pipeline); } zone.close(); - renderType.clearRenderState(); } private void sortTranslucentSections(double camX, double camY, double camZ) { @@ -382,40 +420,69 @@ private void sortTranslucentSections(double camX, double camY, double camZ) { mcProfiler.pop(); } - public void renderBlockEntities(PoseStack poseStack, double camX, double camY, double camZ, - Long2ObjectMap> destructionProgress, float gameTime) { + public void renderBlockEntities(PoseStack poseStack, LevelRenderState levelRenderState, + SubmitNodeStorage submitNodeStorage, + Long2ObjectMap> destructionProgress) { Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); profiler.push("Block-entities"); - MultiBufferSource bufferSource = this.renderBuffers.bufferSource(); + Vec3 vec3 = levelRenderState.cameraRenderState.pos; + double camX = vec3.x(); + double camY = vec3.y(); + double camZ = vec3.z(); for (RenderSection renderSection : this.sectionGraph.getBlockEntitiesSections()) { List list = renderSection.getCompiledSection().getBlockEntities(); if (!list.isEmpty()) { for (BlockEntity blockEntity : list) { BlockPos blockPos = blockEntity.getBlockPos(); - MultiBufferSource bufferSource1 = bufferSource; - poseStack.pushPose(); - poseStack.translate((double) blockPos.getX() - camX, (double) blockPos.getY() - camY, (double) blockPos.getZ() - camZ); - SortedSet sortedset = destructionProgress.get(blockPos.asLong()); - if (sortedset != null && !sortedset.isEmpty()) { - int j1 = sortedset.last().getProgress(); - if (j1 >= 0) { - PoseStack.Pose pose = poseStack.last(); - VertexConsumer vertexconsumer = new SheetedDecalTextureGenerator(this.renderBuffers.crumblingBufferSource().getBuffer(ModelBakery.DESTROY_TYPES.get(j1)), pose, 1.0f); - bufferSource1 = (renderType) -> { - VertexConsumer vertexConsumer2 = bufferSource.getBuffer(renderType); - return renderType.affectsCrumbling() ? VertexMultiConsumer.create(vertexconsumer, vertexConsumer2) : vertexConsumer2; - }; - } + SortedSet sortedSet = destructionProgress.get(blockPos.asLong()); + ModelFeatureRenderer.CrumblingOverlay crumblingOverlay; + if (sortedSet != null && !sortedSet.isEmpty()) { + poseStack.pushPose(); + poseStack.translate(blockPos.getX() - camX, blockPos.getY() - camY, blockPos.getZ() - camZ); + crumblingOverlay = new ModelFeatureRenderer.CrumblingOverlay(sortedSet.last() + .getProgress(), poseStack.last()); + poseStack.popPose(); + } else { + crumblingOverlay = null; } - this.minecraft.getBlockEntityRenderDispatcher().render(blockEntity, gameTime, poseStack, bufferSource1); - poseStack.popPose(); + BlockEntityRenderState blockEntityRenderState = this.blockEntityRenderDispatcher.tryExtractRenderState(blockEntity, this.partialTick, crumblingOverlay); + if (blockEntityRenderState != null) { + levelRenderState.blockEntityRenderStates.add(blockEntityRenderState); + } + } + } + } + + Iterator iterator = this.level.getGloballyRenderedBlockEntities().iterator(); + + while (iterator.hasNext()) { + BlockEntity blockEntity2 = iterator.next(); + if (blockEntity2.isRemoved()) { + iterator.remove(); + } else { + BlockEntityRenderState blockEntityRenderState2 = this.blockEntityRenderDispatcher.tryExtractRenderState(blockEntity2, this.partialTick, null); + if (blockEntityRenderState2 != null) { + levelRenderState.blockEntityRenderStates.add(blockEntityRenderState2); } } } + + for (BlockEntityRenderState blockEntityRenderState : levelRenderState.blockEntityRenderStates) { + BlockPos blockPos = blockEntityRenderState.blockPos; + poseStack.pushPose(); + poseStack.translate(blockPos.getX() - camX, blockPos.getY() - camY, blockPos.getZ() - camZ); + var blockEntityRenderDispatcher = this.minecraft.getBlockEntityRenderDispatcher(); + blockEntityRenderDispatcher.submit(blockEntityRenderState, poseStack, submitNodeStorage, levelRenderState.cameraRenderState); + poseStack.popPose(); + } + } + + public void setPartialTick(float partialTick) { + this.partialTick = partialTick; } public void scheduleGraphUpdate() { @@ -457,6 +524,10 @@ public int getRenderDistance() { } public String getChunkStatistics() { + if (this.sectionGraph == null) { + return null; + } + return this.sectionGraph.getStatistics(); } @@ -465,4 +536,16 @@ public void cleanUp() { Arrays.stream(indirectBuffers).forEach(Buffer::scheduleFree); } + public static WorldRenderer getInstance() { + return INSTANCE; + } + + public static ClientLevel getLevel() { + return INSTANCE.level; + } + + public static Vec3 getCameraPos() { + return INSTANCE.cameraPos; + } + } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 4d01f40c64..f9402f0ce1 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -1,6 +1,5 @@ package net.vulkanmod.render.chunk.build; -import net.fabricmc.fabric.api.rendering.data.v1.RenderAttachedBlockView; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -26,7 +25,7 @@ import java.util.Map; import java.util.function.Function; -public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView { +public class RenderRegion implements BlockAndTintGetter { public static final int WIDTH = 3; public static final int SIZE = WIDTH * WIDTH * WIDTH; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java index c61e9b064c..49e49c502a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java @@ -1,15 +1,28 @@ package net.vulkanmod.render.chunk.build.frapi; -import java.util.HashMap; - +import com.mojang.blaze3d.vertex.PoseStack; import net.fabricmc.fabric.api.renderer.v1.mesh.MutableMesh; -import net.minecraft.resources.ResourceLocation; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.renderer.v1.render.BlockVertexConsumerProvider; +import net.fabricmc.fabric.api.renderer.v1.render.FabricBlockModelRenderer; +import net.fabricmc.fabric.api.renderer.v1.render.RenderLayerHelper; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.core.BlockPos; import net.fabricmc.fabric.api.renderer.v1.Renderer; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.vulkanmod.render.chunk.build.frapi.material.MaterialFinderImpl; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.state.BlockState; +import net.vulkanmod.mixin.render.frapi.BlockRenderDispatcherAccessor; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; +import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; +import net.vulkanmod.render.chunk.build.frapi.render.SimpleBlockRenderContext; /** * The Fabric default renderer implementation. Supports all @@ -18,14 +31,6 @@ public class VulkanModRenderer implements Renderer { public static final VulkanModRenderer INSTANCE = new VulkanModRenderer(); - public static final RenderMaterial STANDARD_MATERIAL = INSTANCE.materialFinder().find(); - - static { - INSTANCE.registerMaterial(RenderMaterial.STANDARD_ID, STANDARD_MATERIAL); - } - - private final HashMap materialMap = new HashMap<>(); - private VulkanModRenderer() {} @Override @@ -34,21 +39,40 @@ public MutableMesh mutableMesh() { } @Override - public MaterialFinder materialFinder() { - return new MaterialFinderImpl(); + public void render(ModelBlockRenderer modelBlockRenderer, BlockAndTintGetter blockAndTintGetter, + BlockStateModel blockStateModel, BlockState blockState, BlockPos blockPos, PoseStack poseStack, + BlockVertexConsumerProvider blockVertexConsumerProvider, boolean cull, long seed, int overlay) { + BlockRenderContext.POOL.get().render(blockAndTintGetter, blockStateModel, blockState, blockPos, poseStack, blockVertexConsumerProvider, cull, seed, overlay); } @Override - public RenderMaterial materialById(ResourceLocation id) { - return materialMap.get(id); + public void render(PoseStack.Pose pose, BlockVertexConsumerProvider blockVertexConsumerProvider, BlockStateModel blockStateModel, + float v, float v1, float v2, int i, int i1, BlockAndTintGetter blockAndTintGetter, + BlockPos blockPos, BlockState blockState) { + SimpleBlockRenderContext.POOL.get().bufferModel(pose, blockVertexConsumerProvider, blockStateModel, v, v1, v2, i, i1, blockAndTintGetter, blockPos, blockState); } @Override - public boolean registerMaterial(ResourceLocation id, RenderMaterial material) { - if (materialMap.containsKey(id)) return false; + public void renderBlockAsEntity(BlockRenderDispatcher blockRenderDispatcher, BlockState blockState, + PoseStack poseStack, MultiBufferSource multiBufferSource, int light, int overlay, + BlockAndTintGetter blockAndTintGetter, BlockPos pos) { + RenderShape blockRenderType = blockState.getRenderShape(); + + if (blockRenderType != RenderShape.INVISIBLE) { + BlockStateModel model = blockRenderDispatcher.getBlockModel(blockState); + int tint = ((BlockRenderDispatcherAccessor) blockRenderDispatcher).getBlockColors().getColor(blockState, null, null, 0); + float red = (tint >> 16 & 255) / 255.0F; + float green = (tint >> 8 & 255) / 255.0F; + float blue = (tint & 255) / 255.0F; + FabricBlockModelRenderer.render(poseStack.last(), layer -> multiBufferSource.getBuffer(RenderLayerHelper.getEntityBlockLayer(layer)), model, red, green, blue, light, overlay, blockAndTintGetter, pos, blockState); + ((BlockRenderDispatcherAccessor) blockRenderDispatcher).getBlockEntityModelsGetter().get().renderByBlock(blockState.getBlock(), ItemDisplayContext.NONE, poseStack, Minecraft.getInstance().gameRenderer.getSubmitNodeStorage(), light, overlay, 0); + } + } - // cast to prevent acceptance of impostor implementations - materialMap.put(id, material); - return true; + @Override + public QuadEmitter getLayerRenderStateEmitter(ItemStackRenderState.LayerRenderState layer) { + // TODO +// return ((AccessLayerRenderState) layer).fabric_getMutableMesh().emitter(); + return null; } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java new file mode 100644 index 0000000000..3bca8c85d2 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java @@ -0,0 +1,9 @@ +package net.vulkanmod.render.chunk.build.frapi.accessor; + +import net.fabricmc.fabric.impl.client.indigo.renderer.render.MeshItemCommand; + +import java.util.List; + +public interface AccessBatchingRenderCommandQueue { + List fabric_getMeshItemCommands(); +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessChunkRendererRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessChunkRendererRegion.java new file mode 100644 index 0000000000..a24048ae34 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessChunkRendererRegion.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.accessor; + +import net.fabricmc.fabric.impl.client.indigo.renderer.render.TerrainRenderContext; + +/** + * Used to stash block renderer reference in local scope during + * chunk rebuild, thus avoiding repeated thread-local lookups. + */ +public interface AccessChunkRendererRegion { + TerrainRenderContext fabric_getRenderer(); + + void fabric_setRenderer(TerrainRenderContext renderer); +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java new file mode 100644 index 0000000000..4b76f13cc0 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.frapi.accessor; + +import net.fabricmc.fabric.impl.client.indigo.renderer.mesh.MutableMeshImpl; + +public interface AccessLayerRenderState { + MutableMeshImpl fabric_getMutableMesh(); +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java new file mode 100644 index 0000000000..0b285ca5f6 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java @@ -0,0 +1,15 @@ +package net.vulkanmod.render.chunk.build.frapi.accessor; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; + + +import java.util.List; + +public interface AccessRenderCommandQueue { + void fabric_submitItem(PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh); +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java index 2723331b2e..80003422e3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java @@ -28,6 +28,16 @@ private ColorHelper() { } private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + /** + * Component-wise max. + */ + public static int maxLight(int l0, int l1) { + if (l0 == 0) return l1; + if (l1 == 0) return l0; + + return Math.max(l0 & 0xFFFF, l1 & 0xFFFF) | Math.max(l0 & 0xFFFF0000, l1 & 0xFFFF0000); + } + /** Component-wise multiply. Components need to be in same order in both inputs! */ public static int multiplyColor(int color1, int color2) { if (color1 == -1) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java deleted file mode 100644 index ed75223ebd..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import java.util.Objects; - -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; - -public class MaterialFinderImpl extends MaterialViewImpl implements MaterialFinder { - private static final int DEFAULT_BITS; - - static { - // Start with all zeroes - MaterialFinderImpl finder = new MaterialFinderImpl(0); - // Apply non-zero defaults - finder.ambientOcclusion(TriState.DEFAULT); - DEFAULT_BITS = finder.bits; - - if (!areBitsValid(DEFAULT_BITS)) { - throw new AssertionError("Default MaterialFinder bits are not valid!"); - } - } - - protected MaterialFinderImpl(int bits) { - super(bits); - } - - public MaterialFinderImpl() { - this(DEFAULT_BITS); - } - - @Override - public MaterialFinder blendMode(BlendMode blendMode) { - Objects.requireNonNull(blendMode, "BlendMode may not be null"); - - bits = (bits & ~BLEND_MODE_MASK) | (blendMode.ordinal() << BLEND_MODE_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder emissive(boolean isEmissive) { - bits = isEmissive ? (bits | EMISSIVE_FLAG) : (bits & ~EMISSIVE_FLAG); - return this; - } - - @Override - public MaterialFinder disableDiffuse(boolean disable) { - bits = disable ? (bits | DIFFUSE_FLAG) : (bits & ~DIFFUSE_FLAG); - return this; - } - - @Override - public MaterialFinder ambientOcclusion(TriState mode) { - Objects.requireNonNull(mode, "ambient occlusion TriState may not be null"); - - bits = (bits & ~AO_MASK) | (mode.ordinal() << AO_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder glintMode(GlintMode mode) { - Objects.requireNonNull(mode, "GlintMode may not be null"); - - bits = (bits & ~GLINT_MODE_MASK) | (mode.ordinal() << GLINT_MODE_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder shadeMode(ShadeMode mode) { - Objects.requireNonNull(mode, "ShadeMode may not be null"); - - bits = (bits & ~SHADE_MODE_MASK) | (mode.ordinal() << SHADE_MODE_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder copyFrom(MaterialView material) { - bits = ((MaterialViewImpl) material).bits; - return this; - } - - @Override - public MaterialFinder clear() { - bits = DEFAULT_BITS; - return this; - } - - @Override - public RenderMaterial find() { - return RenderMaterialImpl.byIndex(bits); - } -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java deleted file mode 100644 index 3733f6da74..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import net.minecraft.util.Mth; - -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; - -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.bitMask; - -/** - * Default implementation of the standard render materials. - * The underlying representation is simply an int with bit-wise - * packing of the various material properties. This offers - * easy/fast interning via int/object hashmap. - */ -public class MaterialViewImpl implements MaterialView { - private static final BlendMode[] BLEND_MODES = BlendMode.values(); - private static final int BLEND_MODE_COUNT = BLEND_MODES.length; - private static final TriState[] TRI_STATES = TriState.values(); - private static final int TRI_STATE_COUNT = TRI_STATES.length; - private static final GlintMode[] GLINT_MODES = GlintMode.values(); - private static final int GLINT_MODE_COUNT = GLINT_MODES.length; - private static final ShadeMode[] SHADE_MODES = ShadeMode.values(); - private static final int SHADE_MODE_COUNT = SHADE_MODES.length; - - protected static final int BLEND_MODE_BIT_LENGTH = Mth.ceillog2(BLEND_MODE_COUNT); - protected static final int EMISSIVE_BIT_LENGTH = 1; - protected static final int DIFFUSE_BIT_LENGTH = 1; - protected static final int AO_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); - protected static final int GLINT_MODE_BIT_LENGTH = Mth.ceillog2(GLINT_MODE_COUNT); - protected static final int SHADE_MODE_BIT_LENGTH = Mth.ceillog2(SHADE_MODE_COUNT); - - protected static final int BLEND_MODE_BIT_OFFSET = 0; - protected static final int EMISSIVE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; - protected static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; - protected static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; - protected static final int GLINT_MODE_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; - protected static final int SHADE_MODE_BIT_OFFSET = GLINT_MODE_BIT_OFFSET + GLINT_MODE_BIT_LENGTH; - public static final int TOTAL_BIT_LENGTH = SHADE_MODE_BIT_OFFSET + SHADE_MODE_BIT_LENGTH; - - protected static final int BLEND_MODE_MASK = bitMask(BLEND_MODE_BIT_LENGTH, BLEND_MODE_BIT_OFFSET); - protected static final int EMISSIVE_FLAG = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); - protected static final int DIFFUSE_FLAG = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); - protected static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); - protected static final int GLINT_MODE_MASK = bitMask(GLINT_MODE_BIT_LENGTH, GLINT_MODE_BIT_OFFSET); - protected static final int SHADE_MODE_MASK = bitMask(SHADE_MODE_BIT_LENGTH, SHADE_MODE_BIT_OFFSET); - - protected static boolean areBitsValid(int bits) { - int blendMode = (bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET; - int ao = (bits & AO_MASK) >>> AO_BIT_OFFSET; - int glintMode = (bits & GLINT_MODE_MASK) >>> GLINT_MODE_BIT_OFFSET; - int shadeMode = (bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET; - - return blendMode < BLEND_MODE_COUNT - && ao < TRI_STATE_COUNT - && glintMode < GLINT_MODE_COUNT - && shadeMode < SHADE_MODE_COUNT; - } - - protected int bits; - - protected MaterialViewImpl(int bits) { - this.bits = bits; - } - - @Override - public BlendMode blendMode() { - return BLEND_MODES[(bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET]; - } - - @Override - public boolean emissive() { - return (bits & EMISSIVE_FLAG) != 0; - } - - @Override - public boolean disableDiffuse() { - return (bits & DIFFUSE_FLAG) != 0; - } - - @Override - public TriState ambientOcclusion() { - return TRI_STATES[(bits & AO_MASK) >>> AO_BIT_OFFSET]; - } - - @Override - public GlintMode glintMode() { - return GLINT_MODES[(bits & GLINT_MODE_MASK) >>> GLINT_MODE_BIT_OFFSET]; - } - - @Override - public ShadeMode shadeMode() { - return SHADE_MODES[(bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET]; - } -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java deleted file mode 100644 index 17e4602bb1..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; - -public class RenderMaterialImpl extends MaterialViewImpl implements RenderMaterial { - public static final int VALUE_COUNT = 1 << TOTAL_BIT_LENGTH; - private static final RenderMaterialImpl[] BY_INDEX = new RenderMaterialImpl[VALUE_COUNT]; - - static { - for (int i = 0; i < VALUE_COUNT; i++) { - if (areBitsValid(i)) { - BY_INDEX[i] = new RenderMaterialImpl(i); - } - } - } - - private RenderMaterialImpl(int bits) { - super(bits); - } - - public int index() { - return bits; - } - - public static RenderMaterialImpl byIndex(int index) { - return BY_INDEX[index]; - } - - public static RenderMaterialImpl setDisableDiffuse(RenderMaterialImpl material, boolean disable) { - if (material.disableDiffuse() != disable) { - return byIndex(disable ? (material.bits | DIFFUSE_FLAG) : (material.bits & ~DIFFUSE_FLAG)); - } - - return material; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java index 259c4186bc..a0de501460 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java @@ -19,12 +19,15 @@ import com.google.common.base.Preconditions; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; +import net.fabricmc.fabric.api.renderer.v1.mesh.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.Nullable; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; -import net.vulkanmod.render.chunk.build.frapi.material.MaterialViewImpl; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; import net.minecraft.core.Direction; import net.minecraft.util.Mth; @@ -75,36 +78,60 @@ private EncodingFormat() { } Preconditions.checkState(QUAD_STRIDE == QuadView.VANILLA_QUAD_STRIDE, "Indigo quad stride (%s) mismatched with rendering API (%s)", QUAD_STRIDE, QuadView.VANILLA_QUAD_STRIDE); } - /** used for quick clearing of quad buffers. */ - static final int[] EMPTY = new int[TOTAL_STRIDE]; - private static final int DIRECTION_COUNT = Direction.values().length; private static final int NULLABLE_DIRECTION_COUNT = DIRECTION_COUNT + 1; + private static final @Nullable ChunkSectionLayer[] NULLABLE_BLOCK_RENDER_LAYERS = ArrayUtils.add(ChunkSectionLayer.values(), null); + private static final int NULLABLE_BLOCK_RENDER_LAYER_COUNT = NULLABLE_BLOCK_RENDER_LAYERS.length; + private static final TriState[] TRI_STATES = TriState.values(); + private static final int TRI_STATE_COUNT = TRI_STATES.length; + private static final @Nullable ItemStackRenderState.FoilType[] NULLABLE_GLINTS = ArrayUtils.add(ItemStackRenderState.FoilType.values(), null); + private static final int NULLABLE_GLINT_COUNT = NULLABLE_GLINTS.length; + private static final ShadeMode[] SHADE_MODES = ShadeMode.values(); + private static final int SHADE_MODE_COUNT = SHADE_MODES.length; + + private static final int NULL_RENDER_LAYER_INDEX = NULLABLE_BLOCK_RENDER_LAYER_COUNT - 1; + private static final int NULL_GLINT_INDEX = NULLABLE_GLINT_COUNT - 1; + private static final int CULL_BIT_LENGTH = Mth.ceillog2(NULLABLE_DIRECTION_COUNT); private static final int LIGHT_BIT_LENGTH = Mth.ceillog2(DIRECTION_COUNT); private static final int NORMALS_BIT_LENGTH = 4; private static final int GEOMETRY_BIT_LENGTH = GeometryHelper.FLAG_BIT_COUNT; - private static final int MATERIAL_BIT_LENGTH = MaterialViewImpl.TOTAL_BIT_LENGTH; + private static final int RENDER_LAYER_BIT_LENGTH = Mth.ceillog2(NULLABLE_BLOCK_RENDER_LAYER_COUNT); + private static final int EMISSIVE_BIT_LENGTH = 1; + private static final int DIFFUSE_BIT_LENGTH = 1; + private static final int AO_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); + private static final int GLINT_BIT_LENGTH = Mth.ceillog2(NULLABLE_GLINT_COUNT); + private static final int SHADE_MODE_BIT_LENGTH = Mth.ceillog2(SHADE_MODE_COUNT); private static final int CULL_BIT_OFFSET = 0; private static final int LIGHT_BIT_OFFSET = CULL_BIT_OFFSET + CULL_BIT_LENGTH; private static final int NORMALS_BIT_OFFSET = LIGHT_BIT_OFFSET + LIGHT_BIT_LENGTH; private static final int GEOMETRY_BIT_OFFSET = NORMALS_BIT_OFFSET + NORMALS_BIT_LENGTH; - private static final int MATERIAL_BIT_OFFSET = GEOMETRY_BIT_OFFSET + GEOMETRY_BIT_LENGTH; - private static final int TOTAL_BIT_LENGTH = MATERIAL_BIT_OFFSET + MATERIAL_BIT_LENGTH; + private static final int RENDER_LAYER_BIT_OFFSET = GEOMETRY_BIT_OFFSET + GEOMETRY_BIT_LENGTH; + private static final int EMISSIVE_BIT_OFFSET = RENDER_LAYER_BIT_OFFSET + RENDER_LAYER_BIT_LENGTH; + private static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; + private static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; + private static final int GLINT_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; + private static final int SHADE_MODE_BIT_OFFSET = GLINT_BIT_OFFSET + GLINT_BIT_LENGTH; + private static final int TOTAL_BIT_LENGTH = SHADE_MODE_BIT_OFFSET + SHADE_MODE_BIT_LENGTH; private static final int CULL_MASK = bitMask(CULL_BIT_LENGTH, CULL_BIT_OFFSET); private static final int LIGHT_MASK = bitMask(LIGHT_BIT_LENGTH, LIGHT_BIT_OFFSET); private static final int NORMALS_MASK = bitMask(NORMALS_BIT_LENGTH, NORMALS_BIT_OFFSET); private static final int GEOMETRY_MASK = bitMask(GEOMETRY_BIT_LENGTH, GEOMETRY_BIT_OFFSET); - private static final int MATERIAL_MASK = bitMask(MATERIAL_BIT_LENGTH, MATERIAL_BIT_OFFSET); + private static final int RENDER_LAYER_MASK = bitMask(RENDER_LAYER_BIT_LENGTH, RENDER_LAYER_BIT_OFFSET); + private static final int EMISSIVE_MASK = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); + private static final int DIFFUSE_MASK = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); + private static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); + private static final int GLINT_MASK = bitMask(GLINT_BIT_LENGTH, GLINT_BIT_OFFSET); + private static final int SHADE_MODE_MASK = bitMask(SHADE_MODE_BIT_LENGTH, SHADE_MODE_BIT_OFFSET); static { Preconditions.checkArgument(TOTAL_BIT_LENGTH <= 32, "Indigo header encoding bit count (%s) exceeds integer bit length)", TOTAL_STRIDE); } - public static int bitMask(int bitLength, int bitOffset) { + private static int bitMask(int bitLength, int bitOffset) { return ((1 << bitLength) - 1) << bitOffset; } @@ -142,11 +169,55 @@ static int geometryFlags(int bits, int geometryFlags) { return (bits & ~GEOMETRY_MASK) | ((geometryFlags << GEOMETRY_BIT_OFFSET) & GEOMETRY_MASK); } - static RenderMaterialImpl material(int bits) { - return RenderMaterialImpl.byIndex((bits & MATERIAL_MASK) >>> MATERIAL_BIT_OFFSET); + @Nullable + static ChunkSectionLayer renderLayer(int bits) { + return NULLABLE_BLOCK_RENDER_LAYERS[(bits & RENDER_LAYER_MASK) >>> RENDER_LAYER_BIT_OFFSET]; + } + + static int renderLayer(int bits, @Nullable ChunkSectionLayer renderLayer) { + int index = renderLayer == null ? NULL_RENDER_LAYER_INDEX : renderLayer.ordinal(); + return (bits & ~RENDER_LAYER_MASK) | (index << RENDER_LAYER_BIT_OFFSET); + } + + static boolean emissive(int bits) { + return (bits & EMISSIVE_MASK) != 0; + } + + static int emissive(int bits, boolean emissive) { + return emissive ? (bits | EMISSIVE_MASK) : (bits & ~EMISSIVE_MASK); + } + + static boolean diffuseShade(int bits) { + return (bits & DIFFUSE_MASK) != 0; + } + + static int diffuseShade(int bits, boolean shade) { + return shade ? (bits | DIFFUSE_MASK) : (bits & ~DIFFUSE_MASK); + } + + static TriState ambientOcclusion(int bits) { + return TRI_STATES[(bits & AO_MASK) >>> AO_BIT_OFFSET]; + } + + static int ambientOcclusion(int bits, TriState ao) { + return (bits & ~AO_MASK) | (ao.ordinal() << AO_BIT_OFFSET); + } + + @Nullable + static ItemStackRenderState.FoilType glint(int bits) { + return NULLABLE_GLINTS[(bits & GLINT_MASK) >>> GLINT_BIT_OFFSET]; + } + + static int glint(int bits, @Nullable ItemStackRenderState.FoilType glint) { + int index = glint == null ? NULL_GLINT_INDEX : glint.ordinal(); + return (bits & ~GLINT_MASK) | (index << GLINT_BIT_OFFSET); + } + + static ShadeMode shadeMode(int bits) { + return SHADE_MODES[(bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET]; } - static int material(int bits, RenderMaterialImpl material) { - return (bits & ~MATERIAL_MASK) | (material.index() << MATERIAL_BIT_OFFSET); + static int shadeMode(int bits, ShadeMode mode) { + return (bits & ~SHADE_MODE_MASK) | (mode.ordinal() << SHADE_MODE_BIT_OFFSET); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java index 38ac8c8a1d..6a2dd65381 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java @@ -1,17 +1,6 @@ package net.vulkanmod.render.chunk.build.frapi.mesh; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.impl.renderer.VanillaModelEncoder; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; - -import java.util.function.Predicate; -import java.util.function.Supplier; public interface ExtendedQuadEmitter { @@ -19,11 +8,11 @@ static ExtendedQuadEmitter of(QuadEmitter quadEmitter) { return (ExtendedQuadEmitter) quadEmitter; } - default void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { - VanillaModelEncoder.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); - } - - default void emitItemQuads(QuadEmitter emitter,BakedModel model, BlockState state, Supplier randomSupplier) { - VanillaModelEncoder.emitItemQuads(emitter, model, state, randomSupplier); - } +// default void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { +// VanillaModelEncoder.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); +// } +// +// default void emitItemQuads(QuadEmitter emitter,BakedModel model, BlockState state, Supplier randomSupplier) { +// VanillaModelEncoder.emitItemQuads(emitter, model, state, randomSupplier); +// } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 7b27594839..43e6c47ae3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -17,22 +17,25 @@ package net.vulkanmod.render.chunk.build.frapi.mesh; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.fabricmc.fabric.api.renderer.v1.mesh.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.item.ItemStackRenderState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import net.vulkanmod.render.model.quad.ModelQuadView; import org.jetbrains.annotations.Nullable; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadTransform; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; import net.vulkanmod.render.chunk.build.frapi.helper.TextureHelper; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; +import java.util.Objects; + import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.*; /** @@ -63,7 +66,11 @@ protected void emitDirectly() { // Apply non-zero defaults quad.color(-1, -1, -1, -1); quad.cullFace(null); - quad.material(VulkanModRenderer.STANDARD_MATERIAL); + quad.renderLayer(null); + quad.diffuseShade(true); + quad.ambientOcclusion(TriState.DEFAULT); + quad.glint(null); + quad.tintIndex(-1); quad.tintIndex(-1); } @@ -154,6 +161,12 @@ public final void populateMissingNormals() { normalFlags(0b1111); } + @Override + public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { + nominalFace = face; + return this; + } + @Override public final MutableQuadViewImpl cullFace(@Nullable Direction face) { data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(data[baseIndex + HEADER_BITS], face); @@ -162,14 +175,40 @@ public final MutableQuadViewImpl cullFace(@Nullable Direction face) { } @Override - public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { - nominalFace = face; + public MutableQuadViewImpl renderLayer(@Nullable ChunkSectionLayer renderLayer) { + data[baseIndex + HEADER_BITS] = EncodingFormat.renderLayer(data[baseIndex + HEADER_BITS], renderLayer); + return this; + } + + @Override + public MutableQuadViewImpl emissive(boolean emissive) { + data[baseIndex + HEADER_BITS] = EncodingFormat.emissive(data[baseIndex + HEADER_BITS], emissive); + return this; + } + + @Override + public MutableQuadViewImpl diffuseShade(boolean shade) { + data[baseIndex + HEADER_BITS] = EncodingFormat.diffuseShade(data[baseIndex + HEADER_BITS], shade); + return this; + } + + @Override + public MutableQuadViewImpl ambientOcclusion(TriState ao) { + Objects.requireNonNull(ao, "ambient occlusion TriState may not be null"); + data[baseIndex + HEADER_BITS] = EncodingFormat.ambientOcclusion(data[baseIndex + HEADER_BITS], ao); return this; } @Override - public final MutableQuadViewImpl material(RenderMaterial material) { - data[baseIndex + HEADER_BITS] = EncodingFormat.material(data[baseIndex + HEADER_BITS], (RenderMaterialImpl) material); + public MutableQuadViewImpl glint(@Nullable ItemStackRenderState.FoilType glint) { + data[baseIndex + HEADER_BITS] = EncodingFormat.glint(data[baseIndex + HEADER_BITS], glint); + return this; + } + + @Override + public MutableQuadViewImpl shadeMode(ShadeMode mode) { + Objects.requireNonNull(mode, "ShadeMode may not be null"); + data[baseIndex + HEADER_BITS] = EncodingFormat.shadeMode(data[baseIndex + HEADER_BITS], mode); return this; } @@ -204,32 +243,38 @@ public final MutableQuadViewImpl fromVanilla(int[] quadData, int startIndex) { System.arraycopy(quadData, startIndex, data, baseIndex + HEADER_STRIDE, VANILLA_QUAD_STRIDE); isGeometryInvalid = true; + int normalFlags = 0; int colorIndex = baseIndex + VERTEX_COLOR; + int normalIndex = baseIndex + VERTEX_NORMAL; for (int i = 0; i < 4; i++) { data[colorIndex] = ColorHelper.fromVanillaColor(data[colorIndex]); + + // Set normal flag if normal is not zero, ignoring W component + if ((data[normalIndex] & 0xFFFFFF) != 0) { + normalFlags |= 1 << i; + } + colorIndex += VERTEX_STRIDE; + normalIndex += VERTEX_STRIDE; } + normalFlags(normalFlags); return this; } @Override - public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial material, @Nullable Direction cullFace) { - fromVanilla(quad.getVertices(), 0); - data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); - nominalFace(quad.getDirection()); - tintIndex(quad.getTintIndex()); - - if (!quad.isShade()) { - material = RenderMaterialImpl.setDisableDiffuse((RenderMaterialImpl) material, true); - } + public final MutableQuadViewImpl fromBakedQuad(BakedQuad quad) { + fromVanilla(quad.vertices(), 0); +// data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); + nominalFace(quad.direction()); + diffuseShade(quad.shade()); + tintIndex(quad.tintIndex()); - material(material); - tag(0); +// tag(0); // Copy data from BakedQuad instead of calculating properties - ModelQuadView quadView = (ModelQuadView) quad; + ModelQuadView quadView = (ModelQuadView) (Object) quad; int normal = quadView.getNormal(); data[baseIndex + HEADER_FACE_NORMAL] = normal; NormalHelper.unpackNormalTo(normal, faceNormal); @@ -241,7 +286,7 @@ public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial mate this.facing = quadView.getQuadFacing(); this.isGeometryInvalid = false; - int lightEmission = quad.getLightEmission(); + int lightEmission = quad.lightEmission(); if (lightEmission > 0) { for (int i = 0; i < 4; i++) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java index d6e63b13ba..723e80792b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java @@ -32,6 +32,10 @@ import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Y; import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Z; +import net.fabricmc.fabric.api.renderer.v1.mesh.ShadeMode; +import net.fabricmc.fabric.api.util.TriState; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.item.ItemStackRenderState; import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.model.quad.ModelQuadFlags; import net.vulkanmod.render.model.quad.ModelQuadView; @@ -43,7 +47,6 @@ import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; import net.minecraft.core.Direction; /** @@ -100,10 +103,6 @@ public int geometryFlags() { return EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS]); } - public boolean hasShade() { - return !material().disableDiffuse(); - } - @Override public float x(int vertexIndex) { return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X]); @@ -220,12 +219,6 @@ public final Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { } } - @Override - @Nullable - public final Direction cullFace() { - return EncodingFormat.cullFace(data[baseIndex + HEADER_BITS]); - } - @Override @NotNull public final Direction lightFace() { @@ -251,8 +244,41 @@ public final Vector3f faceNormal() { } @Override - public final RenderMaterialImpl material() { - return EncodingFormat.material(data[baseIndex + HEADER_BITS]); + @Nullable + public final Direction cullFace() { + return EncodingFormat.cullFace(data[baseIndex + HEADER_BITS]); + } + + @Override + @Nullable + public ChunkSectionLayer renderLayer() { + return EncodingFormat.renderLayer(data[baseIndex + HEADER_BITS]); + } + + @Override + public boolean emissive() { + return EncodingFormat.emissive(data[baseIndex + HEADER_BITS]); + } + + @Override + public boolean diffuseShade() { + return EncodingFormat.diffuseShade(data[baseIndex + HEADER_BITS]); + } + + @Override + public TriState ambientOcclusion() { + return EncodingFormat.ambientOcclusion(data[baseIndex + HEADER_BITS]); + } + + @Override + @Nullable + public ItemStackRenderState.FoilType glint() { + return EncodingFormat.glint(data[baseIndex + HEADER_BITS]); + } + + @Override + public ShadeMode shadeMode() { + return EncodingFormat.shadeMode(data[baseIndex + HEADER_BITS]); } @Override diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java index 5fc917a3dd..9750c2f471 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java @@ -1,5 +1,6 @@ package net.vulkanmod.render.chunk.build.frapi.render; +import com.mojang.blaze3d.vertex.VertexConsumer; import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; import net.fabricmc.fabric.api.renderer.v1.Renderer; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; @@ -7,8 +8,11 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BlockModelPart; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.BlockGetter; @@ -21,9 +25,6 @@ import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import org.jetbrains.annotations.Nullable; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; @@ -38,8 +39,6 @@ public abstract class AbstractBlockRenderContext extends AbstractRenderContext { private static final Renderer RENDERER = VulkanModRenderer.INSTANCE; - protected static final RenderMaterial STANDARD_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).find(); - protected static final RenderMaterial NO_AO_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).ambientOcclusion(TriState.FALSE).find(); protected final BlockColorRegistry blockColorRegistry; @@ -54,20 +53,21 @@ public void emitDirectly() { renderQuad(this); } - @Override - public void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, - Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { - if (this.hasTransform) { - super.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); - } else { - AbstractBlockRenderContext.this.emitVanillaBlockQuads(model, state, randomSupplier, cullTest); - } - } +// @Override +// public void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, +// Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { +// if (this.hasTransform) { +// super.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); +// } else { +// AbstractBlockRenderContext.this.emitVanillaBlockQuads(model, state, randomSupplier, cullTest); +// } +// } }; protected BlockState blockState; protected BlockPos blockPos; protected BlockPos.MutableBlockPos tempPos = new BlockPos.MutableBlockPos(); + protected ChunkSectionLayer defaultLayer; protected BlockAndTintGetter renderRegion; @@ -83,14 +83,7 @@ protected void rehash(int i) { protected boolean useAO; protected boolean defaultAO; - protected long seed; protected RandomSource random; - public final Supplier randomSupplier = () -> { - long seed = this.seed; - - random.setSeed(seed); - return random; - }; protected boolean enableCulling = true; protected int cullCompletionFlags; @@ -116,6 +109,7 @@ public void prepareForWorld(BlockAndTintGetter blockView, boolean enableCulling) public void prepareForBlock(BlockState blockState, BlockPos blockPos, boolean modelAo) { this.blockPos = blockPos; this.blockState = blockState; + this.defaultLayer = ItemBlockRenderTypes.getChunkRenderType(blockState); this.useAO = Minecraft.useAmbientOcclusion(); this.defaultAO = this.useAO && modelAo && blockState.getLightEmission() == 0; @@ -204,6 +198,8 @@ protected void bufferQuad(MutableQuadViewImpl quadView) { this.renderQuad(quadView); } + protected abstract VertexConsumer getVertexConsumer(ChunkSectionLayer layer); + private void renderQuad(MutableQuadViewImpl quad) { if (isFaceCulled(quad.cullFace())) { return; @@ -238,7 +234,7 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, QuadLightData data = this.quadLightData; // TODO: enhanced AO - lightPipeline.calculate(quad, this.blockPos, data, quad.cullFace(), quad.lightFace(), quad.hasShade()); + lightPipeline.calculate(quad, this.blockPos, data, quad.cullFace(), quad.lightFace(), quad.diffuseShade()); if (emissive) { for (int i = 0; i < 4; i++) { @@ -255,9 +251,13 @@ protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, } } - public void emitVanillaBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, Predicate cullTest) { + public ChunkSectionLayer effectiveRenderLayer(@Nullable ChunkSectionLayer quadRenderLayer) { + return quadRenderLayer == null ? defaultLayer : quadRenderLayer; + } + + public void emitVanillaBlockQuads(BlockStateModel model, @Nullable BlockState state, Supplier randomSupplier, Predicate cullTest) { MutableQuadViewImpl quad = this.editorQuad; - final RenderMaterial defaultMaterial = model.useAmbientOcclusion() ? STANDARD_MATERIAL : NO_AO_MATERIAL; +// final RenderMaterial defaultMaterial = state.getLightEmission() == 0 ? STANDARD_MATERIAL : NO_AO_MATERIAL; for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { final Direction cullFace = ModelHelper.faceFromIndex(i); @@ -267,15 +267,11 @@ public void emitVanillaBlockQuads(BakedModel model, @Nullable BlockState state, continue; } - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - quad.fromVanilla(q, defaultMaterial, cullFace); + final List parts = ((BlockStateModel) this).collectParts(random); + final int partCount = parts.size(); - this.endRenderQuad(quad); + for (int j = 0; j < partCount; j++) { + parts.get(j).emitQuads(quad, cullTest); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java index c3d47270f8..d983218761 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java @@ -16,8 +16,10 @@ package net.vulkanmod.render.chunk.build.frapi.render; +import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -26,14 +28,28 @@ public abstract class AbstractRenderContext { + private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { + { + data = new int[EncodingFormat.TOTAL_STRIDE]; + clear(); + } + + @Override + protected void emitDirectly() { + bufferQuad(this); + } + }; + private final Vector4f posVec = new Vector4f(); private final Vector3f normalVec = new Vector3f(); - protected Matrix4f matrix; - protected Matrix3f normalMatrix; + protected PoseStack.Pose matrices; protected int overlay; - protected abstract QuadEmitter getEmitter(); + protected QuadEmitter getEmitter() { + editorQuad.clear(); + return editorQuad; + } protected abstract void bufferQuad(MutableQuadViewImpl quadView); @@ -41,32 +57,26 @@ public abstract class AbstractRenderContext { protected void bufferQuad(MutableQuadViewImpl quad, VertexConsumer vertexConsumer) { final Vector4f posVec = this.posVec; final Vector3f normalVec = this.normalVec; + final PoseStack.Pose matrices = this.matrices; + final Matrix4f posMatrix = matrices.pose(); final boolean useNormals = quad.hasVertexNormals(); if (useNormals) { quad.populateMissingNormals(); } else { - normalVec.set(quad.faceNormal()); - normalVec.mul(normalMatrix); + matrices.transformNormal(quad.faceNormal(), normalVec); } for (int i = 0; i < 4; i++) { posVec.set(quad.x(i), quad.y(i), quad.z(i), 1.0f); - posVec.mul(matrix); - vertexConsumer.addVertex(posVec.x(), posVec.y(), posVec.z()); - - final int color = quad.color(i); - vertexConsumer.setColor(color); - vertexConsumer.setUv(quad.u(i), quad.v(i)); - vertexConsumer.setOverlay(overlay); - vertexConsumer.setLight(quad.lightmap(i)); + posVec.mul(posMatrix); if (useNormals) { quad.copyNormal(i, normalVec); - normalVec.mul(normalMatrix); + matrices.transformNormal(normalVec, normalVec); } - vertexConsumer.setNormal(normalVec.x(), normalVec.y(), normalVec.z()); + vertexConsumer.addVertex(posVec.x(), posVec.y(), posVec.z(), quad.color(i), quad.u(i), quad.v(i), overlay, quad.lightmap(i), normalVec.x(), normalVec.y(), normalVec.z()); } } } \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java index 1f75c1f437..872671b4b4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java @@ -1,53 +1,35 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package net.vulkanmod.render.chunk.build.frapi.render; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import net.fabricmc.fabric.api.renderer.v1.mesh.ShadeMode; +import net.fabricmc.fabric.api.renderer.v1.render.BlockVertexConsumerProvider; import net.fabricmc.fabric.api.util.TriState; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.vulkanmod.Initializer; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; import net.vulkanmod.render.chunk.build.light.LightMode; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.ArrayLightDataCache; -import net.vulkanmod.render.chunk.build.light.data.QuadLightData; import net.vulkanmod.render.chunk.build.light.flat.FlatLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.NewSmoothLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.SmoothLightPipeline; -import org.joml.Vector3f; -import org.joml.Vector4f; /** * Context for non-terrain block rendering. */ public class BlockRenderContext extends AbstractBlockRenderContext { - private VertexConsumer vertexConsumer; + public static final ThreadLocal POOL = ThreadLocal.withInitial(BlockRenderContext::new); + + private BlockVertexConsumerProvider vertexConsumers; + private ChunkSectionLayer defaultRenderLayer; private final ArrayLightDataCache lightDataCache = new ArrayLightDataCache(); @@ -63,37 +45,44 @@ public BlockRenderContext() { } this.setupLightPipelines(flatLightPipeline, smoothLightPipeline); + + random = RandomSource.create(); } - public void render(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrixStack, VertexConsumer buffer, boolean cull, RandomSource random, long seed, int overlay) { + public void render(BlockAndTintGetter blockView, BlockStateModel model, BlockState state, BlockPos pos, PoseStack matrixStack, BlockVertexConsumerProvider buffers, boolean cull, long seed, int overlay) { Vec3 offset = state.getOffset(pos); matrixStack.translate(offset.x, offset.y, offset.z); this.blockPos = pos; - this.vertexConsumer = buffer; - this.matrix = matrixStack.last().pose(); - this.normalMatrix = matrixStack.last().normal(); + this.vertexConsumers = buffers; + this.defaultRenderLayer = ItemBlockRenderTypes.getChunkRenderType(state); + this.matrices = matrixStack.last(); this.overlay = overlay; - - this.random = random; - this.seed = seed; + this.random.setSeed(seed); this.lightDataCache.reset(blockView, pos); this.prepareForWorld(blockView, cull); - this.prepareForBlock(state, pos, model.useAmbientOcclusion()); + this.prepareForBlock(state, pos, state.getLightEmission() == 0); + + model.emitQuads(getEmitter(), blockView, pos, state, random, this::isFaceCulled); - model.emitBlockQuads(getEmitter(), blockView, state, pos, this.randomSupplier, this::isFaceCulled); + this.vertexConsumers = null; + } - this.vertexConsumer = null; + @Override + protected VertexConsumer getVertexConsumer(ChunkSectionLayer layer) { + return vertexConsumers.getBuffer(layer); } protected void endRenderQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final TriState aoMode = mat.ambientOcclusion(); + final TriState aoMode = quad.ambientOcclusion(); final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); - final boolean emissive = mat.emissive(); - final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; + final boolean emissive = quad.emissive(); + final boolean vanillaShade = quad.shadeMode() == ShadeMode.VANILLA; + final ChunkSectionLayer quadRenderLayer = quad.renderLayer(); + final ChunkSectionLayer renderLayer = quadRenderLayer == null ? defaultRenderLayer : quadRenderLayer; + final VertexConsumer vertexConsumer = getVertexConsumer(renderLayer); LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index b063874df0..e206865104 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -1,216 +1,216 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.render; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.math.MatrixUtil; - -import java.util.Arrays; -import java.util.function.Supplier; - -import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; -import net.minecraft.client.renderer.item.ItemStackRenderState; -import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.Sheets; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.level.block.state.BlockState; -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; - -import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; - -/** - * The render context used for item rendering. - */ -@SuppressWarnings("removal") -public class ItemRenderContext extends AbstractRenderContext { - /** Value vanilla uses for item rendering. The only sensible choice, of course. */ - private static final long ITEM_RANDOM_SEED = 42L; - private static final int GLINT_COUNT = ItemStackRenderState.FoilType.values().length; - - private final RandomSource random = RandomSource.create(); - private final Supplier randomSupplier = () -> { - random.setSeed(ITEM_RANDOM_SEED); - return random; - }; - - private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { - { - data = new int[EncodingFormat.TOTAL_STRIDE]; - clear(); - } - - @Override - public void emitDirectly() { - bufferQuad(this); - } - - @Override - public void emitItemQuads(QuadEmitter emitter, BakedModel model, BlockState state, - Supplier randomSupplier) { - super.emitItemQuads(emitter, model, state, randomSupplier); - } - }; - - private ItemDisplayContext transformMode; - private PoseStack matrixStack; - private MultiBufferSource vertexConsumerProvider; - private int lightmap; - private int[] tints; - - private RenderType defaultLayer; - private ItemStackRenderState.FoilType defaultGlint; - - private PoseStack.Pose specialGlintEntry; - private final VertexConsumer[] vertexConsumerCache = new VertexConsumer[3 * GLINT_COUNT]; - - public ItemRenderContext() { - } - - public QuadEmitter getEmitter() { - editorQuad.clear(); - return editorQuad; - } - - public void renderModel(ItemDisplayContext transformMode, PoseStack matrixStack, MultiBufferSource bufferSource, int lightmap, int overlay, int[] tints, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType) { - this.transformMode = transformMode; - this.matrixStack = matrixStack; - this.vertexConsumerProvider = bufferSource; - this.lightmap = lightmap; - this.overlay = overlay; - this.tints = tints; - - defaultLayer = renderType; - defaultGlint = foilType; - - matrix = matrixStack.last().pose(); - normalMatrix = matrixStack.last().normal(); - - model.emitItemQuads(getEmitter(), randomSupplier); - - this.matrixStack = null; - this.vertexConsumerProvider = null; - this.tints = null; - - specialGlintEntry = null; - Arrays.fill(vertexConsumerCache, null); - } - - @Override - protected void bufferQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final boolean emissive = mat.emissive(); - final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glintMode()); - - tintQuad(quad); - shadeQuad(quad, emissive); - bufferQuad(quad, vertexConsumer); - } - - private void tintQuad(MutableQuadViewImpl quad) { - int tintIndex = quad.tintIndex(); - - if (tintIndex != -1 && tintIndex < tints.length) { - final int tint = tints[tintIndex]; - - for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyColor(tint, quad.color(i))); - } - } - } - - private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { - if (emissive) { - for (int i = 0; i < 4; i++) { - quad.lightmap(i, LightTexture.FULL_BRIGHT); - } - } else { - final int lightmap = this.lightmap; - - for (int i = 0; i < 4; i++) { - quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); - } - } - } - - private VertexConsumer getVertexConsumer(BlendMode blendMode, GlintMode glintMode) { - RenderType layer; - ItemStackRenderState.FoilType glint; - - if (blendMode == BlendMode.DEFAULT) { - layer = defaultLayer; - } else { - layer = blendMode == BlendMode.TRANSLUCENT ? Sheets.translucentItemSheet() : Sheets.cutoutBlockSheet(); - } - - if (glintMode == GlintMode.DEFAULT) { - glint = defaultGlint; - } else { - glint = glintMode.glint; - } - - int cacheIndex; - - if (layer == Sheets.translucentItemSheet()) { - cacheIndex = 0; - } else if (layer == Sheets.cutoutBlockSheet()) { - cacheIndex = GLINT_COUNT; - } else { - cacheIndex = 2 * GLINT_COUNT; - } - - cacheIndex += glint.ordinal(); - VertexConsumer vertexConsumer = vertexConsumerCache[cacheIndex]; - - if (vertexConsumer == null) { - vertexConsumer = createVertexConsumer(layer, glint); - vertexConsumerCache[cacheIndex] = vertexConsumer; - } - - return vertexConsumer; - } - - private VertexConsumer createVertexConsumer(RenderType layer, ItemStackRenderState.FoilType glint) { - if (glint == ItemStackRenderState.FoilType.SPECIAL) { - if (specialGlintEntry == null) { - specialGlintEntry = matrixStack.last().copy(); - - if (transformMode == ItemDisplayContext.GUI) { - MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.5F); - } else if (transformMode.firstPerson()) { - MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.75F); - } - } - - return ItemRendererAccessor.getCompassFoilBuffer(vertexConsumerProvider, layer, specialGlintEntry); - } - - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint != ItemStackRenderState.FoilType.NONE); - } - -} +// TODO +///* +// * Copyright (c) 2016, 2017, 2018, 2019 FabricMC +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +// +//package net.vulkanmod.render.chunk.build.frapi.render; +// +//import com.mojang.blaze3d.vertex.PoseStack; +//import com.mojang.blaze3d.vertex.VertexConsumer; +//import com.mojang.math.MatrixUtil; +// +//import java.util.Arrays; +//import java.util.function.Supplier; +// +//import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; +//import net.minecraft.client.renderer.item.ItemStackRenderState; +//import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; +//import net.minecraft.client.renderer.LightTexture; +//import net.minecraft.client.renderer.MultiBufferSource; +//import net.minecraft.client.renderer.RenderType; +//import net.minecraft.client.renderer.Sheets; +//import net.minecraft.client.renderer.entity.ItemRenderer; +//import net.minecraft.util.RandomSource; +//import net.minecraft.world.item.ItemDisplayContext; +//import net.minecraft.world.level.block.state.BlockState; +//import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +//import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +//import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +//import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +//import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; +//import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +// +//import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; +// +///** +// * The render context used for item rendering. +// */ +//@SuppressWarnings("removal") +//public class ItemRenderContext extends AbstractRenderContext { +// /** Value vanilla uses for item rendering. The only sensible choice, of course. */ +// private static final long ITEM_RANDOM_SEED = 42L; +// private static final int GLINT_COUNT = ItemStackRenderState.FoilType.values().length; +// +// private final RandomSource random = RandomSource.create(); +// private final Supplier randomSupplier = () -> { +// random.setSeed(ITEM_RANDOM_SEED); +// return random; +// }; +// +// private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { +// { +// data = new int[EncodingFormat.TOTAL_STRIDE]; +// clear(); +// } +// +// @Override +// public void emitDirectly() { +// bufferQuad(this); +// } +// +// @Override +// public void emitItemQuads(QuadEmitter emitter, BakedModel model, BlockState state, +// Supplier randomSupplier) { +// super.emitItemQuads(emitter, model, state, randomSupplier); +// } +// }; +// +// private ItemDisplayContext transformMode; +// private PoseStack matrixStack; +// private MultiBufferSource vertexConsumerProvider; +// private int lightmap; +// private int[] tints; +// +// private RenderType defaultLayer; +// private ItemStackRenderState.FoilType defaultGlint; +// +// private PoseStack.Pose specialGlintEntry; +// private final VertexConsumer[] vertexConsumerCache = new VertexConsumer[3 * GLINT_COUNT]; +// +// public ItemRenderContext() { +// } +// +// public QuadEmitter getEmitter() { +// editorQuad.clear(); +// return editorQuad; +// } +// +// public void renderModel(ItemDisplayContext transformMode, PoseStack matrixStack, MultiBufferSource bufferSource, int lightmap, int overlay, int[] tints, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType) { +// this.transformMode = transformMode; +// this.matrixStack = matrixStack; +// this.vertexConsumerProvider = bufferSource; +// this.lightmap = lightmap; +// this.overlay = overlay; +// this.tints = tints; +// +// defaultLayer = renderType; +// defaultGlint = foilType; +// +// matrix = matrixStack.last().pose(); +// normalMatrix = matrixStack.last().normal(); +// +// model.emitItemQuads(getEmitter(), randomSupplier); +// +// this.matrixStack = null; +// this.vertexConsumerProvider = null; +// this.tints = null; +// +// specialGlintEntry = null; +// Arrays.fill(vertexConsumerCache, null); +// } +// +// @Override +// protected void bufferQuad(MutableQuadViewImpl quad) { +// final RenderMaterial mat = quad.material(); +// final boolean emissive = mat.emissive(); +// final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glintMode()); +// +// tintQuad(quad); +// shadeQuad(quad, emissive); +// bufferQuad(quad, vertexConsumer); +// } +// +// private void tintQuad(MutableQuadViewImpl quad) { +// int tintIndex = quad.tintIndex(); +// +// if (tintIndex != -1 && tintIndex < tints.length) { +// final int tint = tints[tintIndex]; +// +// for (int i = 0; i < 4; i++) { +// quad.color(i, ColorHelper.multiplyColor(tint, quad.color(i))); +// } +// } +// } +// +// private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { +// if (emissive) { +// for (int i = 0; i < 4; i++) { +// quad.lightmap(i, LightTexture.FULL_BRIGHT); +// } +// } else { +// final int lightmap = this.lightmap; +// +// for (int i = 0; i < 4; i++) { +// quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); +// } +// } +// } +// +// private VertexConsumer getVertexConsumer(BlendMode blendMode, GlintMode glintMode) { +// RenderType layer; +// ItemStackRenderState.FoilType glint; +// +// if (blendMode == BlendMode.DEFAULT) { +// layer = defaultLayer; +// } else { +// layer = blendMode == BlendMode.TRANSLUCENT ? Sheets.translucentItemSheet() : Sheets.cutoutBlockSheet(); +// } +// +// if (glintMode == GlintMode.DEFAULT) { +// glint = defaultGlint; +// } else { +// glint = glintMode.glint; +// } +// +// int cacheIndex; +// +// if (layer == Sheets.translucentItemSheet()) { +// cacheIndex = 0; +// } else if (layer == Sheets.cutoutBlockSheet()) { +// cacheIndex = GLINT_COUNT; +// } else { +// cacheIndex = 2 * GLINT_COUNT; +// } +// +// cacheIndex += glint.ordinal(); +// VertexConsumer vertexConsumer = vertexConsumerCache[cacheIndex]; +// +// if (vertexConsumer == null) { +// vertexConsumer = createVertexConsumer(layer, glint); +// vertexConsumerCache[cacheIndex] = vertexConsumer; +// } +// +// return vertexConsumer; +// } +// +// private VertexConsumer createVertexConsumer(RenderType layer, ItemStackRenderState.FoilType glint) { +// if (glint == ItemStackRenderState.FoilType.SPECIAL) { +// if (specialGlintEntry == null) { +// specialGlintEntry = matrixStack.last().copy(); +// +// if (transformMode == ItemDisplayContext.GUI) { +// MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.5F); +// } else if (transformMode.firstPerson()) { +// MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.75F); +// } +// } +// +// return ItemRendererAccessor.getCompassFoilBuffer(vertexConsumerProvider, layer, specialGlintEntry); +// } +// +// return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint != ItemStackRenderState.FoilType.NONE); +// } +// +//} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/SimpleBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/SimpleBlockRenderContext.java new file mode 100644 index 0000000000..275738cfb8 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/SimpleBlockRenderContext.java @@ -0,0 +1,119 @@ +package net.vulkanmod.render.chunk.build.frapi.render; +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.renderer.v1.render.BlockVertexConsumerProvider; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.core.BlockPos; +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import org.jetbrains.annotations.Nullable; + +public class SimpleBlockRenderContext extends AbstractRenderContext { + public static final ThreadLocal POOL = ThreadLocal.withInitial(SimpleBlockRenderContext::new); + + private final RandomSource random = RandomSource.create(); + + private BlockVertexConsumerProvider vertexConsumers; + private ChunkSectionLayer defaultRenderLayer; + private float red; + private float green; + private float blue; + private int light; + + @Nullable + private ChunkSectionLayer lastRenderLayer; + @Nullable + private VertexConsumer lastVertexConsumer; + + @Override + protected void bufferQuad(MutableQuadViewImpl quad) { + final ChunkSectionLayer quadRenderLayer = quad.renderLayer(); + final ChunkSectionLayer renderLayer = quadRenderLayer == null ? defaultRenderLayer : quadRenderLayer; + final VertexConsumer vertexConsumer; + + if (renderLayer == lastRenderLayer) { + vertexConsumer = lastVertexConsumer; + } else { + lastVertexConsumer = vertexConsumer = vertexConsumers.getBuffer(renderLayer); + lastRenderLayer = renderLayer; + } + + tintQuad(quad); + shadeQuad(quad, quad.emissive()); + bufferQuad(quad, vertexConsumer); + } + + private void tintQuad(MutableQuadViewImpl quad) { + if (quad.tintIndex() != -1) { + final float red = this.red; + final float green = this.green; + final float blue = this.blue; + + for (int i = 0; i < 4; i++) { + quad.color(i, ARGB.scaleRGB(quad.color(i), red, green, blue)); + } + } + } + + private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { + if (emissive) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, LightTexture.FULL_BRIGHT); + } + } else { + final int light = this.light; + + for (int i = 0; i < 4; i++) { + quad.lightmap(i, ColorHelper.maxLight(quad.lightmap(i), light)); + } + } + } + + public void bufferModel(PoseStack.Pose entry, BlockVertexConsumerProvider vertexConsumers, BlockStateModel model, float red, float green, float blue, int light, int overlay, BlockAndTintGetter blockView, BlockPos pos, BlockState state) { + matrices = entry; + this.overlay = overlay; + + this.vertexConsumers = vertexConsumers; + this.defaultRenderLayer = ItemBlockRenderTypes.getChunkRenderType(state); + this.red = Mth.clamp(red, 0, 1); + this.green = Mth.clamp(green, 0, 1); + this.blue = Mth.clamp(blue, 0, 1); + this.light = light; + + random.setSeed(42L); + + model.emitQuads(getEmitter(), blockView, pos, state, random, cullFace -> false); + + matrices = null; + this.vertexConsumers = null; + lastRenderLayer = null; + lastVertexConsumer = null; + } +} + diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java index 3152c48d1f..d2e5327385 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java @@ -108,7 +108,7 @@ protected int compute(int x, int y, int z) { sl = region.getBrightness(LightLayer.SKY, pos); } else { - int light = LevelRenderer.getLightColor(region, state, pos); + int light = LevelRenderer.getLightColor(LevelRenderer.BrightnessGetter.DEFAULT, region, state, pos); bl = LightTexture.block(light); sl = LightTexture.sky(light); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index 06c27945a6..86b2c001d8 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -1,15 +1,17 @@ package net.vulkanmod.render.chunk.build.renderer; -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.renderer.v1.mesh.ShadeMode; import net.fabricmc.fabric.api.util.TriState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.SingleThreadedRandomSource; import net.minecraft.world.phys.Vec3; @@ -54,7 +56,7 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) this.pos = pos; this.blockPos = blockPos; this.blockState = blockState; - this.seed = blockState.getSeed(blockPos); + this.random.setSeed(blockState.getSeed(blockPos)); TerrainRenderType renderType = TerrainRenderType.get(ItemBlockRenderTypes.getChunkRenderType(blockState)); renderType = TerrainRenderType.getRemapped(renderType); @@ -62,25 +64,37 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) this.terrainBuilder = this.resources.builderPack.builder(renderType); this.terrainBuilder.setBlockAttributes(blockState); - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); + BlockStateModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); BlockAndTintGetter renderRegion = this.renderRegion; Vec3 offset = blockState.getOffset(blockPos); pos.add((float) offset.x, (float) offset.y, (float) offset.z); - this.prepareForBlock(blockState, blockPos, model.useAmbientOcclusion()); + // Debug + if (blockState.getBlock() == Blocks.REDSTONE_WALL_TORCH) { + System.nanoTime(); + } + if (blockState.getLightEmission() > 0) { + System.nanoTime(); + } + + this.prepareForBlock(blockState, blockPos, blockState.getLightEmission() == 0); + + model.emitQuads(this.getEmitter(), renderRegion, blockPos, blockState, this.random, this::isFaceCulled); + } - model.emitBlockQuads(this.getEmitter(), renderRegion, blockState, blockPos, this.randomSupplier, this::isFaceCulled); + @Override + protected VertexConsumer getVertexConsumer(ChunkSectionLayer layer) { + return null; } protected void endRenderQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final TriState aoMode = mat.ambientOcclusion(); + final TriState aoMode = quad.ambientOcclusion(); final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); - final boolean emissive = mat.emissive(); - final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; + final boolean emissive = quad.emissive(); + final boolean vanillaShade = quad.shadeMode() == ShadeMode.VANILLA; - TerrainBuilder terrainBuilder = getBufferBuilder(mat.blendMode()); + TerrainBuilder terrainBuilder = getBufferBuilder(quad.renderLayer()); LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; @@ -89,11 +103,11 @@ protected void endRenderQuad(MutableQuadViewImpl quad) { bufferQuad(terrainBuilder, this.pos, quad, this.quadLightData); } - private TerrainBuilder getBufferBuilder(BlendMode blendMode) { - if (blendMode == BlendMode.DEFAULT) { + private TerrainBuilder getBufferBuilder(ChunkSectionLayer layer) { + if (layer == null) { return this.terrainBuilder; } else { - TerrainRenderType renderType = TerrainRenderType.get(blendMode.blockRenderLayer); + TerrainRenderType renderType = TerrainRenderType.get(layer); renderType = TerrainRenderType.getRemapped(renderType); TerrainBuilder bufferBuilder = this.resources.builderPack.builder(renderType); bufferBuilder.setBlockAttributes(this.blockState); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java index cb19f0a8c6..f29acae11f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java @@ -86,7 +86,7 @@ private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Directio } VoxelShape voxelShape = Shapes.box(0.0, 0.0, 0.0, 1.0, h, 1.0); - return Shapes.blockOccudes(voxelShape, occlusionShape, direction); + return Shapes.blockOccludes(voxelShape, occlusionShape, direction); } else { return false; } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java index a3dc33e5f8..0da19e2e18 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java @@ -2,6 +2,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; import net.minecraft.client.renderer.chunk.VisGraph; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.RenderShape; @@ -181,10 +182,10 @@ private TerrainRenderType compactRenderTypes(TerrainRenderType renderType) { } private void handleBlockEntity(CompileResult compileResult, E blockEntity) { - BlockEntityRenderer blockEntityRenderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(blockEntity); + BlockEntityRenderer blockEntityRenderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(blockEntity); if (blockEntityRenderer != null) { compileResult.blockEntities.add(blockEntity); - if (blockEntityRenderer.shouldRenderOffScreen(blockEntity)) { + if (blockEntityRenderer.shouldRenderOffScreen()) { compileResult.globalBlockEntities.add(blockEntity); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java index 84102838f4..64d7026038 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java @@ -12,7 +12,7 @@ public class ThreadBuilderPack { private static Function terrainBuilderConstructor; public static void defaultTerrainBuilderConstructor() { - terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getRenderType(renderType).bufferSize()); + terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getLayer(renderType).bufferSize()); } public static void setTerrainBuilderConstructor(Function constructor) { diff --git a/src/main/java/net/vulkanmod/render/engine/EGlProgram.java b/src/main/java/net/vulkanmod/render/engine/EGlProgram.java new file mode 100644 index 0000000000..9bc7905d99 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/EGlProgram.java @@ -0,0 +1,87 @@ +package net.vulkanmod.render.engine; + +import com.google.common.collect.Sets; +import com.mojang.blaze3d.opengl.*; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.logging.LogUtils; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; + +import java.util.*; + +public class EGlProgram { + private static final Logger LOGGER = LogUtils.getLogger(); + public static Set BUILT_IN_UNIFORMS = Sets.newHashSet("Projection", "Lighting", "Fog", "Globals"); + public static EGlProgram INVALID_PROGRAM = new EGlProgram(-1, "invalid"); + private final Map uniformsByName = new HashMap(); + private final int programId; + private final String debugLabel; + + public EGlProgram(int i, String string) { + this.programId = i; + this.debugLabel = string; + } + + public void setupUniforms(Pipeline pipeline, List uniformDescriptions, List samplers) { + int i = 0; + int j = 0; + + for (RenderPipeline.UniformDescription uniformDescription : uniformDescriptions) { + String name = uniformDescription.name(); + + Uniform uniform = switch (uniformDescription.type()) { + case UNIFORM_BUFFER -> { + UBO ubo = pipeline.getUBO(name); + + if (ubo == null) { + yield null; + } + + int binding = ubo.binding; + yield new Uniform.Ubo(binding); + } + case TEXEL_BUFFER -> { + int binding = i++; + yield new Uniform.Utb(binding, 0, Objects.requireNonNull(uniformDescription.textureFormat())); + } + }; + + this.uniformsByName.put(name, uniform); + } + + for (String samplerName : samplers) { + var imageDescriptor = pipeline.getImageDescriptor(samplerName); + int binding = imageDescriptor.getBinding(); + int imageIdx = VTextureSelector.getTextureIdx(samplerName); + this.uniformsByName.put(samplerName, new Uniform.Sampler(binding, imageIdx)); + } + + } + + @Nullable + public Uniform getUniform(String string) { + RenderSystem.assertOnRenderThread(); + return (Uniform)this.uniformsByName.get(string); + } + + public int getProgramId() { + return this.programId; + } + + public String toString() { + return this.debugLabel; + } + + public String getDebugLabel() { + return this.debugLabel; + } + + public Map getUniforms() { + return this.uniformsByName; + } + +} diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java new file mode 100644 index 0000000000..89f84c42f4 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -0,0 +1,878 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.buffers.GpuFence; +import com.mojang.blaze3d.opengl.*; +import com.mojang.blaze3d.pipeline.BlendFunction; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.platform.DepthTestFunction; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.logging.LogUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.util.ARGB; +import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.interfaces.shader.ExtendedRenderPipeline; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.Synchronization; +import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.framebuffer.Framebuffer; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.queue.GraphicsQueue; +import net.vulkanmod.vulkan.queue.Queue; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.converter.Sampler; +import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.texture.ImageUtil; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.*; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.vulkan.KHRDynamicRendering; +import org.lwjgl.vulkan.VK11; +import org.lwjgl.vulkan.VkCommandBuffer; +import org.slf4j.Logger; + +import java.nio.ByteBuffer; +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.VK10.VK_INDEX_TYPE_UINT16; +import static org.lwjgl.vulkan.VK10.VK_INDEX_TYPE_UINT32; + +public class VkCommandEncoder implements CommandEncoder { + private static final Logger LOGGER = LogUtils.getLogger(); + private final VkGpuDevice device; + + @Nullable + private RenderPipeline lastPipeline; + private boolean inRenderPass; + + @Nullable + private EGlProgram lastProgram; + + private int framebufferId = VkGlFramebuffer.genFramebufferId(); + + protected VkCommandEncoder(VkGpuDevice glDevice) { + this.device = glDevice; + } + + @Override + public RenderPass createRenderPass(Supplier supplier, GpuTextureView gpuTexture, OptionalInt optionalInt) { + return this.createRenderPass(supplier, gpuTexture, optionalInt, null, OptionalDouble.empty()); + } + + @Override + public RenderPass createRenderPass(Supplier supplier, GpuTextureView colorTexture, OptionalInt optionalInt, @Nullable GpuTextureView depthTexture, OptionalDouble optionalDouble) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } else { + if (optionalDouble.isPresent() && depthTexture == null) { + LOGGER.warn("Depth clear value was provided but no depth texture is being used"); + } + + if (Minecraft.getInstance().getMainRenderTarget().getColorTexture() == colorTexture.texture()) { + Renderer.getInstance().getMainPass().rebindMainTarget(); + + int j = 0; + if (optionalInt.isPresent()) { + int k = optionalInt.getAsInt(); + GL11.glClearColor(ARGB.redFloat(k), ARGB.greenFloat(k), ARGB.blueFloat(k), ARGB.alphaFloat(k)); + j |= 16384; + } + + if (depthTexture != null && optionalDouble.isPresent()) { + GL11.glClearDepth(optionalDouble.getAsDouble()); + j |= 256; + } + + if (j != 0) { + GlStateManager._disableScissorTest(); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); + GlStateManager._clear(j); + } + + return new VkRenderPass(this, depthTexture != null); + } + + if (colorTexture.isClosed()) { + throw new IllegalStateException("Color texture is closed"); + } else if (depthTexture != null && depthTexture.isClosed()) { + throw new IllegalStateException("Depth texture is closed"); + } else { + this.inRenderPass = true; + GpuTexture depthTexture1 = depthTexture != null ? depthTexture.texture() : null; + VkFbo fbo = ((VkGpuTexture)colorTexture.texture()).getFbo(depthTexture1); + fbo.bind(); + + int j = 0; + if (optionalInt.isPresent()) { + int k = optionalInt.getAsInt(); + GL11.glClearColor(ARGB.redFloat(k), ARGB.greenFloat(k), ARGB.blueFloat(k), ARGB.alphaFloat(k)); + j |= 16384; + } + + if (depthTexture != null && optionalDouble.isPresent()) { + GL11.glClearDepth(optionalDouble.getAsDouble()); + j |= 256; + } + + if (j != 0) { + GlStateManager._disableScissorTest(); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); + GlStateManager._clear(j); + } + + GlStateManager._viewport(0, 0, colorTexture.getWidth(0), colorTexture.getHeight(0)); + this.lastPipeline = null; + return new VkRenderPass(this, depthTexture != null); + } + } + + } + + @Override + public void clearColorTexture(GpuTexture colorAttachment, int color) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } + else if (Renderer.isRecording()) { + VkGpuTexture vkGpuTexture = (VkGpuTexture) colorAttachment; + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, framebufferId); + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, vkGpuTexture.glId(), 0); + + VkGlFramebuffer.beginRendering(VkGlFramebuffer.getFramebuffer(framebufferId)); + VRenderSystem.setClearColor(ARGB.redFloat(color), ARGB.greenFloat(color), ARGB.blueFloat(color), ARGB.alphaFloat(color)); + Renderer.clearAttachments(16384); + Renderer.getInstance().endRenderPass(); + } + else { + GraphicsQueue graphicsQueue = DeviceManager.getGraphicsQueue(); + var commandBuffer = graphicsQueue.getCommandBuffer(); + VkGpuTexture vkGpuTexture = (VkGpuTexture) colorAttachment; + + VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.framebufferId); + glFramebuffer.setAttachmentTexture(GL30.GL_COLOR_ATTACHMENT0, vkGpuTexture.glId()); + glFramebuffer.create(); + + Framebuffer framebuffer = glFramebuffer.getFramebuffer(); + var renderPass = glFramebuffer.getRenderPass(); + try (MemoryStack stack = stackPush()) { + framebuffer.beginRenderPass(commandBuffer.handle, renderPass, stack); + } + + VRenderSystem.setClearColor(ARGB.redFloat(color), ARGB.greenFloat(color), ARGB.blueFloat(color), ARGB.alphaFloat(color)); + Renderer.clearAttachments(commandBuffer.handle, 16384); + renderPass.endRenderPass(commandBuffer.handle); + + long fence = graphicsQueue.submitCommands(commandBuffer); + Synchronization.waitFence(fence); + } + + } + + @Override + public void clearColorAndDepthTextures(GpuTexture colorAttachment, int clearColor, GpuTexture depthAttachment, double clearDepth) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } + else { + if (Minecraft.getInstance().getMainRenderTarget().getColorTexture() == colorAttachment) { + Renderer.getInstance().getMainPass().rebindMainTarget(); + + VRenderSystem.clearDepth(clearDepth); + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + Renderer.clearAttachments(0x4100); + } + else { + VkFbo fbo = ((VkGpuTexture)colorAttachment).getFbo(depthAttachment); + + fbo.clear = 0x4100; + fbo.clearColor = clearColor; + fbo.clearDepth = (float) clearDepth; + + Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); + if (boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() + && boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) + { + fbo.clearAttachments(); + } + } + } + } + + @Override + public void clearColorAndDepthTextures(GpuTexture colorAttachment, int clearColor, GpuTexture depthAttachment, double clearDepth, int x0, int y0, int width, int height) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } else { + VRenderSystem.clearDepth(clearDepth); + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + + int framebufferHeight = colorAttachment.getHeight(0); + y0 = framebufferHeight - height - y0; + + Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); + if (boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() + && boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) + { + Renderer.clearAttachments(0x4100, x0, y0, width, height); + } + else { + // TODO +// throw new IllegalStateException(); + } + } + } + + @Override + public void clearDepthTexture(GpuTexture depthAttachment, double clearDepth) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } + else { + // depthAttachment is not the target here + VRenderSystem.clearDepth(clearDepth); + Renderer.clearAttachments(256); + } + } + + @Override + public void writeToBuffer(GpuBufferSlice gpuBufferSlice, ByteBuffer byteBuffer) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else { + VkGpuBuffer vkGpuBuffer = (VkGpuBuffer) gpuBufferSlice.buffer(); + if (vkGpuBuffer.closed) { + throw new IllegalStateException("Buffer already closed"); + } + else { + int remaining = byteBuffer.remaining(); + if (remaining + gpuBufferSlice.offset() > vkGpuBuffer.size()) { + throw new IllegalArgumentException( + "Cannot write more data than this buffer can hold (attempting to write " + remaining + " bytes at offset " + gpuBufferSlice.offset() + " to " + gpuBufferSlice.length() + " slice size)" + ); + } else { + vkGpuBuffer.buffer.copyBuffer(byteBuffer, byteBuffer.remaining(), gpuBufferSlice.offset()); + } + } + } + } + + @Override + public GpuBuffer.MappedView mapBuffer(GpuBuffer gpuBuffer, boolean readable, boolean writable) { + return this.mapBuffer(gpuBuffer.slice(), readable, writable); + } + + @Override + public GpuBuffer.MappedView mapBuffer(GpuBufferSlice gpuBufferSlice, boolean readable, boolean writable) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else { + VkGpuBuffer gpuBuffer = (VkGpuBuffer)(gpuBufferSlice.buffer()); + if (gpuBuffer.closed) { + throw new IllegalStateException("Buffer already closed"); + } else if (!readable && !writable) { + throw new IllegalArgumentException("At least read or write must be true"); + } else if (readable && (gpuBuffer.usage() & 1) == 0) { + throw new IllegalStateException("Buffer is not readable"); + } else if (writable && (gpuBuffer.usage() & 2) == 0) { + throw new IllegalStateException("Buffer is not writable"); + } else if (gpuBufferSlice.offset() + gpuBufferSlice.length() > gpuBuffer.size()) { + throw new IllegalArgumentException( + "Cannot map more data than this buffer can hold (attempting to map " + + gpuBufferSlice.length() + + " bytes at offset " + + gpuBufferSlice.offset() + + " from " + + gpuBuffer.size() + + " size buffer)" + ); + } else { + int i = 0; + if (readable) { + i |= 1; + } + + if (writable) { + i |= 34; + } + + ByteBuffer byteBuffer = MemoryUtil.memByteBuffer(gpuBuffer.getBuffer().getDataPtr() + gpuBufferSlice.offset(), gpuBufferSlice.length()); + return new VkGpuBuffer.MappedView(0, byteBuffer); + } + } + } + + public void copyToBuffer(GpuBufferSlice gpuBufferSlice, GpuBufferSlice gpuBufferSlice2) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else { + VkGpuBuffer vkGpuBuffer = (VkGpuBuffer) gpuBufferSlice.buffer(); + if (vkGpuBuffer.closed) { + throw new IllegalStateException("Source buffer already closed"); + } else if ((vkGpuBuffer.usage() & 8) == 0) { + throw new IllegalStateException("Source buffer needs USAGE_COPY_DST to be a destination for a copy"); + } else { + VkGpuBuffer vkGpuBuffer2 = (VkGpuBuffer) gpuBufferSlice2.buffer(); + if (vkGpuBuffer2.closed) { + throw new IllegalStateException("Target buffer already closed"); + } else if ((vkGpuBuffer2.usage() & 8) == 0) { + throw new IllegalStateException("Target buffer needs USAGE_COPY_DST to be a destination for a copy"); + } else if (gpuBufferSlice.length() != gpuBufferSlice2.length()) { + int var6 = gpuBufferSlice.length(); + throw new IllegalArgumentException("Cannot copy from slice of size " + var6 + " to slice of size " + gpuBufferSlice2.length() + ", they must be equal"); + } else if (gpuBufferSlice.offset() + gpuBufferSlice.length() > vkGpuBuffer.size()) { + int var5 = gpuBufferSlice.length(); + throw new IllegalArgumentException("Cannot copy more data than the source buffer holds (attempting to copy " + var5 + " bytes at offset " + gpuBufferSlice.offset() + " from " + vkGpuBuffer.size() + " size buffer)"); + } else if (gpuBufferSlice2.offset() + gpuBufferSlice2.length() > vkGpuBuffer2.size()) { + int var10002 = gpuBufferSlice2.length(); + throw new IllegalArgumentException("Cannot copy more data than the target buffer can hold (attempting to copy " + var10002 + " bytes at offset " + gpuBufferSlice2.offset() + " to " + vkGpuBuffer2.size() + " size buffer)"); + } else { +// this.device.directStateAccess().copyBufferSubData(vkGpuBuffer.handle, vkGpuBuffer2.handle, gpuBufferSlice.offset(), gpuBufferSlice2.offset(), gpuBufferSlice.length()); +// vkGpuBuffer.buffer.copyBuffer(byteBuffer, byteBuffer.remaining(), gpuBufferSlice.offset()); + + // TODO + throw new UnsupportedOperationException(); + } + } + } + } + + @Override + public void writeToTexture(GpuTexture gpuTexture, NativeImage nativeImage) { + int i = gpuTexture.getWidth(0); + int j = gpuTexture.getHeight(0); + if (nativeImage.getWidth() != i || nativeImage.getHeight() != j) { + throw new IllegalArgumentException( + "Cannot replace texture of size " + i + "x" + j + " with image of size " + nativeImage.getWidth() + "x" + nativeImage.getHeight() + ); + } else if (gpuTexture.isClosed()) { + throw new IllegalStateException("Destination texture is closed"); + } else { + this.writeToTexture(gpuTexture, nativeImage, 0, 0, 0, 0, i, j, 0, 0); + } + } + + @Override + public void writeToTexture(GpuTexture gpuTexture, NativeImage nativeImage, int level, int arrayLayer, int xOffset, int yOffset, int width, int height, int unpackSkipPixels, int unpackSkipRows) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else if (level >= 0 && level < gpuTexture.getMipLevels()) { + if (unpackSkipPixels + width > nativeImage.getWidth() || unpackSkipRows + height > nativeImage.getHeight()) { + throw new IllegalArgumentException( + "Copy source (" + + nativeImage.getWidth() + + "x" + + nativeImage.getHeight() + + ") is not large enough to read a rectangle of " + + width + + "x" + + height + + " from " + + unpackSkipPixels + + "x" + + unpackSkipRows + ); + } else if (xOffset + width > gpuTexture.getWidth(level) || yOffset + height > gpuTexture.getHeight(level)) { + throw new IllegalArgumentException( + "Dest texture (" + width + "x" + height + ") is not large enough to write a rectangle of " + width + "x" + height + " at " + xOffset + "x" + yOffset + " (at mip level " + level + ")" + ); + } else if (gpuTexture.isClosed()) { + throw new IllegalStateException("Destination texture is closed"); + } else { + VTextureSelector.setActiveTexture(0); + VTextureSelector.bindTexture(((VkGpuTexture) gpuTexture).getVulkanImage()); + VTextureSelector.uploadSubTexture(level, arrayLayer, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, nativeImage.getWidth(), nativeImage.getPointer()); + } + } else { + throw new IllegalArgumentException("Invalid mipLevel " + level + ", must be >= 0 and < " + gpuTexture.getMipLevels()); + } + } + + @Override + public void writeToTexture(GpuTexture gpuTexture, ByteBuffer byteBuffer, NativeImage.Format format, int level, int j, int xOffset, int yOffset, int width, int height) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else if (level >= 0 && level < gpuTexture.getMipLevels()) { + if (width * height * format.components() > byteBuffer.remaining()) { + throw new IllegalArgumentException( + "Copy would overrun the source buffer (remaining length of " + byteBuffer.remaining() + ", but copy is " + width + "x" + height + " of format " + format + ")" + ); + } else if (xOffset + width > gpuTexture.getWidth(level) || yOffset + height > gpuTexture.getHeight(level)) { + throw new IllegalArgumentException( + "Dest texture (" + + gpuTexture.getWidth(level) + + "x" + + gpuTexture.getHeight(level) + + ") is not large enough to write a rectangle of " + + width + + "x" + + height + + " at " + + xOffset + + "x" + + yOffset + ); + } else if (gpuTexture.isClosed()) { + throw new IllegalStateException("Destination texture is closed"); + } else if ((gpuTexture.usage() & 1) == 0) { + throw new IllegalStateException("Color texture must have USAGE_COPY_DST to be a destination for a write"); + } else if (j >= gpuTexture.getDepthOrLayers()) { + throw new UnsupportedOperationException("Depth or layer is out of range, must be >= 0 and < " + gpuTexture.getDepthOrLayers()); + } + else { + GlStateManager._bindTexture(((VkGpuTexture)gpuTexture).id); + + GlStateManager._pixelStore(3314, width); + GlStateManager._pixelStore(3316, 0); + GlStateManager._pixelStore(3315, 0); + GlStateManager._pixelStore(3317, format.components()); + GlStateManager._texSubImage2D(3553, level, xOffset, yOffset, width, height, GlConst.toGl(format), 5121, byteBuffer); + } + } else { + throw new IllegalArgumentException("Invalid mipLevel, must be >= 0 and < " + gpuTexture.getMipLevels()); + } + } + + @Override + public void copyTextureToBuffer(GpuTexture gpuTexture, GpuBuffer gpuBuffer, int i, Runnable runnable, int j) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else { + this.copyTextureToBuffer(gpuTexture, gpuBuffer, i, runnable, j, 0, 0, gpuTexture.getWidth(j), gpuTexture.getHeight(j)); + } + } + + @Override + public void copyTextureToBuffer(GpuTexture gpuTexture, GpuBuffer gpuBuffer, int dstOffset, Runnable runnable, int mipLevel, int xOffset, int yOffset, int width, int height) { + VkGpuBuffer vkGpuBuffer = (VkGpuBuffer) gpuBuffer; + VkGpuTexture vkGpuTexture = (VkGpuTexture) gpuTexture; + + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else if (mipLevel >= 0 && mipLevel < gpuTexture.getMipLevels()) { + if (gpuTexture.getWidth(mipLevel) * gpuTexture.getHeight(mipLevel) * vkGpuTexture.getVulkanImage().formatSize + dstOffset > gpuBuffer.size()) { + throw new IllegalArgumentException( + "Buffer of size " + + gpuBuffer.size() + + " is not large enough to hold " + + width + + "x" + + height + + " pixels (" + + vkGpuTexture.getVulkanImage().formatSize + + " bytes each) starting from offset " + + dstOffset + ); + } + else if (xOffset + width > gpuTexture.getWidth(mipLevel) || yOffset + height > gpuTexture.getHeight(mipLevel)) { + throw new IllegalArgumentException( + "Copy source texture (" + + gpuTexture.getWidth(mipLevel) + + "x" + + gpuTexture.getHeight(mipLevel) + + ") is not large enough to read a rectangle of " + + width + + "x" + + height + + " from " + + xOffset + + "," + + yOffset + ); + } else if (gpuTexture.isClosed()) { + throw new IllegalStateException("Source texture is closed"); + } else if (gpuBuffer.isClosed()) { + throw new IllegalStateException("Destination buffer is closed"); + } else { + ImageUtil.copyImageToBuffer(vkGpuTexture.getVulkanImage(), vkGpuBuffer.getBuffer(), mipLevel, width, height, xOffset, yOffset, dstOffset, width, height); + + runnable.run(); + } + } else { + throw new IllegalArgumentException("Invalid mipLevel " + mipLevel + ", must be >= 0 and < " + gpuTexture.getMipLevels()); + } + } + + @Override + public void copyTextureToTexture(GpuTexture gpuTexture, GpuTexture gpuTexture2, int mipLevel, int j, int k, int l, int m, int n, int o) { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else if (mipLevel >= 0 && mipLevel < gpuTexture.getMipLevels() && mipLevel < gpuTexture2.getMipLevels()) { + if (j + n > gpuTexture2.getWidth(mipLevel) || k + o > gpuTexture2.getHeight(mipLevel)) { + throw new IllegalArgumentException( + "Dest texture (" + + gpuTexture2.getWidth(mipLevel) + + "x" + + gpuTexture2.getHeight(mipLevel) + + ") is not large enough to write a rectangle of " + + n + + "x" + + o + + " at " + + j + + "x" + + k + ); + } else if (l + n > gpuTexture.getWidth(mipLevel) || m + o > gpuTexture.getHeight(mipLevel)) { + throw new IllegalArgumentException( + "Source texture (" + + gpuTexture.getWidth(mipLevel) + + "x" + + gpuTexture.getHeight(mipLevel) + + ") is not large enough to read a rectangle of " + + n + + "x" + + o + + " at " + + l + + "x" + + m + ); + } else if (gpuTexture.isClosed()) { + throw new IllegalStateException("Source texture is closed"); + } else if (gpuTexture2.isClosed()) { + throw new IllegalStateException("Destination texture is closed"); + } else { + // TODO implement + } + } else { + throw new IllegalArgumentException("Invalid mipLevel " + mipLevel + ", must be >= 0 and < " + gpuTexture.getMipLevels() + " and < " + gpuTexture2.getMipLevels()); + } + } + + @Override + public GpuFence createFence() { + if (this.inRenderPass) { + throw new IllegalStateException("Close the existing render pass before performing additional commands"); + } else { +// throw new UnsupportedOperationException(); + // TODO + return new GpuFence() { + @Override + public void close() { + + } + + @Override + public boolean awaitCompletion(long l) { + return true; + } + }; + } + } + + @Override + public void presentTexture(GpuTextureView gpuTexture) { + throw new UnsupportedOperationException(); + } + + protected void executeDrawMultiple( + VkRenderPass renderPass, + Collection> collection, + @Nullable GpuBuffer gpuBuffer, + @Nullable VertexFormat.IndexType indexType, + Collection collection2, + T object + ) { + if (this.trySetup(renderPass)) { + if (indexType == null) { + indexType = VertexFormat.IndexType.SHORT; + } + + Pipeline pipeline = ExtendedRenderPipeline.of(renderPass.getPipeline()).getPipeline(); + + for (RenderPass.Draw draw : collection) { + VertexFormat.IndexType indexType2 = draw.indexType() == null ? indexType : draw.indexType(); + renderPass.setIndexBuffer(draw.indexBuffer() == null ? gpuBuffer : draw.indexBuffer(), indexType2); + renderPass.setVertexBuffer(draw.slot(), draw.vertexBuffer()); + + if (GlRenderPass.VALIDATION) { + if (renderPass.indexBuffer == null) { + throw new IllegalStateException("Missing index buffer"); + } + + if (renderPass.indexBuffer.isClosed()) { + throw new IllegalStateException("Index buffer has been closed!"); + } + + if (renderPass.vertexBuffers[0] == null) { + throw new IllegalStateException("Missing vertex buffer at slot 0"); + } + + if (renderPass.vertexBuffers[0].isClosed()) { + throw new IllegalStateException("Vertex buffer at slot 0 has been closed!"); + } + } + + BiConsumer biConsumer = draw.uniformUploaderConsumer(); + if (biConsumer != null) { + biConsumer.accept(object, (string, gpuBufferSlice) -> { + EGlProgram glProgram = ExtendedRenderPipeline.of(renderPass.pipeline).getProgram(); + if (glProgram.getUniform(string) instanceof Uniform.Ubo ubo) { + + int blockBinding; + try { + blockBinding = ubo.blockBinding(); + } catch (Throwable var7) { + throw new MatchException(var7.toString(), var7); + } + + // TODO +// GL32.glBindBufferRange(35345, blockBinding, ((GlBuffer)gpuBufferSlice.buffer()).handle, (long)gpuBufferSlice.offset(), (long)gpuBufferSlice.length()); + } + }); + + Renderer.getInstance().uploadAndBindUBOs(pipeline); + } + + this.drawFromBuffers(renderPass, 0, draw.firstIndex(), draw.indexCount(), indexType2, renderPass.pipeline, 1); + } + } + } + + protected void executeDraw(VkRenderPass renderPass, int i, int j, int k, @Nullable VertexFormat.IndexType indexType, int l) { + if (this.trySetup(renderPass)) { + if (GlRenderPass.VALIDATION) { + if (indexType != null) { + if (renderPass.indexBuffer == null) { + throw new IllegalStateException("Missing index buffer"); + } + + if (renderPass.indexBuffer.isClosed()) { + throw new IllegalStateException("Index buffer has been closed!"); + } + } + + if (renderPass.vertexBuffers[0] == null) { + throw new IllegalStateException("Missing vertex buffer at slot 0"); + } + + if (renderPass.vertexBuffers[0].isClosed()) { + throw new IllegalStateException("Vertex buffer at slot 0 has been closed!"); + } + } + + this.drawFromBuffers(renderPass, i, j, k, indexType, renderPass.pipeline, l); + } + } + + public void drawFromBuffers(VkRenderPass renderPass, int vertexOffset, int firstIndex, int vertexCount, + @Nullable VertexFormat.IndexType indexType, RenderPipeline renderPipeline, int instanceCount) + { + if (instanceCount < 1) { + instanceCount = 1; + } + if (vertexOffset < 0) { + vertexOffset = 0; + } + + if (renderPipeline.getVertexFormatMode() == VertexFormat.Mode.TRIANGLES) { + System.nanoTime(); + } + + VkCommandBuffer vkCommandBuffer = Renderer.getCommandBuffer(); + VkGpuBuffer vertexBuffer = (VkGpuBuffer)renderPass.vertexBuffers[0]; + try (MemoryStack stack = stackPush()) { + if (vertexBuffer != null) { + VK11.vkCmdBindVertexBuffers(vkCommandBuffer, 0, stack.longs(vertexBuffer.buffer.getId()), stack.longs(0)); + } + + if (renderPass.indexBuffer != null) { + VkGpuBuffer indexBuffer = (VkGpuBuffer)renderPass.indexBuffer; + + int vkIndexType = switch (indexType) { + case SHORT -> VK_INDEX_TYPE_UINT16; + case INT -> VK_INDEX_TYPE_UINT32; + }; + + VK11.vkCmdBindIndexBuffer(vkCommandBuffer, indexBuffer.buffer.getId(), 0, vkIndexType); + VK11.vkCmdDrawIndexed(vkCommandBuffer, vertexCount, instanceCount, firstIndex, vertexOffset, 0); + } + else { + var autoIndexBuffer = Renderer.getDrawer().getAutoIndexBuffer(renderPipeline.getVertexFormatMode(), vertexCount); + if (autoIndexBuffer != null) { + int indexCount = autoIndexBuffer.getIndexCount(vertexCount); + VK11.vkCmdBindIndexBuffer(vkCommandBuffer, autoIndexBuffer.getIndexBuffer().getId(), 0, autoIndexBuffer.getIndexBuffer().indexType.value); + VK11.vkCmdDrawIndexed(vkCommandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, 0); + } + else { + VK11.vkCmdDraw(vkCommandBuffer, vertexCount, instanceCount, vertexOffset, 0); + } + } + } + } + + public boolean trySetup(VkRenderPass renderPass) { + if (VkRenderPass.VALIDATION) { + if (renderPass.pipeline == null) { + throw new IllegalStateException("Can't draw without a render pipeline"); + } + + for (RenderPipeline.UniformDescription uniformDescription : renderPass.pipeline.getUniforms()) { + Object object = renderPass.uniforms.get(uniformDescription.name()); + if (object == null && !GlProgram.BUILT_IN_UNIFORMS.contains(uniformDescription.name())) { + throw new IllegalStateException("Missing uniform " + uniformDescription.name() + " (should be " + uniformDescription.type() + ")"); + } + } + + } + + applyPipelineState(renderPass.pipeline); + setupUniforms(renderPass); + + if (renderPass.isScissorEnabled()) { + GlStateManager._enableScissorTest(); + GlStateManager._scissorBox( + renderPass.getScissorX(), renderPass.getScissorY(), renderPass.getScissorWidth(), renderPass.getScissorHeight() + ); + } else { + GlStateManager._disableScissorTest(); + } + + return bindPipeline(renderPass.pipeline); + } + + // TODO + public void setupUniforms(VkRenderPass renderPass) { + RenderPipeline renderPipeline = renderPass.pipeline; + EGlProgram glProgram = ExtendedRenderPipeline.of(renderPass.pipeline).getProgram(); + Pipeline pipeline = ExtendedRenderPipeline.of(renderPass.pipeline).getPipeline(); + + for (UBO ubo : pipeline.getBuffers()) { + String uniformName = ubo.name; + Uniform uniform = glProgram.getUniform(uniformName); + + GpuBufferSlice gpuBufferSlice = renderPass.uniforms.get(uniformName); + VkGpuBuffer gpuBuffer = (VkGpuBuffer) gpuBufferSlice.buffer(); + + assert ubo != null; + ubo.setUseGlobalBuffer(false); + ubo.getBufferSlice().set(gpuBuffer.buffer, gpuBufferSlice.offset(), gpuBufferSlice.length()); + } + + for (ImageDescriptor imageDescriptor : pipeline.getImageDescriptors()) { + String uniformName = imageDescriptor.name; + + int samplerIndex; + switch (glProgram.getUniform(uniformName)) { + case Uniform.Sampler(int location, int samplerIndex1): + samplerIndex = samplerIndex1; + break; + case Uniform.Utb( + int location, int samplerIndex1, com.mojang.blaze3d.textures.TextureFormat format, int texture + ): + samplerIndex = samplerIndex1; + break; + case null: + continue; + default: + throw new IllegalStateException("Unexpected value: " + glProgram.getUniform(uniformName)); + } + + VkTextureView textureView = (VkTextureView) renderPass.samplers.get(uniformName); + if (textureView == null) { + break; + } + + GlStateManager._activeTexture(33984 + samplerIndex); + VkGpuTexture gpuTexture = textureView.texture(); + GlStateManager._bindTexture(gpuTexture.id); + + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, 33084, textureView.baseMipLevel()); + GlStateManager._texParameter(GL11.GL_TEXTURE_2D, 33085, textureView.baseMipLevel() + textureView.mipLevels() - 1); + gpuTexture.flushModeChanges(GL11.GL_TEXTURE_2D); + } + + } + + public boolean bindPipeline(RenderPipeline renderPipeline) { + Pipeline pipeline = ExtendedRenderPipeline.of(renderPipeline).getPipeline(); + + if (pipeline == null) { + return false; + } + + Renderer renderer = Renderer.getInstance(); + renderer.bindGraphicsPipeline((GraphicsPipeline) pipeline); +// VTextureSelector.bindShaderTextures(pipeline); + + renderer.uploadAndBindUBOs(pipeline); + + return true; + } + + public void applyPipelineState(RenderPipeline renderPipeline) { + if (this.lastPipeline != renderPipeline) { + this.lastPipeline = renderPipeline; + if (renderPipeline.getDepthTestFunction() != DepthTestFunction.NO_DEPTH_TEST) { + GlStateManager._enableDepthTest(); + GlStateManager._depthFunc(GlConst.toGl(renderPipeline.getDepthTestFunction())); + } else { + GlStateManager._disableDepthTest(); + } + + if (renderPipeline.isCull()) { + GlStateManager._enableCull(); + } else { + GlStateManager._disableCull(); + } + + if (renderPipeline.getBlendFunction().isPresent()) { + GlStateManager._enableBlend(); + BlendFunction blendFunction = renderPipeline.getBlendFunction().get(); + GlStateManager._blendFuncSeparate( + GlConst.toGl(blendFunction.sourceColor()), + GlConst.toGl(blendFunction.destColor()), + GlConst.toGl(blendFunction.sourceAlpha()), + GlConst.toGl(blendFunction.destAlpha()) + ); + } else { + GlStateManager._disableBlend(); + } + + GlStateManager._polygonMode(1032, GlConst.toGl(renderPipeline.getPolygonMode())); + GlStateManager._depthMask(renderPipeline.isWriteDepth()); + GlStateManager._colorMask(renderPipeline.isWriteColor(), renderPipeline.isWriteColor(), renderPipeline.isWriteColor(), renderPipeline.isWriteAlpha()); + if (renderPipeline.getDepthBiasConstant() == 0.0F && renderPipeline.getDepthBiasScaleFactor() == 0.0F) { + GlStateManager._disablePolygonOffset(); + } else { + GlStateManager._polygonOffset(renderPipeline.getDepthBiasScaleFactor(), renderPipeline.getDepthBiasConstant()); + GlStateManager._enablePolygonOffset(); + } + + switch (renderPipeline.getColorLogic()) { + case NONE: + GlStateManager._disableColorLogicOp(); + break; + case OR_REVERSE: + GlStateManager._enableColorLogicOp(); + GlStateManager._logicOp(5387); + } + + VRenderSystem.setPrimitiveTopologyGL(GlConst.toGl(renderPipeline.getVertexFormatMode())); + } + } + + public void finishRenderPass() { + this.inRenderPass = false; + } + + protected VkGpuDevice getDevice() { + return this.device; + } +} diff --git a/src/main/java/net/vulkanmod/render/engine/VkDebugLabel.java b/src/main/java/net/vulkanmod/render/engine/VkDebugLabel.java new file mode 100644 index 0000000000..60ac40491e --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkDebugLabel.java @@ -0,0 +1,40 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.opengl.*; +import com.mojang.logging.LogUtils; +import java.util.Set; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import org.slf4j.Logger; + +@Environment(EnvType.CLIENT) +public class VkDebugLabel { + private static final Logger LOGGER = LogUtils.getLogger(); + + public void applyLabel(VkGpuBuffer glBuffer) { + } + + public void applyLabel(VkGpuTexture glTexture) { + } + + public void applyLabel(GlShaderModule glShaderModule) { + } + + public void applyLabel(GlProgram glProgram) { + } + + public void applyLabel(VertexArrayCache.VertexArray vertexArray) { + } + + public static VkDebugLabel create(boolean bl, Set set) { + return new VkDebugLabel(); + } + + public boolean exists() { + return true; + } + + +} + diff --git a/src/main/java/net/vulkanmod/render/engine/VkFbo.java b/src/main/java/net/vulkanmod/render/engine/VkFbo.java new file mode 100644 index 0000000000..22bb06ac58 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkFbo.java @@ -0,0 +1,67 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.opengl.GlStateManager; +import net.minecraft.util.ARGB; +import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.framebuffer.Framebuffer; +import org.lwjgl.opengl.GL33; +import org.lwjgl.system.MemoryStack; + +import static org.lwjgl.system.MemoryStack.stackPush; + +public class VkFbo { + final int glId; + final VkGpuTexture colorAttachment; + final VkGpuTexture depthAttachment; + + int clear = 0; + int clearColor = 0; + float clearDepth = 0.0f; + + protected VkFbo(VkGpuTexture colorAttachment, VkGpuTexture depthAttachment) { + this.glId = GlStateManager.glGenFramebuffers(); + this.colorAttachment = colorAttachment; + this.depthAttachment = depthAttachment; + + // Direct access + VkGlFramebuffer fbo = VkGlFramebuffer.getFramebuffer(this.glId); + + fbo.setAttachmentTexture(GL33.GL_COLOR_ATTACHMENT0, colorAttachment.id); + if (depthAttachment != null) { + fbo.setAttachmentTexture(GL33.GL_DEPTH_ATTACHMENT, depthAttachment.id); + } + } + + protected void bind() { +// VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.glId); +// VkGlFramebuffer.beginRendering(glFramebuffer); +// +// Framebuffer framebuffer = glFramebuffer.getFramebuffer(); +// try (MemoryStack stack = stackPush()) { +// framebuffer.beginRenderPass(currentCmdBuffer, renderPass, stack); +// } + + VkGlFramebuffer.bindFramebuffer(GL33.GL_FRAMEBUFFER, this.glId); + clearAttachments(); + } + + protected void clearAttachments() { + if (clear != 0) { + VRenderSystem.clearDepth(clearDepth); + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + Renderer.clearAttachments(clear); + + clear = 0; + } + } + + protected void close() { + VkGlFramebuffer.deleteFramebuffer(this.glId); + } + + public boolean needsClear() { + return this.clear != 0; + } +} diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuBuffer.java b/src/main/java/net/vulkanmod/render/engine/VkGpuBuffer.java new file mode 100644 index 0000000000..1c672841e2 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuBuffer.java @@ -0,0 +1,111 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.buffers.GpuBuffer; + +import java.nio.ByteBuffer; +import java.util.function.Supplier; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; +import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import org.jetbrains.annotations.Nullable; + +import static org.lwjgl.vulkan.VK10.*; + +@Environment(EnvType.CLIENT) +public class VkGpuBuffer extends GpuBuffer { + protected boolean closed; + @Nullable protected final Supplier label; + + Buffer buffer; + + protected VkGpuBuffer(VkDebugLabel glDebugLabel, @Nullable Supplier supplier, int usage, int size) { + super(usage, size); + this.label = supplier; + + int vkUsage = 0; + if ((usage & GpuBuffer.USAGE_COPY_SRC) != 0) { + vkUsage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + } + if ((usage & GpuBuffer.USAGE_COPY_DST) != 0) { + vkUsage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; + } + if ((usage & GpuBuffer.USAGE_VERTEX) != 0) { + vkUsage |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + } + if ((usage & GpuBuffer.USAGE_INDEX) != 0) { + vkUsage |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; + } + if ((usage & GpuBuffer.USAGE_UNIFORM) != 0) { + vkUsage |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + } + if ((usage & GpuBuffer.USAGE_UNIFORM_TEXEL_BUFFER) != 0) { + vkUsage |= VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; + } + + boolean mappable = (usage & GpuBuffer.USAGE_MAP_READ) != 0 | + (usage & GpuBuffer.USAGE_MAP_WRITE) != 0 | + (usage & GpuBuffer.USAGE_HINT_CLIENT_STORAGE) != 0; + + MemoryType memoryType = mappable ? MemoryTypes.HOST_MEM : MemoryTypes.GPU_MEM; + + this.buffer = new Buffer(vkUsage, memoryType); + this.buffer.createBuffer(this.size()); + } + + @Override + public boolean isClosed() { + return this.closed; + } + + @Override + public void close() { + if (!this.closed) { + this.closed = true; + + MemoryManager.getInstance().addToFreeable(this.buffer); + } + } + + public Buffer getBuffer() { + return buffer; + } + + public static int bufferUsageToGlEnum(int i) { + boolean stream = (i & 4) != 0; + // Draw + if ((i & 2) != 0) { + return stream ? 35040 : 35044; + } + // Read + else if ((i & 1) != 0) { + return stream ? 35041 : 35045; + } else { + return 35044; + } + } + + @Environment(EnvType.CLIENT) + public static class MappedView implements GpuBuffer.MappedView { + private final int target; + private final ByteBuffer data; + + protected MappedView(int i, ByteBuffer byteBuffer) { + this.target = i; + this.data = byteBuffer; + } + + @Override + public ByteBuffer data() { + return this.data; + } + + @Override + public void close() { +// GlStateManager._glUnmapBuffer(this.target); + } + } +} + diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java new file mode 100644 index 0000000000..6c641decfb --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java @@ -0,0 +1,398 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.opengl.*; +import com.mojang.blaze3d.pipeline.CompiledRenderPipeline; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.preprocessor.GlslPreprocessor; +import com.mojang.blaze3d.shaders.ShaderType; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.GpuDevice; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.textures.TextureFormat; +import com.mojang.logging.LogUtils; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.renderer.ShaderDefines; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.Initializer; +import net.vulkanmod.gl.VkGlTexture; +import net.vulkanmod.interfaces.shader.ExtendedRenderPipeline; +import net.vulkanmod.render.shader.ShaderLoadUtil; +import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.Vulkan; +import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.converter.GLSLParser; +import net.vulkanmod.vulkan.shader.converter.Lexer; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.texture.VulkanImage; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.vulkan.VK10; +import org.slf4j.Logger; + +import java.nio.ByteBuffer; +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +@SuppressWarnings("NullableProblems") +public class VkGpuDevice implements GpuDevice { + private static final Logger LOGGER = LogUtils.getLogger(); + + private final VkCommandEncoder encoder; + private final VkDebugLabel debugLabels; + private final int maxSupportedTextureSize; + private final int uniformOffsetAlignment; + private final BiFunction defaultShaderSource; + private final Map pipelineCache = new IdentityHashMap<>(); + private final Map shaderCache = new HashMap<>(); + private final Set enabledExtensions = new HashSet<>(); + + private final Map shaderSrcCache = new HashMap<>(); + + public VkGpuDevice(long l, int i, boolean bl, BiFunction shaderSource, boolean bl2) { + this.debugLabels = VkDebugLabel.create(bl2, this.enabledExtensions); + this.maxSupportedTextureSize = VRenderSystem.maxSupportedTextureSize(); + this.uniformOffsetAlignment = (int) DeviceManager.deviceProperties.limits().minUniformBufferOffsetAlignment(); + this.defaultShaderSource = shaderSource; + + this.encoder = new VkCommandEncoder(this); + } + + public VkDebugLabel debugLabels() { + return this.debugLabels; + } + + @Override + public CommandEncoder createCommandEncoder() { + return this.encoder; + } + + @Override + public GpuTexture createTexture(@Nullable Supplier supplier, int usage, TextureFormat textureFormat, int width, int height, int layers, int mipLevels) { + return this.createTexture(this.debugLabels.exists() && supplier != null ? supplier.get() : null, usage, textureFormat, width, height, layers, mipLevels); + } + + @Override + public GpuTexture createTexture(@Nullable String string, int usage, TextureFormat textureFormat, int width, int height, int layers, int mipLevels) { + if (mipLevels < 1) { + throw new IllegalArgumentException("mipLevels must be at least 1"); + } else { + int id = VkGlTexture.genTextureId(); + if (string == null) { + string = String.valueOf(id); + } + + int format = VkGpuTexture.vkFormat(textureFormat); + int viewType = VkGpuTexture.vkImageViewType(usage); + boolean depthFormat = VulkanImage.isDepthFormat(format); + int attachmentUsage = depthFormat ? VK10.VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK10.VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + VulkanImage texture = VulkanImage.builder(width, height) + .setName(string) + .setFormat(format) + .setArrayLayers(layers) + .setMipLevels(mipLevels) + .addUsage(attachmentUsage) + .setViewType(viewType) + .createVulkanImage(); + + VkGlTexture vGlTexture = VkGlTexture.getTexture(id); + vGlTexture.setVulkanImage(texture); + VkGlTexture.bindTexture(id); + + VkGpuTexture glTexture = new VkGpuTexture(usage, string, textureFormat, width, height, layers, mipLevels, id, vGlTexture); + this.debugLabels.applyLabel(glTexture); + return glTexture; + } + } + + public VkGpuTexture gpuTextureFromVulkanImage(VulkanImage image) { + int id = VkGlTexture.genTextureId(); + VkGlTexture glTexture = VkGlTexture.getTexture(id); + glTexture.setVulkanImage(image); + TextureFormat textureFormat = VkGpuTexture.textureFormat(image.format); + VkGpuTexture gpuTexture = new VkGpuTexture(0, image.name, textureFormat, image.width, image.height, 1, image.mipLevels, id, glTexture); + this.debugLabels.applyLabel(gpuTexture); + return gpuTexture; + } + + @Override + public GpuTextureView createTextureView(GpuTexture gpuTexture) { + return this.createTextureView(gpuTexture, 0, gpuTexture.getMipLevels()); + } + + @Override + public GpuTextureView createTextureView(GpuTexture gpuTexture, int startLevel, int levels) { + if (gpuTexture.isClosed()) { + throw new IllegalArgumentException("Can't create texture view with closed texture"); + } else if (startLevel >= 0 && startLevel + levels <= gpuTexture.getMipLevels()) { + return new VkTextureView((VkGpuTexture) gpuTexture, startLevel, levels); + } else { + throw new IllegalArgumentException( + levels + " mip levels starting from " + startLevel + " would be out of range for texture with only " + gpuTexture.getMipLevels() + " mip levels" + ); + } + } + + @Override + public GpuBuffer createBuffer(@Nullable Supplier supplier, int usage, int size) { + if (size <= 0) { + throw new IllegalArgumentException("Buffer size must be greater than zero"); + } else { + return new VkGpuBuffer(this.debugLabels, supplier, usage, size); + } + } + + @Override + public GpuBuffer createBuffer(@Nullable Supplier supplier, int usage, ByteBuffer byteBuffer) { + if (!byteBuffer.hasRemaining()) { + throw new IllegalArgumentException("Buffer source must not be empty"); + } else { + VkGpuBuffer glBuffer = new VkGpuBuffer(this.debugLabels, supplier, usage, byteBuffer.remaining()); + this.encoder.writeToBuffer(glBuffer.slice(), byteBuffer); + return glBuffer; + } + } + + @Override + public String getImplementationInformation() { + return "Vulkan " + Vulkan.getDevice().vkVersion + ", " + Vulkan.getDevice().vendorIdString; + } + + @Override + public List getLastDebugMessages() { + return Collections.emptyList(); + } + + @Override + public boolean isDebuggingEnabled() { + return false; + } + + @Override + public String getRenderer() { + return "VulkanMod %s".formatted(Initializer.getVersion()) ; + } + + @Override + public String getVendor() { + return Vulkan.getDevice().vendorIdString; + } + + @Override + public String getBackendName() { + return "Vulkan"; + } + + @Override + public String getVersion() { + return Vulkan.getDevice().vkVersion; + } + + private static int getMaxSupportedTextureSize() { + int i = GlStateManager._getInteger(3379); + + for (int j = Math.max(32768, i); j >= 1024; j >>= 1) { + GlStateManager._texImage2D(32868, 0, 6408, j, j, 0, 6408, 5121, null); + int k = GlStateManager._getTexLevelParameter(32868, 0, 4096); + if (k != 0) { + return j; + } + } + + int jx = Math.max(i, 1024); + LOGGER.info("Failed to determine maximum texture size by probing, trying GL_MAX_TEXTURE_SIZE = {}", jx); + return jx; + } + + @Override + public int getMaxTextureSize() { + return this.maxSupportedTextureSize; + } + + @Override + public int getUniformOffsetAlignment() { + return this.uniformOffsetAlignment; + } + + @Override + public void clearPipelineCache() { + for (GlRenderPipeline glRenderPipeline : this.pipelineCache.values()) { + if (glRenderPipeline.program() != GlProgram.INVALID_PROGRAM) { + glRenderPipeline.program().close(); + } + } + + this.pipelineCache.clear(); + + for (GlShaderModule glShaderModule : this.shaderCache.values()) { + if (glShaderModule != GlShaderModule.INVALID_SHADER) { + glShaderModule.close(); + } + } + + this.shaderCache.clear(); + } + + @Override + public List getEnabledExtensions() { + return new ArrayList(this.enabledExtensions); + } + + @Override + public void close() { + this.clearPipelineCache(); + } + + protected GlShaderModule getOrCompileShader( + ResourceLocation resourceLocation, ShaderType shaderType, ShaderDefines shaderDefines, BiFunction biFunction + ) { + ShaderCompilationKey shaderCompilationKey = new ShaderCompilationKey(resourceLocation, shaderType, shaderDefines); + return this.shaderCache.computeIfAbsent(shaderCompilationKey, shaderCompilationKey2 -> this.compileShader(shaderCompilationKey, biFunction)); + } + + protected String getCachedShaderSrc(ResourceLocation resourceLocation, ShaderType shaderType, ShaderDefines shaderDefines, BiFunction shaderSourceGetter) { + ShaderCompilationKey shaderCompilationKey = new ShaderCompilationKey(resourceLocation, shaderType, shaderDefines); + + return this.shaderSrcCache.computeIfAbsent(shaderCompilationKey, compilationKey -> { + String shaderExtension = switch (shaderType) { + case VERTEX -> ".vsh"; + case FRAGMENT -> ".fsh"; + }; + + String shaderName = resourceLocation.getPath() + shaderExtension; + + if (ShaderLoadUtil.REMAPPED_SHADERS.contains(shaderName)) { + String src = ShaderLoadUtil.getShaderSource(resourceLocation, shaderType); + + if (src == null) { + throw new RuntimeException("shader: (%s) not found."); + } + + return src; + } + + return shaderSourceGetter.apply(compilationKey.id, compilationKey.type); + }); + } + + public CompiledRenderPipeline precompilePipeline(RenderPipeline renderPipeline, @Nullable BiFunction shaderSourceGetter) { + shaderSourceGetter = shaderSourceGetter == null ? this.defaultShaderSource : shaderSourceGetter; + compilePipeline(renderPipeline, shaderSourceGetter); + + return new VkRenderPipeline(renderPipeline); + } + + public void compilePipeline(RenderPipeline renderPipeline) { + this.compilePipeline(renderPipeline, this.defaultShaderSource); + } + + private GlShaderModule compileShader(ShaderCompilationKey shaderCompilationKey, BiFunction biFunction) { + String string = biFunction.apply(shaderCompilationKey.id, shaderCompilationKey.type); + if (string == null) { + LOGGER.error("Couldn't find source for {} shader ({})", shaderCompilationKey.type, shaderCompilationKey.id); + return GlShaderModule.INVALID_SHADER; + } else { + String string2 = GlslPreprocessor.injectDefines(string, shaderCompilationKey.defines); + int i = GlStateManager.glCreateShader(GlConst.toGl(shaderCompilationKey.type)); + GlStateManager.glShaderSource(i, string2); + GlStateManager.glCompileShader(i); + if (GlStateManager.glGetShaderi(i, 35713) == 0) { + String string3 = StringUtils.trim(GlStateManager.glGetShaderInfoLog(i, 32768)); + LOGGER.error("Couldn't compile {} shader ({}): {}", shaderCompilationKey.type.getName(), shaderCompilationKey.id, string3); + return GlShaderModule.INVALID_SHADER; + } else { + GlShaderModule glShaderModule = new GlShaderModule(i, shaderCompilationKey.id, shaderCompilationKey.type); + this.debugLabels.applyLabel(glShaderModule); + return glShaderModule; + } + } + } + + private void compilePipeline(RenderPipeline renderPipeline, BiFunction shaderSrcGetter) { + String locationPath = renderPipeline.getLocation().getPath(); + + String configName; + if (locationPath.contains("core")) { + configName = locationPath.split("/")[1]; + } else { + configName = locationPath; + } + + Pipeline.Builder builder = new Pipeline.Builder(renderPipeline.getVertexFormat(), configName); + GraphicsPipeline pipeline; + ExtendedRenderPipeline extPipeline = ExtendedRenderPipeline.of(renderPipeline); + + ResourceLocation vertexShaderLocation = renderPipeline.getVertexShader(); + ResourceLocation fragmentShaderLocation = renderPipeline.getFragmentShader(); + + ShaderDefines shaderDefines = renderPipeline.getShaderDefines(); + + String vshSrc = this.getCachedShaderSrc(vertexShaderLocation, ShaderType.VERTEX, shaderDefines, shaderSrcGetter); + String fshSrc = this.getCachedShaderSrc(fragmentShaderLocation, ShaderType.FRAGMENT, shaderDefines, shaderSrcGetter); + + vshSrc = GlslPreprocessor.injectDefines(vshSrc, shaderDefines); + fshSrc = GlslPreprocessor.injectDefines(fshSrc, shaderDefines); + + Lexer lexer = new Lexer(vshSrc); + GLSLParser parser = new GLSLParser(); + parser.setVertexFormat(renderPipeline.getVertexFormat()); + + try { + parser.parse(lexer, GLSLParser.Stage.VERTEX); + + lexer = new Lexer(fshSrc); + parser.parse(lexer, GLSLParser.Stage.FRAGMENT); + } catch (Exception e) { + throw new RuntimeException("Caught exception while parsing: %s".formatted(renderPipeline.toString()), e); + } + + UBO[] ubos = parser.createUBOs(); + + String vshProcessed = parser.getOutput(GLSLParser.Stage.VERTEX); + String fshProcessed = parser.getOutput(GLSLParser.Stage.FRAGMENT); + + builder.setUniforms(List.of(ubos), parser.getSamplerList()); + builder.compileShaders(configName, vshProcessed, fshProcessed); + + try { + pipeline = builder.createGraphicsPipeline(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Exception while compiling pipeline %s".formatted(renderPipeline)); + } + + EGlProgram eGlProgram = new EGlProgram(1, configName); + eGlProgram.setupUniforms(pipeline, renderPipeline.getUniforms(), renderPipeline.getSamplers()); + extPipeline.setProgram(eGlProgram); + + extPipeline.setPipeline(pipeline); + } + + @Environment(EnvType.CLIENT) + record ShaderCompilationKey(ResourceLocation id, ShaderType type, ShaderDefines defines) { + + public String toString() { + String string = this.id + " (" + this.type + ")"; + return !this.defines.isEmpty() ? string + " with " + this.defines : string; + } + } + + private static class VkRenderPipeline implements CompiledRenderPipeline { + final RenderPipeline renderPipeline; + + public VkRenderPipeline(RenderPipeline renderPipeline) { + this.renderPipeline = renderPipeline; + } + + @Override + public boolean isValid() { + return true; + } + } +} diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java new file mode 100644 index 0000000000..b5e5a5b651 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -0,0 +1,157 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.opengl.GlConst; +import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.opengl.GlTexture; +import com.mojang.blaze3d.textures.AddressMode; +import com.mojang.blaze3d.textures.FilterMode; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.TextureFormat; +import it.unimi.dsi.fastutil.ints.*; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.vulkanmod.gl.VkGlTexture; +import net.vulkanmod.vulkan.texture.SamplerManager; +import net.vulkanmod.vulkan.texture.VulkanImage; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.vulkan.VK10; + +@Environment(EnvType.CLIENT) +//public class VkGpuTexture extends GpuTexture { +public class VkGpuTexture extends GlTexture { + protected VkGlTexture glTexture; + protected final int id; + private final Int2ReferenceMap fboCache = new Int2ReferenceOpenHashMap<>(); + protected boolean closed; + protected boolean modesDirty = true; + + protected VkGpuTexture(int usage, String string, TextureFormat textureFormat, int width, int height, int layers, int mipLevel, int id, VkGlTexture glTexture) { + super(usage, string, textureFormat, width, height, layers, mipLevel, id); + this.id = id; + this.glTexture = glTexture; + } + + @Override + public void close() { + if (!this.closed) { + this.closed = true; + GlStateManager._deleteTexture(this.id); + + for (VkFbo fbo : this.fboCache.values()) { + fbo.close(); + } + } + } + + @Override + public boolean isClosed() { + return this.closed; + } + +// public int getFbo(DirectStateAccess directStateAccess, @Nullable GpuTexture gpuTexture) { +// int i = gpuTexture == null ? 0 : ((VkGpuTexture)gpuTexture).id; +// return this.fboCache.computeIfAbsent(i, j -> { +// int k = directStateAccess.createFrameBufferObject(); +// directStateAccess.bindFrameBufferTextures(k, this.id, i, 0, 0); +// return k; +// }); +// } + + public void flushModeChanges() { + if (this.modesDirty) { +// GlStateManager._texParameter(3553, 10242, GlConst.toGl(this.addressModeU)); +// GlStateManager._texParameter(3553, 10243, GlConst.toGl(this.addressModeV)); +// switch (this.minFilter) { +// case NEAREST: +// GlStateManager._texParameter(3553, 10241, this.useMipmaps ? 9986 : 9728); +// break; +// case LINEAR: +// GlStateManager._texParameter(3553, 10241, this.useMipmaps ? 9987 : 9729); +// } +// +// switch (this.magFilter) { +// case NEAREST: +// GlStateManager._texParameter(3553, 10240, 9728); +// break; +// case LINEAR: +// GlStateManager._texParameter(3553, 10240, 9729); +// } + + byte samplerFlags; + samplerFlags = magFilter == FilterMode.LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; + + // TODO: split min filtering + + if (this.useMipmaps) { + samplerFlags |= SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; + } + + glTexture.getVulkanImage().updateTextureSampler(this.getMipLevels(), samplerFlags); + + this.modesDirty = false; + } + } + + public int glId() { + return this.id; + } + + @Override + public void setAddressMode(AddressMode addressMode, AddressMode addressMode2) { + super.setAddressMode(addressMode, addressMode2); + this.modesDirty = true; + } + + @Override + public void setTextureFilter(FilterMode filterMode, FilterMode filterMode2, boolean bl) { + super.setTextureFilter(filterMode, filterMode2, bl); + this.modesDirty = true; + } + + @Override + public void setUseMipmaps(boolean bl) { + super.setUseMipmaps(bl); + this.modesDirty = true; + } + + public VkFbo getFbo(@Nullable GpuTexture depthAttachment) { + int depthAttachmentId = depthAttachment == null ? 0 : ((VkGpuTexture)depthAttachment).id; + return this.fboCache.computeIfAbsent(depthAttachmentId, j -> new VkFbo(this, (VkGpuTexture) depthAttachment)); + } + + public VulkanImage getVulkanImage() { + return glTexture.getVulkanImage(); + } + + public static TextureFormat textureFormat(int format) { + return switch (format) { + case VK10.VK_FORMAT_R8G8B8A8_UNORM, VK10.VK_FORMAT_B8G8R8A8_UNORM -> TextureFormat.RGBA8; + case VK10.VK_FORMAT_R8_UNORM -> TextureFormat.RED8; + case VK10.VK_FORMAT_D32_SFLOAT -> TextureFormat.DEPTH32; + default -> throw new IllegalStateException("Unexpected value: " + format); + }; + } + + public static int vkFormat(TextureFormat textureFormat) { + return switch (textureFormat) { + case RGBA8 -> VK10.VK_FORMAT_R8G8B8A8_UNORM; + case RED8 -> VK10.VK_FORMAT_R8_UNORM; + case RED8I -> VK10.VK_FORMAT_R8_SINT; + case DEPTH32 -> VK10.VK_FORMAT_D32_SFLOAT; + }; + } + + public static int vkImageViewType(int usage) { + int viewType; + if ((usage & GpuTexture.USAGE_CUBEMAP_COMPATIBLE) != 0) { + viewType = VK10.VK_IMAGE_VIEW_TYPE_CUBE; + } + else { + viewType = VK10.VK_IMAGE_VIEW_TYPE_2D; + } + + return viewType; + } +} + diff --git a/src/main/java/net/vulkanmod/render/engine/VkRenderPass.java b/src/main/java/net/vulkanmod/render/engine/VkRenderPass.java new file mode 100644 index 0000000000..8d9c039bc6 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkRenderPass.java @@ -0,0 +1,212 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.systems.ScissorState; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.VertexFormat; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Supplier; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.SharedConstants; +import net.vulkanmod.interfaces.shader.ExtendedRenderPipeline; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; + +@Environment(EnvType.CLIENT) +public class VkRenderPass implements RenderPass { + protected static final int MAX_VERTEX_BUFFERS = 1; + public static final boolean VALIDATION = SharedConstants.IS_RUNNING_IN_IDE; + private final VkCommandEncoder encoder; + private final boolean hasDepthTexture; + private boolean closed; + @Nullable + protected RenderPipeline pipeline; + protected final GpuBuffer[] vertexBuffers = new GpuBuffer[1]; + @Nullable + protected GpuBuffer indexBuffer; + protected VertexFormat.IndexType indexType = VertexFormat.IndexType.INT; + private final ScissorState scissorState = new ScissorState(); + protected final HashMap uniforms = new HashMap<>(); + protected final HashMap samplers = new HashMap<>(); + protected final Set dirtyUniforms = new HashSet<>(); + protected int pushedDebugGroups; + + public VkRenderPass(VkCommandEncoder commandEncoder, boolean bl) { + this.encoder = commandEncoder; + this.hasDepthTexture = bl; + } + + public boolean hasDepthTexture() { + return this.hasDepthTexture; + } + + @Override + public void pushDebugGroup(Supplier supplier) { + if (this.closed) { + throw new IllegalStateException("Can't use a closed render pass"); + } else { + this.pushedDebugGroups++; +// this.encoder.getDevice().debugLabels().pushDebugGroup(supplier); + } + } + + @Override + public void popDebugGroup() { + if (this.closed) { + throw new IllegalStateException("Can't use a closed render pass"); + } else if (this.pushedDebugGroups == 0) { + throw new IllegalStateException("Can't pop more debug groups than was pushed!"); + } else { + this.pushedDebugGroups--; +// this.encoder.getDevice().debugLabels().popDebugGroup(); + } + } + + @Override + public void setPipeline(RenderPipeline renderPipeline) { + if (this.pipeline == null || this.pipeline != renderPipeline) { + this.dirtyUniforms.addAll(this.uniforms.keySet()); + } + + + this.pipeline = renderPipeline; + + if (ExtendedRenderPipeline.of(renderPipeline).getPipeline() == null) { + this.encoder.getDevice().compilePipeline(renderPipeline); + } + } + + @Override + public void bindSampler(String string, @Nullable GpuTextureView gpuTextureView) { + if (gpuTextureView == null) { + this.samplers.remove(string); + } else { + this.samplers.put(string, gpuTextureView); + } + + this.dirtyUniforms.add(string); + } + + @Override + public void setUniform(String string, GpuBuffer gpuBuffer) { + this.uniforms.put(string, gpuBuffer.slice()); + this.dirtyUniforms.add(string); + } + + @Override + public void setUniform(String string, GpuBufferSlice gpuBufferSlice) { + int i = this.encoder.getDevice().getUniformOffsetAlignment(); + if (gpuBufferSlice.offset() % i > 0) { + throw new IllegalArgumentException("Uniform buffer offset must be aligned to " + i); + } else { + this.uniforms.put(string, gpuBufferSlice); + this.dirtyUniforms.add(string); + } + } + + @Override + public void enableScissor(int i, int j, int k, int l) { + this.scissorState.enable(i, j, k, l); + } + + @Override + public void disableScissor() { + this.scissorState.disable(); + } + + public boolean isScissorEnabled() { + return this.scissorState.enabled(); + } + + public int getScissorX() { + return this.scissorState.x(); + } + + public int getScissorY() { + return this.scissorState.y(); + } + + public int getScissorWidth() { + return this.scissorState.width(); + } + + public int getScissorHeight() { + return this.scissorState.height(); + } + + public ScissorState getScissorState() { return this.scissorState; } + + @Override + public void setVertexBuffer(int i, GpuBuffer gpuBuffer) { + if (i >= 0 && i < 1) { + this.vertexBuffers[i] = gpuBuffer; + } else { + throw new IllegalArgumentException("Vertex buffer slot is out of range: " + i); + } + } + + @Override + public void setIndexBuffer(@Nullable GpuBuffer gpuBuffer, VertexFormat.IndexType indexType) { + this.indexBuffer = gpuBuffer; + this.indexType = indexType; + } + + @Override + public void drawIndexed(int i, int j, int k, int l) { + if (this.closed) { + throw new IllegalStateException("Can't use a closed render pass"); + } else { + this.encoder.executeDraw(this, i, j, k, this.indexType, l); + } + } + + @Override + public void drawMultipleIndexed( + Collection> collection, + @Nullable GpuBuffer gpuBuffer, + @Nullable VertexFormat.IndexType indexType, + Collection collection2, + T object + ) { + if (this.closed) { + throw new IllegalStateException("Can't use a closed render pass"); + } else { + this.encoder.executeDrawMultiple(this, collection, gpuBuffer, indexType, collection2, object); + } + } + + @Override + public void draw(int i, int j) { + if (this.closed) { + throw new IllegalStateException("Can't use a closed render pass"); + } else { + this.encoder.executeDraw(this, i, 0, j, null, 1); + } + } + + @Override + public void close() { + if (!this.closed) { + if (this.pushedDebugGroups > 0) { + throw new IllegalStateException("Render pass had debug groups left open!"); + } + + this.closed = true; + this.encoder.finishRenderPass(); + } + } + + public @Nullable RenderPipeline getPipeline() { + return pipeline; + } +} + diff --git a/src/main/java/net/vulkanmod/render/engine/VkTextureView.java b/src/main/java/net/vulkanmod/render/engine/VkTextureView.java new file mode 100644 index 0000000000..8ad3c6b794 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/engine/VkTextureView.java @@ -0,0 +1,29 @@ +package net.vulkanmod.render.engine; + +import com.mojang.blaze3d.textures.GpuTextureView; + +public class VkTextureView extends GpuTextureView { + private boolean closed; + + protected VkTextureView(VkGpuTexture gpuTexture, int i, int j) { + super(gpuTexture, i, j); + gpuTexture.addViews(); + } + + @Override + public boolean isClosed() { + return this.closed; + } + + @Override + public void close() { + if (!this.closed) { + this.closed = true; + this.texture().removeViews(); + } + } + + public VkGpuTexture texture() { + return (VkGpuTexture) super.texture(); + } +} diff --git a/src/main/java/net/vulkanmod/render/gui/GuiBatchRenderer.java b/src/main/java/net/vulkanmod/render/gui/GuiBatchRenderer.java deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/main/java/net/vulkanmod/render/model/CubeModel.java b/src/main/java/net/vulkanmod/render/model/CubeModel.java index da988f39d1..ef5bb5548b 100644 --- a/src/main/java/net/vulkanmod/render/model/CubeModel.java +++ b/src/main/java/net/vulkanmod/render/model/CubeModel.java @@ -1,15 +1,15 @@ package net.vulkanmod.render.model; -import net.minecraft.client.model.geom.ModelPart; import net.minecraft.core.Direction; import org.joml.Matrix4f; import org.joml.Vector3f; +import org.joml.Vector3fc; import java.util.Set; public class CubeModel { - private ModelPart.Polygon[] polygons = new ModelPart.Polygon[6]; + private Polygon[] polygons; public float minX; public float minY; public float minZ; @@ -17,99 +17,165 @@ public class CubeModel { public float maxY; public float maxZ; - Vector3f[] vertices; - Vector3f[] transformed = new Vector3f[8]; - - public void setVertices(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set) { - this.minX = f; - this.minY = g; - this.minZ = h; - this.maxX = f + k; - this.maxY = g + l; - this.maxZ = h + m; - this.polygons = new ModelPart.Polygon[set.size()]; + Vertex[] vertices; + + public void setVertices(int u, int v, float minX, float minY, float minZ, float dimX, float dimY, float dimZ, float growX, float growY, float growZ, boolean mirror, float uTexScale, float vTexScale, Set set) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = minX + dimX; + this.maxY = minY + dimY; + this.maxZ = minZ + dimZ; + this.polygons = new Polygon[set.size()]; float s = maxX; float t = maxY; - float u = maxZ; - f -= n; - g -= o; - h -= p; - s += n; - t += o; - u += p; - if (bl) { - float v = s; - s = f; - f = v; - } - - this.vertices = new Vector3f[]{ - new Vector3f(f, g, h), - new Vector3f(s, g, h), - new Vector3f(s, t, h), - new Vector3f(f, t, h), - new Vector3f(f, g, u), - new Vector3f(s, g, u), - new Vector3f(s, t, u), - new Vector3f(f, t, u) + float u1 = maxZ; + minX -= growX; + minY -= growY; + minZ -= growZ; + s += growX; + t += growY; + u1 += growZ; + if (mirror) { + float v1 = s; + s = minX; + minX = v1; + } + + this.vertices = new Vertex[]{ + new Vertex(minX, minY, minZ, 0.0F, 0.0F), + new Vertex(s, minY, minZ, 0.0F, 8.0F), + new Vertex(s, t, minZ, 8.0F, 8.0F), + new Vertex(minX, t, minZ, 8.0F, 0.0F), + new Vertex(minX, minY, u1, 0.0F, 0.0F), + new Vertex(s, minY, u1, 0.0F, 8.0F), + new Vertex(s, t, u1, 8.0F, 8.0F), + new Vertex(minX, t, u1, 8.0F, 0.0F) }; - for (int i1 = 0; i1 < 8; i1++) { - //pre-divide all vertices once - this.vertices[i1].div(16.0f); - this.transformed[i1] = new Vector3f(0.0f); - } - - ModelPart.Vertex vertex1 = new ModelPart.Vertex(transformed[0], 0.0F, 0.0F); - ModelPart.Vertex vertex2 = new ModelPart.Vertex(transformed[1], 0.0F, 8.0F); - ModelPart.Vertex vertex3 = new ModelPart.Vertex(transformed[2], 8.0F, 8.0F); - ModelPart.Vertex vertex4 = new ModelPart.Vertex(transformed[3], 8.0F, 0.0F); - ModelPart.Vertex vertex5 = new ModelPart.Vertex(transformed[4], 0.0F, 0.0F); - ModelPart.Vertex vertex6 = new ModelPart.Vertex(transformed[5], 0.0F, 8.0F); - ModelPart.Vertex vertex7 = new ModelPart.Vertex(transformed[6], 8.0F, 8.0F); - ModelPart.Vertex vertex8 = new ModelPart.Vertex(transformed[7], 8.0F, 0.0F); - - float w = (float)i; - float x = (float)i + m; - float y = (float)i + m + k; - float z = (float)i + m + k + k; - float aa = (float)i + m + k + m; - float ab = (float)i + m + k + m + k; - float ac = (float)j; - float ad = (float)j + m; - float ae = (float)j + m + l; + float w = (float)u; + float x = (float)u + dimZ; + float y = (float)u + dimZ + dimX; + float z = (float)u + dimZ + dimX + dimX; + float aa = (float)u + dimZ + dimX + dimZ; + float ab = (float)u + dimZ + dimX + dimZ + dimX; + float ac = (float)v; + float ad = (float)v + dimZ; + float ae = (float)v + dimZ + dimY; + + Vertex vertex1 = this.vertices[0]; + Vertex vertex2 = this.vertices[1]; + Vertex vertex3 = this.vertices[2]; + Vertex vertex4 = this.vertices[3]; + Vertex vertex5 = this.vertices[4]; + Vertex vertex6 = this.vertices[5]; + Vertex vertex7 = this.vertices[6]; + Vertex vertex8 = this.vertices[7]; + int idx = 0; if (set.contains(Direction.DOWN)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex6, vertex5, vertex1, vertex2}, x, ac, y, ad, q, r, bl, Direction.DOWN); + this.polygons[idx++] = new Polygon(new Vertex[]{vertex6, vertex5, vertex1, vertex2}, x, ac, y, ad, uTexScale, vTexScale, mirror, Direction.DOWN); } if (set.contains(Direction.UP)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex3, vertex4, vertex8, vertex7}, y, ad, z, ac, q, r, bl, Direction.UP); + this.polygons[idx++] = new Polygon(new Vertex[]{vertex3, vertex4, vertex8, vertex7}, y, ad, z, ac, uTexScale, vTexScale, mirror, Direction.UP); } if (set.contains(Direction.WEST)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex1, vertex5, vertex8, vertex4}, w, ad, x, ae, q, r, bl, Direction.WEST); + this.polygons[idx++] = new Polygon(new Vertex[]{vertex1, vertex5, vertex8, vertex4}, w, ad, x, ae, uTexScale, vTexScale, mirror, Direction.WEST); } if (set.contains(Direction.NORTH)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex2, vertex1, vertex4, vertex3}, x, ad, y, ae, q, r, bl, Direction.NORTH); + this.polygons[idx++] = new Polygon(new Vertex[]{vertex2, vertex1, vertex4, vertex3}, x, ad, y, ae, uTexScale, vTexScale, mirror, Direction.NORTH); } if (set.contains(Direction.EAST)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex6, vertex2, vertex3, vertex7}, y, ad, aa, ae, q, r, bl, Direction.EAST); + this.polygons[idx++] = new Polygon(new Vertex[]{vertex6, vertex2, vertex3, vertex7}, y, ad, aa, ae, uTexScale, vTexScale, mirror, Direction.EAST); } if (set.contains(Direction.SOUTH)) { - this.polygons[idx] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex5, vertex6, vertex7, vertex8}, aa, ad, ab, ae, q, r, bl, Direction.SOUTH); + this.polygons[idx] = new Polygon(new Vertex[]{vertex5, vertex6, vertex7, vertex8}, aa, ad, ab, ae, uTexScale, vTexScale, mirror, Direction.SOUTH); } } public void transformVertices(Matrix4f matrix) { - //Transform original vertices and store them - for(int i = 0; i < 8; ++i) { - this.vertices[i].mulPosition(matrix, this.transformed[i]); + // Transform original vertices and store them + for (int i = 0; i < 8; ++i) { + Vertex vertex = this.vertices[i]; + vertex.pos.mulPosition(matrix, vertex.transformed); + } + } + + public Polygon[] getPolygons() { + return this.polygons; + } + + public record Polygon(Vertex[] vertices, Vector3fc normal) { + + public Polygon(Vertex[] vertices, float u0, float v0, float u1, float v1, float uSize, float vSize, boolean mirror, Direction direction) { + this(vertices, (mirror ? mirrorFacing(direction) : direction).getUnitVec3f()); + + // This will force NaN if uSize or vSize are 0 + float l = 0.0F / uSize; + float m = 0.0F / vSize; + + vertices[0] = vertices[0].remap(u1 / uSize - l, v0 / vSize + m); + vertices[1] = vertices[1].remap(u0 / uSize + l, v0 / vSize + m); + vertices[2] = vertices[2].remap(u0 / uSize + l, v1 / vSize - m); + vertices[3] = vertices[3].remap(u1 / uSize - l, v1 / vSize - m); + + if (mirror) { + int n = vertices.length; + + for (int o = 0; o < n / 2; o++) { + Vertex vertex = vertices[o]; + vertices[o] = vertices[n - 1 - o]; + vertices[n - 1 - o] = vertex; + } + } + } + + private static Direction mirrorFacing(Direction direction) { + return direction.getAxis() == Direction.Axis.X ? direction.getOpposite() : direction; + } + } + + public static class Vertex { + private static final float SCALE_FACTOR = 16.0F; + + final Vector3f pos; + final Vector3f transformed; + float u, v; + + public Vertex(float x, float y, float z, float u, float v) { + this.pos = new Vector3f(x / SCALE_FACTOR, y / SCALE_FACTOR, z / SCALE_FACTOR); + this.transformed = new Vector3f(); + this.u = u; + this.v = v; + } + + public Vertex(Vector3f pos, Vector3f transformed, float u, float v) { + this.pos = pos; + this.transformed = transformed; + this.u = u; + this.v = v; + } + + Vertex remap(float u, float v) { + return new Vertex(this.pos, this.transformed, u, v); + } + + public Vector3f pos() { + return transformed; + } + + public float u() { + return u; + } + + public float v() { + return v; } } - public ModelPart.Polygon[] getPolygons() { return this.polygons; } } diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index 8f0ffdd9fe..97cf7e4302 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -1,17 +1,15 @@ package net.vulkanmod.render.profiling; import com.google.common.base.Strings; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.build.task.ChunkTask; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.util.ColorUtil; @@ -56,7 +54,6 @@ public static void onKeyPress(int key) { public void render(GuiGraphics guiGraphics) { GuiRenderer.guiGraphics = guiGraphics; - GuiRenderer.pose = guiGraphics.pose(); List infoList = this.buildInfo(); @@ -67,8 +64,7 @@ public void render(GuiGraphics guiGraphics) { Objects.requireNonNull(this.font); - RenderSystem.enableBlend(); - GuiRenderer.beginBatch(); + VRenderSystem.enableBlend(); for (int i = 0; i < infoList.size(); ++i) { String line = infoList.get(i); @@ -82,8 +78,7 @@ public void render(GuiGraphics guiGraphics) { } } - GuiRenderer.endBatch(); - RenderSystem.disableBlend(); + VRenderSystem.disableBlend(); for (int i = 0; i < infoList.size(); ++i) { String line = infoList.get(i); diff --git a/src/main/java/net/vulkanmod/render/shader/CustomRenderPipelines.java b/src/main/java/net/vulkanmod/render/shader/CustomRenderPipelines.java new file mode 100644 index 0000000000..07ca57f3c3 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/shader/CustomRenderPipelines.java @@ -0,0 +1,31 @@ +package net.vulkanmod.render.shader; + +import com.mojang.blaze3d.pipeline.BlendFunction; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.platform.DepthTestFunction; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderPipelines; + +import java.util.ArrayList; +import java.util.List; + +public class CustomRenderPipelines { + + public static final List pipelines = new ArrayList<>(); + + public static final RenderPipeline.Snippet GUI_TRIANGLES_SNIPPET = RenderPipeline.builder(RenderPipelines.MATRICES_PROJECTION_SNIPPET) + .withVertexShader("core/gui") + .withFragmentShader("core/gui") + .withBlend(BlendFunction.TRANSLUCENT) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.TRIANGLES) + .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST) + .buildSnippet(); + + public static final RenderPipeline GUI_TRIANGLES = register(RenderPipeline.builder(GUI_TRIANGLES_SNIPPET).withLocation("pipeline/gui").build()); + + static RenderPipeline register(RenderPipeline pipeline) { + pipelines.add(pipeline); + return pipeline; + } +} diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index b7b036307c..2c7bb55673 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -1,8 +1,10 @@ package net.vulkanmod.render.shader; +import com.google.common.collect.Sets; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.mojang.blaze3d.shaders.ShaderType; import net.minecraft.resources.ResourceLocation; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.SPIRVUtils; @@ -15,11 +17,16 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; public abstract class ShaderLoadUtil { private static final String RESOURCES_PATH = SPIRVUtils.class.getResource("/assets/vulkanmod").toExternalForm(); + public static final Set REMAPPED_SHADERS = Sets.newHashSet("core/screenquad.vsh","core/rendertype_item_entity_translucent_cull.vsh"); + public static void loadShaders(Pipeline.Builder pipelineBuilder, JsonObject config, String configName, String path) { String vertexShader = config.has("vertex") ? config.get("vertex").getAsString() : configName; String fragmentShader = config.has("fragment") ? config.get("fragment").getAsString() : configName; @@ -110,6 +117,57 @@ public static JsonObject getJsonConfig(String path, String rendertype) { } + public static String getShaderSource(ResourceLocation resourceLocation, ShaderType type) { + String shaderExtension = switch (type) { + case VERTEX -> ".vsh"; + case FRAGMENT -> ".fsh"; + }; + + String path = resourceLocation.getPath(); + String[] splitPath = splitPath(path); + String shaderName = "%s%s".formatted(splitPath[1], shaderExtension); + String shaderFile = "%s/shaders/%s/%s".formatted(RESOURCES_PATH, path, shaderName); + + InputStream stream; + try { + stream = getInputStream(shaderFile); + + if (stream == null) { + return null; + } + + String source = IOUtils.toString(new BufferedReader(new InputStreamReader(stream))); + stream.close(); + + return source; + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static String getShaderSource(String path, ShaderType type) { + String shaderExtension = switch (type) { + case VERTEX -> ".vsh"; + case FRAGMENT -> ".fsh"; + }; + + String[] splitPath = splitPath(path); + String shaderName = "%s%s".formatted(splitPath[1], shaderExtension); + + String shaderFile = "%s/shaders/%s/%s".formatted(RESOURCES_PATH, path, shaderName); + + InputStream stream; + try { + stream = getInputStream(shaderFile); + String source = IOUtils.toString(new BufferedReader(new InputStreamReader(stream))); + stream.close(); + + return source; + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + public static String getShaderSource(String basePath, String rendertype, String shaderName, SPIRVUtils.ShaderKind type) { String shaderExtension = switch (type) { case VERTEX_SHADER -> ".vsh"; diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 2fade3880f..60943f029d 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -1,6 +1,6 @@ package net.vulkanmod.render.sky; -import com.mojang.blaze3d.buffers.BufferUsage; +import com.mojang.blaze3d.opengl.GlStateManager; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; @@ -10,16 +10,20 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.Mth; import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.VBO; +import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.util.ColorUtil; import org.apache.commons.lang3.Validate; -import org.joml.Matrix4f; +import org.joml.Matrix4fStack; +import org.lwjgl.opengl.GL11; import java.io.IOException; +import java.util.Optional; public class CloudRenderer { private static final ResourceLocation TEXTURE_LOCATION = ResourceLocation.withDefaultNamespace("textures/environment/clouds.png"); @@ -57,15 +61,16 @@ public void loadTexture() { this.cloudGrid = createCloudGrid(TEXTURE_LOCATION); } - public void renderClouds(ClientLevel level, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { - float cloudHeight = level.effects().getCloudHeight(); + public void renderClouds(ClientLevel level, float ticks, float partialTicks, double camX, double camY, double camZ) { + Optional optional = level.dimensionType().cloudHeight(); - if (Float.isNaN(cloudHeight)) { + if (optional.isEmpty()) { return; } Minecraft minecraft = Minecraft.getInstance(); + int cloudHeight = optional.get(); double timeOffset = (ticks + partialTicks) * 0.03F; double centerX = (camX + timeOffset); double centerZ = camZ + 0.33F * CELL_WIDTH; @@ -110,7 +115,7 @@ else if (centerY > 0.0f) { return; } - this.cloudBuffer = new VBO(BufferUsage.STATIC_WRITE); + this.cloudBuffer = new VBO(true); this.cloudBuffer.upload(cloudsMesh); } @@ -122,37 +127,57 @@ else if (centerY > 0.0f) { float yTranslation = (float) (centerY); float zTranslation = (float) (centerZ - (centerCellZ * CELL_WIDTH)); - Matrix4f matrix4f = new Matrix4f(modelView).translate(-xTranslation, yTranslation, -zTranslation); + Renderer.getInstance().getMainPass().rebindMainTarget(); + + Matrix4fStack poseStack = RenderSystem.getModelViewStack(); + poseStack.pushMatrix(); + poseStack.translate(-xTranslation, yTranslation, -zTranslation); + VRenderSystem.applyModelViewMatrix(poseStack); + VRenderSystem.calculateMVP(); VRenderSystem.setModelOffset(-xTranslation, 0, -zTranslation); + // TODO Vec3 cloudColor = Vec3.fromRGB24(level.getCloudColor(partialTicks)); - RenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); + VRenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); GraphicsPipeline pipeline = PipelineManager.getCloudsPipeline(); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - RenderSystem.enableDepthTest(); + VRenderSystem.enableBlend(); + VRenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + VRenderSystem.enableDepthTest(); + VRenderSystem.depthFunc(GL11.GL_LEQUAL); + GlStateManager._enableDepthTest(); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); + GlStateManager._disablePolygonOffset(); + VRenderSystem.setPolygonModeGL(GL11.GL_FILL); + VRenderSystem.setPrimitiveTopologyGL(GL11.GL_TRIANGLES); boolean fastClouds = this.prevCloudsType == CloudStatus.FAST; boolean insideClouds = yState == Y_INSIDE_CLOUDS; boolean disableCull = insideClouds || (fastClouds && centerY <= 0.0f); if (disableCull) { - RenderSystem.disableCull(); + VRenderSystem.disableCull(); + } else { + VRenderSystem.enableCull(); } if (!fastClouds) { - RenderSystem.colorMask(false, false, false, false); - this.cloudBuffer.drawWithShader(matrix4f, projection, pipeline); + VRenderSystem.colorMask(false, false, false, false); + this.cloudBuffer.bind(pipeline); + this.cloudBuffer.draw(); - RenderSystem.colorMask(true, true, true, true); + VRenderSystem.colorMask(true, true, true, true); } - this.cloudBuffer.drawWithShader(matrix4f, projection, pipeline); - RenderSystem.enableCull(); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + this.cloudBuffer.bind(pipeline); + this.cloudBuffer.draw(); + + poseStack.popMatrix(); + VRenderSystem.enableCull(); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); VRenderSystem.setModelOffset(0.0f, 0.0f, 0.0f); } @@ -171,7 +196,8 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - int renderDistance = 32; + int cloudRange = Math.min(Minecraft.getInstance().options.cloudRange().get(), 128) * 16; + int renderDistance = Mth.ceil(cloudRange / 12.0F); boolean insideClouds = this.prevCloudY == Y_INSIDE_CLOUDS; if (this.prevCloudsType == CloudStatus.FANCY) { diff --git a/src/main/java/net/vulkanmod/render/util/DrawUtil.java b/src/main/java/net/vulkanmod/render/util/DrawUtil.java index f1ba4e9235..b4e527eb84 100644 --- a/src/main/java/net/vulkanmod/render/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/render/util/DrawUtil.java @@ -20,7 +20,7 @@ public static void blitQuad() { public static void drawTexQuad(BufferBuilder builder, float x0, float y0, float x1, float y1, float z, float u0, float v0, float u1, float v1) { - Tesselator tesselator = RenderSystem.renderThreadTesselator(); + Tesselator tesselator = Tesselator.getInstance(); BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferBuilder.addVertex(x0, y0, z).setUv(0.0F, 1.0F); bufferBuilder.addVertex(x1, y0, z).setUv(1.0F, 1.0F); @@ -34,7 +34,7 @@ public static void drawTexQuad(BufferBuilder builder, float x0, float y0, float } public static void blitQuad(float x0, float y0, float x1, float y1) { - Tesselator tesselator = RenderSystem.renderThreadTesselator(); + Tesselator tesselator = Tesselator.getInstance(); BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferBuilder.addVertex(x0, y0, 0.0f).setUv(0.0F, 1.0F); bufferBuilder.addVertex(x1, y0, 0.0f).setUv(1.0F, 1.0F); @@ -48,18 +48,14 @@ public static void blitQuad(float x0, float y0, float x1, float y1) { } public static void drawFramebuffer(GraphicsPipeline pipeline, VulkanImage attachment) { - Renderer.getInstance().bindGraphicsPipeline(pipeline); - VTextureSelector.bindTexture(attachment); Matrix4f projection = new Matrix4f().setOrtho(0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, true); Matrix4fStack poseStack = RenderSystem.getModelViewStack(); poseStack.pushMatrix(); poseStack.identity(); - VRenderSystem.applyMVP(poseStack, projection); - poseStack.popMatrix(); Renderer.getInstance().uploadAndBindUBOs(pipeline); diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java index 2eb1a14d00..2c1281920c 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java @@ -1,6 +1,7 @@ package net.vulkanmod.render.vertex; import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ExtendedRenderType; import net.vulkanmod.vulkan.VRenderSystem; @@ -45,6 +46,16 @@ public static TerrainRenderType get(RenderType renderType) { return ((ExtendedRenderType)renderType).getTerrainRenderType(); } + public static TerrainRenderType get(ChunkSectionLayer layer) { + return switch (layer) { + case SOLID -> SOLID; + case CUTOUT_MIPPED -> CUTOUT_MIPPED; + case CUTOUT -> CUTOUT; + case TRANSLUCENT -> TRANSLUCENT; + case TRIPWIRE -> TRIPWIRE; + }; + } + public static TerrainRenderType get(String name) { return switch (name) { case "solid" -> TerrainRenderType.SOLID; @@ -56,13 +67,13 @@ public static TerrainRenderType get(String name) { }; } - public static RenderType getRenderType(TerrainRenderType renderType) { + public static ChunkSectionLayer getLayer(TerrainRenderType renderType) { return switch (renderType) { - case SOLID -> RenderType.solid(); - case CUTOUT -> RenderType.cutout(); - case CUTOUT_MIPPED -> RenderType.cutoutMipped(); - case TRANSLUCENT -> RenderType.translucent(); - case TRIPWIRE -> RenderType.tripwire(); + case SOLID -> ChunkSectionLayer.SOLID; + case CUTOUT -> ChunkSectionLayer.CUTOUT; + case CUTOUT_MIPPED -> ChunkSectionLayer.CUTOUT_MIPPED; + case TRANSLUCENT -> ChunkSectionLayer.TRANSLUCENT; + case TRIPWIRE -> ChunkSectionLayer.TRIPWIRE; }; } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 45267dcb4a..b943942367 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -1,6 +1,6 @@ package net.vulkanmod.vulkan; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.opengl.GlStateManager; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.client.Minecraft; @@ -39,9 +39,9 @@ import java.util.List; import java.util.Set; -import static com.mojang.blaze3d.platform.GlConst.GL_COLOR_BUFFER_BIT; -import static com.mojang.blaze3d.platform.GlConst.GL_DEPTH_BUFFER_BIT; import static net.vulkanmod.vulkan.Vulkan.*; +import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; +import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.EXTDebugUtils.*; import static org.lwjgl.vulkan.KHRSwapchain.*; @@ -141,7 +141,6 @@ private void allocateCommandBuffers() { commandBuffers = new ArrayList<>(framesNum); try (MemoryStack stack = stackPush()) { - VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); allocInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO); allocInfo.commandPool(getCommandPool()); @@ -399,10 +398,7 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { if (skipRendering || !recordingCmds || this.boundFramebuffer == null) return; - if (!DYNAMIC_RENDERING) - this.boundRenderPass.endRenderPass(currentCmdBuffer); - else - KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); + this.boundRenderPass.endRenderPass(commandBuffer); this.boundRenderPass = null; this.boundFramebuffer = null; @@ -609,15 +605,31 @@ public static void setDepthBias(float constant, float slope) { vkCmdSetDepthBias(commandBuffer, constant, 0.0f, slope); } - public static void clearAttachments(int v) { + public static void clearAttachments(int attachments) { + clearAttachments(INSTANCE.currentCmdBuffer, attachments); + } + + public static void clearAttachments(VkCommandBuffer commandBuffer, int attachments) { Framebuffer framebuffer = Renderer.getInstance().boundFramebuffer; if (framebuffer == null) return; - clearAttachments(v, framebuffer.getWidth(), framebuffer.getHeight()); + clearAttachments(commandBuffer, attachments, framebuffer.getWidth(), framebuffer.getHeight()); + } + + public static void clearAttachments(int attachments, int width, int height) { + clearAttachments(INSTANCE.currentCmdBuffer, attachments, width ,height); } - public static void clearAttachments(int v, int width, int height) { + public static void clearAttachments(int attachments, int x, int y, int width, int height) { + clearAttachments(INSTANCE.currentCmdBuffer, attachments, x, y, width ,height); + } + + public static void clearAttachments(VkCommandBuffer commandBuffer, int attachments, int width, int height) { + clearAttachments(commandBuffer, attachments, 0, 0, width, height); + } + + public static void clearAttachments(VkCommandBuffer commandBuffer, int attachments, int x, int y, int width, int height) { if (skipRendering) return; @@ -630,9 +642,9 @@ public static void clearAttachments(int v, int width, int height) { VkClearValue depthValue = VkClearValue.calloc(stack); depthValue.depthStencil().set(VRenderSystem.clearDepthValue, 0); //Use fast depth clears if possible - int attachmentsCount = v == (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ? 2 : 1; + int attachmentsCount = attachments == (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ? 2 : 1; final VkClearAttachment.Buffer pAttachments = VkClearAttachment.malloc(attachmentsCount, stack); - switch (v) { + switch (attachments) { case GL_DEPTH_BUFFER_BIT -> { VkClearAttachment clearDepth = pAttachments.get(0); @@ -664,7 +676,7 @@ public static void clearAttachments(int v, int width, int height) { //Rect to clear VkRect2D renderArea = VkRect2D.malloc(stack); - renderArea.offset().set(0, 0); + renderArea.offset().set(x, y); renderArea.extent().set(width, height); VkClearRect.Buffer pRect = VkClearRect.malloc(1, stack); @@ -672,7 +684,7 @@ public static void clearAttachments(int v, int width, int height) { pRect.baseArrayLayer(0); pRect.layerCount(1); - vkCmdClearAttachments(INSTANCE.currentCmdBuffer, pAttachments, pRect); + vkCmdClearAttachments(commandBuffer, pAttachments, pRect); } } @@ -713,7 +725,7 @@ public static void setViewport(int x, int y, int width, int height, MemoryStack } public static void setScissor(int x, int y, int width, int height) { - if (INSTANCE.boundFramebuffer == null) + if (!INSTANCE.recordingCmds || INSTANCE.boundFramebuffer == null) return; try (MemoryStack stack = stackPush()) { diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index ca42ee5735..fb1fe44683 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -1,8 +1,11 @@ package net.vulkanmod.vulkan; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.platform.Window; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.fog.FogData; +import net.vulkanmod.render.engine.VkGpuBuffer; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.shader.PipelineState; import net.vulkanmod.vulkan.util.ColorUtil; @@ -50,6 +53,7 @@ public abstract class VRenderSystem { public static MappedBuffer shaderColor = new MappedBuffer(4 * 4); public static MappedBuffer shaderFogColor = new MappedBuffer(4 * 4); + public static FogData fogData; public static MappedBuffer screenSize = new MappedBuffer(2 * 4); @@ -103,6 +107,14 @@ public static void applyProjectionMatrix(Matrix4f mat) { mat.get(projectionMatrix.buffer.asFloatBuffer()); } + public static void applyProjectionMatrix(GpuBufferSlice bufferSlice) { + long ptr = ((VkGpuBuffer) bufferSlice.buffer()).getBuffer().getDataPtr(); + ByteBuffer byteBuffer = MemoryUtil.memByteBuffer(ptr + bufferSlice.offset(), bufferSlice.length()); + Matrix4f matrix4f = new Matrix4f().set(byteBuffer); + + matrix4f.get(projectionMatrix.buffer.asFloatBuffer()); + } + public static void calculateMVP() { org.joml.Matrix4f MV = new org.joml.Matrix4f(modelViewMatrix.buffer.asFloatBuffer()); org.joml.Matrix4f P = new org.joml.Matrix4f(projectionMatrix.buffer.asFloatBuffer()); @@ -153,6 +165,10 @@ public static MappedBuffer getShaderFogColor() { return shaderFogColor; } + public static FogData getFogData() { + return fogData; + } + public static void setClearColor(float f1, float f2, float f3, float f4) { ColorUtil.setRGBA_Buffer(clearColor, f1, f2, f3, f4); } diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 0ab7e71249..f2f0a16462 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -41,7 +41,6 @@ public class Vulkan { public static final boolean ENABLE_VALIDATION_LAYERS = false; // public static final boolean ENABLE_VALIDATION_LAYERS = true; - // public static final boolean DYNAMIC_RENDERING = true; public static final boolean DYNAMIC_RENDERING = false; public static final Set VALIDATION_LAYERS; @@ -148,7 +147,6 @@ public static void initVulkan(long window) { createCommandPool(); setupDepthFormat(); - Renderer.initRenderer(); } static void createStagingBuffers() { diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java index 589f00c218..56300de442 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java @@ -165,13 +165,18 @@ public void beginRenderPass(VkCommandBuffer commandBuffer, long framebufferId, M } public void endRenderPass(VkCommandBuffer commandBuffer) { - vkCmdEndRenderPass(commandBuffer); + if (Vulkan.DYNAMIC_RENDERING) { + KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); + } + else { + vkCmdEndRenderPass(commandBuffer); - if (colorAttachmentInfo != null) - framebuffer.getColorAttachment().setCurrentLayout(colorAttachmentInfo.finalLayout); + if (colorAttachmentInfo != null) + framebuffer.getColorAttachment().setCurrentLayout(colorAttachmentInfo.finalLayout); - if (depthAttachmentInfo != null) - framebuffer.getDepthAttachment().setCurrentLayout(depthAttachmentInfo.finalLayout); + if (depthAttachmentInfo != null) + framebuffer.getDepthAttachment().setCurrentLayout(depthAttachmentInfo.finalLayout); + } Renderer.getInstance().setBoundRenderPass(null); } @@ -219,10 +224,6 @@ public void beginDynamicRendering(VkCommandBuffer commandBuffer, MemoryStack sta KHRDynamicRendering.vkCmdBeginRenderingKHR(commandBuffer, renderingInfo); } - public void endDynamicRendering(VkCommandBuffer commandBuffer) { - KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); - } - public Framebuffer getFramebuffer() { return framebuffer; } diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 857a801238..e760a72d68 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -149,7 +149,7 @@ private void createSwapChain() { for (int i = 0; i < pSwapchainImages.capacity(); i++) { long imageId = pSwapchainImages.get(i); - long imageView = VulkanImage.createImageView(imageId, this.format, VK_IMAGE_ASPECT_COLOR_BIT, 1); + long imageView = VulkanImage.createImageView(imageId, this.format, VK_IMAGE_ASPECT_COLOR_BIT, 1, 1); VulkanImage image = new VulkanImage("Swapchain", imageId, this.format, 1, this.width, this.height, 4, 0, imageView); image.updateTextureSampler(true, true, false); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java index 9e9ea353ae..b52be11215 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java @@ -150,10 +150,10 @@ public synchronized void createBuffer(Buffer buffer, long size, int usage, int p } } - public void createImage(int width, int height, int mipLevels, int format, int tiling, int usage, - int memProperties, - LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { - + public void createImage(int width, int height, int arrayLayers, int mipLevels, + int format, int tiling, int usage, int flags, + int memProperties, + LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { try (MemoryStack stack = stackPush()) { VkImageCreateInfo imageInfo = VkImageCreateInfo.calloc(stack); imageInfo.sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO); @@ -162,12 +162,13 @@ public void createImage(int width, int height, int mipLevels, int format, int ti imageInfo.extent().height(height); imageInfo.extent().depth(1); imageInfo.mipLevels(mipLevels); - imageInfo.arrayLayers(1); + imageInfo.arrayLayers(arrayLayers); imageInfo.format(format); imageInfo.tiling(tiling); imageInfo.initialLayout(VK_IMAGE_LAYOUT_UNDEFINED); imageInfo.usage(usage); imageInfo.samples(VK_SAMPLE_COUNT_1_BIT); + imageInfo.flags(flags); // imageInfo.sharingMode(VK_SHARING_MODE_CONCURRENT); imageInfo.pQueueFamilyIndices( stack.ints(Queue.getQueueFamilies().graphicsFamily, Queue.getQueueFamilies().computeFamily)); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/BufferSlice.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/BufferSlice.java new file mode 100644 index 0000000000..8d3132f9b7 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/BufferSlice.java @@ -0,0 +1,25 @@ +package net.vulkanmod.vulkan.memory.buffer; + +public class BufferSlice { + Buffer buffer; + int offset; + int size; + + public void set(Buffer buffer, int offset, int size) { + this.buffer = buffer; + this.offset = offset; + this.size = size; + } + + public Buffer getBuffer() { + return buffer; + } + + public int getOffset() { + return offset; + } + + public int getSize() { + return size; + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java index a05ae38cf1..6fead50d26 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java @@ -1,8 +1,8 @@ package net.vulkanmod.vulkan.memory.buffer.index; import net.vulkanmod.Initializer; -import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -30,8 +30,7 @@ private void createIndexBuffer(int vertexCount) { IndexBuffer.IndexType indexType = IndexBuffer.IndexType.UINT16; if (vertexCount > U16_MAX_VERTEX_COUNT && - (this.drawType == DrawType.QUADS || this.drawType == DrawType.LINES)) - { + (this.drawType == DrawType.QUADS || this.drawType == DrawType.LINES)) { indexType = IndexBuffer.IndexType.UINT32; } @@ -58,8 +57,8 @@ private void createIndexBuffer(int vertexCount) { } public void checkCapacity(int vertexCount) { - if(vertexCount > this.vertexCount) { - int newVertexCount = this.vertexCount * 2; + if (vertexCount > this.vertexCount) { + int newVertexCount = Math.max(this.vertexCount * 2, vertexCount); Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); this.indexBuffer.scheduleFree(); @@ -67,11 +66,14 @@ public void checkCapacity(int vertexCount) { } } - public IndexBuffer getIndexBuffer() { return this.indexBuffer; } + public IndexBuffer getIndexBuffer() { + return this.indexBuffer; + } public void freeBuffer() { this.indexBuffer.scheduleFree(); } + public int getIndexCount(int vertexCount) { return getIndexCount(this.drawType, vertexCount); } @@ -107,7 +109,7 @@ public static ByteBuffer genQuadIndices(int vertexCount) { ShortBuffer idxs = buffer.asShortBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (short) (i)); idxs.put(j + 1, (short) (i + 1)); idxs.put(j + 2, (short) (i + 2)); @@ -129,7 +131,7 @@ public static ByteBuffer genIntQuadIndices(int vertexCount) { IntBuffer idxs = buffer.asIntBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (i)); idxs.put(j + 1, (i + 1)); idxs.put(j + 2, (i + 2)); @@ -151,7 +153,7 @@ public static ByteBuffer genLinesIndices(int vertexCount) { ShortBuffer idxs = buffer.asShortBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (short) (i)); idxs.put(j + 1, (short) (i + 1)); idxs.put(j + 2, (short) (i + 2)); diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index d063a42e66..94801d7585 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -1,8 +1,12 @@ package net.vulkanmod.vulkan.pass; import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; import net.minecraft.client.Minecraft; -import net.vulkanmod.gl.VkGlTexture; +import net.vulkanmod.render.engine.VkGpuDevice; +import net.vulkanmod.render.engine.VkGpuTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; @@ -29,7 +33,8 @@ public static DefaultMainPass create() { private RenderPass mainRenderPass; private RenderPass auxRenderPass; - private VkGlTexture[] colorAttachmentTextures; + private GpuTexture[] colorAttachmentTextures; + private GpuTextureView[] colorAttachmentTextureViews; DefaultMainPass() { this.mainTarget = Minecraft.getInstance().getMainRenderTarget(); @@ -65,8 +70,9 @@ public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { framebuffer.beginRenderPass(commandBuffer, this.mainRenderPass, stack); - VkViewport.Buffer pViewport = framebuffer.viewport(stack); - vkCmdSetViewport(commandBuffer, 0, pViewport); +// VkViewport.Buffer pViewport = framebuffer.viewport(stack); +// vkCmdSetViewport(commandBuffer, 0, pViewport); + Renderer.setViewport(0, 0, framebuffer.getWidth(), framebuffer.getHeight(), stack); VkRect2D.Buffer pScissor = framebuffer.scissor(stack); vkCmdSetScissor(commandBuffer, 0, pScissor); @@ -133,22 +139,29 @@ public void bindAsTexture() { } @Override - public VkGlTexture getColorAttachment() { + public GpuTexture getColorAttachment() { return this.colorAttachmentTextures[Renderer.getCurrentImage()]; } + @Override + public GpuTextureView getColorAttachmentView() { + return this.colorAttachmentTextureViews[Renderer.getCurrentImage()]; + } + private void createSwapChainTextures() { + VkGpuDevice device = (VkGpuDevice) RenderSystem.getDevice(); + SwapChain swapChain = Renderer.getInstance().getSwapChain(); var swapChainImages = swapChain.getImages(); int imageCount = swapChainImages.size(); - this.colorAttachmentTextures = new VkGlTexture[imageCount]; - - for (int i = 0; i < swapChainImages.size(); i++) { - int id = VkGlTexture.genTextureId(); - VkGlTexture glTexture = VkGlTexture.getTexture(id); - VkGlTexture.bindIdToImage(id, swapChainImages.get(i)); - this.colorAttachmentTextures[i] = glTexture; + this.colorAttachmentTextures = new GpuTexture[imageCount]; + this.colorAttachmentTextureViews = new GpuTextureView[imageCount]; + + for (int i = 0; i < imageCount; ++i) { + VkGpuTexture attachmentTexture = device.gpuTextureFromVulkanImage(swapChainImages.get(i)); + GpuTextureView attachmentTextureView = device.createTextureView(attachmentTexture); + this.colorAttachmentTextures[i] = attachmentTexture; + this.colorAttachmentTextureViews[i] = attachmentTextureView; } } - } diff --git a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java index 7ce2197488..63a843c58a 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java @@ -1,6 +1,7 @@ package net.vulkanmod.vulkan.pass; -import net.vulkanmod.gl.VkGlTexture; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkCommandBuffer; @@ -22,7 +23,11 @@ default void rebindMainTarget() {} default void bindAsTexture() {} - default VkGlTexture getColorAttachment() { - throw new UnsupportedOperationException(); + default GpuTexture getColorAttachment() { + return null; + } + + default GpuTextureView getColorAttachmentView() { + return null; } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java new file mode 100644 index 0000000000..07e1732536 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -0,0 +1,288 @@ +package net.vulkanmod.vulkan.shader; + +import net.vulkanmod.vulkan.Vulkan; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.BufferSlice; +import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; +import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.texture.VulkanImage; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.vulkan.*; + +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.util.Arrays; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK10.vkDestroyDescriptorPool; + +public class DescriptorSets { + private static final VkDevice DEVICE = Vulkan.getVkDevice(); + + private final Pipeline pipeline; + private int poolSize = 10; + private long descriptorPool; + private LongBuffer sets; + private long currentSet; + private int currentIdx = -1; + + private final long[] boundUBs; + private final ImageDescriptor.State[] boundTextures; + private final IntBuffer dynamicOffsets; + + DescriptorSets(Pipeline pipeline) { + this.pipeline = pipeline; + this.boundTextures = new ImageDescriptor.State[pipeline.imageDescriptors.size()]; + this.dynamicOffsets = MemoryUtil.memAllocInt(pipeline.buffers.size()); + this.boundUBs = new long[pipeline.buffers.size()]; + + Arrays.setAll(boundTextures, i -> new ImageDescriptor.State(0, 0)); + + try (MemoryStack stack = stackPush()) { + this.createDescriptorPool(stack); + this.createDescriptorSets(stack); + } + } + + protected void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuffer, int bindPoint) { + try (MemoryStack stack = stackPush()) { + + this.updateUniforms(uniformBuffer); + this.updateDescriptorSet(stack, uniformBuffer); + + vkCmdBindDescriptorSets(commandBuffer, bindPoint, pipeline.pipelineLayout, + 0, stack.longs(currentSet), dynamicOffsets); + } + } + + private void updateUniforms(UniformBuffer globalUB) { + int i = 0; + for (UBO ubo : pipeline.getBuffers()) { + boolean useOwnUB = !ubo.useGlobalBuffer(); + + int offset; + if (useOwnUB) { + BufferSlice bufferSlice = ubo.getBufferSlice(); + offset = bufferSlice.getOffset(); + } + else { + offset = (int) globalUB.getUsedBytes(); + int alignedSize = UniformBuffer.getAlignedSize(ubo.getSize()); + globalUB.checkCapacity(alignedSize); + + ubo.update(globalUB.getPointer()); + globalUB.updateOffset(alignedSize); + + BufferSlice bufferSlice = ubo.getBufferSlice(); + bufferSlice.set(globalUB, offset, alignedSize); + } + + this.dynamicOffsets.put(i, offset); + + ++i; + } + } + + private boolean needsUpdate(UniformBuffer uniformBuffer) { + if (currentIdx == -1) + return true; + + for (int j = 0; j < pipeline.imageDescriptors.size(); ++j) { + ImageDescriptor imageDescriptor = pipeline.imageDescriptors.get(j); + VulkanImage image = imageDescriptor.getImage(); + + if (image == null) { + throw new NullPointerException(); + } + + long view = imageDescriptor.getImageView(image); + long sampler = image.getSampler(); + + if (imageDescriptor.isReadOnlyLayout) + image.readOnlyLayout(); + + if (!this.boundTextures[j].isCurrentState(view, sampler)) { + return true; + } + } + + for (int j = 0; j < pipeline.buffers.size(); ++j) { + UBO ubo = pipeline.buffers.get(j); + Buffer uniformBufferI = ubo.getBufferSlice().getBuffer(); + + + if (uniformBufferI == null) + uniformBufferI = uniformBuffer; + + if (this.boundUBs[j] != uniformBufferI.getId()) { + return true; + } + } + + return false; + } + + private void checkPoolSize(MemoryStack stack) { + if (this.currentIdx >= this.poolSize) { + this.poolSize *= 2; + + this.createDescriptorPool(stack); + this.createDescriptorSets(stack); + this.currentIdx = 0; + } + } + + private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) { + + // Check if update is needed + if (!needsUpdate(uniformBuffer)) + return; + + this.currentIdx++; + + // Check pool size + checkPoolSize(stack); + + this.currentSet = this.sets.get(this.currentIdx); + + VkWriteDescriptorSet.Buffer descriptorWrites = VkWriteDescriptorSet.calloc(pipeline.buffers.size() + pipeline.imageDescriptors.size(), stack); + VkDescriptorBufferInfo.Buffer[] bufferInfos = new VkDescriptorBufferInfo.Buffer[pipeline.buffers.size()]; + + //TODO maybe ubo update is not needed everytime + int i = 0; + for (UBO ubo : pipeline.getBuffers()) { + Buffer ub = ubo.getBufferSlice().getBuffer(); + boundUBs[i] = ub.getId(); + + bufferInfos[i] = VkDescriptorBufferInfo.calloc(1, stack); + bufferInfos[i].buffer(boundUBs[i]); + bufferInfos[i].range(ubo.getSize()); + + VkWriteDescriptorSet descriptorWrite = descriptorWrites.get(i); + descriptorWrite.sType$Default(); + descriptorWrite.dstBinding(ubo.getBinding()); + descriptorWrite.dstArrayElement(0); + descriptorWrite.descriptorType(ubo.getType()); + descriptorWrite.descriptorCount(1); + descriptorWrite.pBufferInfo(bufferInfos[i]); + descriptorWrite.dstSet(currentSet); + + ++i; + } + + VkDescriptorImageInfo.Buffer[] imageInfo = new VkDescriptorImageInfo.Buffer[pipeline.imageDescriptors.size()]; + + for (int j = 0; j < pipeline.imageDescriptors.size(); ++j) { + ImageDescriptor imageDescriptor = pipeline.imageDescriptors.get(j); + VulkanImage image = imageDescriptor.getImage(); + + if (image == null) { + throw new NullPointerException(); + } + + long view = imageDescriptor.getImageView(image); + long sampler = image.getSampler(); + int layout = imageDescriptor.getLayout(); + + if (imageDescriptor.isReadOnlyLayout) + image.readOnlyLayout(); + + imageInfo[j] = VkDescriptorImageInfo.calloc(1, stack); + imageInfo[j].imageLayout(layout); + imageInfo[j].imageView(view); + + if (imageDescriptor.useSampler) { + imageInfo[j].sampler(sampler); + } + + VkWriteDescriptorSet descriptorWrite = descriptorWrites.get(i); + descriptorWrite.sType$Default(); + descriptorWrite.dstBinding(imageDescriptor.getBinding()); + descriptorWrite.dstArrayElement(0); + descriptorWrite.descriptorType(imageDescriptor.getType()); + descriptorWrite.descriptorCount(1); + descriptorWrite.pImageInfo(imageInfo[j]); + descriptorWrite.dstSet(currentSet); + + this.boundTextures[j].set(view, sampler); + ++i; + } + + vkUpdateDescriptorSets(DEVICE, descriptorWrites, null); + } + + private void createDescriptorSets(MemoryStack stack) { + LongBuffer layout = stack.mallocLong(this.poolSize); + + for (int i = 0; i < this.poolSize; ++i) { + layout.put(i, pipeline.descriptorSetLayout); + } + + VkDescriptorSetAllocateInfo allocInfo = VkDescriptorSetAllocateInfo.calloc(stack); + allocInfo.sType$Default(); + allocInfo.descriptorPool(descriptorPool); + allocInfo.pSetLayouts(layout); + + this.sets = MemoryUtil.memAllocLong(this.poolSize); + + int result = vkAllocateDescriptorSets(DEVICE, allocInfo, this.sets); + if (result != VK_SUCCESS) { + throw new RuntimeException("Failed to allocate descriptor sets. Result:" + result); + } + } + + private void createDescriptorPool(MemoryStack stack) { + int size = pipeline.buffers.size() + pipeline.imageDescriptors.size(); + + VkDescriptorPoolSize.Buffer poolSizes = VkDescriptorPoolSize.calloc(size, stack); + + int i; + for (i = 0; i < pipeline.buffers.size(); ++i) { + VkDescriptorPoolSize uniformBufferPoolSize = poolSizes.get(i); + uniformBufferPoolSize.type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC); + uniformBufferPoolSize.descriptorCount(this.poolSize); + } + + for (; i < pipeline.buffers.size() + pipeline.imageDescriptors.size(); ++i) { + VkDescriptorPoolSize textureSamplerPoolSize = poolSizes.get(i); + textureSamplerPoolSize.type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); + textureSamplerPoolSize.descriptorCount(this.poolSize); + } + + VkDescriptorPoolCreateInfo poolInfo = VkDescriptorPoolCreateInfo.calloc(stack); + poolInfo.sType(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO); + poolInfo.pPoolSizes(poolSizes); + poolInfo.maxSets(this.poolSize); + + LongBuffer pDescriptorPool = stack.mallocLong(1); + + if (vkCreateDescriptorPool(DEVICE, poolInfo, null, pDescriptorPool) != VK_SUCCESS) { + throw new RuntimeException("Failed to create descriptor pool"); + } + + if (this.descriptorPool != VK_NULL_HANDLE) { + final long oldDescriptorPool = this.descriptorPool; + MemoryManager.getInstance().addFrameOp(() -> { + vkDestroyDescriptorPool(DEVICE, oldDescriptorPool, null); + }); + } + + this.descriptorPool = pDescriptorPool.get(0); + } + + public void resetIdx() { + this.currentIdx = -1; + } + + public void cleanUp() { + vkResetDescriptorPool(DEVICE, descriptorPool, 0); + vkDestroyDescriptorPool(DEVICE, descriptorPool, null); + + MemoryUtil.memFree(this.dynamicOffsets); + } + +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java index d94ad1b024..abf9e7e079 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -1,5 +1,6 @@ package net.vulkanmod.vulkan.shader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; import it.unimi.dsi.fastutil.objects.Object2LongMap; @@ -16,7 +17,6 @@ import java.nio.LongBuffer; import java.util.List; -import static org.lwjgl.system.MemoryStack.stackGet; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.VK10.*; @@ -80,8 +80,11 @@ private long createGraphicsPipeline(PipelineState state) { VkPipelineVertexInputStateCreateInfo vertexInputInfo = VkPipelineVertexInputStateCreateInfo.calloc(stack); vertexInputInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO); - vertexInputInfo.pVertexBindingDescriptions(vertexInputDescription.bindingDescriptions); - vertexInputInfo.pVertexAttributeDescriptions(vertexInputDescription.attributeDescriptions); + + if (vertexInputDescription != null) { + vertexInputInfo.pVertexBindingDescriptions(vertexInputDescription.bindingDescriptions); + vertexInputInfo.pVertexAttributeDescriptions(vertexInputDescription.attributeDescriptions); + } // ===> ASSEMBLY STAGE <=== @@ -241,13 +244,21 @@ static class VertexInputDescription { final VkVertexInputBindingDescription.Buffer bindingDescriptions; VertexInputDescription(VertexFormat vertexFormat) { - this.bindingDescriptions = getBindingDescription(vertexFormat); - this.attributeDescriptions = getAttributeDescriptions(vertexFormat); + if (vertexFormat != DefaultVertexFormat.EMPTY) { + this.bindingDescriptions = getBindingDescription(vertexFormat); + this.attributeDescriptions = getAttributeDescriptions(vertexFormat); + } + else { + this.bindingDescriptions = null; + this.attributeDescriptions = null; + } } void cleanUp() { - MemoryUtil.memFree(this.bindingDescriptions); - MemoryUtil.memFree(this.attributeDescriptions); + if (this.bindingDescriptions != null) { + MemoryUtil.memFree(this.bindingDescriptions); + MemoryUtil.memFree(this.attributeDescriptions); + } } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 49d146cf2c..2c70890fcf 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -20,21 +20,18 @@ import net.vulkanmod.vulkan.shader.layout.PushConstants; import net.vulkanmod.vulkan.shader.layout.Uniform; import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.texture.VulkanImage; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.lang3.Validate; import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.*; import java.nio.ByteBuffer; -import java.nio.IntBuffer; import java.nio.LongBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; import static org.lwjgl.system.MemoryStack.stackPush; @@ -192,6 +189,44 @@ public long getLayout() { return pipelineLayout; } + public List getBuffers() { + return buffers; + } + + public UBO getUBO(int binding) { + return getUBO(ubo -> ubo.binding == binding); + } + + public UBO getUBO(String name) { + return getUBO(ubo -> ubo.name.equals(name)); + } + + public UBO getUBO(Predicate fn) { + UBO ubo = null; + for (UBO ubo1 : this.buffers) { + if (fn.test(ubo1)) { + ubo = ubo1; + } + } + + return ubo; + } + + public ImageDescriptor getImageDescriptor(String name) { + return getImageDescriptor(imageDescriptor -> imageDescriptor.name.equals(name)); + } + + public ImageDescriptor getImageDescriptor(Predicate fn) { + ImageDescriptor descriptor = null; + for (ImageDescriptor descriptor1 : this.imageDescriptors) { + if (fn.test(descriptor1)) { + descriptor = descriptor1; + } + } + + return descriptor; + } + public List getImageDescriptors() { return imageDescriptors; } @@ -224,261 +259,6 @@ static long createShaderModule(ByteBuffer spirvCode) { } } - protected static class DescriptorSets { - private final Pipeline pipeline; - private int poolSize = 10; - private long descriptorPool; - private LongBuffer sets; - private long currentSet; - private int currentIdx = -1; - - private final long[] boundUBs; - private final ImageDescriptor.State[] boundTextures; - private final IntBuffer dynamicOffsets; - - DescriptorSets(Pipeline pipeline) { - this.pipeline = pipeline; - this.boundTextures = new ImageDescriptor.State[pipeline.imageDescriptors.size()]; - this.dynamicOffsets = MemoryUtil.memAllocInt(pipeline.buffers.size()); - this.boundUBs = new long[pipeline.buffers.size()]; - - Arrays.setAll(boundTextures, i -> new ImageDescriptor.State(0, 0)); - - try (MemoryStack stack = stackPush()) { - this.createDescriptorPool(stack); - this.createDescriptorSets(stack); - } - } - - protected void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuffer, int bindPoint) { - try (MemoryStack stack = stackPush()) { - - this.updateUniforms(uniformBuffer); - this.updateDescriptorSet(stack, uniformBuffer); - - vkCmdBindDescriptorSets(commandBuffer, bindPoint, pipeline.pipelineLayout, - 0, stack.longs(currentSet), dynamicOffsets); - } - } - - private void updateUniforms(UniformBuffer globalUB) { - int i = 0; - for (UBO ubo : pipeline.buffers) { - boolean useOwnUB = ubo.getUniformBuffer() != null; - UniformBuffer ub = useOwnUB ? ubo.getUniformBuffer() : globalUB; - - int currentOffset = (int) ub.getUsedBytes(); - this.dynamicOffsets.put(i, currentOffset); - - // TODO: non mappable memory - - int alignedSize = UniformBuffer.getAlignedSize(ubo.getSize()); - ub.checkCapacity(alignedSize); - - if (!useOwnUB) { - ubo.update(ub.getPointer()); - ub.updateOffset(alignedSize); - } - - ++i; - } - } - - private boolean needsUpdate(UniformBuffer uniformBuffer) { - if (currentIdx == -1) - return true; - - for (int j = 0; j < pipeline.imageDescriptors.size(); ++j) { - ImageDescriptor imageDescriptor = pipeline.imageDescriptors.get(j); - VulkanImage image = imageDescriptor.getImage(); - long view = imageDescriptor.getImageView(image); - long sampler = image.getSampler(); - - if (imageDescriptor.isReadOnlyLayout) - image.readOnlyLayout(); - - if (!this.boundTextures[j].isCurrentState(view, sampler)) { - return true; - } - } - - for (int j = 0; j < pipeline.buffers.size(); ++j) { - UBO ubo = pipeline.buffers.get(j); - UniformBuffer uniformBufferI = ubo.getUniformBuffer(); - - if (uniformBufferI == null) - uniformBufferI = uniformBuffer; - - if (this.boundUBs[j] != uniformBufferI.getId()) { - return true; - } - } - - return false; - } - - private void checkPoolSize(MemoryStack stack) { - if (this.currentIdx >= this.poolSize) { - this.poolSize *= 2; - - this.createDescriptorPool(stack); - this.createDescriptorSets(stack); - this.currentIdx = 0; - - //debug -// System.out.println("resized descriptor pool to: " + this.poolSize); - } - } - - private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) { - - //Check if update is needed - if (!needsUpdate(uniformBuffer)) - return; - - this.currentIdx++; - - //Check pool size - checkPoolSize(stack); - - this.currentSet = this.sets.get(this.currentIdx); - - VkWriteDescriptorSet.Buffer descriptorWrites = VkWriteDescriptorSet.calloc(pipeline.buffers.size() + pipeline.imageDescriptors.size(), stack); - VkDescriptorBufferInfo.Buffer[] bufferInfos = new VkDescriptorBufferInfo.Buffer[pipeline.buffers.size()]; - - //TODO maybe ubo update is not needed everytime - int i = 0; - for (UBO ubo : pipeline.buffers) { - UniformBuffer ub = ubo.getUniformBuffer(); - if (ub == null) - ub = uniformBuffer; - boundUBs[i] = ub.getId(); - - bufferInfos[i] = VkDescriptorBufferInfo.calloc(1, stack); - bufferInfos[i].buffer(boundUBs[i]); - bufferInfos[i].range(ubo.getSize()); - - VkWriteDescriptorSet uboDescriptorWrite = descriptorWrites.get(i); - uboDescriptorWrite.sType$Default(); - uboDescriptorWrite.dstBinding(ubo.getBinding()); - uboDescriptorWrite.dstArrayElement(0); - uboDescriptorWrite.descriptorType(ubo.getType()); - uboDescriptorWrite.descriptorCount(1); - uboDescriptorWrite.pBufferInfo(bufferInfos[i]); - uboDescriptorWrite.dstSet(currentSet); - - ++i; - } - - VkDescriptorImageInfo.Buffer[] imageInfo = new VkDescriptorImageInfo.Buffer[pipeline.imageDescriptors.size()]; - - for (int j = 0; j < pipeline.imageDescriptors.size(); ++j) { - ImageDescriptor imageDescriptor = pipeline.imageDescriptors.get(j); - VulkanImage image = imageDescriptor.getImage(); - long view = imageDescriptor.getImageView(image); - long sampler = image.getSampler(); - int layout = imageDescriptor.getLayout(); - - if (imageDescriptor.isReadOnlyLayout) - image.readOnlyLayout(); - - imageInfo[j] = VkDescriptorImageInfo.calloc(1, stack); - imageInfo[j].imageLayout(layout); - imageInfo[j].imageView(view); - - if (imageDescriptor.useSampler) - imageInfo[j].sampler(sampler); - - VkWriteDescriptorSet samplerDescriptorWrite = descriptorWrites.get(i); - samplerDescriptorWrite.sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET); - samplerDescriptorWrite.dstBinding(imageDescriptor.getBinding()); - samplerDescriptorWrite.dstArrayElement(0); - samplerDescriptorWrite.descriptorType(imageDescriptor.getType()); - samplerDescriptorWrite.descriptorCount(1); - samplerDescriptorWrite.pImageInfo(imageInfo[j]); - samplerDescriptorWrite.dstSet(currentSet); - - this.boundTextures[j].set(view, sampler); - ++i; - } - - vkUpdateDescriptorSets(DEVICE, descriptorWrites, null); - } - - private void createDescriptorSets(MemoryStack stack) { - LongBuffer layout = stack.mallocLong(this.poolSize); -// layout.put(0, descriptorSetLayout); - - for (int i = 0; i < this.poolSize; ++i) { - layout.put(i, pipeline.descriptorSetLayout); - } - - VkDescriptorSetAllocateInfo allocInfo = VkDescriptorSetAllocateInfo.calloc(stack); - allocInfo.sType$Default(); - allocInfo.descriptorPool(descriptorPool); - allocInfo.pSetLayouts(layout); - - this.sets = MemoryUtil.memAllocLong(this.poolSize); - - int result = vkAllocateDescriptorSets(DEVICE, allocInfo, this.sets); - if (result != VK_SUCCESS) { - throw new RuntimeException("Failed to allocate descriptor sets. Result:" + result); - } - } - - private void createDescriptorPool(MemoryStack stack) { - int size = pipeline.buffers.size() + pipeline.imageDescriptors.size(); - - VkDescriptorPoolSize.Buffer poolSizes = VkDescriptorPoolSize.calloc(size, stack); - - int i; - for (i = 0; i < pipeline.buffers.size(); ++i) { - VkDescriptorPoolSize uniformBufferPoolSize = poolSizes.get(i); -// uniformBufferPoolSize.type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER); - uniformBufferPoolSize.type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC); - uniformBufferPoolSize.descriptorCount(this.poolSize); - } - - for (; i < pipeline.buffers.size() + pipeline.imageDescriptors.size(); ++i) { - VkDescriptorPoolSize textureSamplerPoolSize = poolSizes.get(i); - textureSamplerPoolSize.type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); - textureSamplerPoolSize.descriptorCount(this.poolSize); - } - - VkDescriptorPoolCreateInfo poolInfo = VkDescriptorPoolCreateInfo.calloc(stack); - poolInfo.sType(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO); - poolInfo.pPoolSizes(poolSizes); - poolInfo.maxSets(this.poolSize); - - LongBuffer pDescriptorPool = stack.mallocLong(1); - - if (vkCreateDescriptorPool(DEVICE, poolInfo, null, pDescriptorPool) != VK_SUCCESS) { - throw new RuntimeException("Failed to create descriptor pool"); - } - - if (this.descriptorPool != VK_NULL_HANDLE) { - final long oldDescriptorPool = this.descriptorPool; - MemoryManager.getInstance().addFrameOp(() -> { - vkDestroyDescriptorPool(DEVICE, oldDescriptorPool, null); - }); - } - - this.descriptorPool = pDescriptorPool.get(0); - } - - public void resetIdx() { - this.currentIdx = -1; - } - - private void cleanUp() { - vkResetDescriptorPool(DEVICE, descriptorPool, 0); - vkDestroyDescriptorPool(DEVICE, descriptorPool, null); - - MemoryUtil.memFree(this.dynamicOffsets); - } - - } - public static class Builder { final VertexFormat vertexFormat; final String shaderPath; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java index 8015cbf1b0..1c7d0e5cd4 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java @@ -1,6 +1,5 @@ package net.vulkanmod.vulkan.shader; -import com.mojang.blaze3d.platform.GlStateManager; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.framebuffer.RenderPass; @@ -129,21 +128,6 @@ public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlp this.blendOp = blendOp; } - public void setBlendFunction(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - this.srcRgbFactor = glToVulkanBlendFactor(sourceFactor.value); - this.srcAlphaFactor = glToVulkanBlendFactor(sourceFactor.value); - this.dstRgbFactor = glToVulkanBlendFactor(destFactor.value); - this.dstAlphaFactor = glToVulkanBlendFactor(destFactor.value); - } - - public void setBlendFuncSeparate(GlStateManager.SourceFactor srcRgb, GlStateManager.DestFactor dstRgb, - GlStateManager.SourceFactor srcAlpha, GlStateManager.DestFactor dstAlpha) { - this.srcRgbFactor = glToVulkanBlendFactor(srcRgb.value); - this.srcAlphaFactor = glToVulkanBlendFactor(srcAlpha.value); - this.dstRgbFactor = glToVulkanBlendFactor(dstRgb.value); - this.dstAlphaFactor = glToVulkanBlendFactor(dstAlpha.value); - } - /* gl to Vulkan conversion */ public void setBlendFunction(int sourceFactor, int destFactor) { this.srcRgbFactor = glToVulkanBlendFactor(sourceFactor); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index 05c95e547c..a45379fde8 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -22,8 +22,8 @@ import static org.lwjgl.util.shaderc.Shaderc.*; public class SPIRVUtils { - private static final boolean DEBUG = false; - private static final boolean OPTIMIZATIONS = true; + private static final boolean DEBUG = true; + private static final boolean OPTIMIZATIONS = false; private static long compiler; private static long options; @@ -84,9 +84,8 @@ public static SPIRV compileShader(String filename, String source, ShaderKind sha } if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) { - throw new RuntimeException( - "Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message( - result)); + String errorMessage = shaderc_result_get_error_message(result); + throw new RuntimeException("Failed to compile shader %s into SPIR-V:\n\t%s".formatted(filename, errorMessage)); } return new SPIRV(result, shaderc_result_get_bytes(result)); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java index 9a30567ae3..e7e81619d0 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java @@ -29,14 +29,17 @@ public static void setupDefaultUniforms() { //Vec1i vec1i_uniformMap.put("EndPortalLayers", () -> 15); - vec1i_uniformMap.put("FogShape", () -> RenderSystem.getShaderFog().shape().getIndex()); //Vec1 - vec1f_uniformMap.put("FogStart", () -> RenderSystem.getShaderFog().start()); - vec1f_uniformMap.put("FogEnd", () -> RenderSystem.getShaderFog().end()); + vec1f_uniformMap.put("FogStart", () -> VRenderSystem.getFogData().renderDistanceStart); + vec1f_uniformMap.put("FogEnd", () -> VRenderSystem.getFogData().renderDistanceEnd); + vec1f_uniformMap.put("FogEnvironmentalStart", () -> VRenderSystem.getFogData().environmentalStart); + vec1f_uniformMap.put("FogEnvironmentalEnd", () -> VRenderSystem.getFogData().environmentalEnd); + vec1f_uniformMap.put("FogRenderDistanceStart", () -> VRenderSystem.getFogData().renderDistanceStart); + vec1f_uniformMap.put("FogRenderDistanceEnd", () -> VRenderSystem.getFogData().renderDistanceEnd); + vec1f_uniformMap.put("FogSkyEnd", () -> VRenderSystem.getFogData().skyEnd); + vec1f_uniformMap.put("FogCloudsEnd", () -> VRenderSystem.getFogData().cloudEnd); vec1f_uniformMap.put("LineWidth", RenderSystem::getShaderLineWidth); - vec1f_uniformMap.put("GameTime", RenderSystem::getShaderGameTime); - vec1f_uniformMap.put("GlintAlpha", RenderSystem::getShaderGlintAlpha); vec1f_uniformMap.put("AlphaCutout", () -> VRenderSystem.alphaCutout); //Vec2 @@ -46,6 +49,7 @@ public static void setupDefaultUniforms() { vec3f_uniformMap.put("Light0_Direction", () -> VRenderSystem.lightDirection0); vec3f_uniformMap.put("Light1_Direction", () -> VRenderSystem.lightDirection1); vec3f_uniformMap.put("ModelOffset", () -> VRenderSystem.modelOffset); + vec3f_uniformMap.put("ChunkOffset", () -> VRenderSystem.modelOffset); //Vec4 vec4f_uniformMap.put("ColorModulator", VRenderSystem::getShaderColor); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Attribute.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Attribute.java new file mode 100644 index 0000000000..4bce3fb513 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Attribute.java @@ -0,0 +1,29 @@ +package net.vulkanmod.vulkan.shader.converter; + +public class Attribute { + + String ioType; + String type; + String id; + int location; + + public Attribute(String ioType, String type, String id) { + switch (ioType) { + case "in", "out" -> {} + default -> throw new IllegalArgumentException(); + } + + this.ioType = ioType; + this.type = type; + this.id = id; + } + + public void setLocation(int location) { + this.location = location; + } + + public GLSLParser.Node getNode() { + return new GLSLParser.Node("attribute", "layout(location = %d) %s %s %s;\n".formatted(location, ioType, type, id)); + } + +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java deleted file mode 100644 index 7ed82e3fbe..0000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/CodeParser.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.vulkanmod.vulkan.shader.converter; - -import it.unimi.dsi.fastutil.objects.ObjectArrayList; - -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; - -public abstract class CodeParser { - - /* TODO: this is not a proper parser, it just serves the purpose of converting glsl shaders - to solve some simple and common compatibility issues. - Implementing an AST would be a better solution. - */ - public static String parseCodeLine(String line) { - LinkedList tokens = new LinkedList<>(); - StringTokenizer tokenizer = new StringTokenizer(line, " \t\n\r\f,(){}%", true); - - String delims = " \t\n\r\f"; - - String token; - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - - if (!delims.contains(token)) - tokens.add(token); - } - - List processed = new ObjectArrayList<>(); - boolean changed = false; - - int i = 0; - while (i < tokens.size()) { - token = tokens.get(i); - - if (token.equals("%")) { - processed.removeLast(); - - String prevToken = tokens.get(i - 1); - String nextToken = tokens.get(i + 1); - - prevToken = checkTokenMapping(prevToken); - nextToken = checkTokenMapping(nextToken); - - String newToken = "mod(%s, %s)".formatted(prevToken, nextToken); - processed.add(newToken); - - changed = true; - - i += 2; - continue; - } - - String remappedToken = checkTokenMapping(token); - - if (!remappedToken.equals(token)) - changed = true; - - processed.add(remappedToken + " "); - i++; - } - - if (changed) { - StringBuilder stringBuilder = new StringBuilder(); - - for (String s : processed) { - stringBuilder.append(s); - } - - return stringBuilder.toString(); - } else { - return line; - } - } - - private static String checkTokenMapping(String token) { - return switch (token) { - case "gl_VertexID" -> "gl_VertexIndex"; - default -> token; - }; - } -} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java new file mode 100644 index 0000000000..e3fae40555 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java @@ -0,0 +1,483 @@ +package net.vulkanmod.vulkan.shader.converter; + +import com.mojang.blaze3d.vertex.VertexFormat; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; +import net.vulkanmod.vulkan.shader.descriptor.UBO; +import net.vulkanmod.vulkan.shader.layout.AlignedStruct; +import net.vulkanmod.vulkan.shader.layout.Uniform; +import net.vulkanmod.vulkan.texture.VTextureSelector; +import org.lwjgl.vulkan.VK11; + +import java.util.*; + +/** + * Simple parser used to convert GLSL shader code to make it Vulkan compatible + */ +public class GLSLParser { + private Lexer lexer; + private List tokens; + private int currentTokenIdx; + private Token currentToken; + + private Stage stage; + State state = State.DEFAULT; + + LinkedList vsStream = new LinkedList<>(); + LinkedList fsStream = new LinkedList<>(); + + int currentUniformLocation = 0; + List uniformBlocks = new ArrayList<>(); + Map uniformBlockMap = new HashMap<>(); + List samplers = new ArrayList<>(); + Map samplerMap = new HashMap<>(); + + VertexFormat vertexFormat; + int currentInAtt = 0, currentOutAtt = 0; + ArrayList vertInAttributes = new ArrayList<>(); + ArrayList vertOutAttributes = new ArrayList<>(); + ArrayList fragInAttributes = new ArrayList<>(); + ArrayList fragOutAttributes = new ArrayList<>(); + + public GLSLParser() {} + + public void setVertexFormat(VertexFormat vertexFormat) { + this.vertexFormat = vertexFormat; + } + + public void parse(Lexer lexer, Stage stage) { + this.stage = stage; + this.lexer = lexer; + this.tokens = this.lexer.tokenize(); + this.currentTokenIdx = 0; + + this.currentInAtt = 0; + this.currentOutAtt = 0; + + nextToken(); + + // Parse version + if (currentToken.type != Token.TokenType.PREPROCESSOR && !currentToken.value.startsWith("#version")) { + throw new IllegalStateException("First glsl line must contain version"); + } + appendToken(new Token(Token.TokenType.PREPROCESSOR, "#version 450\n")); + nextToken(); + + + while (currentToken.type != Token.TokenType.EOF) { + switch (currentToken.type) { + case PREPROCESSOR -> parsePreprocessor(); + + case IDENTIFIER -> { + switch (currentToken.value) { + case "layout" -> parseUniformBlock(); + case "uniform" -> parseUniform(); + case "in", "out" -> parseAttribute(); + default -> appendToken(currentToken); + } + } + + case OPERATOR -> { + // TODO: need to parse expressions to replace % operator + appendToken(currentToken); + } + + default -> appendToken(currentToken); + } + + nextToken(); + } + } + + private void parsePreprocessor() { + if (!currentToken.value.startsWith("#line")) { + appendToken(currentToken); + } + } + + private void parseUniform() { + nextToken(true); + + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + + switch (currentToken.value) { + case "sampler2D" -> parseSampler(Sampler.Type.SAMPLER_2D); + case "samplerCube" -> parseSampler(Sampler.Type.SAMPLER_CUBE); + case "isamplerBuffer" -> parseSampler(Sampler.Type.I_SAMPLER_BUFFER); + + default -> throw new IllegalStateException("Unrecognized value: %s".formatted(currentToken.value)); + } + // TODO: parse uniform + } + + private void parseSampler(Sampler.Type type) { + nextToken(true); + + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + + String name = currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.SEMICOLON) { + throw new IllegalStateException(); + } + + Token next = this.tokens.get(currentTokenIdx); + if (next.type == Token.TokenType.SPACING) { + if (Objects.equals(next.value, "\n")) { + currentTokenIdx++; + } + else { + int i = next.value.indexOf("\n"); + if (i >= 0) { + next.value = next.value.substring(i + 1); + } + } + } + + Sampler sampler = new Sampler(type, name); + + if (samplerMap.get(name) != null) { + sampler = samplerMap.get(name); + } + else { + sampler.setBinding(currentUniformLocation++); + this.samplerMap.put(name, sampler); + this.samplers.add(sampler); + } + + appendNode(sampler.getNode()); + } + + private void parseUniformBlock() { + this.state = State.LAYOUT; + + nextToken(true); + + if (currentToken.type != Token.TokenType.LEFT_PARENTHESIS) { + throw new IllegalStateException(); + } + + do { + nextToken(true); + } while (currentToken.type != Token.TokenType.RIGHT_PARENTHESIS); + + nextToken(true); + + if (!Objects.equals(this.currentToken.value, "uniform")) { + throw new IllegalStateException(); + } + + nextToken(true); + String name = currentToken.value; + + UniformBlock ub = new UniformBlock(name); + + nextToken(true); + if (currentToken.type != Token.TokenType.LEFT_BRACE) { + throw new IllegalStateException(); + } + + nextToken(true); + + // Recognize fields + while (currentToken.type != Token.TokenType.RIGHT_BRACE) { + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + String fieldType = this.currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + String fieldName = this.currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.SEMICOLON) { + throw new IllegalStateException(); + } + + // Add field + ub.addField(new UniformBlock.Field(fieldType, fieldName)); + + nextToken(true); + } + + nextToken(true); + + switch (currentToken.type) { + case SEMICOLON -> {} + + case IDENTIFIER -> { + ub.setAlias(currentToken.value); + + nextToken(true); + if (currentToken.type != Token.TokenType.SEMICOLON) { + throw new IllegalStateException(); + } + } + + default -> throw new IllegalStateException(); + } + + Token next = this.tokens.get(currentTokenIdx); + if (next.type == Token.TokenType.SPACING) { + if (Objects.equals(next.value, "\n")) { + currentTokenIdx++; + } + else { + int i = next.value.indexOf("\n"); + if (i >= 0) { + next.value = next.value.substring(i + 1); + } + } + } + + if (uniformBlockMap.get(ub.name) != null) { + ub = uniformBlockMap.get(ub.name); + } + else { + ub.setBinding(this.currentUniformLocation++); + this.uniformBlockMap.put(ub.name, ub); + this.uniformBlocks.add(ub); + } + + appendNode(ub.getNode()); + } + + private void parseAttribute() { + this.state = State.ATTRIBUTE; + + String ioType = this.currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + String type = this.currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.IDENTIFIER) { + throw new IllegalStateException(); + } + String id = this.currentToken.value; + + nextToken(true); + if (currentToken.type != Token.TokenType.SEMICOLON) { + throw new IllegalStateException(); + } + + Token next = this.tokens.get(currentTokenIdx); + if (next.type == Token.TokenType.SPACING) { + if (Objects.equals(next.value, "\n")) { + currentTokenIdx++; + } + else { + int i = next.value.indexOf("\n"); + if (i >= 0) { + next.value = next.value.substring(i + 1); + } + } + } + + Attribute attribute = new Attribute(ioType, type, id); + + switch (this.stage) { + case VERTEX -> { + switch (attribute.ioType) { + case "in" -> { + int attributeLocation; + if (this.vertexFormat != null) { + var attributeNames = this.vertexFormat.getElementAttributeNames(); + attributeLocation = attributeNames.indexOf(attribute.id); + + if (attributeLocation == -1) { + throw new IllegalStateException("Element %s not found in elements %s".formatted(attribute.id, attributeNames)); + } + } else { + attributeLocation = currentInAtt++; + } + + attribute.setLocation(attributeLocation); + vertInAttributes.add(attribute); + } + case "out" -> { + attribute.setLocation(currentOutAtt++); + vertOutAttributes.add(attribute); + } + default -> throw new IllegalStateException(); + } + } + case FRAGMENT -> { + switch (attribute.ioType) { + case "in" -> { + // Find matching vertex out attribute + final var vertAttribute = getVertAttribute(attribute); + + if (vertAttribute != null) { + attribute.setLocation(vertAttribute.location); + fragInAttributes.add(attribute); + } + else { + return; + } + } + case "out" -> { + if (currentOutAtt > 0) { + throw new UnsupportedOperationException("Multiple outputs not currently supported."); + } + + attribute.setLocation(currentOutAtt++); + fragOutAttributes.add(attribute); + } + default -> throw new IllegalStateException(); + } + } + } + + this.appendNode(attribute.getNode()); + } + + private Attribute getVertAttribute(Attribute attribute) { + Attribute vertAttribute = null; + for (var attribute1 : vertOutAttributes) { + if (Objects.equals(attribute1.id, attribute.id)) { + vertAttribute = attribute1; + } + } + + if (vertAttribute == null) { +// throw new IllegalStateException("No match found for attribute %s in vertex attribute outputs.".formatted(attribute.id)); + } + return vertAttribute; + } + + private void nextToken() { + nextToken(false); + } + + private void nextToken(boolean skipSpace) { + this.currentToken = this.tokens.get(this.currentTokenIdx++); + + while (skipSpace && this.currentToken.type == Token.TokenType.SPACING) { + this.currentToken = this.tokens.get(this.currentTokenIdx++); + } + } + + private void appendToken(Token token) { + this.appendNode(Node.fromToken(token)); + } + + private void appendNode(Node node) { + switch (this.stage) { + case VERTEX -> this.vsStream.add(node); + case FRAGMENT -> this.fsStream.add(node); + } + } + + public String getOutput(Stage stage) { + StringBuilder stringBuilder = new StringBuilder(); + + var stream = switch (stage) { + case VERTEX -> this.vsStream; + case FRAGMENT -> this.fsStream; + }; + + // Version + Node node = stream.getFirst(); + stringBuilder.append(node.value); + stringBuilder.append("\n"); + + switch (stage) { + case VERTEX -> { + stringBuilder.append("#define gl_VertexID gl_VertexIndex\n\n"); + } + } + + for (int i = 1; i < stream.size(); i++) { + node = stream.get(i); + stringBuilder.append(node.value); + } + + return stringBuilder.toString(); + } + + public UBO[] createUBOs() { + if (this.uniformBlockMap.isEmpty()) { + return new UBO[0]; + } + + int uboCount = this.uniformBlockMap.size(); + UBO[] ubos = new UBO[uboCount]; + + int i = 0; + for (var uniformBlock : this.uniformBlocks) { + AlignedStruct.Builder builder = new AlignedStruct.Builder(); + + for (var field : uniformBlock.fields) { + String name = field.name; + String type = field.type; + + Uniform.Info uniformInfo = Uniform.createUniformInfo(type, name); + + builder.addUniformInfo(uniformInfo); + } + + ubos[i] = builder.buildUBO(uniformBlock.name, uniformBlock.binding, VK11.VK_SHADER_STAGE_ALL); + ++i; + } + + return ubos; + } + + public List getSamplerList() { + List imageDescriptors = new ObjectArrayList<>(); + + for (Sampler sampler : this.samplers) { + + int descriptorType = switch (sampler.type) { + case SAMPLER_2D, SAMPLER_CUBE -> VK11.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + case I_SAMPLER_BUFFER -> VK11.VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; + }; + + int imageIdx = VTextureSelector.getTextureIdx(sampler.id); + imageDescriptors.add(new ImageDescriptor(sampler.binding, "sampler2D", sampler.id, imageIdx, descriptorType)); + } + + return imageDescriptors; + } + + enum State { + LAYOUT, + UNIFORM, + UNIFORM_BLOCK, + ATTRIBUTE, + DEFAULT + } + + public enum Stage { + VERTEX, + FRAGMENT + } + + public static class Node { + String type; + String value; + + public Node(String type, String value) { + this.type = type; + this.value = value; + } + + public static Node fromToken(Token token) { + return new Node("token:%s".formatted(token.type), token.value); + } + } +} + + diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java deleted file mode 100644 index 50d2302a71..0000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java +++ /dev/null @@ -1,203 +0,0 @@ -package net.vulkanmod.vulkan.shader.converter; - -import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; -import net.vulkanmod.vulkan.shader.descriptor.UBO; - -import java.util.*; - -public class GlslConverter { - - ShaderStage shaderStage; - private State state; - - private UniformParser uniformParser; - private InputOutputParser inOutParser; - - private String vshConverted; - private String fshConverted; - - public void process(String vertShader, String fragShader) { - this.uniformParser = new UniformParser(this); - this.inOutParser = new InputOutputParser(this); - - StringBuilder vshOut = this.processShaderFile(ShaderStage.Vertex, vertShader); - vshOut.insert(0, this.inOutParser.createInOutCode()); - - StringBuilder fshOut = this.processShaderFile(ShaderStage.Fragment, fragShader); - fshOut.insert(0, this.inOutParser.createInOutCode()); - - String uniformBlock = this.uniformParser.createUniformsCode(); - vshOut.insert(0, uniformBlock); - fshOut.insert(0, uniformBlock); - - String samplersVertCode = this.uniformParser.createSamplersCode(ShaderStage.Vertex); - String samplersFragCode = this.uniformParser.createSamplersCode(ShaderStage.Fragment); - - vshOut.insert(0, samplersVertCode); - fshOut.insert(0, samplersFragCode); - - vshOut.insert(0, "#version 450\n\n"); - fshOut.insert(0, "#define sample sample1\n"); - fshOut.insert(0, "#version 450\n\n"); - - this.vshConverted = vshOut.toString(); - this.fshConverted = fshOut.toString(); - - } - - private StringBuilder processShaderFile(ShaderStage stage, String shader) { - this.setShaderStage(stage); - - String[] lines = shader.split("\n"); - var out = new StringBuilder(); - - var iterator = Arrays.stream(lines).iterator(); - - while (iterator.hasNext()) { - String line = iterator.next(); - - int semicolons = charOccurences(line, ';'); - - if (semicolons > 1) { - var lines2 = line.splitWithDelimiters(";", 0); - - int matchingFor = 0; - for (int i = 0; i < lines2.length;) { - StringBuilder line2 = new StringBuilder(lines2[i]); - i++; - - matchingFor += charOccurences(line2.toString(), '('); - matchingFor -= charOccurences(line2.toString(), ')'); - - while (matchingFor > 0) { - String next = lines2[i]; - i++; - - matchingFor += charOccurences(next, '('); - matchingFor -= charOccurences(next, ')'); - - line2.append(next); - } - - if (i < lines2.length) { - line2.append(lines2[i]); - i++; - } - - - if (matchingFor == 0) { - String parsedLine = this.parseLine(line2.toString()); - if (parsedLine != null) { - out.append(parsedLine); - out.append("\n"); - } - } - - } - } - else { - String parsedLine = this.parseLine(line); - if (parsedLine != null) { - out.append(parsedLine); - out.append("\n"); - } - } - - } - - return out; - } - - private int charOccurences(String s, char c) { - int count = 0; - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) == c) { - count++; - } - } - - return count; - } - - private String parseLine(String line) { - StringTokenizer tokenizer = new StringTokenizer(line); - - // empty line - if (!tokenizer.hasMoreTokens()) - return "\n"; - - String token = tokenizer.nextToken(); - - switch (token) { - case "uniform" -> this.state = State.MATCHING_UNIFORM; - case "in", "out" -> this.state = State.MATCHING_IN_OUT; - case "#version" -> { - return null; - } - case "#moj_import" -> { - if (tokenizer.countTokens() != 1) { - throw new IllegalArgumentException("Token count != 1"); - } - - return String.format("#include %s", tokenizer.nextToken()); - } - - default -> { - return CodeParser.parseCodeLine(line); - } - } - - if (tokenizer.countTokens() < 2) { - throw new IllegalArgumentException("Less than 3 tokens present"); - } - - feedToken(token); - - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - - feedToken(token); - } - - return null; - } - - private void feedToken(String token) { - switch (this.state) { - case MATCHING_UNIFORM -> this.uniformParser.parseToken(token); - case MATCHING_IN_OUT -> this.inOutParser.parseToken(token); - } - } - - private void setShaderStage(ShaderStage shaderStage) { - this.shaderStage = shaderStage; - this.uniformParser.setCurrentUniforms(this.shaderStage); - this.inOutParser.setShaderStage(this.shaderStage); - } - - public UBO createUBO() { - return this.uniformParser.createUBO(); - } - - public List getSamplerList() { - return this.uniformParser.getSamplers(); - } - - public String getVshConverted() { - return vshConverted; - } - - public String getFshConverted() { - return fshConverted; - } - - enum ShaderStage { - Vertex, - Fragment - } - - enum State { - MATCHING_UNIFORM, - MATCHING_IN_OUT - } -} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java deleted file mode 100644 index cde9e5eff2..0000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.vulkanmod.vulkan.shader.converter; - -import com.mojang.blaze3d.vertex.VertexFormat; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; - -import java.util.List; -import java.util.Objects; - -import static net.vulkanmod.vulkan.shader.converter.UniformParser.removeSemicolon; - -public class InputOutputParser { - private final GlslConverter converterInstance; - private VertexFormat vertexFormat; - - private final AttributeSet vertInAttributes = new AttributeSet(); - private final AttributeSet vertOutAttributes = new AttributeSet(); - - private GlslConverter.ShaderStage shaderStage; - - private int currentLocation = 0; - private String ioType; - private String type; - private String name; - - public InputOutputParser(GlslConverter converterInstance) { - this.converterInstance = converterInstance; - } - - public boolean parseToken(String token) { - - if (this.ioType == null) - this.ioType = token; - else if (this.type == null) - this.type = token; - else if (this.name == null) { - token = removeSemicolon(token); - - this.name = token; - - if(this.shaderStage == GlslConverter.ShaderStage.Vertex) { - switch (this.ioType) { - case "in" -> this.vertInAttributes.add(this.type, this.name); - case "out" -> this.vertOutAttributes.add(this.type, this.name); - } - } - else { - switch (this.ioType) { - case "in" -> { - if(!this.vertOutAttributes.contains(this.type, this.name)) - throw new RuntimeException("fragment in attribute does not match vertex output"); - } - case "out" -> { - //TODO check output - } - } - } - this.resetState(); - return true; - } - - return false; - } - - private void resetState() { - this.ioType = null; - this.type = null; - this.name = null; - } - - public String createInOutCode() { - //TODO - StringBuilder builder = new StringBuilder(); - - if(this.shaderStage == GlslConverter.ShaderStage.Vertex) { - //In - for(Attribute attribute : this.vertInAttributes.attributes) { - builder.append(String.format("layout(location = %d) in %s %s;\n", attribute.location, attribute.type, attribute.name)); - } - builder.append("\n"); - - //Out - for(Attribute attribute : this.vertOutAttributes.attributes) { - builder.append(String.format("layout(location = %d) out %s %s;\n", attribute.location, attribute.type, attribute.name)); - } - builder.append("\n"); - } - else { - //In - for(Attribute attribute : this.vertOutAttributes.attributes) { - builder.append(String.format("layout(location = %d) in %s %s;\n", attribute.location, attribute.type, attribute.name)); - } - builder.append("\n"); - - //TODO multi attachments? - builder.append(String.format("layout(location = 0) out vec4 fragColor;\n\n")); - } - - return builder.toString(); - } - - public void setShaderStage(GlslConverter.ShaderStage shaderStage) { - this.shaderStage = shaderStage; - } - - public record Attribute(int location, String type, String name) {} - - static class AttributeSet { - List attributes = new ObjectArrayList<>(); - int currentLocation = 0; - - void add(String type, String name) { - this.attributes.add(new Attribute(this.currentLocation, type, name)); - this.currentLocation++; - } - - boolean contains(String type, String name) { - return this.attributes.stream().anyMatch(attribute -> Objects.equals(attribute.name, name) && Objects.equals(attribute.type, type)); - } - } -} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java new file mode 100644 index 0000000000..787311453d --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java @@ -0,0 +1,258 @@ +package net.vulkanmod.vulkan.shader.converter; + +import java.util.ArrayList; +import java.util.List; + +public class Lexer { + private final String input; + private int currentPosition; + private char currentChar; + + private State state; + + public Lexer(String input) { + this.input = input; + this.currentPosition = 0; + this.currentChar = !input.isEmpty() ? input.charAt(0) : '\0'; + } + + private void advance() { + advance(1); + } + + private void advance(int i) { + for (int j = 0; j < i; j++) { + currentPosition++; + if (currentPosition >= input.length()) { + currentChar = '\0'; + break; + } else { + currentChar = input.charAt(currentPosition); + } + } + } + + private char peek() { + int peekPosition = currentPosition + 1; + if (peekPosition < input.length()) { + return input.charAt(peekPosition); + } + return '\0'; + } + + public List tokenize() { + List tokens = new ArrayList<>(); + + while (currentPosition < input.length()) { + char currentChar = input.charAt(currentPosition); + + Token token = nextToken(); + if (token != null) { + tokens.add(token); + } else { + throw new RuntimeException("Unknown character: " + currentChar); + } + } + + tokens.add(new Token(Token.TokenType.EOF, null)); + + return tokens; + } + + public Token nextToken() { + if (!checkEOF()) { + return new Token(Token.TokenType.EOF, null); + } + + // Comment + if (currentChar == '/') { + if (peek() == '/') { + advance(2); + return this.comment(); + } + } + + // Handle multi-character operators + switch (currentChar) { + case '=': + if (peek() == '=') { + advance(2); + return new Token(Token.TokenType.OPERATOR, "=="); + } + break; + case '!': + if (peek() == '=') { + advance(2); + return new Token(Token.TokenType.OPERATOR, "!="); + } + break; + case '<': + switch (peek()) { + case '=' -> { + advance(2); + return new Token(Token.TokenType.OPERATOR, "<="); + } + case '<' -> { + advance(2); + return new Token(Token.TokenType.OPERATOR, "<<"); + } + } + break; + case '>': + switch (peek()) { + case '=' -> { + advance(2); + return new Token(Token.TokenType.OPERATOR, ">="); + } + case '>' -> { + advance(2); + return new Token(Token.TokenType.OPERATOR, ">>"); + } + } + break; + } + + Token token = switch (currentChar) { + case '{' -> new Token(Token.TokenType.LEFT_BRACE, "{"); + case '}' -> new Token(Token.TokenType.RIGHT_BRACE, "}"); + case '(' -> new Token(Token.TokenType.LEFT_PARENTHESIS, "("); + case ')' -> new Token(Token.TokenType.RIGHT_PARENTHESIS, ")"); + case ':' -> new Token(Token.TokenType.COLON, ":"); + case ';' -> new Token(Token.TokenType.SEMICOLON, ";"); + case '.' -> new Token(Token.TokenType.DOT, "."); + case ',' -> new Token(Token.TokenType.COMMA, ","); + + case '=' -> new Token(Token.TokenType.OPERATOR, "="); + case '+' -> new Token(Token.TokenType.OPERATOR, "+"); + case '-' -> new Token(Token.TokenType.OPERATOR, "-"); + case '*' -> new Token(Token.TokenType.OPERATOR, "*"); + case '/' -> new Token(Token.TokenType.OPERATOR, "/"); + case '%' -> new Token(Token.TokenType.OPERATOR, "%"); + case '<' -> new Token(Token.TokenType.OPERATOR, "<"); + case '>' -> new Token(Token.TokenType.OPERATOR, ">"); + case '!' -> new Token(Token.TokenType.OPERATOR, "!"); + case '&' -> new Token(Token.TokenType.OPERATOR, "&"); + case '|' -> new Token(Token.TokenType.OPERATOR, "|"); + case '?' -> new Token(Token.TokenType.OPERATOR, "?"); + case '[' -> new Token(Token.TokenType.OPERATOR, "["); + case ']' -> new Token(Token.TokenType.OPERATOR, "]"); + + case '#' -> { + StringBuilder sb = new StringBuilder(); + + while (checkEOF() && currentChar != '\n') { + sb.append(currentChar); + advance(); + } + sb.append('\n'); + + String value = sb.toString(); + yield new Token(Token.TokenType.PREPROCESSOR, value); + } + + case '\"' -> string(); + + default -> null; + }; + + if (token == null) { + if (Character.isLetter(currentChar)) { + return identifier(); + } + + if (Character.isDigit(currentChar)) { + return literal(); + } + + if (Character.isWhitespace(currentChar)) { + return spacing(); + } + } + + if (token == null) { + throw new IllegalStateException("Unrecognized char: " + currentChar); + } + + advance(); + + return token; + } + + private Token comment() { + StringBuilder sb = new StringBuilder(); + sb.append("//"); + while (checkEOF() && currentChar != '\n') { + sb.append(currentChar); + advance(); + } + sb.append(currentChar); + advance(); + + String value = sb.toString(); + return new Token(Token.TokenType.COMMENT, value); + } + + private Token identifier() { + StringBuilder sb = new StringBuilder(); + while (checkEOF() && Character.isJavaIdentifierPart(currentChar)) { + sb.append(currentChar); + advance(); + } + String value = sb.toString(); + return new Token(Token.TokenType.IDENTIFIER, value); + } + + private Token literal() { + StringBuilder sb = new StringBuilder(); + while (Character.isDigit(currentChar)) { + sb.append(currentChar); + advance(); + } + + if (currentChar == '.') { + sb.append(currentChar); + advance(); + } + + while (Character.isDigit(currentChar)) { + sb.append(currentChar); + advance(); + } + + String value = sb.toString(); + return new Token(Token.TokenType.LITERAL, value); + } + + private Token string() { + StringBuilder sb = new StringBuilder(); + while (checkEOF() && currentChar != '\"') { + sb.append(currentChar); + advance(); + } + sb.append(currentChar); + advance(); + + String value = sb.toString(); + return new Token(Token.TokenType.COMMENT, value); + } + + private Token spacing() { + StringBuilder sb = new StringBuilder(); + while (currentChar != '\0' && Character.isWhitespace(currentChar)) { + sb.append(currentChar); + advance(); + } + String value = sb.toString(); + return new Token(Token.TokenType.SPACING, value); + } + + private boolean checkEOF() { + return currentChar != '\0'; + } + + enum State { + UNIFORM_BLOCK, + CODE, + DEFAULT + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Sampler.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Sampler.java new file mode 100644 index 0000000000..e54ea5d2ea --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Sampler.java @@ -0,0 +1,32 @@ +package net.vulkanmod.vulkan.shader.converter; + +public class Sampler { + final Type type; + final String id; + int binding; + + public Sampler(Type type, String id) { + this.type = type; + this.id = id; + } + + public void setBinding(int binding) { + this.binding = binding; + } + + public GLSLParser.Node getNode() { + return new GLSLParser.Node("sampler", "layout(binding = %d) uniform %s %s;\n".formatted(binding, type.name, id)); + } + + public enum Type { + SAMPLER_2D("sampler2D"), + SAMPLER_CUBE("samplerCube"), + I_SAMPLER_BUFFER("isamplerBuffer"); + + public final String name; + + Type(String name) { + this.name = name; + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Token.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Token.java new file mode 100644 index 0000000000..560f9df079 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Token.java @@ -0,0 +1,49 @@ +package net.vulkanmod.vulkan.shader.converter; + +public class Token { + + public enum TokenType { + PREPROCESSOR, + KEYWORD, + IDENTIFIER, + LITERAL, + OPERATOR, + PUNCTUATION, + SPACING, + COMMENT, + + // Symbols + LEFT_BRACE, // { + RIGHT_BRACE, // } + LEFT_PARENTHESIS, // ( + RIGHT_PARENTHESIS, // ) + COLON, // : + SEMICOLON, // ; + DOT, // . + COMMA, // , + + // Data Types + TYPE, + + // GLSL + LAYOUT, + + EOF + } + + public final TokenType type; + public String value; + + public Token(TokenType type, String value) { + this.type = type; + this.value = value; + } + + @Override + public String toString() { + return "Token{" + + "type=" + type + + ", value='" + value + '\'' + + '}'; + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformBlock.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformBlock.java new file mode 100644 index 0000000000..26ef62a57b --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformBlock.java @@ -0,0 +1,61 @@ +package net.vulkanmod.vulkan.shader.converter; + +import java.util.ArrayList; +import java.util.List; + +public class UniformBlock { + int binding; + String name; + String alias; + List fields = new ArrayList<>(); + + public UniformBlock(String name) { + this.name = name; + } + + public void addField(Field field) { + this.fields.add(field); + } + + public void setBinding(int binding) { + this.binding = binding; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public GLSLParser.Node getNode() { + StringBuilder sb = new StringBuilder(); + + sb.append("layout(binding = %d) uniform %s {\n".formatted(binding, name)); + + for (int i = 0, fieldsSize = fields.size(); i < fieldsSize; i++) { + Field field = fields.get(i); + sb.append("\t%s %s;".formatted(field.type, field.name)); + + if (i < fieldsSize - 1) { + sb.append("\n"); + } + } + + sb.append("\n}"); + + if (this.alias != null) { + sb.append(" %s ".formatted(this.alias)); + } + + sb.append(";\n"); + + return new GLSLParser.Node("uniform_block", sb.toString()); + } + + public static class Field { + final String type, name; + + public Field(String type, String name) { + this.type = type; + this.name = name; + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java deleted file mode 100644 index 0fe03111e1..0000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java +++ /dev/null @@ -1,158 +0,0 @@ -package net.vulkanmod.vulkan.shader.converter; - -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.layout.AlignedStruct; -import org.lwjgl.vulkan.VK11; - -import java.util.ArrayList; -import java.util.List; - -public class UniformParser { - - private final GlslConverter converterInstance; - private final StageUniforms[] stageUniforms = new StageUniforms[GlslConverter.ShaderStage.values().length]; - private StageUniforms currentUniforms; - List globalUniforms = new ArrayList<>(); - - private String type; - private String name; - - private List imageDescriptors; - - public UniformParser(GlslConverter converterInstance) { - this.converterInstance = converterInstance; - - for (int i = 0; i < this.stageUniforms.length; ++i) { - this.stageUniforms[i] = new StageUniforms(); - } - } - - public boolean parseToken(String token) { - if (token.matches("uniform")) return false; - - if (this.type == null) { - this.type = token; - - } - else if (this.name == null) { - token = removeSemicolon(token); - - this.name = token; - - //TODO check if already present - Uniform uniform = new Uniform(this.type, this.name); - if ("sampler2D".equals(this.type)) { - if (!this.currentUniforms.samplers.contains(uniform)) - this.currentUniforms.samplers.add(uniform); - } - else { - if (!this.globalUniforms.contains(uniform)) - this.globalUniforms.add(uniform); - } - - this.resetSate(); - return true; - } - - return false; - } - - public void setCurrentUniforms(GlslConverter.ShaderStage shaderStage) { - this.currentUniforms = stageUniforms[shaderStage.ordinal()]; - } - - private void resetSate() { - this.type = null; - this.name = null; -// this.state = State.None; - } - - public String createUniformsCode() { - StringBuilder builder = new StringBuilder(); - - //hardcoded 0 binding as it should always be 0 in this case - builder.append(String.format("layout(binding = %d) uniform UniformBufferObject {\n", 0)); - for (Uniform uniform : this.globalUniforms) { - builder.append(String.format("%s %s;\n", uniform.type, uniform.name)); - } - builder.append("};\n\n"); - - return builder.toString(); - } - - public String createSamplersCode(GlslConverter.ShaderStage shaderStage) { - StringBuilder builder = new StringBuilder(); - - this.imageDescriptors = createSamplerList(); - - for (ImageDescriptor imageDescriptor : this.imageDescriptors) { - builder.append(String.format("layout(binding = %d) uniform %s %s;\n", imageDescriptor.getBinding(), - imageDescriptor.qualifier, imageDescriptor.name)); - } - builder.append("\n"); - - return builder.toString(); - } - - public UBO createUBO() { - AlignedStruct.Builder builder = new AlignedStruct.Builder(); - - for (UniformParser.Uniform uniform : this.globalUniforms) { - String name = uniform.name(); - String type = uniform.type(); - - net.vulkanmod.vulkan.shader.layout.Uniform.Info uniformInfo = net.vulkanmod.vulkan.shader.layout.Uniform.createUniformInfo(type, name); - - builder.addUniformInfo(uniformInfo); - } - - // Use binding 0 for global uniforms - return builder.buildUBO(0, VK11.VK_SHADER_STAGE_ALL); - } - - private List createSamplerList() { - int currentLocation = 1; - - List imageDescriptors = new ObjectArrayList<>(); - - for (StageUniforms stageUniforms : this.stageUniforms) { - for (Uniform uniform : stageUniforms.samplers) { - int imageIdx = currentLocation - 1; - imageDescriptors.add(new ImageDescriptor(currentLocation, uniform.type, uniform.name, imageIdx)); - currentLocation++; - } - } - - return imageDescriptors; - } - - public static String removeSemicolon(String s) { - int last = s.length() - 1; - if ((s.charAt(last)) != ';') - throw new IllegalArgumentException("last char is not ;"); - return s.substring(0, last); - } - - public List getGlobalUniforms() { - return globalUniforms; - } - - public List getSamplers() { - return this.imageDescriptors; - } - - public record Uniform(String type, String name) { - } - - private static class StageUniforms { - List samplers = new ArrayList<>(); - } - - enum State { - Uniform, - Sampler, - None - } -} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java index 40ad7b0705..0354402ac3 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java @@ -13,7 +13,6 @@ public class ImageDescriptor implements Descriptor { public final String name; public final int imageIdx; - public final boolean isStorageImage; public boolean useSampler; public boolean isReadOnlyLayout; private int layout; @@ -24,14 +23,23 @@ public ImageDescriptor(int binding, String type, String name, int imageIdx) { } public ImageDescriptor(int binding, String type, String name, int imageIdx, boolean isStorageImage) { + this(binding, type, name, imageIdx, isStorageImage ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); + } + + public ImageDescriptor(int binding, String type, String name, int imageIdx, int descriptorType) { this.binding = binding; this.qualifier = type; this.name = name; - this.isStorageImage = isStorageImage; - this.useSampler = !isStorageImage; this.imageIdx = imageIdx; - descriptorType = isStorageImage ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + if (this.imageIdx == -1) { + throw new IllegalArgumentException(); + } + + this.descriptorType = descriptorType; + + boolean isStorageImage = isStorageImage(); + this.useSampler = !isStorageImage; setLayout(isStorageImage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } @@ -74,7 +82,7 @@ public VulkanImage getImage() { public long getImageView(VulkanImage image) { long view; - if(mipLevel == -1) + if (mipLevel == -1) view = image.getImageView(); else view = image.getLevelImageView(mipLevel); @@ -82,6 +90,10 @@ public long getImageView(VulkanImage image) { return view; } + public boolean isStorageImage() { + return this.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + } + public static class State { long imageView, sampler; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java index 83db956f61..09ed1e2599 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java @@ -10,7 +10,7 @@ public class ManualUBO extends UBO { private boolean update = true; public ManualUBO(int binding, int type, int size) { - super(binding, type, size * 4, null); + super("manual UBO: %d".formatted(binding), binding, type, size * 4, null); } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java index 1d0a76daa8..402428f89a 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java @@ -1,6 +1,7 @@ package net.vulkanmod.vulkan.shader.descriptor; -import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import net.vulkanmod.vulkan.memory.buffer.BufferSlice; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.layout.Uniform; @@ -9,15 +10,28 @@ import static org.lwjgl.vulkan.VK10.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; public class UBO extends AlignedStruct implements Descriptor { - private final int binding; - private final int stages; + public final String name; + public final int binding; + public final int stages; + public final BufferSlice bufferSlice; + private boolean useGlobalBuffer; - private UniformBuffer uniformBuffer; - - public UBO(int binding, int stages, int size, List infoList) { + public UBO(String name, int binding, int stages, int size, List infoList) { super(infoList, size); + this.name = name; this.binding = binding; this.stages = stages; + + this.bufferSlice = new BufferSlice(); + } + + @Override + public String toString() { + return "UBO{" + + "name='" + name + '\'' + + ", binding=" + binding + + ", useGlobalBuffer=" + useGlobalBuffer + + '}'; } public int getBinding() { @@ -33,11 +47,15 @@ public int getStages() { return stages; } - public UniformBuffer getUniformBuffer() { - return uniformBuffer; + public BufferSlice getBufferSlice() { + return bufferSlice; + } + + public boolean useGlobalBuffer() { + return useGlobalBuffer; } - public void setUniformBuffer(UniformBuffer uniformBuffer) { - this.uniformBuffer = uniformBuffer; + public void setUseGlobalBuffer(boolean useGlobalBuffer) { + this.useGlobalBuffer = useGlobalBuffer; } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java index 11560c621c..3236f70f8c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java @@ -11,6 +11,10 @@ public abstract class AlignedStruct { protected int size; protected AlignedStruct(List infoList, int size) { + if (size <= 0) { + throw new IllegalArgumentException("Struct size cannot be <= 0"); + } + this.size = size; if (infoList == null) @@ -58,8 +62,12 @@ public void addUniformInfo(Uniform.Info uniformInfo) { } public UBO buildUBO(int binding, int stages) { + return this.buildUBO("UBO: %d".formatted(binding), binding, stages); + } + + public UBO buildUBO(String name, int binding, int stages) { //offset is expressed in floats/ints - return new UBO(binding, stages, this.currentOffset * 4, this.uniforms); + return new UBO(name, binding, stages, this.currentOffset * 4, this.uniforms); } public PushConstants buildPushConstant() { diff --git a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java index c6b4ea2a03..84a5665bce 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java @@ -17,7 +17,8 @@ public abstract class ImageUtil { - public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, + public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, + long image, int arrayLayer, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLenght, int bufferImageHeight) { VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); @@ -26,7 +27,7 @@ public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer comma region.bufferImageHeight(bufferImageHeight); region.imageSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); region.imageSubresource().mipLevel(mipLevel); - region.imageSubresource().baseArrayLayer(0); + region.imageSubresource().baseArrayLayer(arrayLayer); region.imageSubresource().layerCount(1); region.imageOffset().set(xOffset, yOffset, 0); region.imageExtent(VkExtent3D.calloc(stack).set(width, height, 1)); diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index f312a5ae10..7441f04367 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -1,11 +1,12 @@ package net.vulkanmod.vulkan.texture; import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; import net.vulkanmod.Initializer; -import net.vulkanmod.gl.GlTexture; +import net.vulkanmod.gl.VkGlTexture; +import net.vulkanmod.render.engine.VkGpuTexture; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; +import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -25,7 +26,7 @@ public static void bindTexture(VulkanImage texture) { } public static void bindTexture(int i, VulkanImage texture) { - if(i < 0 || i >= SIZE) { + if (i < 0 || i >= SIZE) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -35,7 +36,7 @@ public static void bindTexture(int i, VulkanImage texture) { } public static void bindImage(int i, VulkanImage texture, int level) { - if(i < 0 || i > 7) { + if (i < 0 || i > 7) { Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", i, SIZE - 1)); return; } @@ -44,18 +45,28 @@ public static void bindImage(int i, VulkanImage texture, int level) { levels[i] = level; } - public static void uploadSubTexture(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { + public static void uploadSubTexture(int mipLevel, int width, int height, int xOffset, int yOffset, + int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, + ByteBuffer buffer) { + uploadSubTexture(mipLevel, 0, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, + MemoryUtil.memAddress(buffer)); + } + + public static void uploadSubTexture(int mipLevel, int arrayLayer, int width, int height, int xOffset, int yOffset, + int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, + long bufferPtr) { VulkanImage texture = boundTextures[activeTexture]; - if(texture == null) + if (texture == null) throw new NullPointerException("Texture is null at index: " + activeTexture); - texture.uploadSubTextureAsync(mipLevel, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, buffer); + texture.uploadSubTextureAsync(mipLevel, arrayLayer, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, + unpackRowLength, bufferPtr); } public static int getTextureIdx(String name) { return switch (name) { - case "Sampler0", "DiffuseSampler" -> 0; + case "Sampler0", "DiffuseSampler", "InSampler", "CloudFaces" -> 0; case "Sampler1" -> 1; case "Sampler2" -> 2; case "Sampler3" -> 3; @@ -63,7 +74,7 @@ public static int getTextureIdx(String name) { case "Sampler5" -> 5; case "Sampler6" -> 6; case "Sampler7" -> 7; - default -> throw new IllegalStateException("Unknown sampler name: " + name); + default -> -1; }; } @@ -71,9 +82,16 @@ public static void bindShaderTextures(Pipeline pipeline) { var imageDescriptors = pipeline.getImageDescriptors(); for (ImageDescriptor state : imageDescriptors) { - final int shaderTexture = RenderSystem.getShaderTexture(state.imageIdx); + var textureView = RenderSystem.getShaderTexture(state.imageIdx); + + if (textureView == null) + continue; + + VkGpuTexture gpuTexture = (VkGpuTexture) textureView.texture(); + gpuTexture.flushModeChanges(); - GlTexture texture = GlTexture.getTexture(shaderTexture); + final int shaderTexture = gpuTexture.glId(); + VkGlTexture texture = VkGlTexture.getTexture(shaderTexture); if (texture != null && texture.getVulkanImage() != null) { VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); @@ -99,16 +117,23 @@ public static void setOverlayTexture(VulkanImage texture) { } public static void setActiveTexture(int activeTexture) { - if(activeTexture < 0 || activeTexture >= SIZE) { - Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); + if (activeTexture < 0 || activeTexture >= SIZE) { + Initializer.LOGGER.error( + String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); } VTextureSelector.activeTexture = activeTexture; } - public static VulkanImage getBoundTexture() { return boundTextures[activeTexture]; } + public static VulkanImage getBoundTexture() { + return boundTextures[activeTexture]; + } - public static VulkanImage getBoundTexture(int i) { return boundTextures[i]; } + public static VulkanImage getBoundTexture(int i) { + return boundTextures[i]; + } - public static VulkanImage getWhiteTexture() { return whiteTexture; } + public static VulkanImage getWhiteTexture() { + return whiteTexture; + } } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index e44790bbc8..ab89a99d25 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -31,11 +31,13 @@ public class VulkanImage { public final String name; public final int format; public final int aspect; + public final int arrayLayers; public final int mipLevels; public final int width; public final int height; public final int formatSize; public final int usage; + public final int viewType; public final int size; private long id; @@ -54,6 +56,7 @@ public VulkanImage(String name, long id, int format, int mipLevels, int width, i this.mainImageView = imageView; this.name = name; + this.arrayLayers = 1; this.mipLevels = mipLevels; this.width = width; this.height = height; @@ -61,6 +64,7 @@ public VulkanImage(String name, long id, int format, int mipLevels, int width, i this.format = format; this.usage = usage; this.aspect = getAspect(this.format); + this.viewType = VK_IMAGE_VIEW_TYPE_2D; this.size = width * height * formatSize; @@ -72,10 +76,12 @@ private VulkanImage(Builder builder) { this.mipLevels = builder.mipLevels; this.width = builder.width; this.height = builder.height; + this.arrayLayers = builder.arrayLayers; this.formatSize = builder.formatSize; this.format = builder.format; this.usage = builder.usage; this.aspect = getAspect(this.format); + this.viewType = builder.viewType; this.size = width * height * formatSize; } @@ -84,7 +90,7 @@ public static VulkanImage createTextureImage(Builder builder) { VulkanImage image = new VulkanImage(builder); image.createImage(); - image.mainImageView = createImageView(image.id, builder.format, image.aspect, builder.mipLevels); + image.mainImageView = createImageView(image.id, image.viewType, image.format, image.aspect, image.arrayLayers, 0, image.mipLevels); image.sampler = SamplerManager.getTextureSampler(builder.mipLevels, builder.samplerFlags); @@ -122,7 +128,7 @@ public static VulkanImage createWhiteTexture() { .setLinearFiltering(false) .setClamp(false) .createVulkanImage(); - image.uploadSubTextureAsync(0, image.width, image.height, 0, 0, 0, 0, 0, buffer); + image.uploadSubTextureAsync(0, 0, image.width, image.height, 0, 0, 0, 0, 0, buffer); return image; // return createTextureImage(1, 1, 4, false, false, buffer); } @@ -133,12 +139,15 @@ private void createImage() { LongBuffer pTextureImage = stack.mallocLong(1); PointerBuffer pAllocation = stack.pointers(0L); - MemoryManager.getInstance().createImage(width, height, mipLevels, - format, VK_IMAGE_TILING_OPTIMAL, - usage, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - pTextureImage, - pAllocation); + int flags = viewType == VK_IMAGE_VIEW_TYPE_CUBE ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0; + + MemoryManager.getInstance() + .createImage(width, height, arrayLayers, mipLevels, + format, VK_IMAGE_TILING_OPTIMAL, + usage, flags, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + pTextureImage, + pAllocation); id = pTextureImage.get(0); allocation = pAllocation.get(0); @@ -172,24 +181,22 @@ public static boolean isDepthFormat(int format) { }; } - public static long createImageView(long image, int format, int aspectFlags, int mipLevels) { - return createImageView(image, format, aspectFlags, 0, mipLevels); + public static long createImageView(long image, int format, int aspectFlags, int arrayLayers, int mipLevels) { + return createImageView(image, VK_IMAGE_VIEW_TYPE_2D, format, aspectFlags, arrayLayers, 0, mipLevels); } - public static long createImageView(long image, int format, int aspectFlags, int baseMipLevel, int mipLevels) { - + public static long createImageView(long image, int viewType, int format, int aspectFlags, int arrayLayers, int baseMipLevel, int mipLevels) { try (MemoryStack stack = stackPush()) { - VkImageViewCreateInfo viewInfo = VkImageViewCreateInfo.calloc(stack); viewInfo.sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO); viewInfo.image(image); - viewInfo.viewType(VK_IMAGE_VIEW_TYPE_2D); + viewInfo.viewType(viewType); viewInfo.format(format); viewInfo.subresourceRange().aspectMask(aspectFlags); viewInfo.subresourceRange().baseMipLevel(baseMipLevel); viewInfo.subresourceRange().levelCount(mipLevels); viewInfo.subresourceRange().baseArrayLayer(0); - viewInfo.subresourceRange().layerCount(1); + viewInfo.subresourceRange().layerCount(arrayLayers); LongBuffer pImageView = stack.mallocLong(1); @@ -201,13 +208,36 @@ public static long createImageView(long image, int format, int aspectFlags, int } } - public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { - this.uploadSubTextureAsync(mipLevel, width, height, - xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, + public void uploadSubTextureAsync(int mipLevel, + int width, int height, + int xOffset, int yOffset, + int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, + ByteBuffer buffer) + { + this.uploadSubTextureAsync(mipLevel, 0, width, height, + xOffset, yOffset, + unpackSkipRows, unpackSkipPixels, unpackRowLength, MemoryUtil.memAddress(buffer)); } - public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, long srcPtr) { + public void uploadSubTextureAsync(int mipLevel, int arrayLayer, + int width, int height, + int xOffset, int yOffset, + int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, + ByteBuffer buffer) + { + this.uploadSubTextureAsync(mipLevel, arrayLayer, width, height, + xOffset, yOffset, + unpackSkipRows, unpackSkipPixels, unpackRowLength, + MemoryUtil.memAddress(buffer)); + } + + public void uploadSubTextureAsync(int mipLevel, int arrayLayer, + int width, int height, + int xOffset, int yOffset, + int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, + long srcPtr) + { long uploadSize = (long) (unpackRowLength * height - unpackSkipPixels) * this.formatSize; StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); @@ -232,7 +262,8 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs final int srcOffset = (int) (stagingBuffer.getOffset()); - ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, + ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, + arrayLayer, mipLevel, width, height, xOffset, yOffset, srcOffset, unpackRowLength, height); } } @@ -452,8 +483,10 @@ public static class Builder { String name; int format = VulkanImage.DefaultFormat; int formatSize; + int arrayLayers = 1; byte mipLevels = 1; int usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + int viewType = VK_IMAGE_VIEW_TYPE_2D; byte samplerFlags = 0; @@ -474,6 +507,12 @@ public Builder setFormat(int format) { return this; } + public Builder setArrayLayers(int n) { + this.arrayLayers = (byte) n; + + return this; + } + public Builder setMipLevels(int n) { this.mipLevels = (byte) n; @@ -493,6 +532,11 @@ public Builder addUsage(int usage) { return this; } + public Builder setViewType(int viewType) { + this.viewType = viewType; + return this; + } + public Builder setLinearFiltering(boolean b) { this.samplerFlags |= b ? LINEAR_FILTERING_BIT : 0; return this; diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh index 738d242d16..4db8118870 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.fsh @@ -1,10 +1,10 @@ #version 450 -layout(binding = 1) uniform UBO{ +#include "fog.glsl" + +layout(binding = 1) uniform UBO { vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; + float FogCloudsEnd; }; layout(location = 0) in vec4 vertexColor; @@ -13,8 +13,7 @@ layout(location = 1) in float vertexDistance; layout(location = 0) out vec4 fragColor; void main() { - vec4 color = vertexColor * ColorModulator; - - float alpha = smoothstep(FogEnd, FogStart, vertexDistance); - fragColor = vec4(color.rgb, color.a * alpha); + vec4 color = vertexColor; + color.a *= 1.0f - linear_fog_value(vertexDistance, 0, FogCloudsEnd); + fragColor = vec4(color.rgb, color.a); } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json index ccfee165ad..a70792662e 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json @@ -7,11 +7,9 @@ { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } ] }, - { "type": "fragment", "binding": 1, "fields": [ + { "type": "all", "binding": 1, "fields": [ { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } + { "name": "FogCloudsEnd", "type": "float", "count": 1, "values": [ 1.0 ] } ] } ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh index 203842a4ec..09fa14443c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.vsh @@ -5,6 +5,11 @@ layout(binding = 0) uniform UniformBufferObject { vec3 ModelOffset; }; +layout(binding = 1) uniform UBO { + vec4 ColorModulator; + float FogCloudsEnd; +}; + layout(location = 0) in vec3 Position; layout(location = 1) in vec4 Color; @@ -16,5 +21,5 @@ void main() { vec3 viewPos = Position + ModelOffset; vertexDistance = length(viewPos.xyz); - vertexColor = Color; + vertexColor = Color * ColorModulator; } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh index 9da3f09ffd..827c5e8f63 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh @@ -7,14 +7,19 @@ layout(binding = 2) uniform sampler2D Sampler0; layout(binding = 1) uniform UBO { vec4 FogColor; - float FogStart; - float FogEnd; + float FogEnvironmentalStart; + float FogEnvironmentalEnd; + float FogRenderDistanceStart; + float FogRenderDistanceEnd; + float FogSkyEnd; + float FogCloudsEnd; float AlphaCutout; }; layout(location = 0) in vec4 vertexColor; layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; +layout(location = 2) in float sphericalVertexDistance; +layout(location = 3) in float cylindricalVertexDistance; layout(location = 0) out vec4 fragColor; @@ -23,5 +28,5 @@ void main() { if (color.a < AlphaCutout) { discard; } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json index b527c51692..993650ce96 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json @@ -11,8 +11,12 @@ ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogEnvironmentalStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnvironmentalEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogRenderDistanceStart", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogRenderDistanceEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogSkyEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogCloudsEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, { "name": "AlphaCutout", "type": "float", "count": 1, "values": [ 1.0 ] } ] } ], diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh index 37981de842..ee6a6bc57c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh @@ -16,7 +16,8 @@ layout (binding = 3) uniform sampler2D Sampler2; layout (location = 0) out vec4 vertexColor; layout (location = 1) out vec2 texCoord0; -layout (location = 2) out float vertexDistance; +layout (location = 2) out float sphericalVertexDistance; +layout (location = 3) out float cylindricalVertexDistance; #define COMPRESSED_VERTEX @@ -36,21 +37,23 @@ const float UV_INV = 1.0 / 32768.0; const vec3 POSITION_INV = vec3(1.0 / 2048.0); const vec3 POSITION_OFFSET = vec3(4.0); -vec4 getVertexPosition() { +vec3 getVertexPosition() { const vec3 baseOffset = bitfieldExtract(ivec3(gl_InstanceIndex) >> ivec3(0, 16, 8), 0, 8); #ifdef COMPRESSED_VERTEX - return vec4(fma(Position.xyz, POSITION_INV, ModelOffset + baseOffset), 1.0); + return fma(Position.xyz, POSITION_INV, ModelOffset + baseOffset); #else - return vec4(Position.xyz + baseOffset, 1.0); + return Position.xyz + baseOffset; #endif } void main() { - const vec4 pos = getVertexPosition(); - gl_Position = MVP * pos; + const vec3 pos = getVertexPosition(); + gl_Position = MVP * vec4(pos, 1.0); + + sphericalVertexDistance = fog_spherical_distance(pos); + cylindricalVertexDistance = fog_cylindrical_distance(pos); - vertexDistance = fog_distance(pos.xyz, 0); const vec4 Color = unpackUnorm4x8(PackedColor); vertexColor = Color * sample_lightmap2(Sampler2, Position.a); diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh index 6ee8d3e746..7be38bce78 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.fsh @@ -9,17 +9,22 @@ layout(binding = 2) uniform sampler2D Sampler0; layout(binding = 1) uniform UBO { vec4 FogColor; - float FogStart; - float FogEnd; + float FogEnvironmentalStart; + float FogEnvironmentalEnd; + float FogRenderDistanceStart; + float FogRenderDistanceEnd; + float FogSkyEnd; + float FogCloudsEnd; }; layout(location = 0) in vec4 vertexColor; layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; +layout(location = 2) in float sphericalVertexDistance; +layout(location = 3) in float cylindricalVertexDistance; layout(location = 0) out vec4 fragColor; void main() { vec4 color = texture(Sampler0, texCoord0) * vertexColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json index 13062973c5..139dd2e2da 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json @@ -11,8 +11,12 @@ ] }, { "type": "fragment", "binding": 1, "fields": [ { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogEnvironmentalStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnvironmentalEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogRenderDistanceStart", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogRenderDistanceEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogSkyEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogCloudsEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, { "name": "AlphaCutout", "type": "float", "count": 1, "values": [ 1.0 ] } ] } ], diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh deleted file mode 100644 index 471982cdde..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.fsh +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -layout(binding = 0) uniform sampler2D DiffuseSampler; - -layout(location = 0) in vec2 texCoord; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(DiffuseSampler, texCoord); - fragColor = color; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json deleted file mode 100644 index 6405ec09d9..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "vertex": "blit_screen", - "fragment": "blit_screen", - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - ] -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh deleted file mode 100644 index 8cedf72511..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.vsh +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; - -layout(location = 0) out vec2 texCoord; - -void main() { - vec2 screenPos = Position.xy * 2.0 - 1.0; - gl_Position = vec4(screenPos.x, screenPos.y, 1.0, 1.0); - texCoord = Position.xy; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh deleted file mode 100644 index 29fd0268fc..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.fsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh b/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh deleted file mode 100644 index 76e60cbae9..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/entity/entity.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/glint/glint.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh b/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh deleted file mode 100644 index fce9fa7c61..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 vertexColor; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor; - if (color.a == 0.0) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh b/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh deleted file mode 100644 index 5fd8ccf2b3..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/gui/gui.vsh +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh deleted file mode 100644 index 8465e60343..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.fsh +++ /dev/null @@ -1,70 +0,0 @@ -#version 450 - -layout(binding = 0) uniform UniformBufferObject { - float AmbientLightFactor; - float SkyFactor; - float BlockFactor; - int UseBrightLightmap; - vec3 SkyLightColor; - float NightVisionFactor; - float DarknessScale; - float DarkenWorldFactor; - float BrightnessFactor; -}; - -layout(location = 0) in vec2 texCoord; - -layout(location = 0) out vec4 fragColor; - -float get_brightness(float level) { - float curved_level = level / (4.0 - 3.0 * level); - return mix(curved_level, 1.0, AmbientLightFactor); -} - -vec3 notGamma(vec3 x) { - vec3 nx = 1.0 - x; - return 1.0 - nx * nx * nx * nx; -} - -void main() { - float block_brightness = get_brightness(floor(texCoord.x * 16) / 15) * BlockFactor; - float sky_brightness = get_brightness(floor(texCoord.y * 16) / 15) * SkyFactor; - - // cubic nonsense, dips to yellowish in the middle, white when fully saturated - vec3 color = vec3( - block_brightness, - block_brightness * ((block_brightness * 0.6 + 0.4) * 0.6 + 0.4), - block_brightness * (block_brightness * block_brightness * 0.6 + 0.4) - ); - - if (UseBrightLightmap != 0) { - color = mix(color, vec3(0.99, 1.12, 1.0), 0.25); - color = clamp(color, 0.0, 1.0); - } else { - color += SkyLightColor * sky_brightness; - color = mix(color, vec3(0.75), 0.04); - - vec3 darkened_color = color * vec3(0.7, 0.6, 0.6); - color = mix(color, darkened_color, DarkenWorldFactor); - } - - if (NightVisionFactor > 0.0) { - // scale up uniformly until 1.0 is hit by one of the colors - float max_component = max(color.r, max(color.g, color.b)); - if (max_component < 1.0) { - vec3 bright_color = color / max_component; - color = mix(color, bright_color, NightVisionFactor); - } - } - - if (UseBrightLightmap == 0) { - color = clamp(color - vec3(DarknessScale), 0.0, 1.0); - } - - vec3 notGamma = notGamma(color); - color = mix(color, notGamma, BrightnessFactor); - color = mix(color, vec3(0.75), 0.04); - color = clamp(color, 0.0, 1.0); - - fragColor = vec4(color, 1.0); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json deleted file mode 100644 index 5efc51dacc..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "vertex": "blit_screen", - "fragment": "lightmap", - "samplers": [ - ], - "uniforms": [ - { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, - { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, - { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } - ], - "UBOs": [ - { "type": "fragment", "binding": 0, "fields": [ - { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, - { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, - { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh deleted file mode 100644 index 7659168a5b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json deleted file mode 100644 index f43398ce06..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "particle", - "fragment": "particle", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh deleted file mode 100644 index 03430a48cd..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.vsh +++ /dev/null @@ -1,26 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; -layout(location = 2) in vec4 Color; -layout(location = 3) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = UV0; - vertexColor = Color * texelFetch(Sampler2, UV2 / 16, 0); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh deleted file mode 100644 index 3f5a88f372..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position/position.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - fragColor = linear_fog(ColorModulator, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position/position.json b/src/main/resources/assets/vulkanmod/shaders/core/position/position.json deleted file mode 100644 index ea9c19207a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position/position.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position", - "fragment": "position", - "attributes": [], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh deleted file mode 100644 index 3c348837f8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position/position.vsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh deleted file mode 100644 index fce9fa7c61..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 vertexColor; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor; - if (color.a == 0.0) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json deleted file mode 100644 index fd537cf882..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_color", - "fragment": "position_color", - "attributes": [ - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh deleted file mode 100644 index ebb1fafb9b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.vsh +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh deleted file mode 100644 index a94ccfc2e7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord2; - -layout(binding = 1) uniform UBO { - vec4 ColorModulator; -}; - -layout(binding = 2) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler2, texCoord2) * vertexColor; - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json deleted file mode 100644 index ad3eac50cb..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_color_lightmap", - "fragment": "position_color_lightmap", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh deleted file mode 100644 index 78f3e6d997..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord2; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord2 = UV2; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh deleted file mode 100644 index cf7099c9f6..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.fsh +++ /dev/null @@ -1,49 +0,0 @@ -//#version 150 -// -//#moj_import -// -//uniform vec4 ColorModulator; -//uniform float FogStart; -//uniform float FogEnd; -//uniform vec4 FogColor; -// -//in float vertexDistance; -//in vec4 vertexColor; -//in vec4 normal; -// -//out vec4 fragColor; -// -//void main() { -// vec4 color = vertexColor * ColorModulator; -// if (color.a < 0.1) { -// discard; -// } -// fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -//} - -#version 450 - -#include - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - vec4 FogColor; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec4 normal; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json deleted file mode 100644 index afe94f3c73..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_color_normal", - "fragment": "position_color_normal", - "attributes": [ - "Position", - "Color", - "Normal" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh deleted file mode 100644 index 4561090040..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.vsh +++ /dev/null @@ -1,23 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec4 normal; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color; - normal = MVP * vec4(Normal, 0.0); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh deleted file mode 100644 index e1a3c71911..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json deleted file mode 100644 index 4d92a81a6c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_color_tex", - "fragment": "position_color_tex", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh deleted file mode 100644 index dd71051aaf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh deleted file mode 100644 index e1a3c71911..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json deleted file mode 100644 index f6b71e715b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_color_tex_lightmap", - "fragment": "position_color_tex_lightmap", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh deleted file mode 100644 index 4c4d7f86ee..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh deleted file mode 100644 index d8a9e6c874..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.fsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a == 0.0) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json deleted file mode 100644 index 9f91a8dd3d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_tex", - "fragment": "position_tex", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh deleted file mode 100644 index 4abe8e4657..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.vsh +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh deleted file mode 100644 index e1a3c71911..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json deleted file mode 100644 index c3bbf9faf0..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "vertex": "minecraft:core/position_tex_color", - "fragment": "minecraft:core/position_tex_color", - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh deleted file mode 100644 index dd6470006b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 2) in vec4 Color; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh deleted file mode 100644 index 0fcceefff4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.fsh +++ /dev/null @@ -1,27 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} - - diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json deleted file mode 100644 index 067700ceb3..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "position_tex_color_normal", - "fragment": "position_tex_color_normal", - "attributes": [ - "Position", - "UV0", - "Color" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh deleted file mode 100644 index e022017c3a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.vsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; -layout(location = 2) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - texCoord0 = UV0; - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color; -} - - diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh deleted file mode 100644 index 7659168a5b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json deleted file mode 100644 index aaf972afd8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_armor_cutout_no_cull", - "fragment": "rendertype_armor_cutout_no_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh deleted file mode 100644 index ea9fb38c1d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json deleted file mode 100644 index 9ab1295ed8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_armor_entity_glint", - "fragment": "rendertype_armor_entity_glint", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json deleted file mode 100644 index 04bbe696c4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json deleted file mode 100644 index f393b88b00..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - }, - "flags": [ - "NO_OVERLAY" - ] - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh deleted file mode 100644 index e8c3a5316c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.fsh +++ /dev/null @@ -1,28 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 ProjMat; -}; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - color *= vertexColor * ColorModulator; - float fragmentDistance = -ProjMat[3].z / ((gl_FragCoord.z) * -2.0 + 1.0 - ProjMat[2].z); - fragColor = linear_fog(color, fragmentDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json deleted file mode 100644 index 8460562644..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_beacon_beam", - "fragment": "rendertype_beacon_beam", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "all", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh deleted file mode 100644 index edab87decc..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.vsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 ProjMat; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh deleted file mode 100644 index 52cbfe5e59..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.fsh +++ /dev/null @@ -1,24 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 3) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = color * linear_fog_fade(vertexDistance, FogStart, FogEnd); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json deleted file mode 100644 index 5f2a6453e2..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "vertex": "rendertype_breeze_wind", - "fragment": "rendertype_breeze_wind", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh deleted file mode 100644 index 94a186ffd3..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.vsh +++ /dev/null @@ -1,32 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 ModelViewMat; - mat4 TextureMat; - int FogShape; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec4 lightMapColor; -layout(location = 3) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position, FogShape); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - vertexColor = Color * lightMapColor; - - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh deleted file mode 100644 index 2a3e1b3699..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.fsh +++ /dev/null @@ -1,43 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - fragColor = linear_fog(vertexColor, vertexDistance, FogStart, FogEnd, FogColor); -} - -//#version 150 -// -//#moj_import -// -//uniform sampler2D Sampler0; -// -//uniform vec4 ColorModulator; -//uniform float FogStart; -//uniform float FogEnd; -//uniform vec4 FogColor; -// -//in vec2 texCoord0; -//in float vertexDistance; -//in vec4 vertexColor; -// -//out vec4 fragColor; -// -//void main() { -// vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; -// if (color.a < 0.1) { -// discard; -// } -// fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -//} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json deleted file mode 100644 index be8253788a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "vertex": "minecraft:core/rendertype_clouds", - "fragment": "minecraft:core/rendertype_clouds", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "ModelOffset", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh deleted file mode 100644 index 7b65d90584..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.vsh +++ /dev/null @@ -1,28 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; -layout(location = 2) in vec4 Color; -layout(location = 3) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 ModelViewMat; - int FogShape; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; -layout(location = 3) out vec3 normal; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - texCoord0 = UV0; - vec4 pos = ModelViewMat * vec4(Position, 1.0); - vertexDistance = fog_distance(pos.xyz, FogShape); - vertexColor = Color; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh deleted file mode 100644 index 68a45f5902..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json deleted file mode 100644 index 52c1c76081..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_crumbling", - "fragment": "rendertype_crumbling", - "attributes": [ - "Position", - "Color", - "UV0", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh deleted file mode 100644 index d55f8be78c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.vsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh deleted file mode 100644 index a0259eb005..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json deleted file mode 100644 index 18d86581cf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_cutout", - "fragment": "rendertype_cutout", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh deleted file mode 100644 index c1f4566970..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 ChunkOffset; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec2 texCoord0; - -void main() { - vec3 pos = Position + ChunkOffset; - gl_Position = MVP * vec4(pos, 1.0); - - vertexDistance = fog_distance(pos, 0); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh deleted file mode 100644 index fd4834edac..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.5) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json deleted file mode 100644 index 79065cfeab..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_cutout_mipped", - "fragment": "rendertype_cutout_mipped", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh deleted file mode 100644 index c1f4566970..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 ChunkOffset; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec2 texCoord0; - -void main() { - vec3 pos = Position + ChunkOffset; - gl_Position = MVP * vec4(pos, 1.0); - - vertexDistance = fog_distance(pos, 0); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json deleted file mode 100644 index 8e6cb7d0b7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "vertex": "rendertype_end_portal", - "fragment": "rendertype_end_portal", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh deleted file mode 100644 index d41c5f7459..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.fsh +++ /dev/null @@ -1,69 +0,0 @@ -#version 450 - -mat2 mat2_rotate_z(float radians) { - return mat2( - cos(radians), -sin(radians), - sin(radians), cos(radians) - ); -} - -layout(location = 0) in vec4 texProj0; - -layout(binding = 1) uniform UniformBufferObject { - float GameTime; - int EndPortalLayers; -}; - -layout(binding = 2) uniform sampler2D Sampler0; -layout(binding = 3) uniform sampler2D Sampler1; - -const vec3[] COLORS = vec3[]( - vec3(0.022087, 0.098399, 0.110818), - vec3(0.011892, 0.095924, 0.089485), - vec3(0.027636, 0.101689, 0.100326), - vec3(0.046564, 0.109883, 0.114838), - vec3(0.064901, 0.117696, 0.097189), - vec3(0.063761, 0.086895, 0.123646), - vec3(0.084817, 0.111994, 0.166380), - vec3(0.097489, 0.154120, 0.091064), - vec3(0.106152, 0.131144, 0.195191), - vec3(0.097721, 0.110188, 0.187229), - vec3(0.133516, 0.138278, 0.148582), - vec3(0.070006, 0.243332, 0.235792), - vec3(0.196766, 0.142899, 0.214696), - vec3(0.047281, 0.315338, 0.321970), - vec3(0.204675, 0.390010, 0.302066), - vec3(0.080955, 0.314821, 0.661491) -); - -const mat4 SCALE_TRANSLATE = mat4( - 0.5, 0.0, 0.0, 0.25, - 0.0, 0.5, 0.0, 0.25, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 -); - -mat4 end_portal_layer(float layer) { - mat4 translate = mat4( - 1.0, 0.0, 0.0, 17.0 / layer, - 0.0, 1.0, 0.0, (2.0 + layer / 1.5) * (GameTime * 1.5), - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - ); - - mat2 rotate = mat2_rotate_z(radians((layer * layer * 4321.0 + layer * 9.0) * 2.0)); - - mat2 scale = mat2((4.5 - layer / 4.0) * 2.0); - - return mat4(scale * rotate) * translate * SCALE_TRANSLATE; -} - -layout(location = 0) out vec4 fragColor; - -void main() { - vec3 color = textureProj(Sampler0, texProj0).rgb * COLORS[0]; - for (int i = 0; i < EndPortalLayers; i++) { - color += textureProj(Sampler1, texProj0 * end_portal_layer(float(i + 1))).rgb * COLORS[i]; - } - fragColor = vec4(color, 1.0); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json deleted file mode 100644 index 8e6cb7d0b7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "vertex": "rendertype_end_portal", - "fragment": "rendertype_end_portal", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh deleted file mode 100644 index f85a742f12..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.vsh +++ /dev/null @@ -1,23 +0,0 @@ -#version 450 - -//projection.glsl -vec4 projection_from_position(vec4 position) { - vec4 projection = position * 0.5; - projection.xy = vec2(projection.x + projection.w, projection.y + projection.w); - projection.zw = position.zw; - return projection; -} - -layout(location = 0) in vec3 Position; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 texProj0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - texProj0 = projection_from_position(gl_Position); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh deleted file mode 100644 index 3f347be380..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.fsh +++ /dev/null @@ -1,24 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = color * linear_fog_fade(vertexDistance, FogStart, FogEnd); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json deleted file mode 100644 index a47d5e1236..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_energy_swirl", - "fragment": "rendertype_energy_swirl", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh deleted file mode 100644 index f005d27601..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.vsh +++ /dev/null @@ -1,24 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color; - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh deleted file mode 100644 index 5da52f8114..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.fsh +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(binding = 1) uniform sampler2D Sampler0; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < vertexColor.a) { - discard; - } - fragColor = color; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json deleted file mode 100644 index edbd117d59..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "vertex": "rendertype_entity_alpha", - "fragment": "rendertype_entity_alpha", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] } - - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh deleted file mode 100644 index 200022c8e8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json deleted file mode 100644 index ea44c9e1e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - } - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json deleted file mode 100644 index ea44c9e1e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - } - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json deleted file mode 100644 index ea44c9e1e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - } - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh deleted file mode 100644 index 23563e8a6e..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.fsh +++ /dev/null @@ -1,28 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 overlayColor; -layout(location = 2) in vec2 texCoord0; -layout(location = 3) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= vertexColor * ColorModulator; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json deleted file mode 100644 index 7ff5136759..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_decal", - "fragment": "rendertype_entity_decal", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh deleted file mode 100644 index e63fafd909..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.vsh +++ /dev/null @@ -1,34 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 overlayColor; -layout(location = 2) out vec2 texCoord0; -layout(location = 3) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json deleted file mode 100644 index 669060bd44..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_glint", - "fragment": "rendertype_entity_glint", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh deleted file mode 100644 index 8ffd06755d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; - float GlintAlpha; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * ColorModulator; - if (color.a < 0.1) { - discard; - } - float fade = linear_fog_fade(vertexDistance, FogStart, FogEnd) * GlintAlpha; - fragColor = vec4(color.rgb * fade, color.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json deleted file mode 100644 index b7f6179a0e..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_glint_direct", - "fragment": "rendertype_entity_glint_direct", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh deleted file mode 100644 index 71aa44c51c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.vsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - mat4 TextureMat; -}; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh deleted file mode 100644 index d44254ed46..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.fsh +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json deleted file mode 100644 index 4a9b8f4958..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_no_outline", - "fragment": "rendertype_entity_no_outline", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh deleted file mode 100644 index ea9fb38c1d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh deleted file mode 100644 index 4ee8e3d7d2..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.fsh +++ /dev/null @@ -1,18 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, clamp(texCoord0, 0.0, 1.0)); - color *= vertexColor * ColorModulator; - fragColor = color; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json deleted file mode 100644 index 96628895f3..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_shadow", - "fragment": "rendertype_entity_shadow", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh deleted file mode 100644 index 817669d61c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json deleted file mode 100644 index ea44c9e1e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - } - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh deleted file mode 100644 index 0046a94830..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.fsh +++ /dev/null @@ -1,26 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 lightMapColor; -layout(location = 2) in vec4 overlayColor; -layout(location = 3) in vec2 texCoord0; -layout(location = 4) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - color *= lightMapColor; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json deleted file mode 100644 index 0e4e0177ba..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "vertex": "rendertype_entity_solid", - "fragment": "rendertype_entity_solid", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh deleted file mode 100644 index 46038952cf..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.vsh +++ /dev/null @@ -1,36 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 lightMapColor; -layout(location = 2) out vec4 overlayColor; -layout(location = 3) out vec2 texCoord0; -layout(location = 4) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json deleted file mode 100644 index ea44c9e1e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - } - }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh deleted file mode 100644 index c101705b97..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json deleted file mode 100644 index 3586e725a8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "vertex": "rendertype_entity_translucent_cull", - "fragment": "rendertype_entity_translucent_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh deleted file mode 100644 index e2850014e6..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.vsh +++ /dev/null @@ -1,31 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh deleted file mode 100644 index f7ad11db5d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.fsh +++ /dev/null @@ -1,27 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec4 overlayColor; -layout(location = 2) in vec2 texCoord0; -layout(location = 3) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a < 0.1) { - discard; - } - color *= vertexColor * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - fragColor = color * linear_fog_fade(vertexDistance, FogStart, FogEnd); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json deleted file mode 100644 index c69e755083..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_translucent_emissive", - "fragment": "rendertype_entity_translucent_emissive", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh deleted file mode 100644 index 5dd29078b1..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.vsh +++ /dev/null @@ -1,33 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV1; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; -}; - -layout(binding = 3) uniform sampler2D Sampler1; -layout(binding = 4) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec4 overlayColor; -layout(location = 2) out vec2 texCoord0; -layout(location = 3) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); - overlayColor = texelFetch(Sampler1, UV1, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh deleted file mode 100644 index 73da034a12..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.fsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - fragColor = color * ColorModulator * linear_fog_fade(vertexDistance, FogStart, FogEnd); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json deleted file mode 100644 index 57462d602f..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_eyes", - "fragment": "rendertype_eyes", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh deleted file mode 100644 index 74920ad34c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.vsh +++ /dev/null @@ -1,23 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json deleted file mode 100644 index 04bbe696c4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json deleted file mode 100644 index aadaa01d4f..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json deleted file mode 100644 index aadaa01d4f..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json deleted file mode 100644 index 904c1badf1..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json deleted file mode 100644 index 904c1badf1..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json deleted file mode 100644 index 904c1badf1..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json deleted file mode 100644 index 904c1badf1..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh deleted file mode 100644 index c101705b97..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json deleted file mode 100644 index 8bfd379853..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_item_entity_translucent_cull", - "fragment": "rendertype_item_entity_translucent_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh index ea9fb38c1d..a7db8154df 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.vsh @@ -1,30 +1,93 @@ -#version 450 +#version 330 #include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in ivec2 UV2; -layout(location = 5) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 Light0_Direction; - vec3 Light1_Direction; + +layout(std140) uniform Lighting { +vec3 Light0_Direction; +vec3 Light1_Direction; +}; + +layout(std140) uniform Fog { + vec4 FogColor; + float FogEnvironmentalStart; + float FogEnvironmentalEnd; + float FogRenderDistanceStart; + float FogRenderDistanceEnd; + float FogSkyEnd; + float FogCloudsEnd; }; -layout(binding = 3) uniform sampler2D Sampler2; +float linear_fog_value(float vertexDistance, float fogStart, float fogEnd) { + if (vertexDistance <= fogStart) { + return 0.0; + } else if (vertexDistance >= fogEnd) { + return 1.0; + } + + return (vertexDistance - fogStart) / (fogEnd - fogStart); +} + +float total_fog_value(float sphericalVertexDistance, float cylindricalVertexDistance, float environmentalStart, float environmantalEnd, float renderDistanceStart, float renderDistanceEnd) { + return max(linear_fog_value(sphericalVertexDistance, environmentalStart, environmantalEnd), linear_fog_value(cylindricalVertexDistance, renderDistanceStart, renderDistanceEnd)); +} + +vec4 apply_fog(vec4 inColor, float sphericalVertexDistance, float cylindricalVertexDistance, float environmentalStart, float environmantalEnd, float renderDistanceStart, float renderDistanceEnd, vec4 fogColor) { + float fogValue = total_fog_value(sphericalVertexDistance, cylindricalVertexDistance, environmentalStart, environmantalEnd, renderDistanceStart, renderDistanceEnd); + return vec4(mix(inColor.rgb, fogColor.rgb, fogValue * fogColor.a), inColor.a); +} + +float fog_spherical_distance(vec3 pos) { + return length(pos); +} + +float fog_cylindrical_distance(vec3 pos) { + float distXZ = length(pos.xz); + float distY = abs(pos.y); + return max(distXZ, distY); +} + +layout(std140) uniform DynamicTransforms { + mat4 ModelViewMat; + vec4 ColorModulator; + vec3 ModelOffset; + mat4 TextureMat; + float LineWidth; +}; + +layout(std140) uniform Projection { + mat4 ProjMat; +}; + +vec4 projection_from_position(vec4 position) { + vec4 projection = position * 0.5; + projection.xy = vec2(projection.x + projection.w, projection.y + projection.w); + projection.zw = position.zw; + return projection; +} + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +uniform sampler2D Sampler2; -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; +out float sphericalVertexDistance; +out float cylindricalVertexDistance; +out vec4 vertexColor; +out vec2 texCoord0; +out vec2 texCoord1; +out vec2 texCoord2; void main() { - gl_Position = MVP * vec4(Position, 1.0); + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); - vertexDistance = fog_distance(Position.xyz, 0); + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color) * texelFetch(Sampler2, UV2 / 16, 0); texCoord0 = UV0; + texCoord1 = UV1; + texCoord2 = UV2; } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh deleted file mode 100644 index aacb8525d8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) flat in vec4 vertexColor; -layout(location = 1) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - fragColor = linear_fog(vertexColor, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json deleted file mode 100644 index 373975076c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_leash", - "fragment": "rendertype_leash", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh deleted file mode 100644 index 5613737ebd..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.vsh +++ /dev/null @@ -1,24 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec4 ColorModulator; -}; - -layout(binding = 2) uniform sampler2D Sampler2; - -layout(location = 0) flat out vec4 vertexColor; -layout(location = 1) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color * ColorModulator * texelFetch(Sampler2, UV2 / 16, 0); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh deleted file mode 100644 index 611cd42cef..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - fragColor = vertexColor * ColorModulator * linear_fog_fade(vertexDistance, FogStart, FogEnd); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json deleted file mode 100644 index 59a6d6ad02..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_lightning", - "fragment": "rendertype_lightning", - "attributes": [ - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh deleted file mode 100644 index c9312302f0..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.vsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh deleted file mode 100644 index 9d3812f74a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.fsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor * ColorModulator; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json deleted file mode 100644 index b719262ee5..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_lines", - "fragment": "rendertype_lines", - "attributes": [ - "Position", - "Color", - "Normal" - ], - "samplers": [], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "LineWidth", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "ScreenSize", "type": "float", "count": 2, "values": [ 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ScreenSize", "type": "float", "count": 2, "values": [ 1.0, 1.0 ] }, - { "name": "LineWidth", "type": "float", "count": 1, "values": [ 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh deleted file mode 100644 index 60a1d4b8cc..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.vsh +++ /dev/null @@ -1,47 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 ModelViewMat; - mat4 ProjMat; - vec2 ScreenSize; - float LineWidth; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out float vertexDistance; - -const float VIEW_SHRINK = 1.0 - (1.0 / 256.0); -const mat4 VIEW_SCALE = mat4( - VIEW_SHRINK, 0.0, 0.0, 0.0, - 0.0, VIEW_SHRINK, 0.0, 0.0, - 0.0, 0.0, VIEW_SHRINK, 0.0, - 0.0, 0.0, 0.0, 1.0 -); - -void main() { - vec4 linePosStart = ProjMat * VIEW_SCALE * ModelViewMat * vec4(Position, 1.0); - vec4 linePosEnd = ProjMat * VIEW_SCALE * ModelViewMat * vec4(Position + Normal, 1.0); - - vec3 ndc1 = linePosStart.xyz / linePosStart.w; - vec3 ndc2 = linePosEnd.xyz / linePosEnd.w; - - vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * ScreenSize); - vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * LineWidth / ScreenSize; - - if (lineOffset.x < 0.0) { - lineOffset *= -1.0; - } - - if (mod(gl_VertexIndex, 2) == 0) { - gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w); - } else { - gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w); - } - - vertexDistance = length((vec4(Position, 1.0)).xyz); - vertexColor = Color; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh deleted file mode 100644 index 7127479f28..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0); - if (color.a == 0.0) { - discard; - } - fragColor = vec4(ColorModulator.rgb * vertexColor.rgb, ColorModulator.a); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json deleted file mode 100644 index dbb6a88db7..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_outline", - "fragment": "rendertype_outline", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh deleted file mode 100644 index a2486fa8d8..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.vsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec2 UV0; -layout(location = 2) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} - diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh deleted file mode 100644 index 84b4bfba2d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.fsh +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in float vertexDistance; -layout(location = 1) in vec4 vertexColor; -layout(location = 2) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json deleted file mode 100644 index f4cd0c92d2..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_solid", - "fragment": "rendertype_solid", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh deleted file mode 100644 index c1f4566970..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 ChunkOffset; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out float vertexDistance; -layout(location = 1) out vec4 vertexColor; -layout(location = 2) out vec2 texCoord0; - -void main() { - vec3 pos = Position + ChunkOffset; - gl_Position = MVP * vec4(pos, 1.0); - - vertexDistance = fog_distance(pos, 0); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh deleted file mode 100644 index c101705b97..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json deleted file mode 100644 index e72c6b3372..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text", - "fragment": "rendertype_text", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh deleted file mode 100644 index 647a3f1d75..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.vsh +++ /dev/null @@ -1,26 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh deleted file mode 100644 index f4c3c01f6a..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.fsh +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json deleted file mode 100644 index 786c39176d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text_background", - "fragment": "rendertype_text_background", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh deleted file mode 100644 index ae6f0c93e4..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.vsh +++ /dev/null @@ -1,23 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 2) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color * texelFetch(Sampler2, UV2 / 16, 0); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh deleted file mode 100644 index 3d175e2ccd..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 vertexColor; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json deleted file mode 100644 index b70d3129ab..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text_background_see_through", - "fragment": "rendertype_text_background_see_through", - "attributes": [ - "Position", - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh deleted file mode 100644 index 5b5ad04e30..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.vsh +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh deleted file mode 100644 index 957404e3fb..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0).rrrr * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json deleted file mode 100644 index a2bc212218..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text_intensity", - "fragment": "rendertype_text_intensity", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh deleted file mode 100644 index cd7a1176d6..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.vsh +++ /dev/null @@ -1,26 +0,0 @@ -#version 450 - -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexDistance = fog_distance(Position.xyz, 0); - vertexColor = Color * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh deleted file mode 100644 index 931e231275..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.fsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO { - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0).rrrr * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json deleted file mode 100644 index 7c83ff3f2d..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text_intensity_see_through", - "fragment": "rendertype_text_intensity_see_through", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh deleted file mode 100644 index 817669d61c..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.vsh +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh deleted file mode 100644 index 9083d76658..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.fsh +++ /dev/null @@ -1,21 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - if (color.a < 0.1) { - discard; - } - fragColor = color * ColorModulator; -} - diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json deleted file mode 100644 index 42009dce5e..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_text_see_through", - "fragment": "rendertype_text_see_through", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh deleted file mode 100644 index b203fb5099..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.vsh +++ /dev/null @@ -1,20 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} - diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh deleted file mode 100644 index d44254ed46..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.fsh +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json deleted file mode 100644 index 19d8c6f7d2..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_translucent", - "fragment": "rendertype_translucent", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh deleted file mode 100644 index 511c92c803..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 ChunkOffset; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - vec3 pos = Position + ChunkOffset; - gl_Position = MVP * vec4(pos, 1.0); - - vertexDistance = fog_distance(pos, 0); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh deleted file mode 100644 index 88f51fae74..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - fragColor = color * ColorModulator; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json deleted file mode 100644 index 00a20cbba6..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_translucent_moving_block", - "fragment": "rendertype_translucent_moving_block", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh deleted file mode 100644 index 350d59baed..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.vsh +++ /dev/null @@ -1,23 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color * texelFetch(Sampler2, UV2 / 16, 0); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh deleted file mode 100644 index 88f51fae74..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.fsh +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor; - fragColor = color * ColorModulator; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json deleted file mode 100644 index 072428c987..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_translucent_no_crumbling", - "fragment": "rendertype_translucent_no_crumbling", - "attributes": [ - "Position", - "Color", - "UV0", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh deleted file mode 100644 index f9c22186b2..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.vsh +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); - - vertexColor = Color; - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh deleted file mode 100644 index 7659168a5b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.fsh +++ /dev/null @@ -1,25 +0,0 @@ -#version 450 -#include "fog.glsl" - -layout(binding = 2) uniform sampler2D Sampler0; - -layout(binding = 1) uniform UBO{ - vec4 ColorModulator; - vec4 FogColor; - float FogStart; - float FogEnd; -}; - -layout(location = 0) in vec4 vertexColor; -layout(location = 1) in vec2 texCoord0; -layout(location = 2) in float vertexDistance; - -layout(location = 0) out vec4 fragColor; - -void main() { - vec4 color = texture(Sampler0, texCoord0) * vertexColor * ColorModulator; - if (color.a < 0.1) { - discard; - } - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json deleted file mode 100644 index 6a5d92cce5..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_tripwire", - "fragment": "rendertype_tripwire", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh deleted file mode 100644 index 511c92c803..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.vsh +++ /dev/null @@ -1,30 +0,0 @@ -#version 450 - -#include "light.glsl" -#include "fog.glsl" - -layout(location = 0) in vec3 Position; -layout(location = 1) in vec4 Color; -layout(location = 2) in vec2 UV0; -layout(location = 3) in ivec2 UV2; -layout(location = 4) in vec3 Normal; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; - vec3 ChunkOffset; -}; - -layout(binding = 3) uniform sampler2D Sampler2; - -layout(location = 0) out vec4 vertexColor; -layout(location = 1) out vec2 texCoord0; -layout(location = 2) out float vertexDistance; - -void main() { - vec3 pos = Position + ChunkOffset; - gl_Position = MVP * vec4(pos, 1.0); - - vertexDistance = fog_distance(pos, 0); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh deleted file mode 100644 index 252f19600b..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.fsh +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(binding = 1) uniform UniformBufferObject { - vec4 ColorModulator; -}; - -layout(location = 0) out vec4 fragColor; - -void main() { - fragColor = ColorModulator; -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json deleted file mode 100644 index 52f69c0bbb..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_water_mask", - "fragment": "rendertype_water_mask", - "attributes": [], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] -} diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh deleted file mode 100644 index c663f48dec..0000000000 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.vsh +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(location = 0) in vec3 Position; - -layout(binding = 0) uniform UniformBufferObject { - mat4 MVP; -}; - -void main() { - gl_Position = MVP * vec4(Position, 1.0); -} \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/screenquad/screenquad.vsh b/src/main/resources/assets/vulkanmod/shaders/core/screenquad/screenquad.vsh new file mode 100644 index 0000000000..1c317cd740 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/core/screenquad/screenquad.vsh @@ -0,0 +1,11 @@ +#version 330 + +out vec2 texCoord; + +void main() { + vec2 uv = vec2((gl_VertexID << 1) & 2, -(gl_VertexID & 2) + 1); + vec4 pos = vec4(uv * vec2(2, -2) + vec2(-1, +1), 0, 1); + + gl_Position = pos; + texCoord = uv; +} diff --git a/src/main/resources/assets/vulkanmod/shaders/include/fog.glsl b/src/main/resources/assets/vulkanmod/shaders/include/fog.glsl index 2322fb8e76..35fe1ad0f5 100644 --- a/src/main/resources/assets/vulkanmod/shaders/include/fog.glsl +++ b/src/main/resources/assets/vulkanmod/shaders/include/fog.glsl @@ -21,3 +21,32 @@ float fog_distance(vec3 pos, int shape) { return max(distXZ, distY); } } + +float linear_fog_value(float vertexDistance, float fogStart, float fogEnd) { + if (vertexDistance <= fogStart) { + return 0.0; + } else if (vertexDistance >= fogEnd) { + return 1.0; + } + + return (vertexDistance - fogStart) / (fogEnd - fogStart); +} + +float total_fog_value(float sphericalVertexDistance, float cylindricalVertexDistance, float environmentalStart, float environmantalEnd, float renderDistanceStart, float renderDistanceEnd) { + return max(linear_fog_value(sphericalVertexDistance, environmentalStart, environmantalEnd), linear_fog_value(cylindricalVertexDistance, renderDistanceStart, renderDistanceEnd)); +} + +vec4 apply_fog(vec4 inColor, float sphericalVertexDistance, float cylindricalVertexDistance, float environmentalStart, float environmantalEnd, float renderDistanceStart, float renderDistanceEnd, vec4 fogColor) { + float fogValue = total_fog_value(sphericalVertexDistance, cylindricalVertexDistance, environmentalStart, environmantalEnd, renderDistanceStart, renderDistanceEnd); + return vec4(mix(inColor.rgb, fogColor.rgb, fogValue * fogColor.a), inColor.a); +} + +float fog_spherical_distance(vec3 pos) { + return length(pos); +} + +float fog_cylindrical_distance(vec3 pos) { + float distXZ = length(pos.xz); + float distY = abs(pos.y); + return max(distXZ, distY); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/include/light.glsl b/src/main/resources/assets/vulkanmod/shaders/include/light.glsl index 3f95fb01ac..0db8ac7b3c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/include/light.glsl +++ b/src/main/resources/assets/vulkanmod/shaders/include/light.glsl @@ -3,15 +3,6 @@ const float MINECRAFT_LIGHT_POWER = (0.6); const float MINECRAFT_AMBIENT_LIGHT = (0.4); -vec4 minecraft_mix_light(vec3 lightDir0, vec3 lightDir1, vec3 normal, vec4 color) { - lightDir0 = normalize(lightDir0); - lightDir1 = normalize(lightDir1); - float light0 = max(0.0, dot(lightDir0, normal)); - float light1 = max(0.0, dot(lightDir1, normal)); - float lightAccum = min(1.0, fma((light0 + light1), MINECRAFT_LIGHT_POWER, MINECRAFT_AMBIENT_LIGHT)); - return vec4(color.rgb * lightAccum, color.a); -} - vec4 minecraft_sample_lightmap(sampler2D lightMap, ivec2 uv) { return texelFetch(lightMap, bitfieldExtract(uv, 4, 8), 0); //return texture(lightMap, clamp(uv / 256.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0))); @@ -26,3 +17,18 @@ vec4 sample_lightmap2(sampler2D lightMap, uint uv) { // const ivec2 lm = ivec2(uv >> 12, (uv >> 4) & 0xF); return texelFetch(lightMap, lm, 0); } + +vec2 minecraft_compute_light(vec3 lightDir0, vec3 lightDir1, vec3 normal) { + return vec2(dot(lightDir0, normal), dot(lightDir1, normal)); +} + +vec4 minecraft_mix_light_separate(vec2 light, vec4 color) { + vec2 lightValue = max(vec2(0.0), light); + float lightAccum = min(1.0, fma((lightValue.x + lightValue.y), MINECRAFT_LIGHT_POWER, MINECRAFT_AMBIENT_LIGHT)); + return vec4(color.rgb * lightAccum, color.a); +} + +vec4 minecraft_mix_light(vec3 lightDir0, vec3 lightDir1, vec3 normal, vec4 color) { + vec2 light = minecraft_compute_light(lightDir0, lightDir1, normal); + return minecraft_mix_light_separate(light, color); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/post/blit/blit.vsh b/src/main/resources/assets/vulkanmod/shaders/post/blit/blit.vsh new file mode 100644 index 0000000000..1f6cf6e70d --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/post/blit/blit.vsh @@ -0,0 +1,15 @@ +#version 150 + +in vec4 Position; + +uniform mat4 ProjMat; +uniform vec2 OutSize; + +out vec2 texCoord; + +void main(){ + vec4 outPos = ProjMat * vec4(Position.xy * OutSize, 0.0, 1.0); + gl_Position = vec4(outPos.xy, 0.2, 1.0); + + texCoord = vec2(Position.x, 1.0 - Position.y); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/post/blit/blur.vsh b/src/main/resources/assets/vulkanmod/shaders/post/blit/blur.vsh new file mode 100644 index 0000000000..65982295c6 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/post/blit/blur.vsh @@ -0,0 +1,21 @@ +#version 150 + +in vec4 Position; + +uniform mat4 ProjMat; +uniform vec2 InSize; +uniform vec2 OutSize; +uniform vec2 BlurDir; + +out vec2 texCoord; +out vec2 sampleStep; + +void main() { + vec4 outPos = ProjMat * vec4(Position.xy * OutSize, 0.0, 1.0); + gl_Position = vec4(outPos.xy, 0.2, 1.0); + + vec2 oneTexel = 1.0 / InSize; + sampleStep = oneTexel * BlurDir; + + texCoord = vec2(Position.x, 1.0 - Position.y); +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index c1ee1dcd01..fde6241796 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,7 @@ "depends": { "fabricloader": ">=0.14.14", - "minecraft": ">=1.21.4" + "minecraft": ">=1.21.9" }, "custom": { "fabric-renderer-api-v1:contains_renderer": true diff --git a/src/main/resources/vulkanmod.accesswidener b/src/main/resources/vulkanmod.accesswidener index 9a9e7fd208..85ea0ce73e 100644 --- a/src/main/resources/vulkanmod.accesswidener +++ b/src/main/resources/vulkanmod.accesswidener @@ -15,12 +15,6 @@ accessible field net/minecraft/client/renderer/texture/SpriteContents$FrameInfo #1.20 accessible field net/minecraft/client/renderer/RenderStateShard name Ljava/lang/String; -accessible class net/minecraft/client/renderer/ShaderManager$ShaderCompilationKey -accessible method net/minecraft/client/renderer/ShaderManager$ShaderCompilationKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/shaders/CompiledShader$Type;Lnet/minecraft/client/renderer/ShaderDefines;)V accessible class net/minecraft/client/renderer/ShaderManager$ShaderSourceKey -accessible method net/minecraft/client/renderer/ShaderManager$ShaderSourceKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/shaders/CompiledShader$Type;)V -accessible class net/minecraft/client/renderer/ShaderManager$CompilationCache -accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache programs Ljava/util/Map; -accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache shaders Ljava/util/Map; -accessible field net/minecraft/client/renderer/ShaderManager$CompilationCache postChains Ljava/util/Map; -accessible method net/minecraft/client/renderer/CompiledShaderProgram (I)V \ No newline at end of file +accessible method net/minecraft/client/renderer/ShaderManager$ShaderSourceKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/shaders/ShaderType;)V +accessible class net/minecraft/client/renderer/ShaderManager$CompilationCache \ No newline at end of file diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 3949dd9129..645e8cdef1 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -20,29 +20,31 @@ "chunk.ViewAreaM", "chunk.VisibilitySetMixin", - "compatibility.EffectInstanceM", - "compatibility.ProgramM", - "compatibility.UniformM", "compatibility.gl.GL11M", "compatibility.gl.GL15M", "compatibility.gl.GL30M", "debug.crash_report.SystemReportM", - "debug.DebugScreenOverlayM", - "debug.GlDebugInfoM", + "debug.DebugEntryMemoryM", "debug.KeyboardHandlerM", "matrix.Matrix4fM", "matrix.PoseAccessor", + "profiling.ClientMetricsSamplersProviderMixin", "profiling.GuiMixin", "profiling.KeyboardHandlerM", "profiling.LevelRendererMixin", + "profiling.TimerQueryM", - "render.BufferUploaderM", + "render.CompositeStateAccessor", + "render.CompositeRenderTypeM", + "render.FogRendererMixin", "render.GameRendererMixin", + "render.GuiRendererMixin", "render.GlStateManagerM", "render.MinecraftMixin", + "render.PictureInPictureRendererM", "render.RenderSystemMixin", "render.RenderTypeM", "render.biome.BiomeManagerM", @@ -55,38 +57,35 @@ "render.entity.model.ModelPartM", "render.frame.MinecraftMixin", "render.frame.RenderSystemMixin", - "render.frapi.BakedModelM", + "render.frapi.BatchingRenderCommandQueueM", + "render.frapi.BlockModelRendererM", + "render.frapi.BlockRenderDispatcherAccessor", + "render.frapi.BlockRenderManagerM", + "render.frapi.ItemFeatureRendererM", "render.frapi.ItemRendererAccessor", - "render.frapi.ItemRendererMixin", - "render.frapi.ModelBlockRendererM", - "render.frapi.QuadEmitterM", - "render.particle.SingleQuadParticleM", - "render.shader.CompilationCacheM", - "render.shader.CompiledShaderProgramM", - "render.shader.ShadeProgramConfigM", + "render.frapi.ItemRenderStateLayerRenderStateM", + "render.frapi.ItemRenderStateM", + "render.frapi.OrderedRenderCommandQueueImplM", + "render.particle.QuadParticleGroupM", + "render.particle.QuadParticleRenderStateM", + "render.shader.RenderPipelineM", "render.shader.ShaderManagerM", "render.target.MainTargetMixin", "render.target.RenderTargetMixin", "render.vertex.BufferBuilderM", - "render.vertex.FaceBakeryM", "render.vertex.IndexTypeMixin", - "render.vertex.VertexBufferM", "render.vertex.VertexFormatMixin", "screen.ScreenM", "screen.OptionsScreenM", "texture.mip.MipmapGeneratorM", - "texture.image.MNativeImage", "texture.image.NativeImageAccessor", "texture.update.GameRendererM", "texture.update.MLightTexture", "texture.update.MSpriteContents", "texture.update.MTextureManager", - "texture.MAbstractTexture", - "texture.MTextureUtil", - - "util.ScreenshotRecorderM", + "util.ScreenshotMixin", "vertex.EntityOutlineGeneratorM", "vertex.SpriteCoordinateExpanderM", @@ -99,7 +98,6 @@ "texture.mip.MipmapGeneratorM", - "compatibility.PostChainM", "compatibility.PostPassM", "voxel.VoxelShapeMixin" From d0175f313fa33e7c8c56199486c11cb1d965f0ea Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 15 Nov 2025 00:03:44 +0100 Subject: [PATCH 101/177] Set lwjgl stack size to 256 to prevent crash on nvidia --- src/main/java/net/vulkanmod/config/Platform.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/net/vulkanmod/config/Platform.java b/src/main/java/net/vulkanmod/config/Platform.java index 6d63eb68a1..38914708da 100644 --- a/src/main/java/net/vulkanmod/config/Platform.java +++ b/src/main/java/net/vulkanmod/config/Platform.java @@ -2,6 +2,7 @@ import org.apache.commons.lang3.SystemUtils; import org.lwjgl.glfw.GLFW; +import org.lwjgl.system.Configuration; import static net.vulkanmod.Initializer.LOGGER; import static org.lwjgl.glfw.GLFW.*; @@ -11,6 +12,9 @@ public abstract class Platform { private static final String activeDE = determineDE(); public static void init() { + // Increase stack size to 256 KB to prevent out of stack error on nvidia driver + Configuration.STACK_SIZE.set(256); + GLFW.glfwInitHint(GLFW_PLATFORM, activePlat); LOGGER.info("Selecting Platform: {}", getStringFromPlat(activePlat)); LOGGER.info("GLFW: {}", GLFW.glfwGetVersionString()); From 14ef9cd97c513dcf2997fcc7d5884049ca8d7d9a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 15 Nov 2025 00:04:51 +0100 Subject: [PATCH 102/177] Add method overwrite --- .../java/net/vulkanmod/mixin/compatibility/gl/GL11M.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index e004b0aa20..7793470bfc 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -100,6 +100,15 @@ public static void glClearColor(@NativeType("GLfloat") float red, @NativeType("G VRenderSystem.setClearColor(red, green, blue, alpha); } + /** + * @author + * @reason + */ + @Overwrite(remap = false) + public static void glClearDepth(@NativeType("GLdouble") double depth) { + VRenderSystem.clearDepth(depth); + } + /** * @author * @reason From 41e75fe4e9051af63daf08b6c4e7bd0f3baf05a7 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 18 Nov 2025 23:57:09 +0100 Subject: [PATCH 103/177] Port Fabric API implementation --- .../frapi/BatchingRenderCommandQueueM.java | 45 ++ .../render/frapi/BlockModelRendererM.java | 20 + .../render/frapi/BlockRenderManagerM.java | 42 ++ .../render/frapi/ItemFeatureRendererM.java | 43 ++ .../ItemRenderStateLayerRenderStateM.java | 46 ++ .../mixin/render/frapi/ItemRenderStateM.java | 38 ++ .../mixin/render/frapi/ItemRendererMixin.java | 39 -- .../render/frapi/LayerRenderStateMixin.java | 55 --- .../render/frapi/ModelBlockRendererM.java | 43 -- .../frapi/OrderedRenderCommandQueueImplM.java | 47 +++ .../OrderedRenderCommandQueueImplMixin.java | 41 -- .../mixin/render/frapi/QuadEmitterM.java | 11 - .../chunk/build/frapi/VulkanModRenderer.java | 8 +- .../AccessBatchingRenderCommandQueue.java | 5 +- .../accessor/AccessLayerRenderState.java | 5 +- .../accessor/AccessRenderCommandQueue.java | 2 +- .../build/frapi/mesh/ExtendedQuadEmitter.java | 18 - .../build/frapi/mesh/MutableQuadViewImpl.java | 2 +- .../build/frapi/render/ItemRenderContext.java | 392 ++++++++---------- .../build/frapi/render/MeshItemCommand.java | 12 + .../build/frapi/render/QuadToPosPipe.java | 26 ++ 21 files changed, 506 insertions(+), 434 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BatchingRenderCommandQueueM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BlockModelRendererM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderManagerM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemFeatureRendererM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateLayerRenderStateM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java create mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplM.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java delete mode 100644 src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java delete mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/MeshItemCommand.java create mode 100644 src/main/java/net/vulkanmod/render/chunk/build/frapi/render/QuadToPosPipe.java diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BatchingRenderCommandQueueM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BatchingRenderCommandQueueM.java new file mode 100644 index 0000000000..84906672af --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BatchingRenderCommandQueueM.java @@ -0,0 +1,45 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.SubmitNodeCollection; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessBatchingRenderCommandQueue; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessRenderCommandQueue; +import net.vulkanmod.render.chunk.build.frapi.render.MeshItemCommand; +import org.spongepowered.asm.mixin.Mixin; +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.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.ArrayList; +import java.util.List; + +@Mixin(SubmitNodeCollection.class) +abstract class BatchingRenderCommandQueueM implements OrderedSubmitNodeCollector, AccessRenderCommandQueue, AccessBatchingRenderCommandQueue { + @Shadow private boolean wasUsed; + + @Unique private final List meshItemCommands = new ArrayList<>(); + + @Inject(method = "clear()V", at = @At("RETURN")) + public void clear(CallbackInfo ci) { + meshItemCommands.clear(); + } + + @Override + public void submitItem(PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh) { + wasUsed = true; + meshItemCommands.add(new MeshItemCommand(matrices.last().copy(), displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType, mesh)); + } + + @Override + public List getMeshItemCommands() { + return meshItemCommands; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BlockModelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockModelRendererM.java new file mode 100644 index 0000000000..9816ac9033 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockModelRendererM.java @@ -0,0 +1,20 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.renderer.v1.render.FabricBlockModelRenderer; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.EmptyBlockAndTintGetter; +import net.minecraft.world.level.block.Blocks; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@Mixin(ModelBlockRenderer.class) +abstract class BlockModelRendererM { + @Overwrite + public static void renderModel(PoseStack.Pose entry, VertexConsumer vertexConsumer, BlockStateModel model, float red, float green, float blue, int light, int overlay) { + FabricBlockModelRenderer.render(entry, layer -> vertexConsumer, model, red, green, blue, light, overlay, EmptyBlockAndTintGetter.INSTANCE, BlockPos.ZERO, Blocks.AIR.defaultBlockState()); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderManagerM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderManagerM.java new file mode 100644 index 0000000000..cc100aa945 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/BlockRenderManagerM.java @@ -0,0 +1,42 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.fabricmc.fabric.api.renderer.v1.render.FabricBlockModelRenderer; +import net.fabricmc.fabric.api.renderer.v1.render.RenderLayerHelper; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.renderer.block.model.BlockStateModel; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.EmptyBlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +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; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(BlockRenderDispatcher.class) +abstract class BlockRenderManagerM { + + @Shadow + @Final + private ModelBlockRenderer modelRenderer; + + @Inject(method = "renderBreakingTexture", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/client/renderer/block/BlockModelShaper;getBlockModel(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/client/renderer/block/model/BlockStateModel;", shift = At.Shift.AFTER), cancellable = true) + private void afterGetModel(BlockState blockState, BlockPos blockPos, BlockAndTintGetter world, PoseStack matrixStack, VertexConsumer vertexConsumer, CallbackInfo ci, @Local BlockStateModel model) { + modelRenderer.render(world, model, blockState, blockPos, matrixStack, layer -> vertexConsumer, true, blockState.getSeed(blockPos), OverlayTexture.NO_OVERLAY); + ci.cancel(); + } + + @Redirect(method = "renderSingleBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/block/ModelBlockRenderer;renderModel(Lcom/mojang/blaze3d/vertex/PoseStack$Pose;Lcom/mojang/blaze3d/vertex/VertexConsumer;Lnet/minecraft/client/renderer/block/model/BlockStateModel;FFFII)V")) + private void renderProxy(PoseStack.Pose entry, VertexConsumer vertexConsumer, BlockStateModel model, float red, float green, float blue, int light, int overlay, BlockState state, PoseStack matrices, MultiBufferSource vertexConsumers, int light1, int overlay1) { + FabricBlockModelRenderer.render(entry, RenderLayerHelper.entityDelegate(vertexConsumers), model, red, green, blue, light, overlay, EmptyBlockAndTintGetter.INSTANCE, BlockPos.ZERO, state); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemFeatureRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemFeatureRendererM.java new file mode 100644 index 0000000000..778b5c308f --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemFeatureRendererM.java @@ -0,0 +1,43 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.OutlineBufferSource; +import net.minecraft.client.renderer.SubmitNodeCollection; +import net.minecraft.client.renderer.feature.ItemFeatureRenderer; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessBatchingRenderCommandQueue; +import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; +import net.vulkanmod.render.chunk.build.frapi.render.MeshItemCommand; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +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.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ItemFeatureRenderer.class) +public class ItemFeatureRendererM { + + @Shadow @Final private PoseStack poseStack; + + @Unique private final ItemRenderContext itemRenderContext = new ItemRenderContext(); + + @Inject(method = "render", at = @At("RETURN")) + private void onReturnRender(SubmitNodeCollection queue, MultiBufferSource.BufferSource vertexConsumers, OutlineBufferSource outlineVertexConsumers, CallbackInfo ci) { + for (MeshItemCommand itemCommand : ((AccessBatchingRenderCommandQueue) queue).getMeshItemCommands()) { + poseStack.pushPose(); + poseStack.last().set(itemCommand.positionMatrix()); + + itemRenderContext.renderModel(itemCommand.displayContext(), poseStack, vertexConsumers, itemCommand.lightCoords(), itemCommand.overlayCoords(), itemCommand.tintLayers(), itemCommand.quads(), itemCommand.mesh(), itemCommand.renderLayer(), itemCommand.glintType(), false); + + if (itemCommand.outlineColor() != 0) { + outlineVertexConsumers.setColor(itemCommand.outlineColor()); + itemRenderContext.renderModel(itemCommand.displayContext(), poseStack, outlineVertexConsumers, itemCommand.lightCoords(), itemCommand.overlayCoords(), itemCommand.tintLayers(), itemCommand.quads(), itemCommand.mesh(), itemCommand.renderLayer(), ItemStackRenderState.FoilType.NONE, true); + } + + poseStack.popPose(); + } + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateLayerRenderStateM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateLayerRenderStateM.java new file mode 100644 index 0000000000..7c61babc22 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateLayerRenderStateM.java @@ -0,0 +1,46 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.fabricmc.fabric.api.renderer.v1.render.FabricLayerRenderState; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessLayerRenderState; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessRenderCommandQueue; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +@Mixin(value = ItemStackRenderState.LayerRenderState.class) +abstract class ItemRenderStateLayerRenderStateM implements FabricLayerRenderState, AccessLayerRenderState { + @Unique + private final MutableMeshImpl mutableMesh = new MutableMeshImpl(); + + @Inject(method = "clear()V", at = @At("RETURN")) + private void onReturnClear(CallbackInfo ci) { + mutableMesh.clear(); + } + + @Redirect(method = "submit", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/SubmitNodeCollector;submitItem(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/world/item/ItemDisplayContext;III[ILjava/util/List;Lnet/minecraft/client/renderer/RenderType;Lnet/minecraft/client/renderer/item/ItemStackRenderState$FoilType;)V")) + private void submitItemProxy(SubmitNodeCollector commandQueue, PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColor, int[] tints, List quads, RenderType layer, ItemStackRenderState.FoilType glint) { + if (mutableMesh.size() > 0 && commandQueue instanceof AccessRenderCommandQueue access) { + // We don't have to copy the mesh here because vanilla doesn't copy the tint array or quad list either. + access.submitItem(matrices, displayContext, light, overlay, outlineColor, tints, quads, layer, glint, mutableMesh); + } else { + commandQueue.submitItem(matrices, displayContext, light, overlay, outlineColor, tints, quads, layer, glint); + } + } + + @Override + public MutableMeshImpl getMutableMesh() { + return mutableMesh; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateM.java new file mode 100644 index 0000000000..7f6b1584fc --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRenderStateM.java @@ -0,0 +1,38 @@ +package net.vulkanmod.mixin.render.frapi; + +import com.llamalad7.mixinextras.sugar.Local; +import com.llamalad7.mixinextras.sugar.Share; +import com.llamalad7.mixinextras.sugar.ref.LocalRef; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessLayerRenderState; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; +import net.vulkanmod.render.chunk.build.frapi.render.QuadToPosPipe; +import org.joml.Matrix4f; +import org.joml.Vector3f; +import org.joml.Vector3fc; +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 java.util.function.Consumer; + +@Mixin(ItemStackRenderState.class) +abstract class ItemRenderStateM { + @Inject(method = "visitExtents", at = @At(value = "NEW", target = "()Lcom/mojang/blaze3d/vertex/PoseStack$Pose;")) + private void afterInitVecLoad(Consumer posConsumer, CallbackInfo ci, @Local Vector3f vec, @Share("pipe") LocalRef pipeRef) { + pipeRef.set(new QuadToPosPipe(posConsumer, vec)); + } + + @Inject(method = "visitExtents", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack$Pose;setIdentity()V", shift = At.Shift.BEFORE)) + private void afterLayerLoad(Consumer posConsumer, CallbackInfo ci, @Local(ordinal = 0) Vector3f vec, @Local ItemStackRenderState.LayerRenderState layer, @Local Matrix4f matrix, @Share("pipe") LocalRef pipeRef) { + MutableMeshImpl mutableMesh = ((AccessLayerRenderState) layer).getMutableMesh(); + + if (mutableMesh.size() > 0) { + QuadToPosPipe pipe = pipeRef.get(); + pipe.matrix = matrix; + // Use the mutable version here as it does not use a ThreadLocal or cursor stack + mutableMesh.forEachMutable(pipe); + } + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java deleted file mode 100644 index f3f9278b87..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import org.spongepowered.asm.mixin.Mixin; - -import net.minecraft.client.renderer.entity.ItemRenderer; - -@Mixin(ItemRenderer.class) -abstract class ItemRendererMixin { -// @Unique -// private static final ThreadLocal CONTEXTS = ThreadLocal.withInitial(ItemRenderContext::new); - - // TODO: frapi -// @Inject(method = "renderItem", at = @At(value = "HEAD"), cancellable = true) -// private static void hookRenderItem(ItemDisplayContext itemDisplayContext, PoseStack poseStack, -// MultiBufferSource multiBufferSource, int i, int j, int[] is, -// List list, RenderType renderType, -// ItemStackRenderState.FoilType foilType, CallbackInfo ci) { -// if (!model.isVanillaAdapter()) { -// CONTEXTS.get().renderModel(itemDisplayContext, poseStack, multiBufferSource, i, j, is, model, renderType, foilType); -// ci.cancel(); -// } -// } -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java deleted file mode 100644 index c7515f2161..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/LayerRenderStateMixin.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import net.fabricmc.fabric.api.renderer.v1.render.FabricLayerRenderState; -import net.minecraft.client.renderer.item.ItemStackRenderState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(value = ItemStackRenderState.LayerRenderState.class) -abstract class LayerRenderStateMixin implements FabricLayerRenderState { -//abstract class LayerRenderStateMixin implements FabricLayerRenderState, AccessLayerRenderState { -// @Unique -// private final MutableMeshImpl mutableMesh = new MutableMeshImpl(); -// -// @Inject(method = "clear()V", at = @At("RETURN")) -// private void onReturnClear(CallbackInfo ci) { -// mutableMesh.clear(); -// } - - // TODO: frapi -// @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/ItemRenderer;renderItem(Lnet/minecraft/world/item/ItemDisplayContext;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;II[ILjava/util/List;Lnet/minecraft/client/renderer/RenderType;Lnet/minecraft/client/renderer/item/ItemStackRenderState$FoilType;)V")) -// private void renderItemProxy(net.minecraft.world.item.ItemDisplayContext itemDisplayContext, PoseStack poseStack, -// MultiBufferSource multiBufferSource, int i, int j, int[] is, -// List list, RenderType renderType, -// ItemStackRenderState.FoilType foilType) { -// if (mutableMesh.size() > 0) { -// ItemRenderContext.POOL.get().renderItem(displayContext, matrices, vertexConsumers, light, overlay, tints, quads, mutableMesh, layer, glint); -// } else { -// ItemRenderer.renderItem(displayContext, matrices, vertexConsumers, light, overlay, tints, quads, layer, glint); -// } -// } - -// @Override -// public MutableMeshImpl fabric_getMutableMesh() { -// return mutableMesh; -// } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java deleted file mode 100644 index d032bbf3a5..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import net.minecraft.client.renderer.block.ModelBlockRenderer; - -@Mixin(ModelBlockRenderer.class) -public abstract class ModelBlockRendererM { - - // TODO ThreadLocal look ups are slow, same goes for ItemRendererMixin - @Unique - private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(BlockRenderContext::new); - - // TODO: frapi -// @Inject(at = @At("HEAD"), method = "tesselateBlock", cancellable = true) -// private void hookRender(BlockAndTintGetter blockAndTintGetter, List list, BlockState blockState, -// BlockPos blockPos, PoseStack poseStack, VertexConsumer vertexConsumer, boolean bl, int i, -// CallbackInfo ci) { -// if (!model.isVanillaAdapter()) { -// BlockRenderContext context = fabric_contexts.get(); -// context.render(blockView, model, state, pos, matrix, buffer, cull, rand, seed, overlay); -// ci.cancel(); -// } -// } - -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplM.java new file mode 100644 index 0000000000..17a372de20 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplM.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.mixin.render.frapi; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; + +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.SubmitNodeStorage; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessRenderCommandQueue; +import org.spongepowered.asm.mixin.Mixin; + +import java.util.List; + +@Mixin(SubmitNodeStorage.class) +abstract class OrderedRenderCommandQueueImplM implements SubmitNodeCollector, AccessRenderCommandQueue { + @Override + public void submitItem(PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh) { + OrderedSubmitNodeCollector queue = order(0); + + if (queue instanceof AccessRenderCommandQueue access) { + access.submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType, mesh); + } else { + queue.submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType); + } + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java deleted file mode 100644 index f7187bf15e..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/OrderedRenderCommandQueueImplMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; -import net.fabricmc.fabric.impl.client.indigo.renderer.accessor.AccessRenderCommandQueue; - -import net.minecraft.client.renderer.SubmitNodeCollector; -import net.minecraft.client.renderer.SubmitNodeStorage; - -import org.spongepowered.asm.mixin.Mixin; - -import java.util.List; - -@Mixin(SubmitNodeStorage.class) -abstract class OrderedRenderCommandQueueImplMixin implements SubmitNodeCollector, AccessRenderCommandQueue { -// @Override -// public void fabric_submitItem(MatrixStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderLayer renderLayer, ItemRenderState.Glint glintType, MeshView mesh) { -// RenderCommandQueue queue = getBatchingQueue(0); -// -// if (queue instanceof AccessRenderCommandQueue access) { -// access.fabric_submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType, mesh); -// } else { -// queue.submitItem(matrices, displayContext, light, overlay, outlineColors, tintLayers, quads, renderLayer, glintType); -// } -// } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java deleted file mode 100644 index 8e8119d760..0000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/QuadEmitterM.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.vulkanmod.mixin.render.frapi; - -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.vulkanmod.render.chunk.build.frapi.mesh.ExtendedQuadEmitter; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(QuadEmitter.class) -public interface QuadEmitterM extends ExtendedQuadEmitter { - -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java index 49e49c502a..eea26fc79e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java @@ -20,13 +20,13 @@ import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.vulkanmod.mixin.render.frapi.BlockRenderDispatcherAccessor; +import net.vulkanmod.render.chunk.build.frapi.accessor.AccessLayerRenderState; import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; import net.vulkanmod.render.chunk.build.frapi.render.SimpleBlockRenderContext; /** - * The Fabric default renderer implementation. Supports all - * features defined in the API except shaders and offers no special materials. + * Fabric renderer implementation. */ public class VulkanModRenderer implements Renderer { public static final VulkanModRenderer INSTANCE = new VulkanModRenderer(); @@ -71,8 +71,6 @@ public void renderBlockAsEntity(BlockRenderDispatcher blockRenderDispatcher, Blo @Override public QuadEmitter getLayerRenderStateEmitter(ItemStackRenderState.LayerRenderState layer) { - // TODO -// return ((AccessLayerRenderState) layer).fabric_getMutableMesh().emitter(); - return null; + return ((AccessLayerRenderState) layer).getMutableMesh().emitter(); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java index 3bca8c85d2..aa1b3f9927 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessBatchingRenderCommandQueue.java @@ -1,9 +1,10 @@ package net.vulkanmod.render.chunk.build.frapi.accessor; -import net.fabricmc.fabric.impl.client.indigo.renderer.render.MeshItemCommand; + +import net.vulkanmod.render.chunk.build.frapi.render.MeshItemCommand; import java.util.List; public interface AccessBatchingRenderCommandQueue { - List fabric_getMeshItemCommands(); + List getMeshItemCommands(); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java index 4b76f13cc0..f2d56f756a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessLayerRenderState.java @@ -16,8 +16,9 @@ package net.vulkanmod.render.chunk.build.frapi.accessor; -import net.fabricmc.fabric.impl.client.indigo.renderer.mesh.MutableMeshImpl; + +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableMeshImpl; public interface AccessLayerRenderState { - MutableMeshImpl fabric_getMutableMesh(); + MutableMeshImpl getMutableMesh(); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java index 0b285ca5f6..5d958f0880 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/accessor/AccessRenderCommandQueue.java @@ -11,5 +11,5 @@ import java.util.List; public interface AccessRenderCommandQueue { - void fabric_submitItem(PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh); + void submitItem(PoseStack matrices, ItemDisplayContext displayContext, int light, int overlay, int outlineColors, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java deleted file mode 100644 index 6a2dd65381..0000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/ExtendedQuadEmitter.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; - -public interface ExtendedQuadEmitter { - - static ExtendedQuadEmitter of(QuadEmitter quadEmitter) { - return (ExtendedQuadEmitter) quadEmitter; - } - -// default void emitBlockQuads(QuadEmitter emitter, BakedModel model, BlockState state, Supplier randomSupplier, Predicate<@Nullable Direction> cullTest) { -// VanillaModelEncoder.emitBlockQuads(emitter, model, state, randomSupplier, cullTest); -// } -// -// default void emitItemQuads(QuadEmitter emitter,BakedModel model, BlockState state, Supplier randomSupplier) { -// VanillaModelEncoder.emitItemQuads(emitter, model, state, randomSupplier); -// } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java index 43e6c47ae3..215db63984 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java @@ -48,7 +48,7 @@ * render - the editor is serving mainly as a way to access vertex data without magical * numbers. It also allows for a consistent interface for those transformations. */ -public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter, ExtendedQuadEmitter { +public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter { private static final QuadTransform NO_TRANSFORM = q -> true; private static final int[] DEFAULT_QUAD_DATA = new int[EncodingFormat.TOTAL_STRIDE]; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java index e206865104..3448ad0a96 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java @@ -1,216 +1,176 @@ -// TODO -///* -// * Copyright (c) 2016, 2017, 2018, 2019 FabricMC -// * -// * Licensed under the Apache License, Version 2.0 (the "License"); -// * you may not use this file except in compliance with the License. -// * You may obtain a copy of the License at -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// */ -// -//package net.vulkanmod.render.chunk.build.frapi.render; -// -//import com.mojang.blaze3d.vertex.PoseStack; -//import com.mojang.blaze3d.vertex.VertexConsumer; -//import com.mojang.math.MatrixUtil; -// -//import java.util.Arrays; -//import java.util.function.Supplier; -// -//import net.fabricmc.fabric.api.renderer.v1.material.GlintMode; -//import net.minecraft.client.renderer.item.ItemStackRenderState; -//import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; -//import net.minecraft.client.renderer.LightTexture; -//import net.minecraft.client.renderer.MultiBufferSource; -//import net.minecraft.client.renderer.RenderType; -//import net.minecraft.client.renderer.Sheets; -//import net.minecraft.client.renderer.entity.ItemRenderer; -//import net.minecraft.util.RandomSource; -//import net.minecraft.world.item.ItemDisplayContext; -//import net.minecraft.world.level.block.state.BlockState; -//import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -//import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -//import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -//import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -//import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; -//import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -// -//import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; -// -///** -// * The render context used for item rendering. -// */ -//@SuppressWarnings("removal") -//public class ItemRenderContext extends AbstractRenderContext { -// /** Value vanilla uses for item rendering. The only sensible choice, of course. */ -// private static final long ITEM_RANDOM_SEED = 42L; -// private static final int GLINT_COUNT = ItemStackRenderState.FoilType.values().length; -// -// private final RandomSource random = RandomSource.create(); -// private final Supplier randomSupplier = () -> { -// random.setSeed(ITEM_RANDOM_SEED); -// return random; -// }; -// -// private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { -// { -// data = new int[EncodingFormat.TOTAL_STRIDE]; -// clear(); -// } -// -// @Override -// public void emitDirectly() { -// bufferQuad(this); -// } -// -// @Override -// public void emitItemQuads(QuadEmitter emitter, BakedModel model, BlockState state, -// Supplier randomSupplier) { -// super.emitItemQuads(emitter, model, state, randomSupplier); -// } -// }; -// -// private ItemDisplayContext transformMode; -// private PoseStack matrixStack; -// private MultiBufferSource vertexConsumerProvider; -// private int lightmap; -// private int[] tints; -// -// private RenderType defaultLayer; -// private ItemStackRenderState.FoilType defaultGlint; -// -// private PoseStack.Pose specialGlintEntry; -// private final VertexConsumer[] vertexConsumerCache = new VertexConsumer[3 * GLINT_COUNT]; -// -// public ItemRenderContext() { -// } -// -// public QuadEmitter getEmitter() { -// editorQuad.clear(); -// return editorQuad; -// } -// -// public void renderModel(ItemDisplayContext transformMode, PoseStack matrixStack, MultiBufferSource bufferSource, int lightmap, int overlay, int[] tints, BakedModel model, RenderType renderType, ItemStackRenderState.FoilType foilType) { -// this.transformMode = transformMode; -// this.matrixStack = matrixStack; -// this.vertexConsumerProvider = bufferSource; -// this.lightmap = lightmap; -// this.overlay = overlay; -// this.tints = tints; -// -// defaultLayer = renderType; -// defaultGlint = foilType; -// -// matrix = matrixStack.last().pose(); -// normalMatrix = matrixStack.last().normal(); -// -// model.emitItemQuads(getEmitter(), randomSupplier); -// -// this.matrixStack = null; -// this.vertexConsumerProvider = null; -// this.tints = null; -// -// specialGlintEntry = null; -// Arrays.fill(vertexConsumerCache, null); -// } -// -// @Override -// protected void bufferQuad(MutableQuadViewImpl quad) { -// final RenderMaterial mat = quad.material(); -// final boolean emissive = mat.emissive(); -// final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glintMode()); -// -// tintQuad(quad); -// shadeQuad(quad, emissive); -// bufferQuad(quad, vertexConsumer); -// } -// -// private void tintQuad(MutableQuadViewImpl quad) { -// int tintIndex = quad.tintIndex(); -// -// if (tintIndex != -1 && tintIndex < tints.length) { -// final int tint = tints[tintIndex]; -// -// for (int i = 0; i < 4; i++) { -// quad.color(i, ColorHelper.multiplyColor(tint, quad.color(i))); -// } -// } -// } -// -// private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { -// if (emissive) { -// for (int i = 0; i < 4; i++) { -// quad.lightmap(i, LightTexture.FULL_BRIGHT); -// } -// } else { -// final int lightmap = this.lightmap; -// -// for (int i = 0; i < 4; i++) { -// quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); -// } -// } -// } -// -// private VertexConsumer getVertexConsumer(BlendMode blendMode, GlintMode glintMode) { -// RenderType layer; -// ItemStackRenderState.FoilType glint; -// -// if (blendMode == BlendMode.DEFAULT) { -// layer = defaultLayer; -// } else { -// layer = blendMode == BlendMode.TRANSLUCENT ? Sheets.translucentItemSheet() : Sheets.cutoutBlockSheet(); -// } -// -// if (glintMode == GlintMode.DEFAULT) { -// glint = defaultGlint; -// } else { -// glint = glintMode.glint; -// } -// -// int cacheIndex; -// -// if (layer == Sheets.translucentItemSheet()) { -// cacheIndex = 0; -// } else if (layer == Sheets.cutoutBlockSheet()) { -// cacheIndex = GLINT_COUNT; -// } else { -// cacheIndex = 2 * GLINT_COUNT; -// } -// -// cacheIndex += glint.ordinal(); -// VertexConsumer vertexConsumer = vertexConsumerCache[cacheIndex]; -// -// if (vertexConsumer == null) { -// vertexConsumer = createVertexConsumer(layer, glint); -// vertexConsumerCache[cacheIndex] = vertexConsumer; -// } -// -// return vertexConsumer; -// } -// -// private VertexConsumer createVertexConsumer(RenderType layer, ItemStackRenderState.FoilType glint) { -// if (glint == ItemStackRenderState.FoilType.SPECIAL) { -// if (specialGlintEntry == null) { -// specialGlintEntry = matrixStack.last().copy(); -// -// if (transformMode == ItemDisplayContext.GUI) { -// MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.5F); -// } else if (transformMode.firstPerson()) { -// MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.75F); -// } -// } -// -// return ItemRendererAccessor.getCompassFoilBuffer(vertexConsumerProvider, layer, specialGlintEntry); -// } -// -// return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint != ItemStackRenderState.FoilType.NONE); -// } -// -//} +package net.vulkanmod.render.chunk.build.frapi.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.MatrixUtil; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; + +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; +import net.fabricmc.fabric.api.renderer.v1.render.FabricLayerRenderState; +import net.fabricmc.fabric.api.renderer.v1.render.RenderLayerHelper; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.entity.ItemRenderer; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemDisplayContext; +import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; +import org.jetbrains.annotations.Nullable; + + +/** + * Used during item buffering to support geometry added through {@link FabricLayerRenderState#emitter()}. + */ +public class ItemRenderContext extends AbstractRenderContext { + private static final int GLINT_COUNT = ItemStackRenderState.FoilType.values().length; + + private ItemDisplayContext itemDisplayContext; + private PoseStack matrixStack; + private MultiBufferSource vertexConsumerProvider; + private int lightmap; + private int[] tints; + + private RenderType defaultLayer; + private ItemStackRenderState.FoilType defaultGlint; + private boolean ignoreQuadGlint; + + private PoseStack.Pose specialGlintEntry; + private final VertexConsumer[] vertexConsumerCache = new VertexConsumer[3 * GLINT_COUNT]; + + public void renderModel(ItemDisplayContext itemDisplayContext, PoseStack matrixStack, MultiBufferSource bufferSource, int lightmap, int overlay, int[] tints, List modelQuads, MeshView mesh, RenderType renderType, ItemStackRenderState.FoilType foilType, boolean ignoreQuadGlint) { + this.itemDisplayContext = itemDisplayContext; + this.matrixStack = matrixStack; + this.vertexConsumerProvider = bufferSource; + this.lightmap = lightmap; + this.overlay = overlay; + this.tints = tints; + + defaultLayer = renderType; + defaultGlint = foilType; + this.ignoreQuadGlint = ignoreQuadGlint; + + bufferQuads(modelQuads, mesh); + + this.matrixStack = null; + this.vertexConsumerProvider = null; + this.tints = null; + + specialGlintEntry = null; + Arrays.fill(vertexConsumerCache, null); + } + + private void bufferQuads(List vanillaQuads, MeshView mesh) { + QuadEmitter emitter = getEmitter(); + + final int vanillaQuadCount = vanillaQuads.size(); + + for (int i = 0; i < vanillaQuadCount; i++) { + final BakedQuad q = vanillaQuads.get(i); + emitter.fromBakedQuad(q); + emitter.emit(); + } + + mesh.outputTo(emitter); + } + + @Override + protected void bufferQuad(MutableQuadViewImpl quad) { + final VertexConsumer vertexConsumer = getVertexConsumer(quad.renderLayer(), quad.glint()); + + tintQuad(quad); + shadeQuad(quad, quad.emissive()); + bufferQuad(quad, vertexConsumer); + } + + private void tintQuad(MutableQuadViewImpl quad) { + int tintIndex = quad.tintIndex(); + + if (tintIndex != -1 && tintIndex < tints.length) { + final int tint = tints[tintIndex]; + + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyColor(tint, quad.color(i))); + } + } + } + + private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { + if (emissive) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, LightTexture.FULL_BRIGHT); + } + } else { + final int lightmap = this.lightmap; + + for (int i = 0; i < 4; i++) { + quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); + } + } + } + + private VertexConsumer getVertexConsumer(@Nullable ChunkSectionLayer quadRenderLayer, @Nullable ItemStackRenderState.FoilType quadGlint) { + RenderType layer; + ItemStackRenderState.FoilType glint; + + if (quadRenderLayer == null) { + layer = defaultLayer; + } else { + layer = RenderLayerHelper.getEntityBlockLayer(quadRenderLayer); + } + + if (ignoreQuadGlint || quadGlint == null) { + glint = defaultGlint; + } else { + glint = quadGlint; + } + + int cacheIndex; + + if (layer == Sheets.translucentItemSheet()) { + cacheIndex = 0; + } else if (layer == Sheets.cutoutBlockSheet()) { + cacheIndex = GLINT_COUNT; + } else { + cacheIndex = 2 * GLINT_COUNT; + } + + cacheIndex += glint.ordinal(); + VertexConsumer vertexConsumer = vertexConsumerCache[cacheIndex]; + + if (vertexConsumer == null) { + vertexConsumer = createVertexConsumer(layer, glint); + vertexConsumerCache[cacheIndex] = vertexConsumer; + } + + return vertexConsumer; + } + + private VertexConsumer createVertexConsumer(RenderType layer, ItemStackRenderState.FoilType glint) { + if (glint == ItemStackRenderState.FoilType.SPECIAL) { + if (specialGlintEntry == null) { + specialGlintEntry = matrixStack.last().copy(); + + if (itemDisplayContext == ItemDisplayContext.GUI) { + MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.5F); + } else if (itemDisplayContext.firstPerson()) { + MatrixUtil.mulComponentWise(specialGlintEntry.pose(), 0.75F); + } + } + + return ItemRendererAccessor.getSpecialFoilBuffer(vertexConsumerProvider, layer, specialGlintEntry); + } + + return ItemRenderer.getFoilBuffer(vertexConsumerProvider, layer, true, glint != ItemStackRenderState.FoilType.NONE); + } + +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/MeshItemCommand.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/MeshItemCommand.java new file mode 100644 index 0000000000..52acc30b1a --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/MeshItemCommand.java @@ -0,0 +1,12 @@ +package net.vulkanmod.render.chunk.build.frapi.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import java.util.List; +import net.fabricmc.fabric.api.renderer.v1.mesh.MeshView; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.world.item.ItemDisplayContext; + +public record MeshItemCommand(PoseStack.Pose positionMatrix, ItemDisplayContext displayContext, int lightCoords, int overlayCoords, int outlineColor, int[] tintLayers, List quads, RenderType renderLayer, ItemStackRenderState.FoilType glintType, MeshView mesh) { +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/QuadToPosPipe.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/QuadToPosPipe.java new file mode 100644 index 0000000000..151d073c81 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/QuadToPosPipe.java @@ -0,0 +1,26 @@ +package net.vulkanmod.render.chunk.build.frapi.render; + +import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; +import org.joml.Matrix4fc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +import java.util.function.Consumer; + +public class QuadToPosPipe implements Consumer { + private final Consumer posConsumer; + private final Vector3f vec; + public Matrix4fc matrix; + + public QuadToPosPipe(Consumer posConsumer, Vector3f vec) { + this.posConsumer = posConsumer; + this.vec = vec; + } + + @Override + public void accept(QuadView quad) { + for (int i = 0; i < 4; i++) { + posConsumer.accept(quad.copyPos(i, vec).mulPosition(matrix)); + } + } +} From 0535bd26616d81316c559740d24da8c41211fc4d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 23 Nov 2025 16:02:55 +0100 Subject: [PATCH 104/177] Fix polygon offset inverted parameters --- src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 8006d35f61..3f17f536eb 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -235,7 +235,7 @@ public static void _disablePolygonOffset() { @Overwrite(remap = false) public static void _polygonOffset(float f, float g) { RenderSystem.assertOnRenderThread(); - VRenderSystem.polygonOffset(g, f); + VRenderSystem.polygonOffset(f, g); } /** From ca1c5056fca9ec53f609084a5f7c58b3ee619df2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 23 Nov 2025 16:09:01 +0100 Subject: [PATCH 105/177] Mitigate uniform upload sync hazard --- .../render/engine/VkCommandEncoder.java | 40 ++++++++++++------ .../java/net/vulkanmod/vulkan/Renderer.java | 41 +++++++++++++++++++ .../vulkanmod/vulkan/memory/MemoryTypes.java | 5 ++- .../vulkanmod/vulkan/queue/CommandPool.java | 6 +++ 4 files changed, 79 insertions(+), 13 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index 89f84c42f4..4913562374 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -21,14 +21,13 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Synchronization; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.Framebuffer; -import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; +import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.queue.GraphicsQueue; -import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.converter.Sampler; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.texture.ImageUtil; @@ -37,9 +36,7 @@ import org.lwjgl.opengl.*; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; -import org.lwjgl.vulkan.KHRDynamicRendering; -import org.lwjgl.vulkan.VK11; -import org.lwjgl.vulkan.VkCommandBuffer; +import org.lwjgl.vulkan.*; import org.slf4j.Logger; import java.nio.ByteBuffer; @@ -48,8 +45,7 @@ import java.util.function.Supplier; import static org.lwjgl.system.MemoryStack.stackPush; -import static org.lwjgl.vulkan.VK10.VK_INDEX_TYPE_UINT16; -import static org.lwjgl.vulkan.VK10.VK_INDEX_TYPE_UINT32; +import static org.lwjgl.vulkan.VK10.*; public class VkCommandEncoder implements CommandEncoder { private static final Logger LOGGER = LogUtils.getLogger(); @@ -260,13 +256,33 @@ public void writeToBuffer(GpuBufferSlice gpuBufferSlice, ByteBuffer byteBuffer) throw new IllegalStateException("Buffer already closed"); } else { - int remaining = byteBuffer.remaining(); - if (remaining + gpuBufferSlice.offset() > vkGpuBuffer.size()) { + int size = byteBuffer.remaining(); + if (size + gpuBufferSlice.offset() > vkGpuBuffer.size()) { throw new IllegalArgumentException( - "Cannot write more data than this buffer can hold (attempting to write " + remaining + " bytes at offset " + gpuBufferSlice.offset() + " to " + gpuBufferSlice.length() + " slice size)" + "Cannot write more data than this buffer can hold (attempting to write " + size + " bytes at offset " + gpuBufferSlice.offset() + " to " + gpuBufferSlice.length() + " slice size)" ); } else { - vkGpuBuffer.buffer.copyBuffer(byteBuffer, byteBuffer.remaining(), gpuBufferSlice.offset()); + int dstOffset = gpuBufferSlice.offset(); + + var commandBuffer = Renderer.getInstance().getTransferCb(); + + StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); + stagingBuffer.copyBuffer(size, byteBuffer); + + long srcOffset = stagingBuffer.getOffset(); + + try (MemoryStack stack = MemoryStack.stackPush()) { + if (!commandBuffer.isRecording()) { + commandBuffer.begin(stack); + } + + VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); + copyRegion.size(size); + copyRegion.srcOffset(srcOffset); + copyRegion.dstOffset(dstOffset); + + vkCmdCopyBuffer(commandBuffer.handle, stagingBuffer.getId(), vkGpuBuffer.buffer.getId(), copyRegion); + } } } } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index b943942367..f5e4c4abb0 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -19,6 +19,7 @@ import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.pass.DefaultMainPass; import net.vulkanmod.vulkan.pass.MainPass; +import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.PipelineState; @@ -89,6 +90,7 @@ public static int getCurrentImage() { private ArrayList imageAvailableSemaphores; private ArrayList renderFinishedSemaphores; private ArrayList inFlightFences; + private List transferCbs; private Framebuffer boundFramebuffer; private RenderPass boundRenderPass; @@ -158,6 +160,19 @@ private void allocateCommandBuffers() { commandBuffers.add(new VkCommandBuffer(pCommandBuffers.get(i), device)); } } + + if (transferCbs != null) { + transferCbs.forEach(commandBuffer -> { + vkResetCommandBuffer(commandBuffer.handle, 0); + commandBuffer.reset(); + }); + } + + transferCbs = new ArrayList<>(framesNum); + + for (int i = 0; i < framesNum; i++) { + transferCbs.add(DeviceManager.getTransferQueue().getCommandPool().getCommandBuffer()); + } } private void createSyncObjects() { @@ -302,6 +317,7 @@ public void endFrame() { mainPass.end(currentCmdBuffer); + submitUploads(); waitFences(); submitFrame(); @@ -377,6 +393,7 @@ public void flushCmds() { vkResetFences(device, inFlightFences.get(currentFrame)); + submitUploads(); waitFences(); if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { @@ -390,6 +407,25 @@ public void flushCmds() { } } + public void submitUploads() { + var transferCb = transferCbs.get(currentFrame); + + if (transferCb.isRecording()) { + + try (MemoryStack stack = MemoryStack.stackPush()) { + transferCb.submitCommands(stack, + DeviceManager.getTransferQueue().queue(), + false); + } + + Synchronization.INSTANCE.addCommandBuffer(transferCb); + + transferCbs.set(currentFrame, DeviceManager.getTransferQueue() + .getCommandPool() + .getCommandBuffer()); + } + } + public void endRenderPass() { endRenderPass(currentCmdBuffer); } @@ -465,6 +501,7 @@ void waitForSwapChain() { @SuppressWarnings("UnreachableCode") private void recreateSwapChain() { + submitUploads(); waitFences(); Vulkan.waitIdle(); @@ -593,6 +630,10 @@ public SwapChain getSwapChain() { return swapChain; } + public CommandPool.CommandBuffer getTransferCb() { + return transferCbs.get(currentFrame); + } + private static void resetDynamicState(VkCommandBuffer commandBuffer) { vkCmdSetDepthBias(commandBuffer, 0.0F, 0.0F, 0.0F); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 9becd6202d..3db5c790db 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -106,7 +106,10 @@ static abstract class MappableMemory extends MemoryType { @Override public void copyToBuffer(Buffer buffer, ByteBuffer src, long size, long srcOffset, long dstOffset) { - VUtil.memcpy(src, buffer, size, srcOffset, dstOffset); + StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); + stagingBuffer.copyBuffer((int) size, src); + + DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.getId(), stagingBuffer.getOffset(), buffer.getId(), dstOffset, size); } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java index d6de2982e8..8500e8da47 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java @@ -41,6 +41,12 @@ public void createCommandPool(int queueFamily) { } } + public CommandBuffer getCommandBuffer() { + try (MemoryStack stack = stackPush()) { + return getCommandBuffer(stack); + } + } + public CommandBuffer getCommandBuffer(MemoryStack stack) { if (availableCmdBuffers.isEmpty()) { allocateCommandBuffers(stack); From b6fe3aee1cd25641d8be04f8b0b4b910ce933d8a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 23 Nov 2025 16:09:48 +0100 Subject: [PATCH 106/177] Add "disable animations" option --- src/main/java/net/vulkanmod/config/Config.java | 1 + .../java/net/vulkanmod/config/option/Options.java | 13 +++++++++---- .../mixin/texture/update/MTextureManager.java | 3 ++- src/main/resources/assets/vulkanmod/lang/en_us.json | 4 +++- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index 05b4e7c622..e2bebdb7f5 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -28,6 +28,7 @@ public class Config { public int builderThreads = 0; public boolean backFaceCulling = true; + public boolean textureAnimations = true; public void write() { diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index 702b3b754a..560e6d2c93 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -310,6 +310,13 @@ public static OptionBlock[] getOtherOpts() { Renderer.scheduleSwapChainUpdate(); }, () -> config.frameQueueSize) .setTooltip(Component.translatable("vulkanmod.options.frameQueue.tooltip")), + new SwitchOption(Component.translatable("vulkanmod.options.textureAnimations"), + value -> { + config.textureAnimations = value; + }, + () -> config.textureAnimations), + }), + new OptionBlock("", new Option[]{ new CyclingOption<>(Component.translatable("vulkanmod.options.deviceSelector"), IntStream.range(-1, DeviceManager.suitableDevices.size()).boxed() .toArray(Integer[]::new), @@ -321,10 +328,8 @@ public static OptionBlock[] getOtherOpts() { value).deviceName) ) .setTooltip(Component.nullToEmpty("%s: %s".formatted( - Component.translatable("vulkanmod.options.deviceSelector.tooltip").getString(), - DeviceManager.device.deviceName - )) - ) + Component.translatable("vulkanmod.options.deviceSelector.tooltip").getString(), + DeviceManager.device.deviceName))) }) }; diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java index 551f797eea..595ca054c0 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java @@ -2,6 +2,7 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.Tickable; +import net.vulkanmod.Initializer; import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Final; @@ -21,7 +22,7 @@ public abstract class MTextureManager { */ @Overwrite public void tick() { - if (Renderer.skipRendering) + if (Renderer.skipRendering || !Initializer.CONFIG.textureAnimations) return; //Debug D diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 6947a8a905..09be191c71 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -44,5 +44,7 @@ "vulkanmod.options.windowMode.windowedFullscreen": "Windowed Fullscreen", "vulkanmod.options.builderThreads": "Chunk Builder Threads", - "vulkanmod.options.builderThreads.auto": "Auto" + "vulkanmod.options.builderThreads.auto": "Auto", + + "vulkanmod.options.textureAnimations": "Texture Animations" } \ No newline at end of file From 2992891a5bbc6e5f4821c2ac66d7074b5d8ae058 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 24 Nov 2025 16:02:33 +0100 Subject: [PATCH 107/177] Fix uniform upload bug when loading new dimension --- .../java/net/vulkanmod/vulkan/Renderer.java | 22 +++++++++---------- .../net/vulkanmod/vulkan/queue/Queue.java | 12 +++++----- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index f5e4c4abb0..5e5a30f754 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -220,6 +220,7 @@ public void preInitFrame() { // runTick might be called recursively, // this check forces sync to avoid upload corruption if (lastReset == currentFrame) { + submitUploads(); waitFences(); } lastReset = currentFrame; @@ -345,7 +346,7 @@ private void submitFrame() { vkResetFences(device, inFlightFences.get(currentFrame)); - if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { + if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().vkQueue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult))); } @@ -360,7 +361,7 @@ private void submitFrame() { presentInfo.pImageIndices(stack.ints(imageIndex)); - vkResult = vkQueuePresentKHR(DeviceManager.getPresentQueue().queue(), presentInfo); + vkResult = vkQueuePresentKHR(DeviceManager.getPresentQueue().vkQueue(), presentInfo); if (vkResult == VK_ERROR_OUT_OF_DATE_KHR || vkResult == VK_SUBOPTIMAL_KHR || swapChainUpdate) { swapChainUpdate = true; @@ -396,7 +397,7 @@ public void flushCmds() { submitUploads(); waitFences(); - if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { + if ((vkResult = vkQueueSubmit(DeviceManager.getGraphicsQueue().vkQueue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, inFlightFences.get(currentFrame)); throw new RuntimeException("Failed to submit draw command buffer: %s".formatted(VkResult.decode(vkResult))); } @@ -411,19 +412,17 @@ public void submitUploads() { var transferCb = transferCbs.get(currentFrame); if (transferCb.isRecording()) { - + final var transferQueue = DeviceManager.getTransferQueue(); try (MemoryStack stack = MemoryStack.stackPush()) { - transferCb.submitCommands(stack, - DeviceManager.getTransferQueue().queue(), - false); + transferCb.submitCommands(stack, transferQueue.vkQueue(), false); } Synchronization.INSTANCE.addCommandBuffer(transferCb); - transferCbs.set(currentFrame, DeviceManager.getTransferQueue() - .getCommandPool() - .getCommandBuffer()); + transferCbs.set(currentFrame, transferQueue.getCommandPool().getCommandBuffer()); } + + ImageUploadHelper.INSTANCE.submitCommands(); } public void endRenderPass() { @@ -468,7 +467,6 @@ public void removeUsedPipeline(Pipeline pipeline) { private void waitFences() { // Make sure there are no uploads/transitions scheduled - ImageUploadHelper.INSTANCE.submitCommands(); Synchronization.INSTANCE.waitFences(); Vulkan.getStagingBuffer().reset(); } @@ -494,7 +492,7 @@ void waitForSwapChain() { .pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))) .pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); - vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), info, inFlightFences.get(currentFrame)); + vkQueueSubmit(DeviceManager.getGraphicsQueue().vkQueue(), info, inFlightFences.get(currentFrame)); vkWaitForFences(device, inFlightFences.get(currentFrame), true, -1); } } diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index c6bb611821..3e5b07fcea 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -21,7 +21,7 @@ public abstract class Queue { private static VkDevice device; private static QueueFamilyIndices queueFamilyIndices; - private final VkQueue queue; + private final VkQueue vkQueue; protected CommandPool commandPool; @@ -41,7 +41,7 @@ public synchronized CommandPool.CommandBuffer beginCommands() { Queue(MemoryStack stack, int familyIndex, boolean initCommandPool) { PointerBuffer pQueue = stack.mallocPointer(1); vkGetDeviceQueue(DeviceManager.vkDevice, familyIndex, 0, pQueue); - this.queue = new VkQueue(pQueue.get(0), DeviceManager.vkDevice); + this.vkQueue = new VkQueue(pQueue.get(0), DeviceManager.vkDevice); if (initCommandPool) this.commandPool = new CommandPool(familyIndex); @@ -49,12 +49,12 @@ public synchronized CommandPool.CommandBuffer beginCommands() { public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { try (MemoryStack stack = stackPush()) { - return commandBuffer.submitCommands(stack, queue, false); + return commandBuffer.submitCommands(stack, vkQueue, false); } } - public VkQueue queue() { - return this.queue; + public VkQueue vkQueue() { + return this.vkQueue; } public void cleanUp() { @@ -63,7 +63,7 @@ public void cleanUp() { } public void waitIdle() { - vkQueueWaitIdle(queue); + vkQueueWaitIdle(vkQueue); } public CommandPool getCommandPool() { From d9b2844c590bb4b3ad1f04baa9cdcef27b01f274 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 24 Nov 2025 16:18:30 +0100 Subject: [PATCH 108/177] Remove debug code --- .../render/entity/model/ModelPartCubeM.java | 25 ++----------------- .../chunk/build/renderer/BlockRenderer.java | 8 ------ 2 files changed, 2 insertions(+), 31 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java index 9fdf1ac151..a8be49c77f 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java @@ -4,9 +4,8 @@ import net.minecraft.core.Direction; import net.vulkanmod.interfaces.ModelPartCubeMixed; import net.vulkanmod.render.model.CubeModel; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -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.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -15,11 +14,7 @@ @Mixin(ModelPart.Cube.class) public class ModelPartCubeM implements ModelPartCubeMixed { - - @Shadow - @Final - public ModelPart.Polygon[] polygons; - CubeModel cube; + @Unique CubeModel cube; @Inject(method = "", at = @At(value = "FIELD", target = "Lnet/minecraft/client/model/geom/ModelPart$Cube;polygons:[Lnet/minecraft/client/model/geom/ModelPart$Polygon;", @@ -30,22 +25,6 @@ private void getVertices(int i, int j, float f, float g, float h, float k, float this.cube = cube; } - @Inject(method = "", at = @At("RETURN")) - private void debug(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set, CallbackInfo ci) { - // Debug - CubeModel.Polygon[] polygons = cube.getPolygons(); - for (int i1 = 0; i1 < polygons.length; i1++) { - var v = polygons[i1].vertices(); - var v2 = this.polygons[i1].vertices(); - - for (int s = 0; s < v.length; s++) { - if (v[s].u() != v2[s].u() || v[s].v() != v2[s].v()) { - System.nanoTime(); - } - } - } - } - @Override public CubeModel getCubeModel() { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index 86b2c001d8..74e75ce192 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -70,14 +70,6 @@ public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) Vec3 offset = blockState.getOffset(blockPos); pos.add((float) offset.x, (float) offset.y, (float) offset.z); - // Debug - if (blockState.getBlock() == Blocks.REDSTONE_WALL_TORCH) { - System.nanoTime(); - } - if (blockState.getLightEmission() > 0) { - System.nanoTime(); - } - this.prepareForBlock(blockState, blockPos, blockState.getLightEmission() == 0); model.emitQuads(this.getEmitter(), renderRegion, blockPos, blockState, this.random, this::isFaceCulled); From 29c9d77a900347e7de63134fc901a988e770c9b7 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 25 Nov 2025 00:02:24 +0100 Subject: [PATCH 109/177] Fix NPE when uniform buffer is not bound --- .../net/vulkanmod/render/engine/VkCommandEncoder.java | 9 ++++++++- .../net/vulkanmod/vulkan/shader/DescriptorSets.java | 4 +++- .../net/vulkanmod/vulkan/shader/descriptor/UBO.java | 11 ++++++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index 4913562374..cc833fb28b 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -763,7 +763,6 @@ public boolean trySetup(VkRenderPass renderPass) { return bindPipeline(renderPass.pipeline); } - // TODO public void setupUniforms(VkRenderPass renderPass) { RenderPipeline renderPipeline = renderPass.pipeline; EGlProgram glProgram = ExtendedRenderPipeline.of(renderPass.pipeline).getProgram(); @@ -774,6 +773,14 @@ public void setupUniforms(VkRenderPass renderPass) { Uniform uniform = glProgram.getUniform(uniformName); GpuBufferSlice gpuBufferSlice = renderPass.uniforms.get(uniformName); + + // In case uniform buffer is not set, ignore it + if (gpuBufferSlice == null) { + ubo.setUseGlobalBuffer(true); + ubo.setUpdate(false); + continue; + } + VkGpuBuffer gpuBuffer = (VkGpuBuffer) gpuBufferSlice.buffer(); assert ubo != null; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java index 07e1732536..1a02ff71c8 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -74,7 +74,9 @@ private void updateUniforms(UniformBuffer globalUB) { int alignedSize = UniformBuffer.getAlignedSize(ubo.getSize()); globalUB.checkCapacity(alignedSize); - ubo.update(globalUB.getPointer()); + if (ubo.shouldUpdate()) { + ubo.update(globalUB.getPointer()); + } globalUB.updateOffset(alignedSize); BufferSlice bufferSlice = ubo.getBufferSlice(); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java index 402428f89a..1229f1adad 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java @@ -1,6 +1,5 @@ package net.vulkanmod.vulkan.shader.descriptor; -import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.buffer.BufferSlice; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.layout.Uniform; @@ -15,12 +14,14 @@ public class UBO extends AlignedStruct implements Descriptor { public final int stages; public final BufferSlice bufferSlice; private boolean useGlobalBuffer; + private boolean update; public UBO(String name, int binding, int stages, int size, List infoList) { super(infoList, size); this.name = name; this.binding = binding; this.stages = stages; + this.update = true; this.bufferSlice = new BufferSlice(); } @@ -58,4 +59,12 @@ public boolean useGlobalBuffer() { public void setUseGlobalBuffer(boolean useGlobalBuffer) { this.useGlobalBuffer = useGlobalBuffer; } + + public boolean shouldUpdate() { + return update; + } + + public void setUpdate(boolean update) { + this.update = update; + } } From 2f98a8d55fda322039233cd791adbed6cded60a3 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 25 Nov 2025 00:32:41 +0100 Subject: [PATCH 110/177] Add chunk memory stats debug entry --- .../mixin/debug/DebugScreenEntriesM.java | 25 +++++++++++++++++ .../vulkanmod/render/chunk/WorldRenderer.java | 2 ++ .../profiling/DebugEntryMemoryStats.java | 28 +++++++++++++++++++ src/main/resources/vulkanmod.mixins.json | 1 + 4 files changed, 56 insertions(+) create mode 100644 src/main/java/net/vulkanmod/mixin/debug/DebugScreenEntriesM.java create mode 100644 src/main/java/net/vulkanmod/render/profiling/DebugEntryMemoryStats.java diff --git a/src/main/java/net/vulkanmod/mixin/debug/DebugScreenEntriesM.java b/src/main/java/net/vulkanmod/mixin/debug/DebugScreenEntriesM.java new file mode 100644 index 0000000000..1f0843eddd --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/debug/DebugScreenEntriesM.java @@ -0,0 +1,25 @@ +package net.vulkanmod.mixin.debug; + +import net.minecraft.client.gui.components.debug.DebugScreenEntries; +import net.minecraft.client.gui.components.debug.DebugScreenEntry; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.render.profiling.DebugEntryMemoryStats; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(DebugScreenEntries.class) +public abstract class DebugScreenEntriesM { + + @Shadow + public static ResourceLocation register(ResourceLocation resourceLocation, DebugScreenEntry debugScreenEntry) { + return null; + } + + @Inject(method = "", at = @At("RETURN")) + private static void addEntry(CallbackInfo ci) { + register(ResourceLocation.fromNamespaceAndPath("vkmod","stats"), new DebugEntryMemoryStats()); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 9d64bc902c..6bbffe097d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -508,6 +508,8 @@ public SectionGrid getSectionGrid() { } public ChunkAreaManager getChunkAreaManager() { + if (this.sectionGrid == null) + return null; return this.sectionGrid.chunkAreaManager; } diff --git a/src/main/java/net/vulkanmod/render/profiling/DebugEntryMemoryStats.java b/src/main/java/net/vulkanmod/render/profiling/DebugEntryMemoryStats.java new file mode 100644 index 0000000000..7742cc0e1c --- /dev/null +++ b/src/main/java/net/vulkanmod/render/profiling/DebugEntryMemoryStats.java @@ -0,0 +1,28 @@ +package net.vulkanmod.render.profiling; + +import net.minecraft.client.gui.components.debug.DebugScreenDisplayer; +import net.minecraft.client.gui.components.debug.DebugScreenEntry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.LevelChunk; +import net.vulkanmod.render.chunk.WorldRenderer; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class DebugEntryMemoryStats implements DebugScreenEntry { + private static final ResourceLocation GROUP = ResourceLocation.withDefaultNamespace("vk_memory"); + + @Override + public void display(DebugScreenDisplayer debugScreenDisplayer, @Nullable Level level, + @Nullable LevelChunk levelChunk, @Nullable LevelChunk levelChunk2) { + var chunkAreaManager = WorldRenderer.getInstance().getChunkAreaManager(); + + if (chunkAreaManager != null) { + debugScreenDisplayer.addToGroup( + GROUP, + List.of(chunkAreaManager.getStats()) + ); + } + } +} diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 645e8cdef1..a9f1f7eb05 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -26,6 +26,7 @@ "debug.crash_report.SystemReportM", "debug.DebugEntryMemoryM", + "debug.DebugScreenEntriesM", "debug.KeyboardHandlerM", "matrix.Matrix4fM", From 39fe59890662f2282556060fca07f7eed52a0b87 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 25 Nov 2025 15:54:57 +0100 Subject: [PATCH 111/177] Use correct descriptor type on descriptor pool creation --- .../vulkanmod/vulkan/shader/DescriptorSets.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java index 1a02ff71c8..3bfb14bca9 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -242,17 +242,21 @@ private void createDescriptorPool(MemoryStack stack) { VkDescriptorPoolSize.Buffer poolSizes = VkDescriptorPoolSize.calloc(size, stack); - int i; - for (i = 0; i < pipeline.buffers.size(); ++i) { + int i = 0; + for (var buffer : pipeline.getBuffers()) { VkDescriptorPoolSize uniformBufferPoolSize = poolSizes.get(i); - uniformBufferPoolSize.type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC); + uniformBufferPoolSize.type(buffer.getType()); uniformBufferPoolSize.descriptorCount(this.poolSize); + + ++i; } - for (; i < pipeline.buffers.size() + pipeline.imageDescriptors.size(); ++i) { + for (var imageDescriptor : pipeline.getImageDescriptors()) { VkDescriptorPoolSize textureSamplerPoolSize = poolSizes.get(i); - textureSamplerPoolSize.type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); + textureSamplerPoolSize.type(imageDescriptor.getType()); textureSamplerPoolSize.descriptorCount(this.poolSize); + + ++i; } VkDescriptorPoolCreateInfo poolInfo = VkDescriptorPoolCreateInfo.calloc(stack); From ad0fdc003690cb685bdbb7db084bc6299e2cc888 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 25 Nov 2025 16:03:52 +0100 Subject: [PATCH 112/177] Add sampler name --- .../java/net/vulkanmod/vulkan/texture/VTextureSelector.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index 7441f04367..58d1b31a70 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -67,7 +67,7 @@ public static void uploadSubTexture(int mipLevel, int arrayLayer, int width, int public static int getTextureIdx(String name) { return switch (name) { case "Sampler0", "DiffuseSampler", "InSampler", "CloudFaces" -> 0; - case "Sampler1" -> 1; + case "Sampler1", "BlurSampler" -> 1; case "Sampler2" -> 2; case "Sampler3" -> 3; case "Sampler4" -> 4; From 7a500e9e670ef08c22d7bb0f7d67a59fe8008624 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 29 Nov 2025 17:33:08 +0100 Subject: [PATCH 113/177] Add fallback to prevent crash --- .../net/vulkanmod/vulkan/shader/converter/GLSLParser.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java index e3fae40555..8ba2352d81 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java @@ -2,6 +2,7 @@ import com.mojang.blaze3d.vertex.VertexFormat; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.vulkanmod.Initializer; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; @@ -297,8 +298,11 @@ private void parseAttribute() { attributeLocation = attributeNames.indexOf(attribute.id); if (attributeLocation == -1) { - throw new IllegalStateException("Element %s not found in elements %s".formatted(attribute.id, attributeNames)); + Initializer.LOGGER.error("Element %s not found in elements %s".formatted(attribute.id, attributeNames)); + attributeLocation = currentInAtt; } + + currentInAtt++; } else { attributeLocation = currentInAtt++; } From bbf81b698fc7b2bc7e1a5b62f6578a2d4305f89b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 29 Nov 2025 17:46:59 +0100 Subject: [PATCH 114/177] Improve compatibility with GlTexture - Implement clearDepthTexture method --- .../mixin/render/target/MainTargetMixin.java | 5 ++ .../render/engine/VkCommandEncoder.java | 21 ++++-- .../net/vulkanmod/render/engine/VkFbo.java | 44 +++++++------ .../vulkanmod/render/engine/VkGpuDevice.java | 6 ++ .../vulkanmod/render/engine/VkGpuTexture.java | 65 ++++++++++--------- .../vulkan/pass/DefaultMainPass.java | 25 ++++--- .../net/vulkanmod/vulkan/pass/MainPass.java | 5 ++ 7 files changed, 103 insertions(+), 68 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java index 9eb4a00cf1..356500b531 100644 --- a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java @@ -66,4 +66,9 @@ public GpuTexture getColorTexture() { public GpuTextureView getColorTextureView() { return Renderer.getInstance().getMainPass().getColorAttachmentView(); } + + @Override + public GpuTexture getDepthTexture() { + return Renderer.getInstance().getMainPass().getDepthAttachment(); + } } diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index cc833fb28b..0cbf679d24 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -17,6 +17,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.ARGB; import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.interfaces.shader.ExtendedRenderPipeline; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.Synchronization; @@ -196,9 +197,8 @@ public void clearColorAndDepthTextures(GpuTexture colorAttachment, int clearColo else { VkFbo fbo = ((VkGpuTexture)colorAttachment).getFbo(depthAttachment); - fbo.clear = 0x4100; - fbo.clearColor = clearColor; - fbo.clearDepth = (float) clearDepth; + ((VkGpuTexture) colorAttachment).setClearColor(clearColor); + ((VkGpuTexture) depthAttachment).setDepthClearValue((float) clearDepth); Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); if (boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() @@ -240,9 +240,14 @@ public void clearDepthTexture(GpuTexture depthAttachment, double clearDepth) { throw new IllegalStateException("Close the existing render pass before creating a new one!"); } else { - // depthAttachment is not the target here - VRenderSystem.clearDepth(clearDepth); - Renderer.clearAttachments(256); + Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); + if (boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) { + VRenderSystem.clearDepth(clearDepth); + Renderer.clearAttachments(0x100); + } + else { + ((VkGpuTexture) depthAttachment).setDepthClearValue((float) clearDepth); + } } } @@ -411,7 +416,9 @@ public void writeToTexture(GpuTexture gpuTexture, NativeImage nativeImage, int l throw new IllegalStateException("Destination texture is closed"); } else { VTextureSelector.setActiveTexture(0); - VTextureSelector.bindTexture(((VkGpuTexture) gpuTexture).getVulkanImage()); + var glTexture = VkGlTexture.getTexture(((GlTexture) gpuTexture).glId()); +// VTextureSelector.bindTexture(((VkGpuTexture) gpuTexture).getVulkanImage()); + VTextureSelector.bindTexture(glTexture.getVulkanImage()); VTextureSelector.uploadSubTexture(level, arrayLayer, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, nativeImage.getWidth(), nativeImage.getPointer()); } } else { diff --git a/src/main/java/net/vulkanmod/render/engine/VkFbo.java b/src/main/java/net/vulkanmod/render/engine/VkFbo.java index 22bb06ac58..3c44224c7f 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkFbo.java +++ b/src/main/java/net/vulkanmod/render/engine/VkFbo.java @@ -5,21 +5,13 @@ import net.vulkanmod.gl.VkGlFramebuffer; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.framebuffer.Framebuffer; import org.lwjgl.opengl.GL33; -import org.lwjgl.system.MemoryStack; - -import static org.lwjgl.system.MemoryStack.stackPush; public class VkFbo { final int glId; final VkGpuTexture colorAttachment; final VkGpuTexture depthAttachment; - int clear = 0; - int clearColor = 0; - float clearDepth = 0.0f; - protected VkFbo(VkGpuTexture colorAttachment, VkGpuTexture depthAttachment) { this.glId = GlStateManager.glGenFramebuffers(); this.colorAttachment = colorAttachment; @@ -35,25 +27,35 @@ protected VkFbo(VkGpuTexture colorAttachment, VkGpuTexture depthAttachment) { } protected void bind() { -// VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.glId); -// VkGlFramebuffer.beginRendering(glFramebuffer); -// -// Framebuffer framebuffer = glFramebuffer.getFramebuffer(); -// try (MemoryStack stack = stackPush()) { -// framebuffer.beginRenderPass(currentCmdBuffer, renderPass, stack); -// } - VkGlFramebuffer.bindFramebuffer(GL33.GL_FRAMEBUFFER, this.glId); clearAttachments(); } protected void clearAttachments() { - if (clear != 0) { - VRenderSystem.clearDepth(clearDepth); + int clear = 0; + float clearDepth; + int clearColor; + + if (colorAttachment.needsClear()) { + clear |= 0x4000; + clearColor = colorAttachment.clearColor; + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); - Renderer.clearAttachments(clear); - clear = 0; + colorAttachment.needsClear = false; + } + + if (depthAttachment != null && depthAttachment.needsClear()) { + clear |= 0x100; + clearDepth = depthAttachment.depthClearValue; + + VRenderSystem.clearDepth(clearDepth); + + depthAttachment.needsClear = false; + } + + if (clear != 0) { + Renderer.clearAttachments(clear); } } @@ -62,6 +64,6 @@ protected void close() { } public boolean needsClear() { - return this.clear != 0; + return this.colorAttachment.needsClear() || (this.depthAttachment != null && this.depthAttachment.needsClear()); } } diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java index 6c641decfb..78cf830a6b 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java @@ -131,6 +131,12 @@ public GpuTextureView createTextureView(GpuTexture gpuTexture, int startLevel, i if (gpuTexture.isClosed()) { throw new IllegalArgumentException("Can't create texture view with closed texture"); } else if (startLevel >= 0 && startLevel + levels <= gpuTexture.getMipLevels()) { + + // Try to convert gpuTexture to VkGpuTexture in case it's not + if (gpuTexture.getClass() != VkGpuTexture.class) { + gpuTexture = VkGpuTexture.fromGlTexture((GlTexture) gpuTexture); + } + return new VkTextureView((VkGpuTexture) gpuTexture, startLevel, levels); } else { throw new IllegalArgumentException( diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java index b5e5a5b651..05b16988cb 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -1,6 +1,5 @@ package net.vulkanmod.render.engine; -import com.mojang.blaze3d.opengl.GlConst; import com.mojang.blaze3d.opengl.GlStateManager; import com.mojang.blaze3d.opengl.GlTexture; import com.mojang.blaze3d.textures.AddressMode; @@ -8,24 +7,29 @@ import com.mojang.blaze3d.textures.GpuTexture; import com.mojang.blaze3d.textures.TextureFormat; import it.unimi.dsi.fastutil.ints.*; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.texture.SamplerManager; import net.vulkanmod.vulkan.texture.VulkanImage; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; import org.lwjgl.vulkan.VK10; @Environment(EnvType.CLIENT) -//public class VkGpuTexture extends GpuTexture { public class VkGpuTexture extends GlTexture { + private static final Reference2ReferenceOpenHashMap glToVkMap = new Reference2ReferenceOpenHashMap<>(); + protected VkGlTexture glTexture; protected final int id; private final Int2ReferenceMap fboCache = new Int2ReferenceOpenHashMap<>(); protected boolean closed; protected boolean modesDirty = true; + boolean needsClear = false; + int clearColor = 0; + float depthClearValue = 1.0f; + protected VkGpuTexture(int usage, String string, TextureFormat textureFormat, int width, int height, int layers, int mipLevel, int id, VkGlTexture glTexture) { super(usage, string, textureFormat, width, height, layers, mipLevel, id); this.id = id; @@ -49,35 +53,8 @@ public boolean isClosed() { return this.closed; } -// public int getFbo(DirectStateAccess directStateAccess, @Nullable GpuTexture gpuTexture) { -// int i = gpuTexture == null ? 0 : ((VkGpuTexture)gpuTexture).id; -// return this.fboCache.computeIfAbsent(i, j -> { -// int k = directStateAccess.createFrameBufferObject(); -// directStateAccess.bindFrameBufferTextures(k, this.id, i, 0, 0); -// return k; -// }); -// } - public void flushModeChanges() { if (this.modesDirty) { -// GlStateManager._texParameter(3553, 10242, GlConst.toGl(this.addressModeU)); -// GlStateManager._texParameter(3553, 10243, GlConst.toGl(this.addressModeV)); -// switch (this.minFilter) { -// case NEAREST: -// GlStateManager._texParameter(3553, 10241, this.useMipmaps ? 9986 : 9728); -// break; -// case LINEAR: -// GlStateManager._texParameter(3553, 10241, this.useMipmaps ? 9987 : 9729); -// } -// -// switch (this.magFilter) { -// case NEAREST: -// GlStateManager._texParameter(3553, 10240, 9728); -// break; -// case LINEAR: -// GlStateManager._texParameter(3553, 10240, 9729); -// } - byte samplerFlags; samplerFlags = magFilter == FilterMode.LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; @@ -115,6 +92,20 @@ public void setUseMipmaps(boolean bl) { this.modesDirty = true; } + public void setClearColor(int clearColor) { + this.needsClear = true; + this.clearColor = clearColor; + } + + public void setDepthClearValue(float depthClearValue) { + this.needsClear = true; + this.depthClearValue = depthClearValue; + } + + public boolean needsClear() { + return needsClear; + } + public VkFbo getFbo(@Nullable GpuTexture depthAttachment) { int depthAttachmentId = depthAttachment == null ? 0 : ((VkGpuTexture)depthAttachment).id; return this.fboCache.computeIfAbsent(depthAttachmentId, j -> new VkFbo(this, (VkGpuTexture) depthAttachment)); @@ -124,6 +115,20 @@ public VulkanImage getVulkanImage() { return glTexture.getVulkanImage(); } + public static VkGpuTexture fromGlTexture(GlTexture glTexture) { + return glToVkMap.computeIfAbsent(glTexture, glTexture1 -> { + var name = glTexture.getLabel(); + int id = glTexture.glId(); + VkGlTexture vglTexture = VkGlTexture.getTexture(id); + VkGpuTexture gpuTexture = new VkGpuTexture(0, name, glTexture.getFormat(), + glTexture.getWidth(0), glTexture.getHeight(0), + 1, glTexture.getMipLevels(), + glTexture.glId(), vglTexture); + + return gpuTexture; + }); + } + public static TextureFormat textureFormat(int format) { return switch (format) { case VK10.VK_FORMAT_R8G8B8A8_UNORM, VK10.VK_FORMAT_B8G8R8A8_UNORM -> TextureFormat.RGBA8; diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index 94801d7585..44726df8d2 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -1,10 +1,8 @@ package net.vulkanmod.vulkan.pass; -import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.textures.GpuTexture; import com.mojang.blaze3d.textures.GpuTextureView; -import net.minecraft.client.Minecraft; import net.vulkanmod.render.engine.VkGpuDevice; import net.vulkanmod.render.engine.VkGpuTexture; import net.vulkanmod.vulkan.Renderer; @@ -16,7 +14,6 @@ import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkCommandBuffer; import org.lwjgl.vulkan.VkRect2D; -import org.lwjgl.vulkan.VkViewport; import static org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; import static org.lwjgl.vulkan.VK10.*; @@ -27,7 +24,6 @@ public static DefaultMainPass create() { return new DefaultMainPass(); } - private RenderTarget mainTarget; private final Framebuffer mainFramebuffer; private RenderPass mainRenderPass; @@ -35,13 +31,13 @@ public static DefaultMainPass create() { private GpuTexture[] colorAttachmentTextures; private GpuTextureView[] colorAttachmentTextureViews; + private GpuTexture depthAttachmentTexture; DefaultMainPass() { - this.mainTarget = Minecraft.getInstance().getMainRenderTarget(); this.mainFramebuffer = Renderer.getInstance().getSwapChain(); createRenderPasses(); - createSwapChainTextures(); + createAttachmentTextures(); } private void createRenderPasses() { @@ -70,8 +66,6 @@ public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { framebuffer.beginRenderPass(commandBuffer, this.mainRenderPass, stack); -// VkViewport.Buffer pViewport = framebuffer.viewport(stack); -// vkCmdSetViewport(commandBuffer, 0, pViewport); Renderer.setViewport(0, 0, framebuffer.getWidth(), framebuffer.getHeight(), stack); VkRect2D.Buffer pScissor = framebuffer.scissor(stack); @@ -101,7 +95,7 @@ public void cleanUp() { @Override public void onResize() { - this.createSwapChainTextures(); + this.createAttachmentTextures(); } public void rebindMainTarget() { @@ -148,11 +142,20 @@ public GpuTextureView getColorAttachmentView() { return this.colorAttachmentTextureViews[Renderer.getCurrentImage()]; } - private void createSwapChainTextures() { + @Override + public GpuTexture getDepthAttachment() { + return this.depthAttachmentTexture; + } + + private void createAttachmentTextures() { VkGpuDevice device = (VkGpuDevice) RenderSystem.getDevice(); SwapChain swapChain = Renderer.getInstance().getSwapChain(); var swapChainImages = swapChain.getImages(); + + if (swapChain.getWidth() == 0 && swapChain.getHeight() == 0) + return; + int imageCount = swapChainImages.size(); this.colorAttachmentTextures = new GpuTexture[imageCount]; this.colorAttachmentTextureViews = new GpuTextureView[imageCount]; @@ -163,5 +166,7 @@ private void createSwapChainTextures() { this.colorAttachmentTextures[i] = attachmentTexture; this.colorAttachmentTextureViews[i] = attachmentTextureView; } + + this.depthAttachmentTexture = device.gpuTextureFromVulkanImage(swapChain.getDepthAttachment()); } } diff --git a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java index 63a843c58a..d5e1b44c87 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java @@ -30,4 +30,9 @@ default GpuTexture getColorAttachment() { default GpuTextureView getColorAttachmentView() { return null; } + + default GpuTexture getDepthAttachment() { + return null; + } + } From 69f6b76cace078d807f1518f1199065a5b2665d2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 29 Nov 2025 20:02:19 +0100 Subject: [PATCH 115/177] Prevent crash when texture format is unrecognized --- src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java index 05b16988cb..886bb0aa13 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -134,7 +134,7 @@ public static TextureFormat textureFormat(int format) { case VK10.VK_FORMAT_R8G8B8A8_UNORM, VK10.VK_FORMAT_B8G8R8A8_UNORM -> TextureFormat.RGBA8; case VK10.VK_FORMAT_R8_UNORM -> TextureFormat.RED8; case VK10.VK_FORMAT_D32_SFLOAT -> TextureFormat.DEPTH32; - default -> throw new IllegalStateException("Unexpected value: " + format); + default -> null; }; } From b044f06db6ff42c7e79255147a30bcb5126f0386 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 16:27:42 +0100 Subject: [PATCH 116/177] Extend and refactor sampler management --- .../net/vulkanmod/gl/VkGlRenderbuffer.java | 32 ++- .../java/net/vulkanmod/gl/VkGlTexture.java | 35 ++- .../vulkanmod/render/engine/VkGpuTexture.java | 14 +- .../vulkan/framebuffer/SwapChain.java | 4 +- .../vulkan/texture/SamplerManager.java | 199 +++++++++++++----- .../vulkanmod/vulkan/texture/VulkanImage.java | 109 ++++------ 6 files changed, 244 insertions(+), 149 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java index e811144a2c..63b7a62edb 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java @@ -159,16 +159,34 @@ void updateSampler() { if (vulkanImage == null) return; - byte samplerFlags = magFilter == GL11.GL_LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; + int addressMode = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + int vkMagFilter, vkMinFilter, mipmapMode; - samplerFlags |= switch (minFilter) { - case GL11.GL_LINEAR_MIPMAP_LINEAR -> - SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; - case GL11.GL_NEAREST_MIPMAP_NEAREST -> SamplerManager.USE_MIPMAPS_BIT; - default -> 0; + switch (minFilter) { + case GL11.GL_LINEAR_MIPMAP_LINEAR, GL11.GL_LINEAR -> { + vkMinFilter = VK_FILTER_LINEAR; mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + } + case GL11.GL_LINEAR_MIPMAP_NEAREST -> { + vkMinFilter = VK_FILTER_LINEAR; mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + } + case GL11.GL_NEAREST_MIPMAP_NEAREST, GL11.GL_NEAREST -> { + vkMinFilter = VK_FILTER_NEAREST; mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + } + case GL11.GL_NEAREST_MIPMAP_LINEAR -> { + vkMinFilter = VK_FILTER_NEAREST; mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + } + default -> throw new IllegalStateException("Unexpected min filter value: %d".formatted(minFilter)); + } + + vkMagFilter = switch (magFilter) { + case GL11.GL_LINEAR -> VK_FILTER_LINEAR; + case GL11.GL_NEAREST -> VK_FILTER_NEAREST; + default -> throw new IllegalStateException("Unexpected mag filter value: %d".formatted(magFilter)); }; - vulkanImage.updateTextureSampler(maxLod, samplerFlags); + long sampler = SamplerManager.getSampler(addressMode, addressMode, vkMinFilter, vkMagFilter, mipmapMode, maxLod, false, 0, -1); + + vulkanImage.setSampler(sampler); } private void uploadImage(ByteBuffer pixels) { diff --git a/src/main/java/net/vulkanmod/gl/VkGlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java index 8d39e536e4..5b4e173b47 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -279,7 +279,7 @@ public static VkGlTexture getBoundTexture() { boolean needsUpdate = false; int maxLevel = 0; int maxLod = 0; - int minFilter, magFilter = GL11.GL_LINEAR; + int minFilter = GL11.GL_NEAREST, magFilter = GL11.GL_NEAREST; boolean clamp = true; @@ -340,17 +340,34 @@ void updateSampler() { if (vulkanImage == null) return; - byte samplerFlags; - samplerFlags = clamp ? SamplerManager.CLAMP_BIT : 0; - samplerFlags |= magFilter == GL11.GL_LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; + int addressMode = clamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + int vkMagFilter, vkMinFilter, mipmapMode; - samplerFlags |= switch (minFilter) { - case GL11.GL_LINEAR_MIPMAP_LINEAR -> SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; - case GL11.GL_NEAREST_MIPMAP_NEAREST -> SamplerManager.USE_MIPMAPS_BIT; - default -> 0; + switch (minFilter) { + case GL11.GL_LINEAR_MIPMAP_LINEAR, GL11.GL_LINEAR -> { + vkMinFilter = VK_FILTER_LINEAR; mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + } + case GL11.GL_LINEAR_MIPMAP_NEAREST -> { + vkMinFilter = VK_FILTER_LINEAR; mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + } + case GL11.GL_NEAREST_MIPMAP_NEAREST, GL11.GL_NEAREST -> { + vkMinFilter = VK_FILTER_NEAREST; mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + } + case GL11.GL_NEAREST_MIPMAP_LINEAR -> { + vkMinFilter = VK_FILTER_NEAREST; mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + } + default -> throw new IllegalStateException("Unexpected min filter value: %d".formatted(minFilter)); + } + + vkMagFilter = switch (magFilter) { + case GL11.GL_LINEAR -> VK_FILTER_LINEAR; + case GL11.GL_NEAREST -> VK_FILTER_NEAREST; + default -> throw new IllegalStateException("Unexpected mag filter value: %d".formatted(magFilter)); }; - vulkanImage.updateTextureSampler(maxLod, samplerFlags); + long sampler = SamplerManager.getSampler(addressMode, addressMode, vkMinFilter, vkMagFilter, mipmapMode, maxLod, false, 0, -1); + + vulkanImage.setSampler(sampler); } private void uploadSubImage(int level, int xOffset, int yOffset, int width, int height, int format, ByteBuffer pixels) { diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java index 886bb0aa13..7ee10650ec 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -55,16 +55,16 @@ public boolean isClosed() { public void flushModeChanges() { if (this.modesDirty) { - byte samplerFlags; - samplerFlags = magFilter == FilterMode.LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; + int maxLod = this.useMipmaps ? this.getMipLevels() - 1 : 0; - // TODO: split min filtering + int magFilterVk = magFilter == FilterMode.LINEAR ? VK10.VK_FILTER_LINEAR : VK10.VK_FILTER_NEAREST; + int minFilterVk = minFilter == FilterMode.LINEAR ? VK10.VK_FILTER_LINEAR : VK10.VK_FILTER_NEAREST; - if (this.useMipmaps) { - samplerFlags |= SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; - } + long sampler = SamplerManager.getSampler(VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + minFilterVk, magFilterVk, VK10.VK_SAMPLER_MIPMAP_MODE_LINEAR, + maxLod, false, 0, -1); - glTexture.getVulkanImage().updateTextureSampler(this.getMipLevels(), samplerFlags); + glTexture.getVulkanImage().setSampler(sampler); this.modesDirty = false; } diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index e760a72d68..115e8311ed 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -7,6 +7,7 @@ import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.queue.Queue; +import net.vulkanmod.vulkan.texture.SamplerManager; import net.vulkanmod.vulkan.texture.VulkanImage; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.*; @@ -152,7 +153,8 @@ private void createSwapChain() { long imageView = VulkanImage.createImageView(imageId, this.format, VK_IMAGE_ASPECT_COLOR_BIT, 1, 1); VulkanImage image = new VulkanImage("Swapchain", imageId, this.format, 1, this.width, this.height, 4, 0, imageView); - image.updateTextureSampler(true, true, false); + long samplerId = SamplerManager.getSampler(true, true, 0); + image.setSampler(samplerId); this.swapChainImages.add(image); } } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java b/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java index f58fb4255d..2698f62298 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java @@ -1,9 +1,8 @@ package net.vulkanmod.vulkan.texture; -import it.unimi.dsi.fastutil.shorts.Short2LongMap; -import it.unimi.dsi.fastutil.shorts.Short2LongOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2LongMap; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import net.vulkanmod.vulkan.device.DeviceManager; -import org.apache.commons.lang3.Validate; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkSamplerCreateInfo; import org.lwjgl.vulkan.VkSamplerReductionModeCreateInfo; @@ -13,81 +12,86 @@ import static net.vulkanmod.vulkan.Vulkan.getVkDevice; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.VK10.*; -import static org.lwjgl.vulkan.VK12.VK_SAMPLER_REDUCTION_MODE_MAX; -import static org.lwjgl.vulkan.VK12.VK_SAMPLER_REDUCTION_MODE_MIN; public abstract class SamplerManager { + public static final int ADDRESS_MODE_BITS = 2; + public static final int REDUCTION_MODE_BITS = 2; + + public static final int ADDRESS_MODE_U_OFFSET = 0; + public static final int ADDRESS_MODE_V_OFFSET = 2; + public static final int MIN_FILTER_OFFSET = 4; + public static final int MAG_FILTER_OFFSET = 5; + public static final int MIPMAP_MODE_OFFSET = 6; + public static final int ANISOTROPY_OFFSET = 7; + public static final int REDUCTION_MODE_ENABLE_OFFSET = 8; + public static final int REDUCTION_MODE_OFFSET = 9; + static final float MIP_BIAS = -0.5f; - static final Short2LongMap SAMPLERS = new Short2LongOpenHashMap(); + static final Object2LongMap SAMPLERS = new Object2LongOpenHashMap<>(); + + public static long getSampler(boolean clamp, boolean linearFiltering, int maxLod) { + return getSampler(clamp, linearFiltering, maxLod, false, 0); + } + + public static long getSampler(boolean clamp, boolean linearFiltering, int maxLod, boolean anisotropy, int maxAnisotropy) { + int addressMode = clamp ? VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE : VK_SAMPLER_ADDRESS_MODE_REPEAT; + int filter = linearFiltering ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + int mipmapMode = linearFiltering ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; + + return getSampler(addressMode, addressMode, filter, filter, mipmapMode, maxLod, anisotropy, maxAnisotropy, -1); + } + + public static long getSampler(int addressModeU, int addressModeV, + int minFilter, int magFilter, int mipmapMode, float maxLod, + boolean anisotropy, float maxAnisotropy, int reductionMode) { + SamplerInfo samplerInfo = new SamplerInfo(addressModeU, addressModeV, minFilter, magFilter, mipmapMode, maxLod, anisotropy, maxAnisotropy, reductionMode); - public static long getTextureSampler(byte maxLod, byte flags) { - short key = (short) (flags | (maxLod << 8)); - long sampler = SAMPLERS.getOrDefault(key, 0L); + long sampler = SAMPLERS.getOrDefault(samplerInfo, 0L); if (sampler == 0L) { - sampler = createTextureSampler(maxLod, flags); - SAMPLERS.put(key, sampler); + sampler = createTextureSampler(samplerInfo); + SAMPLERS.put(samplerInfo, sampler); } return sampler; } - private static long createTextureSampler(byte maxLod, byte flags) { - Validate.isTrue( - (flags & (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT)) != (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT) - ); + public static long getDefaultSampler() { + return getSampler(false, false, 0); + } - try (MemoryStack stack = stackPush()) { + private static long createTextureSampler(SamplerInfo sampler) { + int state = sampler.encodedState; + try (MemoryStack stack = stackPush()) { VkSamplerCreateInfo samplerInfo = VkSamplerCreateInfo.calloc(stack); samplerInfo.sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO); - if ((flags & LINEAR_FILTERING_BIT) != 0) { - samplerInfo.magFilter(VK_FILTER_LINEAR); - samplerInfo.minFilter(VK_FILTER_LINEAR); - } else { - samplerInfo.magFilter(VK_FILTER_NEAREST); - samplerInfo.minFilter(VK_FILTER_NEAREST); - } + samplerInfo.magFilter(sampler.getMagFilter()); + samplerInfo.minFilter(sampler.getMinFilter()); - if ((flags & CLAMP_BIT) != 0) { - samplerInfo.addressModeU(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); - samplerInfo.addressModeV(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); - samplerInfo.addressModeW(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); - } else { - samplerInfo.addressModeU(VK_SAMPLER_ADDRESS_MODE_REPEAT); - samplerInfo.addressModeV(VK_SAMPLER_ADDRESS_MODE_REPEAT); - samplerInfo.addressModeW(VK_SAMPLER_ADDRESS_MODE_REPEAT); - } + samplerInfo.addressModeU(sampler.getAddressModeU()); + samplerInfo.addressModeV(sampler.getAddressModeV()); + samplerInfo.addressModeW(VK_SAMPLER_ADDRESS_MODE_REPEAT); - samplerInfo.anisotropyEnable(false); - //samplerInfo.maxAnisotropy(16.0f); + samplerInfo.anisotropyEnable(sampler.getAnisotropy()); + samplerInfo.maxAnisotropy(sampler.getMaxAnisotropy()); samplerInfo.borderColor(VK_BORDER_COLOR_INT_OPAQUE_WHITE); samplerInfo.unnormalizedCoordinates(false); samplerInfo.compareEnable(false); samplerInfo.compareOp(VK_COMPARE_OP_ALWAYS); - if ((flags & USE_MIPMAPS_BIT) == 0) { - samplerInfo.mipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST); - samplerInfo.maxLod(0.0F); - samplerInfo.minLod(0.0F); - } else { - if ((flags & MIPMAP_LINEAR_FILTERING_BIT) != 0) { - samplerInfo.mipmapMode(VK_SAMPLER_MIPMAP_MODE_LINEAR); - } else { - samplerInfo.mipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST); - } - samplerInfo.maxLod(maxLod); - samplerInfo.minLod(0.0F); - samplerInfo.mipLodBias(MIP_BIAS); - } + samplerInfo.mipmapMode(sampler.getMipmapMode()); + samplerInfo.maxLod(sampler.getMaxLod()); + samplerInfo.minLod(0.0F); + samplerInfo.mipLodBias(MIP_BIAS); - //Reduction Mode - if ((flags & (REDUCTION_MAX_BIT | REDUCTION_MIN_BIT)) != 0) { + // Reduction Mode + if (sampler.hasReductionMode()) { VkSamplerReductionModeCreateInfo reductionModeInfo = VkSamplerReductionModeCreateInfo.calloc(stack); reductionModeInfo.sType$Default(); - reductionModeInfo.reductionMode((flags & REDUCTION_MAX_BIT) != 0 ? VK_SAMPLER_REDUCTION_MODE_MAX : VK_SAMPLER_REDUCTION_MODE_MIN); + reductionModeInfo.reductionMode(sampler.getReductionMode()); samplerInfo.pNext(reductionModeInfo.address()); } @@ -107,10 +111,91 @@ public static void cleanUp() { } } - public static final byte LINEAR_FILTERING_BIT = 0b1; - public static final byte CLAMP_BIT = 0b10; - public static final byte USE_MIPMAPS_BIT = 0b100; - public static final byte MIPMAP_LINEAR_FILTERING_BIT = 0b1000; - public static final byte REDUCTION_MIN_BIT = 0b10000; - public static final byte REDUCTION_MAX_BIT = 0b100000; + public static class SamplerInfo { + final int encodedState; + final int maxLod; + final int maxAnisotropy; + + public SamplerInfo() { + this(VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, + VK_FILTER_NEAREST, VK_FILTER_NEAREST, VK_SAMPLER_MIPMAP_MODE_NEAREST, + 0, false, 0, -1); + } + + + + public SamplerInfo(int addressModeU, int addressModeV, int minFilter, int magFilter, int mipmapMode, + float maxLod, boolean anisotropy, float maxAnisotropy, int reductionMode) { + this.maxLod = (int) maxLod; + this.maxAnisotropy = (int) maxAnisotropy; + + int encodedState = (addressModeU & ADDRESS_MODE_BITS) << ADDRESS_MODE_U_OFFSET; + encodedState |= (addressModeV & ADDRESS_MODE_BITS) << ADDRESS_MODE_V_OFFSET; + encodedState |= (minFilter & 1) << MIN_FILTER_OFFSET; + encodedState |= (magFilter & 1) << MAG_FILTER_OFFSET; + encodedState |= (mipmapMode & 1) << MIPMAP_MODE_OFFSET; + encodedState |= ((anisotropy ? 1 : 0) & 1) << ANISOTROPY_OFFSET; + encodedState |= (reductionMode != -1 ? 1 : 0) << REDUCTION_MODE_ENABLE_OFFSET; + encodedState |= (reductionMode & REDUCTION_MODE_BITS) << REDUCTION_MODE_OFFSET; + + this.encodedState = encodedState; + } + + public int getAddressModeU() { + return (this.encodedState >> ADDRESS_MODE_U_OFFSET) & ADDRESS_MODE_BITS; + } + + public int getAddressModeV() { + return (this.encodedState >> ADDRESS_MODE_V_OFFSET) & ADDRESS_MODE_BITS; + } + + public int getMinFilter() { + return (this.encodedState >> MIN_FILTER_OFFSET) & 1; + } + + public int getMagFilter() { + return (this.encodedState >> MAG_FILTER_OFFSET) & 1; + } + + public int getMipmapMode() { + return (this.encodedState >> MIPMAP_MODE_OFFSET) & 1; + } + + public boolean getAnisotropy() { + return ((this.encodedState >> ANISOTROPY_OFFSET) & 1) != 0; + } + + public boolean hasReductionMode() { + return ((this.encodedState >> REDUCTION_MODE_ENABLE_OFFSET) & 1) != 0; + } + + public int getReductionMode() { + return (this.encodedState >> REDUCTION_MODE_OFFSET) & REDUCTION_MODE_BITS; + } + + public int getMaxAnisotropy() { + return maxAnisotropy; + } + + public int getMaxLod() { + return maxLod; + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + + SamplerInfo samplerInfo = (SamplerInfo) o; + return maxLod == samplerInfo.maxLod && maxAnisotropy == samplerInfo.maxAnisotropy && encodedState == samplerInfo.encodedState; + } + + @Override + public int hashCode() { + int result = encodedState; + result = 31 * result + maxLod; + result = 31 * result + maxAnisotropy; + return result; + } + } + } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index ab89a99d25..03f86b62bd 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -9,16 +9,12 @@ import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; -import org.lwjgl.vulkan.VkCommandBuffer; -import org.lwjgl.vulkan.VkDevice; -import org.lwjgl.vulkan.VkImageMemoryBarrier; -import org.lwjgl.vulkan.VkImageViewCreateInfo; +import org.lwjgl.vulkan.*; import java.nio.ByteBuffer; import java.nio.LongBuffer; import java.util.Arrays; -import static net.vulkanmod.vulkan.texture.SamplerManager.*; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; import static org.lwjgl.vulkan.VK10.*; @@ -44,7 +40,7 @@ public class VulkanImage { private long allocation; private long mainImageView; - private long[] levelImageViews; + private final long[] levelImageViews; private long sampler; @@ -67,8 +63,9 @@ public VulkanImage(String name, long id, int format, int mipLevels, int width, i this.viewType = VK_IMAGE_VIEW_TYPE_2D; this.size = width * height * formatSize; + this.levelImageViews = new long[mipLevels]; - this.sampler = SamplerManager.getTextureSampler((byte) this.mipLevels, (byte) 0); + this.sampler = SamplerManager.getDefaultSampler(); } private VulkanImage(Builder builder) { @@ -84,6 +81,7 @@ private VulkanImage(Builder builder) { this.viewType = builder.viewType; this.size = width * height * formatSize; + this.levelImageViews = new long[builder.mipLevels]; } public static VulkanImage createTextureImage(Builder builder) { @@ -92,26 +90,18 @@ public static VulkanImage createTextureImage(Builder builder) { image.createImage(); image.mainImageView = createImageView(image.id, image.viewType, image.format, image.aspect, image.arrayLayers, 0, image.mipLevels); - image.sampler = SamplerManager.getTextureSampler(builder.mipLevels, builder.samplerFlags); - - if (builder.levelViews) { - image.levelImageViews = new long[builder.mipLevels]; - - for (int i = 0; i < builder.mipLevels; ++i) { - image.levelImageViews[i] = createImageView(image.id, image.format, image.aspect, i, 1); - } - } + image.sampler = SamplerManager.getSampler(builder.clamp, builder.linearFiltering, builder.mipLevels - 1); return image; } public static VulkanImage createDepthImage(int format, int width, int height, int usage, boolean blur, boolean clamp) { VulkanImage image = VulkanImage.builder(width, height) - .setFormat(format) - .setUsage(usage) - .setLinearFiltering(blur) - .setClamp(clamp) - .createVulkanImage(); + .setFormat(format) + .setUsage(usage) + .setLinearFiltering(blur) + .setClamp(clamp) + .createVulkanImage(); return image; } @@ -123,14 +113,13 @@ public static VulkanImage createWhiteTexture() { buffer.putInt(0, i); VulkanImage image = VulkanImage.builder(1, 1) - .setFormat(DefaultFormat) - .setUsage(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) - .setLinearFiltering(false) - .setClamp(false) - .createVulkanImage(); + .setFormat(DefaultFormat) + .setUsage(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) + .setLinearFiltering(false) + .setClamp(false) + .createVulkanImage(); image.uploadSubTextureAsync(0, 0, image.width, image.height, 0, 0, 0, 0, 0, buffer); return image; -// return createTextureImage(1, 1, 4, false, false, buffer); } } @@ -293,20 +282,8 @@ public void readOnlyLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } - public void updateTextureSampler(boolean blur, boolean clamp, boolean mipmaps) { - byte flags = blur ? LINEAR_FILTERING_BIT : 0; - flags |= clamp ? CLAMP_BIT : 0; - flags |= (byte) (mipmaps ? USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT : 0); - - this.updateTextureSampler(flags); - } - - public void updateTextureSampler(byte flags) { - updateTextureSampler(this.mipLevels - 1, flags); - } - - public void updateTextureSampler(int maxLod, byte flags) { - this.sampler = SamplerManager.getTextureSampler((byte) maxLod, flags); + public void setSampler(long sampler) { + this.sampler = sampler; } public void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, int newLayout) { @@ -315,7 +292,6 @@ public void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuff public static void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int newLayout) { if (image.currentLayout == newLayout) { -// System.out.println("new layout is equal to current layout"); return; } @@ -377,13 +353,13 @@ public static void transitionImageLayout(MemoryStack stack, VkCommandBuffer comm } transitionLayout(stack, commandBuffer, image, image.currentLayout, newLayout, - sourceStage, srcAccessMask, destinationStage, dstAccessMask); + sourceStage, srcAccessMask, destinationStage, dstAccessMask); } public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int oldLayout, int newLayout, int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { transitionLayout(stack, commandBuffer, image, 0, oldLayout, newLayout, - sourceStage, srcAccessMask, destinationStage, dstAccessMask); + sourceStage, srcAccessMask, destinationStage, dstAccessMask); } public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int baseLevel, int oldLayout, int newLayout, @@ -408,11 +384,11 @@ public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBu barrier.dstAccessMask(dstAccessMask); vkCmdPipelineBarrier(commandBuffer, - sourceStage, destinationStage, - 0, - null, - null, - barrier); + sourceStage, destinationStage, + 0, + null, + null, + barrier); image.currentLayout = newLayout; } @@ -435,7 +411,11 @@ public void doFree() { if (this.levelImageViews != null) Arrays.stream(this.levelImageViews).forEach( - imageView -> vkDestroyImageView(Vulkan.getVkDevice(), this.mainImageView, null)); + imageView -> { + if (imageView != 0L) { + vkDestroyImageView(Vulkan.getVkDevice(), imageView, null); + } + }); this.id = 0L; } @@ -461,6 +441,9 @@ public long getImageView() { } public long getLevelImageView(int i) { + if (this.levelImageViews[i] == 0L) { + this.levelImageViews[i] = createImageView(this.id, VK_IMAGE_VIEW_TYPE_2D, this.format, this.aspect, this.arrayLayers, i, 1); + } return levelImageViews[i]; } @@ -488,9 +471,10 @@ public static class Builder { int usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; int viewType = VK_IMAGE_VIEW_TYPE_2D; - byte samplerFlags = 0; - - boolean levelViews = false; + // Sampler settings + boolean linearFiltering = false; + boolean clamp = false; + int reductionMode = -1; public Builder(int width, int height) { this.width = width; @@ -509,16 +493,11 @@ public Builder setFormat(int format) { public Builder setArrayLayers(int n) { this.arrayLayers = (byte) n; - return this; } public Builder setMipLevels(int n) { this.mipLevels = (byte) n; - - if (n > 1) - this.samplerFlags |= USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT; - return this; } @@ -538,22 +517,17 @@ public Builder setViewType(int viewType) { } public Builder setLinearFiltering(boolean b) { - this.samplerFlags |= b ? LINEAR_FILTERING_BIT : 0; + this.linearFiltering = b; return this; } public Builder setClamp(boolean b) { - this.samplerFlags |= b ? CLAMP_BIT : 0; - return this; - } - - public Builder setSamplerReductionModeMin() { - this.samplerFlags = REDUCTION_MIN_BIT | LINEAR_FILTERING_BIT; + this.clamp = b; return this; } - public Builder setLevelViews(boolean b) { - this.levelViews = b; + public Builder setSamplerReductionMode(int reductionMode) { + this.reductionMode = reductionMode; return this; } @@ -571,7 +545,6 @@ private static int formatSize(int format) { case VK_FORMAT_R8_UNORM -> 1; default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); -// default -> 0; }; } } From da9395d454220c17176ae2a1714f4c8d0b970eac Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 16:28:46 +0100 Subject: [PATCH 117/177] Revert direct mem copy to fix perf regression --- src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index 3db5c790db..9becd6202d 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -106,10 +106,7 @@ static abstract class MappableMemory extends MemoryType { @Override public void copyToBuffer(Buffer buffer, ByteBuffer src, long size, long srcOffset, long dstOffset) { - StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - stagingBuffer.copyBuffer((int) size, src); - - DeviceManager.getTransferQueue().copyBufferCmd(stagingBuffer.getId(), stagingBuffer.getOffset(), buffer.getId(), dstOffset, size); + VUtil.memcpy(src, buffer, size, srcOffset, dstOffset); } @Override From 9be5fe8ff0678d2903c75c1ce9535c165933b7dc Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 16:34:57 +0100 Subject: [PATCH 118/177] Improve cmd buffer sync - Use semaphores to sync cmd buffers in the same frame --- .../render/texture/ImageUploadHelper.java | 4 +- .../java/net/vulkanmod/vulkan/Renderer.java | 24 ++++++-- .../net/vulkanmod/vulkan/Synchronization.java | 55 +++++++++++++++++-- .../vulkanmod/vulkan/queue/CommandPool.java | 4 ++ .../net/vulkanmod/vulkan/queue/Queue.java | 8 ++- 5 files changed, 80 insertions(+), 15 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java index 9e5f80493f..46d4cc6986 100644 --- a/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java +++ b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java @@ -21,8 +21,8 @@ public void submitCommands() { return; } - long fence = queue.submitCommands(this.currentCmdBuffer); - Synchronization.INSTANCE.addCommandBuffer(this.currentCmdBuffer); + queue.submitCommands(this.currentCmdBuffer, true); + Synchronization.INSTANCE.addCommandBuffer(this.currentCmdBuffer, true); this.currentCmdBuffer = null; } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 5e5a30f754..5ad86e5b31 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -338,9 +338,20 @@ private void submitFrame() { VkSubmitInfo submitInfo = VkSubmitInfo.calloc(stack); submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO); - submitInfo.waitSemaphoreCount(1); - submitInfo.pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))); - submitInfo.pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)); + Synchronization.INSTANCE.addWaitSemaphore(imageAvailableSemaphores.get(currentFrame)); + var waitSemaphores = Synchronization.INSTANCE.getWaitSemaphores(stack); + int waitSemaphoreCount = waitSemaphores.limit(); + IntBuffer waitDstStageMask = stack.mallocInt(waitSemaphoreCount); + + for (int i = 0; i < waitSemaphoreCount - 1; i++) { + waitDstStageMask.put(i, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + } + // Image available semaphore mask + waitDstStageMask.put(waitSemaphoreCount - 1, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + + submitInfo.pWaitSemaphores(waitSemaphores); + submitInfo.waitSemaphoreCount(waitSemaphores.limit()); + submitInfo.pWaitDstStageMask(waitDstStageMask); submitInfo.pSignalSemaphores(stack.longs(renderFinishedSemaphores.get(currentFrame))); submitInfo.pCommandBuffers(stack.pointers(currentCmdBuffer)); @@ -370,6 +381,9 @@ private void submitFrame() { throw new RuntimeException("Failed to present rendered frame: %s".formatted(VkResult.decode(vkResult))); } + // Semaphore waited command buffers will be reset right after waiting this command buffer's fence + Synchronization.INSTANCE.scheduleCbReset(); + currentFrame = (currentFrame + 1) % framesNum; } } @@ -414,10 +428,10 @@ public void submitUploads() { if (transferCb.isRecording()) { final var transferQueue = DeviceManager.getTransferQueue(); try (MemoryStack stack = MemoryStack.stackPush()) { - transferCb.submitCommands(stack, transferQueue.vkQueue(), false); + transferCb.submitCommands(stack, transferQueue.vkQueue(), true); } - Synchronization.INSTANCE.addCommandBuffer(transferCb); + Synchronization.INSTANCE.addCommandBuffer(transferCb, true); transferCbs.set(currentFrame, transferQueue.getCommandPool().getCommandBuffer()); } diff --git a/src/main/java/net/vulkanmod/vulkan/Synchronization.java b/src/main/java/net/vulkanmod/vulkan/Synchronization.java index 609052db31..8a1b971d82 100644 --- a/src/main/java/net/vulkanmod/vulkan/Synchronization.java +++ b/src/main/java/net/vulkanmod/vulkan/Synchronization.java @@ -1,8 +1,11 @@ package net.vulkanmod.vulkan; +import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.util.VUtil; +import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkDevice; @@ -10,6 +13,9 @@ import static org.lwjgl.vulkan.VK10.*; +/*** + * Synchronization utility to sync in frame ops that need to be completed before executing main cmd buffer. + */ public class Synchronization { private static final int ALLOCATION_SIZE = 50; @@ -18,15 +24,28 @@ public class Synchronization { private final LongBuffer fences; private int idx = 0; - private ObjectArrayList commandBuffers = new ObjectArrayList<>(); + private final ObjectArrayList fenceCbs = new ObjectArrayList<>(); + + private final LongArrayList semaphores = new LongArrayList(); + private final ObjectArrayList semaphoreCbs = new ObjectArrayList<>(); Synchronization(int allocSize) { this.fences = MemoryUtil.memAllocLong(allocSize); } - public synchronized void addCommandBuffer(CommandPool.CommandBuffer commandBuffer) { - this.addFence(commandBuffer.getFence()); - this.commandBuffers.add(commandBuffer); + public void addCommandBuffer(CommandPool.CommandBuffer commandBuffer) { + addCommandBuffer(commandBuffer, false); + } + + public synchronized void addCommandBuffer(CommandPool.CommandBuffer commandBuffer, boolean useSemaphore) { + if (!useSemaphore) { + this.addFence(commandBuffer.getFence()); + this.fenceCbs.add(commandBuffer); + } + else { + this.semaphores.add(commandBuffer.getSemaphore()); + this.semaphoreCbs.add(commandBuffer); + } } public synchronized void addFence(long fence) { @@ -47,13 +66,37 @@ public synchronized void waitFences() { vkWaitForFences(device, fences, true, VUtil.UINT64_MAX); - this.commandBuffers.forEach(CommandPool.CommandBuffer::reset); - this.commandBuffers.clear(); + this.fenceCbs.forEach(CommandPool.CommandBuffer::reset); + this.fenceCbs.clear(); fences.limit(ALLOCATION_SIZE); idx = 0; } + public synchronized void addWaitSemaphore(long semaphore) { + this.semaphores.add(semaphore); + } + + public LongBuffer getWaitSemaphores(MemoryStack stack) { + var buffer = stack.mallocLong(this.semaphores.size()) + .put(this.semaphores.elements(), 0, this.semaphores.size()); + buffer.flip(); + + this.semaphores.clear(); + return buffer; + } + + public void scheduleCbReset() { + final var frameSemaphoreCbs = this.semaphoreCbs.clone(); + MemoryManager.getInstance().addFrameOp( + () -> { + frameSemaphoreCbs.forEach(CommandPool.CommandBuffer::reset); + } + ); + + this.semaphoreCbs.clear(); + } + public static void waitFence(long fence) { VkDevice device = Vulkan.getVkDevice(); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java index 8500e8da47..bf30ebec68 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java @@ -130,6 +130,10 @@ public long getFence() { return fence; } + public long getSemaphore() { + return semaphore; + } + public boolean isSubmitted() { return submitted; } diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index 3e5b07fcea..6169ed7fb9 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -47,9 +47,13 @@ public synchronized CommandPool.CommandBuffer beginCommands() { this.commandPool = new CommandPool(familyIndex); } - public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { + public long submitCommands(CommandPool.CommandBuffer commandBuffer) { + return submitCommands(commandBuffer, false); + } + + public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer, boolean useSemaphore) { try (MemoryStack stack = stackPush()) { - return commandBuffer.submitCommands(stack, vkQueue, false); + return commandBuffer.submitCommands(stack, vkQueue, useSemaphore); } } From e0cf951f0ea84f36f901b65ac2a7b83de5500914 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 16:35:26 +0100 Subject: [PATCH 119/177] Add version string --- .../java/net/vulkanmod/render/profiling/ProfilerOverlay.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index 97cf7e4302..ed85d1a977 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -1,10 +1,12 @@ package net.vulkanmod.render.profiling; import com.google.common.base.Strings; +import net.minecraft.SharedConstants; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; +import net.vulkanmod.Initializer; import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.build.task.ChunkTask; @@ -96,6 +98,7 @@ private List buildInfo() { List list = new ArrayList<>(); list.add(""); list.add("Profiler"); + list.add("Version: %s %s ".formatted(Initializer.getVersion(), SharedConstants.getCurrentVersion().name())); this.updateResults(); From 1447cf4db865c9f2c9c7fe3dc936b7f114f3fb92 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 17:55:53 +0100 Subject: [PATCH 120/177] Fix swapchain recreation issues on some device --- .../net/vulkanmod/vulkan/framebuffer/SwapChain.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 115e8311ed..9fe29eec76 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -123,18 +123,16 @@ private void createSwapChain() { createInfo.presentMode(presentMode); createInfo.clipped(true); - createInfo.oldSwapchain(this.swapChainId); + if (this.swapChainId != VK_NULL_HANDLE) { + this.swapChainImages.forEach(image -> vkDestroyImageView(device, image.getImageView(), null)); + vkDestroySwapchainKHR(device, this.swapChainId, null); + } LongBuffer pSwapChain = stack.longs(VK_NULL_HANDLE); int result = vkCreateSwapchainKHR(device, createInfo, null, pSwapChain); Vulkan.checkResult(result, "Failed to create swap chain"); - if (this.swapChainId != VK_NULL_HANDLE) { - this.swapChainImages.forEach(image -> vkDestroyImageView(device, image.getImageView(), null)); - vkDestroySwapchainKHR(device, this.swapChainId, null); - } - this.swapChainId = pSwapChain.get(0); vkGetSwapchainImagesKHR(device, this.swapChainId, imageCount, null); From 8bd1b9d490dd130f1a4e8d5b24bcc2c6f2d8dc74 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 4 Jan 2026 17:57:53 +0100 Subject: [PATCH 121/177] Fix dynamic rendering missing layout transition --- .../vulkan/framebuffer/RenderPass.java | 111 ++++++++++++------ 1 file changed, 73 insertions(+), 38 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java index 56300de442..3172e51b0c 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java @@ -54,17 +54,17 @@ private void createRenderPass() { if (colorAttachmentInfo != null) { VkAttachmentDescription colorAttachment = attachments.get(i); colorAttachment.format(colorAttachmentInfo.format) - .samples(VK_SAMPLE_COUNT_1_BIT) - .loadOp(colorAttachmentInfo.loadOp) - .storeOp(colorAttachmentInfo.storeOp) - .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) - .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) - .initialLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) - .finalLayout(colorAttachmentInfo.finalLayout); + .samples(VK_SAMPLE_COUNT_1_BIT) + .loadOp(colorAttachmentInfo.loadOp) + .storeOp(colorAttachmentInfo.storeOp) + .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) + .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) + .initialLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + .finalLayout(colorAttachmentInfo.finalLayout); VkAttachmentReference colorAttachmentRef = attachmentRefs.get(0) - .attachment(0) - .layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + .attachment(0) + .layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); subpass.colorAttachmentCount(1); subpass.pColorAttachments(VkAttachmentReference.calloc(1, stack).put(0, colorAttachmentRef)); @@ -76,49 +76,49 @@ private void createRenderPass() { if (depthAttachmentInfo != null) { VkAttachmentDescription depthAttachment = attachments.get(i); depthAttachment.format(depthAttachmentInfo.format) - .samples(VK_SAMPLE_COUNT_1_BIT) - .loadOp(depthAttachmentInfo.loadOp) - .storeOp(depthAttachmentInfo.storeOp) - .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) - .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) - .initialLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) - .finalLayout(depthAttachmentInfo.finalLayout); + .samples(VK_SAMPLE_COUNT_1_BIT) + .loadOp(depthAttachmentInfo.loadOp) + .storeOp(depthAttachmentInfo.storeOp) + .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) + .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) + .initialLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) + .finalLayout(depthAttachmentInfo.finalLayout); VkAttachmentReference depthAttachmentRef = attachmentRefs.get(1) - .attachment(1) - .layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + .attachment(1) + .layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); subpass.pDepthStencilAttachment(depthAttachmentRef); } VkRenderPassCreateInfo renderPassInfo = VkRenderPassCreateInfo.calloc(stack); renderPassInfo.sType$Default() - .pAttachments(attachments) - .pSubpasses(subpass); + .pAttachments(attachments) + .pSubpasses(subpass); //Layout transition subpass depency switch (colorAttachmentInfo.finalLayout) { case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR -> { VkSubpassDependency.Buffer subpassDependencies = VkSubpassDependency.calloc(1, stack); subpassDependencies.get(0) - .srcSubpass(VK_SUBPASS_EXTERNAL) - .dstSubpass(0) - .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) - .dstStageMask(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT) - .srcAccessMask(0) - .dstAccessMask(0); + .srcSubpass(VK_SUBPASS_EXTERNAL) + .dstSubpass(0) + .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) + .dstStageMask(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT) + .srcAccessMask(0) + .dstAccessMask(0); renderPassInfo.pDependencies(subpassDependencies); } case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL -> { VkSubpassDependency.Buffer subpassDependencies = VkSubpassDependency.calloc(1, stack); subpassDependencies.get(0) - .srcSubpass(0) - .dstSubpass(VK_SUBPASS_EXTERNAL) - .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) - .dstStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) - .srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) - .dstAccessMask(VK_ACCESS_SHADER_READ_BIT); + .srcSubpass(0) + .dstSubpass(VK_SUBPASS_EXTERNAL) + .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) + .dstStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) + .srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) + .dstAccessMask(VK_ACCESS_SHADER_READ_BIT); renderPassInfo.pDependencies(subpassDependencies); } @@ -137,11 +137,17 @@ private void createRenderPass() { public void beginRenderPass(VkCommandBuffer commandBuffer, long framebufferId, MemoryStack stack) { if (colorAttachmentInfo != null - && framebuffer.getColorAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) - framebuffer.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + && framebuffer.getColorAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + { + framebuffer.getColorAttachment() + .transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + } if (depthAttachmentInfo != null - && framebuffer.getDepthAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) - framebuffer.getDepthAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + && framebuffer.getDepthAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) + { + framebuffer.getDepthAttachment() + .transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + } VkRenderPassBeginInfo renderPassInfo = VkRenderPassBeginInfo.calloc(stack); renderPassInfo.sType$Default(); @@ -167,6 +173,22 @@ public void beginRenderPass(VkCommandBuffer commandBuffer, long framebufferId, M public void endRenderPass(VkCommandBuffer commandBuffer) { if (Vulkan.DYNAMIC_RENDERING) { KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); + + try (MemoryStack stack = MemoryStack.stackPush()) { + if (colorAttachmentInfo != null + && framebuffer.getColorAttachment().getCurrentLayout() != this.colorAttachmentInfo.finalLayout) + { + framebuffer.getColorAttachment() + .transitionImageLayout(stack, commandBuffer, this.colorAttachmentInfo.finalLayout); + } + if (depthAttachmentInfo != null + && framebuffer.getDepthAttachment().getCurrentLayout() != this.depthAttachmentInfo.finalLayout) + { + framebuffer.getDepthAttachment() + .transitionImageLayout(stack, commandBuffer, this.depthAttachmentInfo.finalLayout); + } + } + } else { vkCmdEndRenderPass(commandBuffer); @@ -182,12 +204,25 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { } public void beginDynamicRendering(VkCommandBuffer commandBuffer, MemoryStack stack) { + if (colorAttachmentInfo != null + && framebuffer.getColorAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + { + framebuffer.getColorAttachment() + .transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + } + if (depthAttachmentInfo != null + && framebuffer.getDepthAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) + { + framebuffer.getDepthAttachment() + .transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + } + VkRect2D renderArea = VkRect2D.malloc(stack); renderArea.offset().set(0, 0); renderArea.extent().set(framebuffer.getWidth(), framebuffer.getHeight()); VkClearValue.Buffer clearValues = VkClearValue.malloc(2, stack); - clearValues.get(0).color().float32(stack.floats(0.0f, 0.0f, 0.0f, 1.0f)); + clearValues.get(0).color().float32(VRenderSystem.clearColor); clearValues.get(1).depthStencil().set(1.0f, 0); VkRenderingInfo renderingInfo = VkRenderingInfo.calloc(stack); @@ -208,7 +243,7 @@ public void beginDynamicRendering(VkCommandBuffer commandBuffer, MemoryStack sta renderingInfo.pColorAttachments(colorAttachment); } - //Depth attachment + // Depth attachment if (depthAttachmentInfo != null) { VkRenderingAttachmentInfo depthAttachment = VkRenderingAttachmentInfo.calloc(stack); depthAttachment.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR); From f375b8f1c747aca37569403f5640f1479dfa269e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 01:38:11 +0100 Subject: [PATCH 122/177] Use automatic image indexing --- .../vulkanmod/render/engine/EGlProgram.java | 5 +- .../net/vulkanmod/vulkan/shader/Pipeline.java | 59 +++++++++++-------- .../vulkan/shader/converter/GLSLParser.java | 3 +- 3 files changed, 38 insertions(+), 29 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/EGlProgram.java b/src/main/java/net/vulkanmod/render/engine/EGlProgram.java index 9bc7905d99..11613d4f32 100644 --- a/src/main/java/net/vulkanmod/render/engine/EGlProgram.java +++ b/src/main/java/net/vulkanmod/render/engine/EGlProgram.java @@ -7,7 +7,6 @@ import com.mojang.logging.LogUtils; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.texture.VTextureSelector; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -56,7 +55,7 @@ public void setupUniforms(Pipeline pipeline, List= this.nextBinding) this.nextBinding = binding + 1; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java index 8ba2352d81..cbd3b18040 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java @@ -442,6 +442,7 @@ public UBO[] createUBOs() { public List getSamplerList() { List imageDescriptors = new ObjectArrayList<>(); + int imageIdx = 0; for (Sampler sampler : this.samplers) { int descriptorType = switch (sampler.type) { @@ -449,8 +450,8 @@ public List getSamplerList() { case I_SAMPLER_BUFFER -> VK11.VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; }; - int imageIdx = VTextureSelector.getTextureIdx(sampler.id); imageDescriptors.add(new ImageDescriptor(sampler.binding, "sampler2D", sampler.id, imageIdx, descriptorType)); + imageIdx++; } return imageDescriptors; From 2eabf9ac79e68384ce988405c323c93a57a0eb38 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 12:51:21 +0100 Subject: [PATCH 123/177] Prevent crash if texture id is invalid --- src/main/java/net/vulkanmod/gl/VkGlTexture.java | 10 +++++++--- .../net/vulkanmod/render/engine/VkCommandEncoder.java | 6 +++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/gl/VkGlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java index 5b4e173b47..d1a3ecec00 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -1,6 +1,7 @@ package net.vulkanmod.gl; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; +import net.vulkanmod.Initializer; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.texture.ImageUtil; import net.vulkanmod.vulkan.texture.SamplerManager; @@ -43,11 +44,14 @@ public static void bindTexture(int id) { boundTextureId = id; boundTexture = map.get(id); - if (id <= 0) + if (id <= 0) { return; + } - if (boundTexture == null) - throw new NullPointerException("bound texture is null"); + if (boundTexture == null) { + Initializer.LOGGER.error("Invalid id({}) value", id); + return; + } VulkanImage vulkanImage = boundTexture.vulkanImage; if (vulkanImage != null) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index 0cbf679d24..f15820f5e5 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -819,8 +819,12 @@ public void setupUniforms(VkRenderPass renderPass) { break; } - GlStateManager._activeTexture(33984 + samplerIndex); VkGpuTexture gpuTexture = textureView.texture(); + if (gpuTexture.isClosed()) { + break; + } + + GlStateManager._activeTexture(33984 + samplerIndex); GlStateManager._bindTexture(gpuTexture.id); GlStateManager._texParameter(GL11.GL_TEXTURE_2D, 33084, textureView.baseMipLevel()); From 00f3013226706b354610b2b57a95e3379eac363b Mon Sep 17 00:00:00 2001 From: Icyllis Milica Date: Fri, 19 Dec 2025 20:07:09 +0800 Subject: [PATCH 124/177] Fix 1 leak --- .../java/net/vulkanmod/vulkan/shader/DescriptorSets.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java index 3bfb14bca9..76d296c47a 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -25,8 +25,8 @@ public class DescriptorSets { private final Pipeline pipeline; private int poolSize = 10; - private long descriptorPool; - private LongBuffer sets; + private long descriptorPool = VK_NULL_HANDLE; + private long[] sets; private long currentSet; private int currentIdx = -1; @@ -149,7 +149,7 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) // Check pool size checkPoolSize(stack); - this.currentSet = this.sets.get(this.currentIdx); + this.currentSet = this.sets[this.currentIdx]; VkWriteDescriptorSet.Buffer descriptorWrites = VkWriteDescriptorSet.calloc(pipeline.buffers.size() + pipeline.imageDescriptors.size(), stack); VkDescriptorBufferInfo.Buffer[] bufferInfos = new VkDescriptorBufferInfo.Buffer[pipeline.buffers.size()]; @@ -229,7 +229,8 @@ private void createDescriptorSets(MemoryStack stack) { allocInfo.descriptorPool(descriptorPool); allocInfo.pSetLayouts(layout); - this.sets = MemoryUtil.memAllocLong(this.poolSize); + // Not hotspot code, use heap array + this.sets = new long[this.poolSize]; int result = vkAllocateDescriptorSets(DEVICE, allocInfo, this.sets); if (result != VK_SUCCESS) { From 397186af1dec1079124a6cb3be0aed40ffad5251 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 18:46:14 +0100 Subject: [PATCH 125/177] Fix out of stack memory error --- .../java/net/vulkanmod/vulkan/shader/DescriptorSets.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java index 76d296c47a..457ad51b8c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -218,16 +218,16 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) } private void createDescriptorSets(MemoryStack stack) { - LongBuffer layout = stack.mallocLong(this.poolSize); + LongBuffer layouts = MemoryUtil.memAllocLong(this.poolSize); for (int i = 0; i < this.poolSize; ++i) { - layout.put(i, pipeline.descriptorSetLayout); + layouts.put(i, pipeline.descriptorSetLayout); } VkDescriptorSetAllocateInfo allocInfo = VkDescriptorSetAllocateInfo.calloc(stack); allocInfo.sType$Default(); allocInfo.descriptorPool(descriptorPool); - allocInfo.pSetLayouts(layout); + allocInfo.pSetLayouts(layouts); // Not hotspot code, use heap array this.sets = new long[this.poolSize]; @@ -236,6 +236,8 @@ private void createDescriptorSets(MemoryStack stack) { if (result != VK_SUCCESS) { throw new RuntimeException("Failed to allocate descriptor sets. Result:" + result); } + + MemoryUtil.memFree(layouts); } private void createDescriptorPool(MemoryStack stack) { From 82330c28d91905f92e801d9db7ee900d22bff229 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 18:48:50 +0100 Subject: [PATCH 126/177] Add uniform types --- .../vulkanmod/vulkan/shader/layout/Uniform.java | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java index 8c1509df14..ca4200ec48 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java @@ -41,7 +41,7 @@ void update(long ptr) { public static Uniform createField(Info info) { return switch (info.type) { - case "mat4", "vec3", "vec4", "vec2" -> new Uniform(info); + case "mat4", "vec3", "vec4", "vec2", "ivec3", "ivec2" -> new Uniform(info); case "mat3" -> new Mat3(info); case "float" -> new Vec1f(info); case "int" -> new Vec1i(info); @@ -63,7 +63,6 @@ public String toString() { return String.format("%s: %s offset: %d", info.type, info.name, info.offset); } - //TODO public static Info createUniformInfo(String type, String name, int count) { return switch (type) { case "matrix4x4" -> new Info("mat4", name, 4, 16); @@ -75,7 +74,14 @@ public static Info createUniformInfo(String type, String name, int count) { default -> throw new IllegalStateException("Unexpected value: " + count); }; - case "int" -> new Info("int", name, 1, 1); + case "int" -> switch (count) { + case 4 -> new Info("ivec4", name, 4, 4); + case 3 -> new Info("ivec3", name, 4, 3); + case 2 -> new Info("ivec2", name, 2, 2); + case 1 -> new Info("int", name, 1, 1); + + default -> throw new IllegalStateException("Unexpected value: " + count); + }; default -> throw new RuntimeException("not admitted type.."); }; } @@ -86,8 +92,8 @@ public static Info createUniformInfo(String type, String name) { case "mat3" -> new Info(type, name, 4, 9); case "vec4" -> new Info(type, name, 4, 4); - case "vec3" -> new Info(type, name, 4, 3); - case "vec2" -> new Info(type, name, 2, 2); + case "vec3", "ivec3" -> new Info(type, name, 4, 3); + case "vec2", "ivec2" -> new Info(type, name, 2, 2); case "float", "int" -> new Info(type, name, 1, 1); From d54f3cbc000f7e82a48125895032172a5124cd1a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 18:49:43 +0100 Subject: [PATCH 127/177] Add workaround for glsl reserved keywords --- .../net/vulkanmod/vulkan/shader/converter/GLSLParser.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java index cbd3b18040..8a0fafbaf3 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java @@ -403,6 +403,10 @@ public String getOutput(Stage stage) { } } + // Rename glsl reserved keywords + stringBuilder.append("#define sampler sampler1\n\n"); + stringBuilder.append("#define sample sample1\n\n"); + for (int i = 1; i < stream.size(); i++) { node = stream.get(i); stringBuilder.append(node.value); From d5fe0575475bc5f3a68115897bb0a06e5ed0e239 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 18:50:02 +0100 Subject: [PATCH 128/177] Remove debug code --- .../java/net/vulkanmod/render/engine/VkCommandEncoder.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index f15820f5e5..aaeab2c0fe 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -704,10 +704,6 @@ public void drawFromBuffers(VkRenderPass renderPass, int vertexOffset, int first vertexOffset = 0; } - if (renderPipeline.getVertexFormatMode() == VertexFormat.Mode.TRIANGLES) { - System.nanoTime(); - } - VkCommandBuffer vkCommandBuffer = Renderer.getCommandBuffer(); VkGpuBuffer vertexBuffer = (VkGpuBuffer)renderPass.vertexBuffers[0]; try (MemoryStack stack = stackPush()) { From 4a76da27e381329814388cc70f851e5e35ce479d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 18:56:09 +0100 Subject: [PATCH 129/177] Update icon identifier --- .../assets/vulkanmod/{Vlogo.png => vlogo.png} | Bin src/main/resources/fabric.mod.json | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename src/main/resources/assets/vulkanmod/{Vlogo.png => vlogo.png} (100%) diff --git a/src/main/resources/assets/vulkanmod/Vlogo.png b/src/main/resources/assets/vulkanmod/vlogo.png similarity index 100% rename from src/main/resources/assets/vulkanmod/Vlogo.png rename to src/main/resources/assets/vulkanmod/vlogo.png diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index fde6241796..9a0c18d82c 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -13,7 +13,7 @@ "sources": "https://github.com/xCollateral/VulkanMod" }, - "icon": "assets/vulkanmod/Vlogo.png", + "icon": "assets/vulkanmod/vlogo.png", "environment": "client", "entrypoints": { From a2a2ee842368895f67240a93a7a6db92b09347e3 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 5 Jan 2026 19:06:51 +0100 Subject: [PATCH 130/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ba55088d98..4f3df43d09 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.5.7-dev +mod_version = 0.5.8-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From 3f293edd503427587a42c2dba609bacfdc65dd2c Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 6 Jan 2026 20:18:45 +0100 Subject: [PATCH 131/177] Bind light texture on terrain rendering --- .../java/net/vulkanmod/render/chunk/WorldRenderer.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 6bbffe097d..2d643076d4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -345,10 +345,11 @@ public void renderSectionLayer(TerrainRenderType renderType, double camX, double renderer.bindGraphicsPipeline(pipeline); TextureManager textureManager = Minecraft.getInstance().getTextureManager(); - AbstractTexture abstractTexture = textureManager.getTexture(TextureAtlas.LOCATION_BLOCKS); - abstractTexture.setUseMipmaps(true); - var texView = abstractTexture.getTextureView(); - RenderSystem.setShaderTexture(0, texView); + AbstractTexture blockAtlasTexture = textureManager.getTexture(TextureAtlas.LOCATION_BLOCKS); + blockAtlasTexture.setUseMipmaps(true); + + RenderSystem.setShaderTexture(0, blockAtlasTexture.getTextureView()); + RenderSystem.setShaderTexture(2, Minecraft.getInstance().gameRenderer.lightTexture().getTextureView()); VTextureSelector.bindShaderTextures(pipeline); From 45b97c303aa00aa44e08a173c3b7b914218b6957 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 25 Jan 2026 17:05:38 +0100 Subject: [PATCH 132/177] Mitigate translucency sorting issue --- .../java/net/vulkanmod/render/chunk/WorldRenderer.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 2d643076d4..8191d48af2 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -400,7 +400,6 @@ private void sortTranslucentSections(double camX, double camY, double camZ) { double d0 = camX - this.xTransparentOld; double d1 = camY - this.yTransparentOld; double d2 = camZ - this.zTransparentOld; -// if (d0 * d0 + d1 * d1 + d2 * d2 > 1.0D) { if (d0 * d0 + d1 * d1 + d2 * d2 > 2.0D) { this.xTransparentOld = camX; this.yTransparentOld = camY; @@ -409,12 +408,13 @@ private void sortTranslucentSections(double camX, double camY, double camZ) { Iterator iterator = this.sectionGraph.getSectionQueue().iterator(false); - while (iterator.hasNext() && j < 15) { + while (iterator.hasNext() && j < 200) { RenderSection section = iterator.next(); - section.resortTransparency(this.taskDispatcher); - ++j; + if (!section.isCompletelyEmpty()) { + ++j; + } } } From 7bf69cedfd709c526d7d3d1033b78a97f04890f2 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 25 Jan 2026 17:07:07 +0100 Subject: [PATCH 133/177] Add missing token --- src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java index 787311453d..c6c2abca63 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java @@ -133,6 +133,7 @@ public Token nextToken() { case '!' -> new Token(Token.TokenType.OPERATOR, "!"); case '&' -> new Token(Token.TokenType.OPERATOR, "&"); case '|' -> new Token(Token.TokenType.OPERATOR, "|"); + case '^' -> new Token(Token.TokenType.OPERATOR, "^"); case '?' -> new Token(Token.TokenType.OPERATOR, "?"); case '[' -> new Token(Token.TokenType.OPERATOR, "["); case ']' -> new Token(Token.TokenType.OPERATOR, "]"); From fdbf57f1dd5ce28269491fb680115271e7122808 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 25 Jan 2026 17:14:23 +0100 Subject: [PATCH 134/177] Move stack size setting earlier --- .../java/net/vulkanmod/config/Platform.java | 3 --- .../net/vulkanmod/mixin/fix/MainMixin.java | 18 ++++++++++++++++++ src/main/resources/vulkanmod.mixins.json | 2 ++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 src/main/java/net/vulkanmod/mixin/fix/MainMixin.java diff --git a/src/main/java/net/vulkanmod/config/Platform.java b/src/main/java/net/vulkanmod/config/Platform.java index 38914708da..9e55146420 100644 --- a/src/main/java/net/vulkanmod/config/Platform.java +++ b/src/main/java/net/vulkanmod/config/Platform.java @@ -12,9 +12,6 @@ public abstract class Platform { private static final String activeDE = determineDE(); public static void init() { - // Increase stack size to 256 KB to prevent out of stack error on nvidia driver - Configuration.STACK_SIZE.set(256); - GLFW.glfwInitHint(GLFW_PLATFORM, activePlat); LOGGER.info("Selecting Platform: {}", getStringFromPlat(activePlat)); LOGGER.info("GLFW: {}", GLFW.glfwGetVersionString()); diff --git a/src/main/java/net/vulkanmod/mixin/fix/MainMixin.java b/src/main/java/net/vulkanmod/mixin/fix/MainMixin.java new file mode 100644 index 0000000000..97ccccdfe2 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/fix/MainMixin.java @@ -0,0 +1,18 @@ +package net.vulkanmod.mixin.fix; + +import net.minecraft.client.main.Main; +import org.lwjgl.system.Configuration; +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(Main.class) +public class MainMixin { + + @Inject(method = "main", at=@At("HEAD")) + private static void inj1(String[] strings, CallbackInfo ci) { + // Increase stack size to 256 KB to prevent out of stack error on nvidia driver + Configuration.STACK_SIZE.set(256); + } +} diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index a9f1f7eb05..73ec0d9027 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -29,6 +29,8 @@ "debug.DebugScreenEntriesM", "debug.KeyboardHandlerM", + "fix.MainMixin", + "matrix.Matrix4fM", "matrix.PoseAccessor", From 4ad7a972389b4162c57e8d2ceaf7883280c380fb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 26 Jan 2026 15:02:47 +0100 Subject: [PATCH 135/177] Improve frame flow --- .../net/vulkanmod/gl/VkGlFramebuffer.java | 2 +- .../mixin/render/frame/MinecraftMixin.java | 20 ++---- .../mixin/texture/update/GameRendererM.java | 27 ------- .../render/engine/VkCommandEncoder.java | 38 +++++++--- .../java/net/vulkanmod/vulkan/Renderer.java | 70 +++++++++++++------ .../vulkan/framebuffer/Framebuffer.java | 6 -- .../vulkan/pass/DefaultMainPass.java | 8 +-- src/main/resources/vulkanmod.mixins.json | 1 - 8 files changed, 85 insertions(+), 87 deletions(-) delete mode 100644 src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java diff --git a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java index fffacde972..7048f38cd5 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java @@ -157,7 +157,7 @@ public static VkGlFramebuffer getFramebuffer(int id) { } boolean beginRendering() { - return Renderer.getInstance().beginRendering(this.renderPass, this.framebuffer); + return Renderer.getInstance().beginRenderPass(this.renderPass, this.framebuffer); } public void setAttachmentTexture(int attachment, int id) { diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java index 1298815bf9..a53035f3d4 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java @@ -4,10 +4,10 @@ import com.mojang.blaze3d.systems.CommandEncoder; import com.mojang.blaze3d.textures.GpuTexture; import net.minecraft.client.Minecraft; +import net.vulkanmod.render.texture.ImageUploadHelper; import net.vulkanmod.vulkan.Renderer; import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -16,23 +16,17 @@ @Mixin(Minecraft.class) public class MinecraftMixin { - @Shadow public boolean noRender; - @Inject(method = "runTick", at = @At(value = "HEAD")) - private void preFrameOps(boolean bl, CallbackInfo ci) { - Renderer.getInstance().preInitFrame(); - } - - //Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/CommandEncoder;clearColorAndDepthTextures(Lcom/mojang/blaze3d/textures/GpuTexture;ILcom/mojang/blaze3d/textures/GpuTexture;D)V")) - private void beginRender(CommandEncoder instance, GpuTexture gpuTexture, int i, GpuTexture gpuTexture2, double v) { + private void beginFrame(boolean bl, CallbackInfo ci) { Renderer.getInstance().beginFrame(); Renderer.clearAttachments(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_COLOR_BUFFER_BIT); } - @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At(value = "RETURN")) - private void beginRender2(CallbackInfo ci) { - Renderer.getInstance().beginFrame(); + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/CommandEncoder;clearColorAndDepthTextures(Lcom/mojang/blaze3d/textures/GpuTexture;ILcom/mojang/blaze3d/textures/GpuTexture;D)V")) + private void redirectClear(CommandEncoder instance, GpuTexture gpuTexture, int i, GpuTexture gpuTexture2, double v) { + // Remove framebuffer clear as it's not needed + + ImageUploadHelper.INSTANCE.submitCommands(); } @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen()V")) diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java b/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java deleted file mode 100644 index bb0ce2b696..0000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/update/GameRendererM.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.vulkanmod.mixin.texture.update; - -import net.minecraft.client.DeltaTracker; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GameRenderer; -import net.vulkanmod.render.texture.ImageUploadHelper; -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; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(GameRenderer.class) -public abstract class GameRendererM { - - @Shadow - @Final - Minecraft minecraft; - - @Inject(method = "render", at = @At("HEAD")) - private void onRender(DeltaTracker deltaTracker, boolean bl, CallbackInfo ci) { - if (this.minecraft.noRender || !(bl && this.minecraft.level != null && this.minecraft.isGameLoadFinished())) { - ImageUploadHelper.INSTANCE.submitCommands(); - } - } -} diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index aaeab2c0fe..13bcaa8dbf 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -142,19 +142,36 @@ public RenderPass createRenderPass(Supplier supplier, GpuTextureView col } @Override - public void clearColorTexture(GpuTexture colorAttachment, int color) { + public void clearColorTexture(GpuTexture colorAttachment, int clearColor) { if (this.inRenderPass) { throw new IllegalStateException("Close the existing render pass before creating a new one!"); } else if (Renderer.isRecording()) { - VkGpuTexture vkGpuTexture = (VkGpuTexture) colorAttachment; - VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, framebufferId); - VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, vkGpuTexture.glId(), 0); + if (Minecraft.getInstance().getMainRenderTarget().getColorTexture() == colorAttachment) { + Renderer.getInstance().getMainPass().rebindMainTarget(); + + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + Renderer.clearAttachments(0x4000); + } + else { + VkGpuTexture vkGpuTexture = (VkGpuTexture) colorAttachment; + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, framebufferId); + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, vkGpuTexture.glId(), 0); + + VkGlFramebuffer.beginRendering(VkGlFramebuffer.getFramebuffer(framebufferId)); + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + Renderer.clearAttachments(0x4000); + Renderer.getInstance().endRenderPass(); - VkGlFramebuffer.beginRendering(VkGlFramebuffer.getFramebuffer(framebufferId)); - VRenderSystem.setClearColor(ARGB.redFloat(color), ARGB.greenFloat(color), ARGB.blueFloat(color), ARGB.alphaFloat(color)); - Renderer.clearAttachments(16384); - Renderer.getInstance().endRenderPass(); + VkFbo fbo = ((VkGpuTexture)colorAttachment).getFbo(null); + + ((VkGpuTexture) colorAttachment).setClearColor(clearColor); + + Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); + if (boundFramebuffer != null && boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage()) { + fbo.clearAttachments(); + } + } } else { GraphicsQueue graphicsQueue = DeviceManager.getGraphicsQueue(); @@ -171,14 +188,13 @@ else if (Renderer.isRecording()) { framebuffer.beginRenderPass(commandBuffer.handle, renderPass, stack); } - VRenderSystem.setClearColor(ARGB.redFloat(color), ARGB.greenFloat(color), ARGB.blueFloat(color), ARGB.alphaFloat(color)); - Renderer.clearAttachments(commandBuffer.handle, 16384); + VRenderSystem.setClearColor(ARGB.redFloat(clearColor), ARGB.greenFloat(clearColor), ARGB.blueFloat(clearColor), ARGB.alphaFloat(clearColor)); + Renderer.clearAttachments(commandBuffer.handle, 0x4000, 0, 0, framebuffer.getWidth(), framebuffer.getHeight()); renderPass.endRenderPass(commandBuffer.handle); long fence = graphicsQueue.submitCommands(commandBuffer); Synchronization.waitFence(fence); } - } @Override diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 5ad86e5b31..665f4911ea 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -86,7 +86,7 @@ public static int getCurrentImage() { private SwapChain swapChain; private int framesNum; - private List commandBuffers; + private List mainCommandBuffers; private ArrayList imageAvailableSemaphores; private ArrayList renderFinishedSemaphores; private ArrayList inFlightFences; @@ -100,6 +100,7 @@ public static int getCurrentImage() { private static int lastReset = -1; private VkCommandBuffer currentCmdBuffer; private boolean recordingCmds = false; + int recursion = 0; MainPass mainPass; @@ -136,11 +137,11 @@ private void init() { } private void allocateCommandBuffers() { - if (commandBuffers != null) { - commandBuffers.forEach(commandBuffer -> vkFreeCommandBuffers(device, Vulkan.getCommandPool(), commandBuffer)); + if (mainCommandBuffers != null) { + mainCommandBuffers.forEach(commandBuffer -> vkFreeCommandBuffers(device, Vulkan.getCommandPool(), commandBuffer)); } - commandBuffers = new ArrayList<>(framesNum); + mainCommandBuffers = new ArrayList<>(framesNum); try (MemoryStack stack = stackPush()) { VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); @@ -157,7 +158,7 @@ private void allocateCommandBuffers() { } for (int i = 0; i < framesNum; i++) { - commandBuffers.add(new VkCommandBuffer(pCommandBuffers.get(i), device)); + mainCommandBuffers.add(new VkCommandBuffer(pCommandBuffers.get(i), device)); } } @@ -232,10 +233,6 @@ public void preInitFrame() { } public void beginFrame() { - Profiler p = Profiler.getMainProfiler(); - p.pop(); - p.push("Frame_fence"); - if (swapChainUpdate) { recreateSwapChain(); swapChainUpdate = false; @@ -249,9 +246,22 @@ public void beginFrame() { } } - - if (skipRendering || recordingCmds) + if (skipRendering) { return; + } + + this.recursion++; + + // In case this is a recursive call end prev frame + if (this.recursion > 1) { + this.endFrame(); + } + + this.preInitFrame(); + + Profiler p = Profiler.getMainProfiler(); + p.pop(); + p.push("Frame_fence"); vkWaitForFences(device, inFlightFences.get(currentFrame), true, VUtil.UINT64_MAX); @@ -263,11 +273,10 @@ public void beginFrame() { resetDescriptors(); - currentCmdBuffer = commandBuffers.get(currentFrame); + currentCmdBuffer = mainCommandBuffers.get(currentFrame); vkResetCommandBuffer(currentCmdBuffer, 0); try (MemoryStack stack = stackPush()) { - IntBuffer pImageIndex = stack.mallocInt(1); int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, @@ -276,7 +285,7 @@ public void beginFrame() { if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) { swapChainUpdate = true; skipRendering = true; - beginFrame(); + this.beginFrame(); return; } else if (vkResult != VK_SUCCESS) { @@ -285,13 +294,13 @@ public void beginFrame() { imageIndex = pImageIndex.get(0); - this.beginRenderPass(stack); + this.beginMainRenderPass(stack); } p.pop(); } - private void beginRenderPass(MemoryStack stack) { + private void beginMainRenderPass(MemoryStack stack) { VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack); beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); @@ -313,6 +322,11 @@ public void endFrame() { if (skipRendering || !recordingCmds) return; + if (this.recursion == 0) { + return; + } + this.recursion--; + Profiler p = Profiler.getMainProfiler(); p.push("End_rendering"); @@ -418,7 +432,7 @@ public void flushCmds() { vkWaitForFences(device, inFlightFences.get(currentFrame), true, VUtil.UINT64_MAX); - this.beginRenderPass(stack); + this.beginMainRenderPass(stack); } } @@ -455,10 +469,17 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { VkGlFramebuffer.resetBoundFramebuffer(); } - public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) { - if (skipRendering || !recordingCmds) + public boolean beginRenderPass(RenderPass renderPass, Framebuffer framebuffer) { + // TODO: minimizing could trigger this preventing rendering (e.g. texture atlas uploads) + if (skipRendering) return false; + if (!recordingCmds) { + this.beginFrame(); + + recordingCmds = true; + } + if (this.boundFramebuffer != framebuffer) { this.endRenderPass(currentCmdBuffer); @@ -467,7 +488,12 @@ public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) { } this.boundFramebuffer = framebuffer; + this.boundRenderPass = renderPass; + + Renderer.setViewportState(0, 0, framebuffer.getWidth(), framebuffer.getHeight()); + Renderer.setScissor(0, 0, framebuffer.getWidth(), framebuffer.getHeight()); } + return true; } @@ -517,7 +543,7 @@ private void recreateSwapChain() { waitFences(); Vulkan.waitIdle(); - commandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0)); + mainCommandBuffers.forEach(commandBuffer -> vkResetCommandBuffer(commandBuffer, 0)); recordingCmds = false; swapChain.recreate(); @@ -671,11 +697,11 @@ public static void clearAttachments(VkCommandBuffer commandBuffer, int attachmen } public static void clearAttachments(int attachments, int width, int height) { - clearAttachments(INSTANCE.currentCmdBuffer, attachments, width ,height); + clearAttachments(INSTANCE.currentCmdBuffer, attachments, width , height); } public static void clearAttachments(int attachments, int x, int y, int width, int height) { - clearAttachments(INSTANCE.currentCmdBuffer, attachments, x, y, width ,height); + clearAttachments(INSTANCE.currentCmdBuffer, attachments, x, y, width , height); } public static void clearAttachments(VkCommandBuffer commandBuffer, int attachments, int width, int height) { diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java index 8a2d5ad09b..047da14368 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java @@ -122,12 +122,6 @@ public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass } else { renderPass.beginDynamicRendering(commandBuffer, stack); } - - Renderer.getInstance().setBoundRenderPass(renderPass); - Renderer.getInstance().setBoundFramebuffer(this); - - Renderer.setViewportState(0, 0, this.width, this.height); - Renderer.setScissor(0, 0, this.width, this.height); } protected long getFramebufferId(RenderPass renderPass) { diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index 44726df8d2..d382fa5634 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -64,7 +64,7 @@ public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { VulkanImage colorAttachment = framebuffer.getColorAttachment(); colorAttachment.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - framebuffer.beginRenderPass(commandBuffer, this.mainRenderPass, stack); + Renderer.getInstance().beginRenderPass(this.mainRenderPass, framebuffer); Renderer.setViewport(0, 0, framebuffer.getWidth(), framebuffer.getHeight(), stack); @@ -108,11 +108,7 @@ public void rebindMainTarget() { return; Renderer.getInstance().endRenderPass(commandBuffer); - - try (MemoryStack stack = MemoryStack.stackPush()) { - swapChain.beginRenderPass(commandBuffer, this.auxRenderPass, stack); - } - + Renderer.getInstance().beginRenderPass(this.auxRenderPass, swapChain); } @Override diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 73ec0d9027..fee540ab0f 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -84,7 +84,6 @@ "texture.mip.MipmapGeneratorM", "texture.image.NativeImageAccessor", - "texture.update.GameRendererM", "texture.update.MLightTexture", "texture.update.MSpriteContents", "texture.update.MTextureManager", From 4cd44e713982a1822e74f8afe4944ebd58402332 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:55:13 +0100 Subject: [PATCH 136/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 4f3df43d09..702efd9043 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.5.8-dev +mod_version = 0.5.9-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From abfdb11e36f3f9d6f0841bd9fbd8444df8641318 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:55:52 +0100 Subject: [PATCH 137/177] Update mc dependency versions --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 9a0c18d82c..5d5d0fdd0f 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,7 @@ "depends": { "fabricloader": ">=0.14.14", - "minecraft": ">=1.21.9" + "minecraft": ["1.21.9", "1.21.10"] }, "custom": { "fabric-renderer-api-v1:contains_renderer": true From 922114aca09d5c1c042467baace6ee526dcacbd5 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:56:25 +0100 Subject: [PATCH 138/177] Fix image path --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 917d9bdb6e..ef4118897b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# VulkanMod +# VulkanMod This is a fabric mod that introduces a brand new **Vulkan** based voxel rendering engine to **Minecraft java** in order to both replace the default OpenGL renderer and bring performance improvements. From 160fcb19d71b47c14e7f2a923b3a14fa8e45f8c5 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:50:03 +0100 Subject: [PATCH 139/177] Fix crash on clear when no framebuffer is bound --- .../java/net/vulkanmod/render/engine/VkCommandEncoder.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index 13bcaa8dbf..a932e0f57b 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -217,7 +217,7 @@ public void clearColorAndDepthTextures(GpuTexture colorAttachment, int clearColo ((VkGpuTexture) depthAttachment).setDepthClearValue((float) clearDepth); Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); - if (boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() + if (boundFramebuffer != null && boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() && boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) { fbo.clearAttachments(); @@ -238,7 +238,7 @@ public void clearColorAndDepthTextures(GpuTexture colorAttachment, int clearColo y0 = framebufferHeight - height - y0; Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); - if (boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() + if (boundFramebuffer != null && boundFramebuffer.getColorAttachment() == ((VkGpuTexture) colorAttachment).getVulkanImage() && boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) { Renderer.clearAttachments(0x4100, x0, y0, width, height); @@ -257,7 +257,7 @@ public void clearDepthTexture(GpuTexture depthAttachment, double clearDepth) { } else { Framebuffer boundFramebuffer = Renderer.getInstance().getBoundFramebuffer(); - if (boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) { + if (boundFramebuffer != null && boundFramebuffer.getDepthAttachment() == ((VkGpuTexture) depthAttachment).getVulkanImage()) { VRenderSystem.clearDepth(clearDepth); Renderer.clearAttachments(0x100); } From 5a4fa0441bcf48d9e9744991eeb8099f6be1993c Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:53:09 +0100 Subject: [PATCH 140/177] Refactor shader loading from path --- .../net/vulkanmod/render/PipelineManager.java | 5 ++- .../render/shader/ShaderLoadUtil.java | 41 ++++++++++++++----- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 9368e5ad1a..aa7d252696 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -48,10 +48,11 @@ private static void createBasicPipelines() { private static GraphicsPipeline createPipeline(String configName, VertexFormat vertexFormat) { Pipeline.Builder pipelineBuilder = new Pipeline.Builder(vertexFormat, configName); - JsonObject config = ShaderLoadUtil.getJsonConfig("basic", configName); + final String path = ShaderLoadUtil.resolveShaderPath("basic"); + JsonObject config = ShaderLoadUtil.getJsonConfig(path, configName); pipelineBuilder.parseBindings(config); - ShaderLoadUtil.loadShaders(pipelineBuilder, config, configName, "basic"); + ShaderLoadUtil.loadShaders(pipelineBuilder, config, configName, path); var pipeline = pipelineBuilder.createGraphicsPipeline(); diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index 2c7bb55673..0a224062f6 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -17,20 +17,34 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.HashSet; -import java.util.Map; import java.util.Set; public abstract class ShaderLoadUtil { - private static final String RESOURCES_PATH = SPIRVUtils.class.getResource("/assets/vulkanmod").toExternalForm(); + public static final String RESOURCES_PATH = SPIRVUtils.class.getResource("/assets/vulkanmod").toExternalForm(); + public static final String SHADERS_PATH = "%s/shaders/".formatted(RESOURCES_PATH); public static final Set REMAPPED_SHADERS = Sets.newHashSet("core/screenquad.vsh","core/rendertype_item_entity_translucent_cull.vsh"); + public static String resolveShaderPath(String path) { + return resolveShaderPath(SHADERS_PATH, path); + } + + public static String resolveShaderPath(String shaderPath, String path) { + return "%s%s".formatted(shaderPath, path); + } + public static void loadShaders(Pipeline.Builder pipelineBuilder, JsonObject config, String configName, String path) { String vertexShader = config.has("vertex") ? config.get("vertex").getAsString() : configName; String fragmentShader = config.has("fragment") ? config.get("fragment").getAsString() : configName; + if (vertexShader == null) { + vertexShader = configName; + } + if (fragmentShader == null) { + fragmentShader = configName; + } + vertexShader = removeNameSpace(vertexShader); fragmentShader = removeNameSpace(fragmentShader); @@ -50,9 +64,7 @@ public static void loadShader(Pipeline.Builder pipelineBuilder, String configNam } public static void loadShader(Pipeline.Builder pipelineBuilder, String configName, String path, String shaderName, SPIRVUtils.ShaderKind type) { - String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); - - String source = getShaderSource(basePath, configName, shaderName, type); + String source = getShaderSource(path, configName, shaderName, type); SPIRVUtils.SPIRV spirv = SPIRVUtils.compileShader(shaderName, source, type); @@ -91,7 +103,7 @@ public static JsonObject getJsonConfig(String path, String rendertype) { return null; } - String basePath = "%s/shaders/%s".formatted(RESOURCES_PATH, path); + String basePath = path; String configPath = "%s/%s/%s.json".formatted(basePath, rendertype, rendertype); InputStream stream; @@ -168,14 +180,17 @@ public static String getShaderSource(String path, ShaderType type) { } } - public static String getShaderSource(String basePath, String rendertype, String shaderName, SPIRVUtils.ShaderKind type) { + public static String getShaderSource(String path, String configName, String shaderName, SPIRVUtils.ShaderKind type) { String shaderExtension = switch (type) { case VERTEX_SHADER -> ".vsh"; case FRAGMENT_SHADER -> ".fsh"; + case COMPUTE_SHADER -> ".comp"; default -> throw new UnsupportedOperationException("shader type %s unsupported"); }; - String shaderPath = "/%s/%s".formatted(rendertype, rendertype); + String basePath = path; + + String shaderPath = "/%s/%s".formatted(configName, configName); String shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); InputStream stream; @@ -183,7 +198,13 @@ public static String getShaderSource(String basePath, String rendertype, String stream = getInputStream(shaderFile); if (stream == null) { - shaderPath = "/%s/%s".formatted(rendertype, shaderName); + shaderPath = "/%s".formatted(shaderName); + shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); + stream = getInputStream(shaderFile); + } + + if (stream == null) { + shaderPath = "/%s/%s".formatted(configName, shaderName); shaderFile = "%s%s%s".formatted(basePath, shaderPath, shaderExtension); stream = getInputStream(shaderFile); } From 74a077aa425765fde825b7c6ce966ea5e691f777 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Feb 2026 18:54:26 +0100 Subject: [PATCH 141/177] Fix: clear framebuffer if needed before reading --- .../mixin/compatibility/PostPassM.java | 104 +++--------------- .../net/vulkanmod/render/engine/VkFbo.java | 2 +- 2 files changed, 14 insertions(+), 92 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java index 99580bb1dd..db125cafac 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java @@ -1,116 +1,38 @@ package net.vulkanmod.mixin.compatibility; -import com.mojang.blaze3d.ProjectionType; -import com.mojang.blaze3d.buffers.GpuBuffer; import com.mojang.blaze3d.buffers.GpuBufferSlice; -import com.mojang.blaze3d.buffers.Std140Builder; -import com.mojang.blaze3d.framegraph.FrameGraphBuilder; -import com.mojang.blaze3d.framegraph.FramePass; -import com.mojang.blaze3d.pipeline.RenderPipeline; -import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.resource.ResourceHandle; -import com.mojang.blaze3d.systems.CommandEncoder; -import com.mojang.blaze3d.systems.RenderPass; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.textures.GpuTextureView; import com.mojang.blaze3d.vertex.*; -import com.mojang.datafixers.util.Pair; -import net.minecraft.client.renderer.MappableRingBuffer; import net.minecraft.client.renderer.PostPass; -import net.minecraft.resources.ResourceLocation; import net.vulkanmod.render.engine.*; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; import java.util.Map; -import java.util.OptionalDouble; -import java.util.OptionalInt; @Mixin(PostPass.class) public abstract class PostPassM { - @Shadow @Final private String name; @Shadow @Final private List inputs; - @Shadow @Final private ResourceLocation outputTargetId; - @Shadow @Final private RenderPipeline pipeline; - @Shadow @Final private MappableRingBuffer infoUbo; - @Shadow @Final private Map customUniforms; - /** - * @author - * @reason - */ - @Overwrite - public void addToFrame(FrameGraphBuilder frameGraphBuilder, Map> map, GpuBufferSlice gpuBufferSlice) { - FramePass framePass = frameGraphBuilder.addPass(this.name); + @Inject(method = "method_67884", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/GpuDevice;createCommandEncoder()Lcom/mojang/blaze3d/systems/CommandEncoder;")) + private void transitionLayouts(ResourceHandle resourceHandle, GpuBufferSlice gpuBufferSlice, Map map, + CallbackInfo ci) { + Renderer.getInstance().endRenderPass(); - for (PostPass.Input input : this.inputs) { - input.addToPass(framePass, map); - } - - ResourceHandle resourceHandle = (ResourceHandle)map.computeIfPresent( - this.outputTargetId, (resourceLocation, resourceHandlex) -> framePass.readsAndWrites(resourceHandlex) - ); - if (resourceHandle == null) { - throw new IllegalStateException("Missing handle for target " + this.outputTargetId); - } else { - framePass.executes( - () -> { - RenderTarget renderTarget = resourceHandle.get(); - RenderSystem.backupProjectionMatrix(); - RenderSystem.setProjectionMatrix(gpuBufferSlice, ProjectionType.ORTHOGRAPHIC); - CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); - List> list = this.inputs.stream().map(inputxx -> Pair.of(inputxx.samplerName(), inputxx.texture(map))).toList(); - - try (GpuBuffer.MappedView mappedView = commandEncoder.mapBuffer(this.infoUbo.currentBuffer(), false, true)) { - Std140Builder std140Builder = Std140Builder.intoBuffer(mappedView.data()); - std140Builder.putVec2(renderTarget.width, renderTarget.height); - - for (Pair pair : list) { - std140Builder.putVec2(pair.getSecond().getWidth(0), pair.getSecond().getHeight(0)); - } - } - - Renderer.getInstance().endRenderPass(); - - for (var input : this.inputs) { - VkGpuTexture gpuTexture = (VkGpuTexture) input.texture(map).texture(); - gpuTexture.getVulkanImage().readOnlyLayout(); - } - - try (RenderPass renderPass = commandEncoder.createRenderPass( - () -> "Post pass " + this.name, - renderTarget.getColorTextureView(), - OptionalInt.empty(), - renderTarget.useDepth ? renderTarget.getDepthTextureView() : null, - OptionalDouble.empty() - )) { - renderPass.setPipeline(this.pipeline); - RenderSystem.bindDefaultUniforms(renderPass); - renderPass.setUniform("SamplerInfo", this.infoUbo.currentBuffer()); - - for (Map.Entry entry : this.customUniforms.entrySet()) { - renderPass.setUniform((String)entry.getKey(), (GpuBuffer)entry.getValue()); - } - - for (Pair pair2 : list) { - renderPass.bindSampler(pair2.getFirst() + "Sampler", pair2.getSecond()); - } - - renderPass.draw(0, 3); - } + for (var input : this.inputs) { + VkGpuTexture gpuTexture = (VkGpuTexture) input.texture(map).texture(); - this.infoUbo.rotate(); - RenderSystem.restoreProjectionMatrix(); + if (gpuTexture.needsClear()) { + gpuTexture.getFbo(null).bind(); + } - for (PostPass.Input inputx : this.inputs) { - inputx.cleanup(map); - } - } - ); + gpuTexture.getVulkanImage().readOnlyLayout(); } } diff --git a/src/main/java/net/vulkanmod/render/engine/VkFbo.java b/src/main/java/net/vulkanmod/render/engine/VkFbo.java index 3c44224c7f..1b61c1f49e 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkFbo.java +++ b/src/main/java/net/vulkanmod/render/engine/VkFbo.java @@ -26,7 +26,7 @@ protected VkFbo(VkGpuTexture colorAttachment, VkGpuTexture depthAttachment) { } } - protected void bind() { + public void bind() { VkGlFramebuffer.bindFramebuffer(GL33.GL_FRAMEBUFFER, this.glId); clearAttachments(); } From c2e78605785a83a9c057675f42a285a0de3e708e Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:42:49 +0100 Subject: [PATCH 142/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 702efd9043..c6367426f0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.5.9-dev +mod_version = 0.5.10-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From babff0c646db24b37213d9a84e16c6c53537fc33 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 16 Feb 2026 11:19:37 +0100 Subject: [PATCH 143/177] Fix memory leak on section upload - Fix memory leak if upload was interrupted on forced updates - Fix index buffer reallocation bug --- .../build/task/SortTransparencyTask.java | 1 + .../chunk/build/task/TaskDispatcher.java | 50 +++++++++++-------- .../chunk/build/thread/BuilderResources.java | 4 +- .../chunk/build/thread/ThreadBuilderPack.java | 4 +- .../render/vertex/TerrainBufferBuilder.java | 4 ++ .../render/vertex/TerrainBuilder.java | 13 +++-- 6 files changed, 47 insertions(+), 29 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java index 122ab3751f..f6d1a72d6c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/SortTransparencyTask.java @@ -49,6 +49,7 @@ public Result runTask(BuilderResources context) { bufferBuilder.reset(); if (this.cancelled.get()) { + compileResult.renderedLayers.values().forEach(UploadBuffer::release); return Result.CANCELLED; } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java index e9bdac8452..e78146d83c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java @@ -7,10 +7,9 @@ import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.build.UploadBuffer; -import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.vertex.TerrainRenderType; - import org.jetbrains.annotations.Nullable; import java.util.Queue; @@ -38,15 +37,15 @@ public void createThreads() { } public void createThreads(int n) { - if(!this.stopThreads) { + if (!this.stopThreads) { this.stopThreads(); } this.stopThreads = false; - if(this.resources != null) { + if (this.resources != null) { for (BuilderResources resources : this.resources) { - resources.clear(); + resources.free(); } } @@ -61,7 +60,7 @@ public void createThreads(int n) { for (int i = 0; i < n; i++) { BuilderResources builderResources = new BuilderResources(); Thread thread = new Thread(() -> runTaskThread(builderResources), - "Builder-" + i); + "Builder-" + i); thread.setPriority(Thread.NORM_PRIORITY); this.threads[i] = thread; @@ -71,10 +70,10 @@ public void createThreads(int n) { } private void runTaskThread(BuilderResources builderResources) { - while(!this.stopThreads) { + while (!this.stopThreads) { ChunkTask task = this.pollTask(); - if(task == null) + if (task == null) synchronized (this) { try { this.idleThreads++; @@ -85,7 +84,7 @@ private void runTaskThread(BuilderResources builderResources) { this.idleThreads--; } - if(task == null) + if (task == null) continue; task.runTask(builderResources); @@ -93,12 +92,13 @@ private void runTaskThread(BuilderResources builderResources) { } public void schedule(ChunkTask chunkTask) { - if(chunkTask == null) + if (chunkTask == null) return; if (chunkTask.highPriority) { this.highPriorityTasks.offer(chunkTask); - } else { + } + else { this.lowPriorityTasks.offer(chunkTask); } @@ -111,14 +111,14 @@ public void schedule(ChunkTask chunkTask) { private ChunkTask pollTask() { ChunkTask task = this.highPriorityTasks.poll(); - if(task == null) + if (task == null) task = this.lowPriorityTasks.poll(); return task; } public void stopThreads() { - if(this.stopThreads) + if (this.stopThreads) return; this.stopThreads = true; @@ -140,7 +140,7 @@ public void stopThreads() { public boolean updateSections() { CompileResult result; boolean flag = false; - while((result = this.compileResults.poll()) != null) { + while ((result = this.compileResults.poll()) != null) { flag = true; doSectionUpdate(result); } @@ -159,17 +159,21 @@ private void doSectionUpdate(CompileResult compileResult) { // Check if area has been dismissed before uploading ChunkAreaManager chunkAreaManager = WorldRenderer.getInstance().getChunkAreaManager(); - if (chunkAreaManager.getChunkArea(renderArea.index) != renderArea) + if (chunkAreaManager.getChunkArea(renderArea.index) != renderArea) { + compileResult.renderedLayers.values() + .forEach(UploadBuffer::release); return; + } - if(compileResult.fullUpdate) { + if (compileResult.fullUpdate) { var renderLayers = compileResult.renderedLayers; - for(TerrainRenderType renderType : TerrainRenderType.VALUES) { + for (TerrainRenderType renderType : TerrainRenderType.VALUES) { UploadBuffer uploadBuffer = renderLayers.get(renderType); - if(uploadBuffer != null) { + if (uploadBuffer != null) { drawBuffers.upload(section, uploadBuffer, renderType); - } else { + } + else { section.resetDrawParameters(renderType); } } @@ -182,17 +186,19 @@ private void doSectionUpdate(CompileResult compileResult) { } } - public boolean isIdle() { return this.idleThreads == this.threads.length && this.compileResults.isEmpty(); } + public boolean isIdle() { + return this.idleThreads == this.threads.length && this.compileResults.isEmpty(); + } public void clearBatchQueue() { - while(!this.highPriorityTasks.isEmpty()) { + while (!this.highPriorityTasks.isEmpty()) { ChunkTask chunkTask = this.highPriorityTasks.poll(); if (chunkTask != null) { chunkTask.cancel(); } } - while(!this.lowPriorityTasks.isEmpty()) { + while (!this.lowPriorityTasks.isEmpty()) { ChunkTask chunkTask = this.lowPriorityTasks.poll(); if (chunkTask != null) { chunkTask.cancel(); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java index fd6e69f114..83418108e0 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java @@ -53,8 +53,8 @@ public void update(RenderRegion region, RenderSection renderSection) { this.lightDataCache.reset(region, renderSection.xOffset(), renderSection.yOffset(), renderSection.zOffset()); } - public void clear() { - builderPack.clearAll(); + public void free() { + builderPack.freeAll(); } public void updateBuildStats(int buildTime) { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java index 64d7026038..5573005586 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java @@ -34,8 +34,8 @@ public TerrainBuilder builder(TerrainRenderType renderType) { return this.builders.get(renderType); } - public void clearAll() { - this.builders.values().forEach(TerrainBuilder::clear); + public void freeAll() { + this.builders.values().forEach(TerrainBuilder::free); } } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java index 9e8651dae0..248aa5dfef 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java @@ -72,6 +72,10 @@ public void clear() { this.vertices = 0; } + public void free() { + ALLOCATOR.free(this.bufferPtr); + } + public ByteBuffer getBuffer() { return MemoryUtil.memByteBuffer(this.bufferPtr, this.vertices * this.vertexSize); } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index f12c69a175..7b23ae68cb 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -17,7 +17,6 @@ public class TerrainBuilder { protected long indexBufferPtr; private int indexBufferCapacity; - protected long bufferPtr; private final VertexFormat format; @@ -62,9 +61,9 @@ private void ensureIndexCapacity(int size) { } private void resizeIndexBuffer(int i) { - this.bufferPtr = ALLOCATOR.realloc(this.bufferPtr, i); + this.indexBufferPtr = ALLOCATOR.realloc(this.indexBufferPtr, i); LOGGER.debug("Needed to grow index buffer: Old size {} bytes, new size {} bytes.", this.indexBufferCapacity, i); - if (this.bufferPtr == 0L) { + if (this.indexBufferPtr == 0L) { throw new OutOfMemoryError("Failed to resize buffer from " + this.indexBufferCapacity + " bytes to " + i + " bytes"); } else { this.indexBufferCapacity = i; @@ -161,6 +160,14 @@ public void clear() { } } + public void free() { + ALLOCATOR.free(this.indexBufferPtr); + + for (TerrainBufferBuilder bufferBuilder : this.bufferBuilders) { + bufferBuilder.free(); + } + } + public void setBlockAttributes(BlockState blockState) { } From 01c898d334b20ab32e8733249d0a3114b09b40ce Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 16 Feb 2026 11:44:55 +0100 Subject: [PATCH 144/177] Refactor option widgets --- .../net/vulkanmod/config/gui/VOptionList.java | 15 ++------ .../vulkanmod/config/gui/VOptionScreen.java | 8 ++++ .../gui/widget/CyclingOptionWidget.java | 37 +++++++++++++------ .../config/gui/widget/OptionWidget.java | 22 +++++------ .../config/gui/widget/RangeOptionWidget.java | 15 +++----- .../config/gui/widget/SwitchOptionWidget.java | 5 +-- .../config/gui/widget/VAbstractWidget.java | 11 ++++++ .../config/gui/widget/VButtonWidget.java | 9 ++--- .../config/option/CyclingOption.java | 4 +- .../net/vulkanmod/config/option/Option.java | 32 ++++++++++++++-- .../vulkanmod/config/option/OptionPage.java | 11 +++++- .../vulkanmod/config/option/RangeOption.java | 4 +- .../vulkanmod/config/option/SwitchOption.java | 4 +- 13 files changed, 113 insertions(+), 64 deletions(-) diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index 6e353f2f46..c96ddce629 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -52,24 +52,15 @@ public void addAll(OptionBlock[] blocks) { int margin = this.itemMargin; - this.addEntry(new Entry(option.createOptionWidget(x0, 0, width, height), margin)); + final OptionWidget optionWidget = option.getWidget(); + optionWidget.setDimensions(x0, 0, width, height); + this.addEntry(new Entry(optionWidget, margin)); } this.addEntry(new Entry(null, 12)); } } - public void addAll(Option[] options) { - for (Option option : options) { - int x0 = this.x; - int width = this.itemWidth; - int height = this.itemHeight; - - this.addEntry(new Entry(option.createOptionWidget(x0, 0, width, height), this.itemMargin)); -// this.addEntry(new Entry(options[i].createOptionWidget(width / 2 - 155, 0, 200, 20))); - } - } - private void addEntry(Entry entry) { this.children.add(entry); diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java index fcf879d71e..8f80a0a14b 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java @@ -118,6 +118,7 @@ protected void init() { private void buildLists(int left, int top, int listWidth, int listHeight, int itemHeight) { for (OptionPage page : this.optionPages) { page.createList(left, top, listWidth, listHeight, itemHeight); + page.updateOptionStates(); } } @@ -291,6 +292,12 @@ private void updateState() { modified |= page.optionChanged(); } + if (modified) { + for (var page : this.optionPages) { + page.optionChanged(); + } + } + this.applyButton.active = modified; } @@ -306,6 +313,7 @@ private void applyOptions() { List pages = List.copyOf(this.optionPages); for (var page : pages) { page.applyOptionChanges(); + page.updateOptionStates(); } Initializer.CONFIG.write(); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java index 6ec5157d2b..0537396ccf 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java @@ -10,18 +10,23 @@ import net.vulkanmod.vulkan.util.ColorUtil; public class CyclingOptionWidget extends OptionWidget> { - private Button leftButton; - private Button rightButton; + private final Button leftButton; + private final Button rightButton; private boolean focused; - public CyclingOptionWidget(CyclingOption option, int x, int y, int width, int height, Component name) { - super(x, y, width, height, name); - this.option = option; - this.leftButton = new Button(this.controlX, 16, Button.Direction.LEFT); - this.rightButton = new Button(this.controlX + this.controlWidth - 16, 16, Button.Direction.RIGHT); + public CyclingOptionWidget(CyclingOption option, Component name) { + super(option, name); + this.leftButton = new Button(Button.Direction.LEFT); + this.rightButton = new Button(Button.Direction.RIGHT); + } + + @Override + public void setDimensions(int x, int y, int width, int height) { + super.setDimensions(x, y, width, height); -// updateDisplayedValue(option.getValueText()); + this.leftButton.setDimensions(this.controlX, 16); + this.rightButton.setDimensions(this.controlX + this.controlWidth - 16, 16); } @Override @@ -68,6 +73,13 @@ public void renderBars() { } } + public void setActive(boolean active) { + this.active = active; + + this.leftButton.active &= active; + this.rightButton.active &= active; + } + @Override public void onClick(double mouseX, double mouseY) { if (leftButton.isHovered(mouseX, mouseY)) { @@ -108,13 +120,16 @@ class Button { boolean active; Direction direction; - Button(int x, int width, Direction direction) { - this.x = x; - this.width = width; + Button(Direction direction) { this.active = true; this.direction = direction; } + public void setDimensions(int x, int width) { + this.x = x; + this.width = width; + } + boolean isHovered(double mouseX, double mouseY) { return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height; } diff --git a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java index b3ee793459..e70d8e05fe 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java @@ -13,9 +13,7 @@ import net.vulkanmod.config.option.Option; import net.vulkanmod.vulkan.util.ColorUtil; -public abstract class OptionWidget> extends VAbstractWidget - implements NarratableEntry { - +public abstract class OptionWidget> extends VAbstractWidget implements NarratableEntry { public int controlX; public int controlWidth; private final Component name; @@ -23,24 +21,22 @@ public abstract class OptionWidget> extends VAbstractWidget protected boolean controlHovered; - O option; + final O option; - public OptionWidget(int x, int y, int width, int height, Component name) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; + public OptionWidget(O option, Component name) { + this.option = option; this.name = name; this.displayedValue = Component.literal("N/A"); + } + + @Override + public void setDimensions(int x, int y, int width, int height) { + super.setDimensions(x, y, width, height); this.controlWidth = Math.min((int) (width * 0.5f) - 8, 120); this.controlX = this.x + this.width - this.controlWidth - 8; } - public void setOption(O option) { - this.option = option; - } - public void render(double mouseX, double mouseY) { if (!this.visible) { return; diff --git a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java index 277386177b..47ccb0dddf 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java @@ -8,7 +8,6 @@ import net.minecraft.util.Mth; import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.option.RangeOption; -import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.glfw.GLFW; @@ -17,11 +16,9 @@ public class RangeOptionWidget extends OptionWidget { private boolean focused; - public RangeOptionWidget(RangeOption option, int x, int y, int width, int height, Component name) { - super(x, y, width, height, name); - this.setOption(option); + public RangeOptionWidget(RangeOption option, Component name) { + super(option, name); this.setValue(option.getScaledValue()); - } @Override @@ -33,7 +30,7 @@ protected int getYImage(boolean hovered) { protected void renderControls(double mouseX, double mouseY) { int valueX = this.controlX + (int) (this.value * (this.controlWidth)); - if (this.controlHovered) { + if (this.controlHovered && this.active) { int halfWidth = 2; int halfHeight = 4; @@ -44,13 +41,14 @@ protected void renderControls(double mouseX, double mouseY) { int color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f); GuiRenderer.renderBorder(valueX - halfWidth, y0 - halfHeight, valueX + halfWidth, y1 + halfHeight, 1, color); -// GuiRenderer.fill(valueX - halfWidth, y0 - 3.0f, valueX + halfWidth, y1 + 3.0f, color); } else { int y0 = (int) (this.y + this.height - 5.0f); int y1 = (int) (y0 + 1.5f); GuiRenderer.fill(this.controlX, y0, this.controlX + this.controlWidth, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.3f)); - GuiRenderer.fill(this.controlX, y0, valueX, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 0.8f)); + + float alpha = this.active ? 0.8f : 0.3f; + GuiRenderer.fill(this.controlX, y0, valueX, y1, ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, alpha)); } int color = this.active ? 0xFFFFFFFF : 0xFFA0A0A0; @@ -58,7 +56,6 @@ protected void renderControls(double mouseX, double mouseY) { var text = this.getDisplayedValue(); int width = font.width(text); int x = this.controlX + this.controlWidth / 2 - width / 2; -// int x = (int) (this.x + 0.5f * width); int y = this.y + (this.height - 9) / 2; GuiRenderer.drawString(font, text.getVisualOrderText(), x, y, color); } diff --git a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java index f4b0b5f9f0..61966ed0c7 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java @@ -10,9 +10,8 @@ public class SwitchOptionWidget extends OptionWidget { private boolean focused; - public SwitchOptionWidget(SwitchOption option, int x, int y, int width, int height, Component name) { - super(x, y, width, height, name); - this.option = option; + public SwitchOptionWidget(SwitchOption option, Component name) { + super(option, name); updateDisplayedValue(); } diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java index 0a76bd6ff3..43959f7a8a 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java @@ -17,6 +17,13 @@ public abstract class VAbstractWidget extends GuiElement { protected Component message; + public void setDimensions(int x, int y, int width, int height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + public void render(double mX, double mY) { this.updateState(mX, mY); this.renderWidget(mX, mY); @@ -34,6 +41,10 @@ public void onRelease(double mX, double mY) { protected void onDrag(double mX, double mY, double f, double g) { } + public void setActive(boolean active) { + this.active = active; + } + protected void renderHovering(int xPadding, int yPadding) { float hoverMultiplier = this.getHoverMultiplier(200); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java index 3055259d60..b1effb5edf 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java @@ -37,17 +37,16 @@ public void renderWidget(double mouseX, double mouseY) { this.renderHovering(0, 0); } - int j = this.active ? 0xFFFFFF : 0xA0A0A0; - GuiRenderer.drawCenteredString(textRenderer, this.message, this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0f) << 24); - - - if(this.selected) { + if (this.selected) { color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 1.0f); GuiRenderer.fillBox(this.x, this.y, (int) 1.5f, this.height, color); color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 0.2f); GuiRenderer.fillBox(this.x, this.y, this.width, this.height, color); } + + int j = this.active ? 0xFFFFFF : 0xA0A0A0; + GuiRenderer.drawCenteredString(textRenderer, this.message, this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0f) << 24); } public void setSelected(boolean selected) { diff --git a/src/main/java/net/vulkanmod/config/option/CyclingOption.java b/src/main/java/net/vulkanmod/config/option/CyclingOption.java index d6080f7fdd..45487f278f 100644 --- a/src/main/java/net/vulkanmod/config/option/CyclingOption.java +++ b/src/main/java/net/vulkanmod/config/option/CyclingOption.java @@ -20,8 +20,8 @@ public CyclingOption(Component name, E[] values, Consumer setter, Supplier } @Override - public OptionWidget createOptionWidget(int x, int y, int width, int height) { - return new CyclingOptionWidget(this, x, y, width, height, this.name); + public OptionWidget createWidget() { + return new CyclingOptionWidget(this, this.name); } public void updateOption(E[] values, Consumer setter, Supplier getter) { diff --git a/src/main/java/net/vulkanmod/config/option/Option.java b/src/main/java/net/vulkanmod/config/option/Option.java index a1425ccf80..6918a4e5da 100644 --- a/src/main/java/net/vulkanmod/config/option/Option.java +++ b/src/main/java/net/vulkanmod/config/option/Option.java @@ -19,8 +19,11 @@ public abstract class Option { protected Function translator; + OptionWidget widget; + protected boolean active; protected Runnable onChange; + protected Supplier activationFn; public Option(Component name, Consumer setter, Supplier getter, Function translator) { this.name = name; @@ -59,10 +62,19 @@ public Option setTranslator(Function translator) { public Option setActive(boolean active) { this.active = active; + this.widget.active = active; return this; } - public abstract OptionWidget createOptionWidget(int x, int y, int width, int height); + abstract OptionWidget createWidget(); + + public OptionWidget getWidget() { + if (this.widget == null) { + this.widget = this.createWidget(); + } + + return this.widget; + } public void setNewValue(T t) { this.newValue = t; @@ -71,6 +83,17 @@ public void setNewValue(T t) { onChange.run(); } + public void updateActiveState() { + if (this.activationFn != null) { + this.active = this.activationFn.get(); + } + else { + this.active = true; + } + + this.widget.setActive(this.active); + } + public Component getName() { return this.name; } @@ -79,14 +102,15 @@ public void setOnChange(Runnable runnable) { onChange = runnable; } + public void setActivationFn(Supplier activationFn) { + this.activationFn = activationFn; + } + public boolean isChanged() { return !this.newValue.equals(this.value); } public void apply() { - if(!isChanged()) - return; - onApply.accept(this.newValue); this.value = this.newValue; } diff --git a/src/main/java/net/vulkanmod/config/option/OptionPage.java b/src/main/java/net/vulkanmod/config/option/OptionPage.java index 8d783fe4e1..7000e14682 100644 --- a/src/main/java/net/vulkanmod/config/option/OptionPage.java +++ b/src/main/java/net/vulkanmod/config/option/OptionPage.java @@ -36,8 +36,17 @@ public boolean optionChanged() { public void applyOptionChanges() { for (var block : this.optionBlocks) { for (var option : block.options()) { - if (option.isChanged()) + if (option.isChanged()) { option.apply(); + } + } + } + } + + public void updateOptionStates() { + for (var block : this.optionBlocks) { + for (var option : block.options()) { + option.updateActiveState(); } } } diff --git a/src/main/java/net/vulkanmod/config/option/RangeOption.java b/src/main/java/net/vulkanmod/config/option/RangeOption.java index 1a3270cb35..89d5f03557 100644 --- a/src/main/java/net/vulkanmod/config/option/RangeOption.java +++ b/src/main/java/net/vulkanmod/config/option/RangeOption.java @@ -25,8 +25,8 @@ public RangeOption(Component name, int min, int max, int step, Consumer this(name, min, max, step, (i) -> Component.literal(String.valueOf(i)), setter, getter); } - public OptionWidget createOptionWidget(int x, int y, int width, int height) { - return new RangeOptionWidget(this, x, y, width, height, this.name); + public OptionWidget createWidget() { + return new RangeOptionWidget(this, this.name); } public Component getName() { diff --git a/src/main/java/net/vulkanmod/config/option/SwitchOption.java b/src/main/java/net/vulkanmod/config/option/SwitchOption.java index aa4fd84b06..455810d83b 100644 --- a/src/main/java/net/vulkanmod/config/option/SwitchOption.java +++ b/src/main/java/net/vulkanmod/config/option/SwitchOption.java @@ -13,8 +13,8 @@ public SwitchOption(Component name, Consumer setter, Supplier } @Override - public OptionWidget createOptionWidget(int x, int y, int width, int height) { - return new SwitchOptionWidget(this, x, y, width, height, this.name); + public OptionWidget createWidget() { + return new SwitchOptionWidget(this, this.name); } } From 0ffef6d834ff0cf05e8517dc7050441a84bdbf93 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 16 Feb 2026 23:20:44 +0100 Subject: [PATCH 145/177] Improve image layout tracking and transitioning --- .../net/vulkanmod/mixin/texture/update/MSpriteContents.java | 4 ++-- .../java/net/vulkanmod/render/texture/ImageUploadHelper.java | 2 ++ .../java/net/vulkanmod/render/texture/SpriteUpdateUtil.java | 2 +- .../java/net/vulkanmod/vulkan/texture/VTextureSelector.java | 3 +++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java index f61bf5539f..1389df367e 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java @@ -2,8 +2,8 @@ import com.mojang.blaze3d.textures.GpuTexture; import net.minecraft.client.renderer.texture.SpriteContents; +import net.vulkanmod.render.engine.VkGpuTexture; import net.vulkanmod.render.texture.SpriteUpdateUtil; -import net.vulkanmod.vulkan.texture.VTextureSelector; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -32,7 +32,7 @@ private void checkUpload(int i, int j, GpuTexture gpuTexture, CallbackInfo ci) { ci.cancel(); } else { - SpriteUpdateUtil.addTransitionedLayout(VTextureSelector.getBoundTexture()); + SpriteUpdateUtil.addTransitionedLayout(((VkGpuTexture) gpuTexture).getVulkanImage()); } } } diff --git a/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java index 46d4cc6986..8554c36c63 100644 --- a/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java +++ b/src/main/java/net/vulkanmod/render/texture/ImageUploadHelper.java @@ -21,6 +21,8 @@ public void submitCommands() { return; } + SpriteUpdateUtil.transitionLayouts(); + queue.submitCommands(this.currentCmdBuffer, true); Synchronization.INSTANCE.addCommandBuffer(this.currentCmdBuffer, true); diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index 82f0ceab20..681629f89e 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -25,7 +25,7 @@ public static void addTransitionedLayout(VulkanImage image) { } public static void transitionLayouts() { - if (!doUpload || transitionedLayouts.isEmpty()) { + if (transitionedLayouts.isEmpty()) { return; } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index 58d1b31a70..5d580d369b 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -4,6 +4,7 @@ import net.vulkanmod.Initializer; import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.render.engine.VkGpuTexture; +import net.vulkanmod.render.texture.SpriteUpdateUtil; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; import org.lwjgl.system.MemoryUtil; @@ -60,6 +61,8 @@ public static void uploadSubTexture(int mipLevel, int arrayLayer, int width, int if (texture == null) throw new NullPointerException("Texture is null at index: " + activeTexture); + SpriteUpdateUtil.addTransitionedLayout(texture); + texture.uploadSubTextureAsync(mipLevel, arrayLayer, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, bufferPtr); } From 2e462154386db5017ce2e3130ed132d5caaf0456 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 16 Feb 2026 23:24:34 +0100 Subject: [PATCH 146/177] Fix typo --- .../vulkanmod/interfaces/shader/ExtendedRenderPipeline.java | 3 +-- .../net/vulkanmod/mixin/render/shader/RenderPipelineM.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java b/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java index dc927f0f09..0975acc287 100644 --- a/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java +++ b/src/main/java/net/vulkanmod/interfaces/shader/ExtendedRenderPipeline.java @@ -3,7 +3,6 @@ import com.mojang.blaze3d.pipeline.RenderPipeline; import net.vulkanmod.render.engine.EGlProgram; import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; public interface ExtendedRenderPipeline { @@ -15,7 +14,7 @@ static ExtendedRenderPipeline of(RenderPipeline renderPipeline) { void setProgram(EGlProgram program); - Pipeline getPipeline(); + GraphicsPipeline getPipeline(); EGlProgram getProgram(); } diff --git a/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java b/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java index 465ae4a925..9bfea846a6 100644 --- a/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java +++ b/src/main/java/net/vulkanmod/mixin/render/shader/RenderPipelineM.java @@ -29,7 +29,7 @@ public EGlProgram getProgram() { } @Override - public Pipeline getPipeline() { + public GraphicsPipeline getPipeline() { return this.pipeline; } } From d029353e3f6abf0f1de0586bcc791767abe01cbd Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:22:12 +0100 Subject: [PATCH 147/177] Add formats --- src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java | 2 +- src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java index 7ee10650ec..400d489106 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -131,7 +131,7 @@ public static VkGpuTexture fromGlTexture(GlTexture glTexture) { public static TextureFormat textureFormat(int format) { return switch (format) { - case VK10.VK_FORMAT_R8G8B8A8_UNORM, VK10.VK_FORMAT_B8G8R8A8_UNORM -> TextureFormat.RGBA8; + case VK10.VK_FORMAT_R8G8B8A8_UNORM, VK10.VK_FORMAT_B8G8R8A8_UNORM, VK10.VK_FORMAT_R8G8B8A8_SRGB -> TextureFormat.RGBA8; case VK10.VK_FORMAT_R8_UNORM -> TextureFormat.RED8; case VK10.VK_FORMAT_D32_SFLOAT -> TextureFormat.DEPTH32; default -> null; diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index 03f86b62bd..29b07a0b78 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -541,8 +541,11 @@ private static int formatSize(int format) { return switch (format) { case VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, - VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT -> 4; + VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT, + VK_FORMAT_R32_SFLOAT -> 4; + case VK_FORMAT_R16_SFLOAT -> 2; case VK_FORMAT_R8_UNORM -> 1; + case VK_FORMAT_R16G16B16A16_SFLOAT -> 8; default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); }; From 78a721281e6f23041453be7b19a2089a4e77f185 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:27:43 +0100 Subject: [PATCH 148/177] Improve uniform compatibility in case of no bound buffer --- .../net/vulkanmod/mixin/render/CompositeRenderTypeM.java | 4 ++++ .../net/vulkanmod/render/engine/VkCommandEncoder.java | 4 ++-- .../java/net/vulkanmod/vulkan/shader/DescriptorSets.java | 8 +++++++- src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java | 6 ++---- .../java/net/vulkanmod/vulkan/shader/layout/Uniform.java | 4 ++++ 5 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java b/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java index c701142d79..060e440b6f 100644 --- a/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java +++ b/src/main/java/net/vulkanmod/mixin/render/CompositeRenderTypeM.java @@ -13,6 +13,7 @@ import net.minecraft.client.renderer.RenderType; import net.vulkanmod.render.engine.*; import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.joml.Vector3f; import org.joml.Vector4f; @@ -94,6 +95,9 @@ public void draw(MeshData meshData) { } } + VRenderSystem.applyModelViewMatrix(RenderSystem.getModelViewMatrix()); + VRenderSystem.calculateMVP(); + renderPass.setIndexBuffer(gpuBuffer2, indexType); VkCommandEncoder commandEncoder = (VkCommandEncoder) RenderSystem.getDevice().createCommandEncoder(); diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index a932e0f57b..5f3215403a 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -793,10 +793,10 @@ public void setupUniforms(VkRenderPass renderPass) { GpuBufferSlice gpuBufferSlice = renderPass.uniforms.get(uniformName); - // In case uniform buffer is not set, ignore it + // In case uniform buffer is not set, fallback to global buffer if (gpuBufferSlice == null) { ubo.setUseGlobalBuffer(true); - ubo.setUpdate(false); + ubo.setUpdate(true); continue; } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java index 457ad51b8c..deda2cd75d 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/DescriptorSets.java @@ -48,7 +48,7 @@ public class DescriptorSets { } } - protected void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuffer, int bindPoint) { + public void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuffer, int bindPoint) { try (MemoryStack stack = stackPush()) { this.updateUniforms(uniformBuffer); @@ -62,6 +62,12 @@ protected void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuff private void updateUniforms(UniformBuffer globalUB) { int i = 0; for (UBO ubo : pipeline.getBuffers()) { + // Prevent NPE in case UBO has no bound buffer slice + if (ubo.getBufferSlice().getBuffer() == null) { + ubo.setUseGlobalBuffer(true); + ubo.setUpdate(true); + } + boolean useOwnUB = !ubo.useGlobalBuffer(); int offset; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 1ed1f69a7f..8837c11f86 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -163,7 +163,7 @@ public void scheduleCleanUp() { public abstract void cleanUp(); - void destroyDescriptorSets() { + protected void destroyDescriptorSets() { for (DescriptorSets descriptorSets : this.descriptorSets) { descriptorSets.cleanUp(); } @@ -240,10 +240,8 @@ public void bindDescriptorSets(VkCommandBuffer commandBuffer, UniformBuffer unif this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS); } - static long createShaderModule(ByteBuffer spirvCode) { - + protected static long createShaderModule(ByteBuffer spirvCode) { try (MemoryStack stack = stackPush()) { - VkShaderModuleCreateInfo createInfo = VkShaderModuleCreateInfo.calloc(stack); createInfo.sType(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java index ca4200ec48..6feaf1dbe8 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java @@ -34,6 +34,10 @@ public String getName() { } void update(long ptr) { + if (this.values == null) { + return; + } + MappedBuffer src = values.get(); MemoryUtil.memCopy(src.ptr, ptr + this.offset, this.size); From 6bc78c7c9d1d41f4badd5818b3b1a151d753aa5b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:32:11 +0100 Subject: [PATCH 149/177] Refactor --- .../vulkanmod/mixin/util/ScreenshotMixin.java | 78 +---------------- .../vulkanmod/render/chunk/WorldRenderer.java | 2 +- .../vulkanmod/vulkan/util/ScreenshotUtil.java | 87 +++++++++++++++++++ 3 files changed, 90 insertions(+), 77 deletions(-) create mode 100644 src/main/java/net/vulkanmod/vulkan/util/ScreenshotUtil.java diff --git a/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java b/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java index 04075bab5a..7e2c4ef14a 100644 --- a/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java +++ b/src/main/java/net/vulkanmod/mixin/util/ScreenshotMixin.java @@ -1,18 +1,9 @@ package net.vulkanmod.mixin.util; -import com.mojang.blaze3d.buffers.GpuBuffer; import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.CommandEncoder; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.textures.GpuTexture; -import com.mojang.blaze3d.textures.TextureFormat; import net.minecraft.client.Screenshot; -import net.minecraft.util.ARGB; -import net.vulkanmod.render.engine.VkGpuTexture; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.lwjgl.vulkan.VK10; +import net.vulkanmod.vulkan.util.ScreenshotUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -23,72 +14,7 @@ public class ScreenshotMixin { @Overwrite public static void takeScreenshot(RenderTarget renderTarget, int mipLevel, Consumer consumer) { - int width = renderTarget.width; - int height = renderTarget.height; - GpuTexture gpuTexture = renderTarget.getColorTexture(); - if (gpuTexture == null) { - throw new IllegalStateException("Tried to capture screenshot of an incomplete framebuffer"); - } else { - // Need to submit and wait cmds if screenshot was requested - // before the end of the frame - Renderer.getInstance().flushCmds(); - - int pixelSize = TextureFormat.RGBA8.pixelSize(); - GpuBuffer gpuBuffer = RenderSystem.getDevice() - .createBuffer(() -> "Screenshot buffer", 9, width * height * pixelSize); - CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); - RenderSystem.getDevice().createCommandEncoder().copyTextureToBuffer(gpuTexture, gpuBuffer, 0, () -> { - try (GpuBuffer.MappedView readView = commandEncoder.mapBuffer(gpuBuffer, true, false)) { - NativeImage nativeImage = new NativeImage(width, height, false); - - var colorAttachment = ((VkGpuTexture) Renderer.getInstance() - .getMainPass() - .getColorAttachment()); - boolean isBgraFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); - - int size = mipLevel * mipLevel; - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - - if (mipLevel == 1) { - int color = readView.data().getInt((x + y * width) * pixelSize); - - if (isBgraFormat) { - color = ColorUtil.BGRAtoRGBA(color); - } - - nativeImage.setPixelABGR(x, y, color | 0xFF000000); - } else { - int red = 0; - int green = 0; - int blue = 0; - - for (int x1 = 0; x1 < mipLevel; x1++) { - for (int y1 = 0; y1 < mipLevel; y1++) { - int color = readView.data().getInt(((x + x1) + (y + y1) * width) * pixelSize); - - if (isBgraFormat) { - color = ColorUtil.BGRAtoRGBA(color); - } - - red += ARGB.red(color); - green += ARGB.green(color); - blue += ARGB.blue(color); - } - } - - nativeImage.setPixelABGR(x, y, ARGB.color(255, red / size, green / size, blue / size)); - } - } - } - - consumer.accept(nativeImage); - } - - gpuBuffer.close(); - }, 0); - } + ScreenshotUtil.takeScreenshot(renderTarget, mipLevel, consumer); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index 8191d48af2..06d5a0a5d4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -200,7 +200,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus //Debug // this.graphNeedsUpdate = true; - if (this.graphNeedsUpdate) { + if (this.graphNeedsUpdate()) { this.graphNeedsUpdate = false; this.lastCameraX = cameraX; this.lastCameraY = cameraY; diff --git a/src/main/java/net/vulkanmod/vulkan/util/ScreenshotUtil.java b/src/main/java/net/vulkanmod/vulkan/util/ScreenshotUtil.java new file mode 100644 index 0000000000..bae0ef9383 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/util/ScreenshotUtil.java @@ -0,0 +1,87 @@ +package net.vulkanmod.vulkan.util; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.TextureFormat; +import net.minecraft.util.ARGB; +import net.vulkanmod.render.engine.VkGpuTexture; +import net.vulkanmod.vulkan.Renderer; +import org.lwjgl.vulkan.VK10; + +import java.util.function.Consumer; + +public abstract class ScreenshotUtil { + + public static void takeScreenshot(RenderTarget renderTarget, int mipLevel, Consumer consumer) { + int width = renderTarget.width; + int height = renderTarget.height; + GpuTexture gpuTexture = renderTarget.getColorTexture(); + if (gpuTexture == null) { + throw new IllegalStateException("Tried to capture screenshot of an incomplete framebuffer"); + } else { + // Need to submit and wait cmds if screenshot was requested + // before the end of the frame + Renderer.getInstance().flushCmds(); + + int pixelSize = TextureFormat.RGBA8.pixelSize(); + GpuBuffer gpuBuffer = RenderSystem.getDevice() + .createBuffer(() -> "Screenshot buffer", 9, width * height * pixelSize); + CommandEncoder commandEncoder = RenderSystem.getDevice().createCommandEncoder(); + RenderSystem.getDevice().createCommandEncoder().copyTextureToBuffer(gpuTexture, gpuBuffer, 0, () -> { + try (GpuBuffer.MappedView readView = commandEncoder.mapBuffer(gpuBuffer, true, false)) { + NativeImage nativeImage = new NativeImage(width, height, false); + + var colorAttachment = ((VkGpuTexture) Renderer.getInstance() + .getMainPass() + .getColorAttachment()); + boolean isBgraFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); + + int size = mipLevel * mipLevel; + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + if (mipLevel == 1) { + int color = readView.data().getInt((x + y * width) * pixelSize); + + if (isBgraFormat) { + color = ColorUtil.BGRAtoRGBA(color); + } + + nativeImage.setPixelABGR(x, y, color | 0xFF000000); + } else { + int red = 0; + int green = 0; + int blue = 0; + + for (int x1 = 0; x1 < mipLevel; x1++) { + for (int y1 = 0; y1 < mipLevel; y1++) { + int color = readView.data().getInt(((x + x1) + (y + y1) * width) * pixelSize); + + if (isBgraFormat) { + color = ColorUtil.BGRAtoRGBA(color); + } + + red += ARGB.red(color); + green += ARGB.green(color); + blue += ARGB.blue(color); + } + } + + nativeImage.setPixelABGR(x, y, ARGB.color(255, red / size, green / size, blue / size)); + } + } + } + + consumer.accept(nativeImage); + } + + gpuBuffer.close(); + }, 0); + } + } +} From fc452ad385f94933f107014c4165f78c8b05cccc Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 17 Feb 2026 16:32:38 +0100 Subject: [PATCH 150/177] Use quad normal instead of facing --- .../vulkanmod/render/chunk/build/renderer/BlockRenderer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index 74e75ce192..0c3607e719 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -117,8 +117,7 @@ public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadVie TerrainBufferBuilder bufferBuilder = terrainBuilder.getBufferBuilder(quadFacing.ordinal()); - Vec3i normal = quad.getFacingDirection().getUnitVec3i(); - int packedNormal = I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); + int packedNormal = quad.getNormal(); float[] brightnessArr = quadLightData.br; int[] lights = quadLightData.lm; From cd0f2e618d78df536f42898205e420374b2cd3eb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 24 Feb 2026 17:04:31 +0100 Subject: [PATCH 151/177] Update TerrainBuilder --- .../chunk/build/thread/ThreadBuilderPack.java | 13 ++++++++++++- .../net/vulkanmod/render/vertex/TerrainBuilder.java | 9 ++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java index 5573005586..86ca915a6a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java @@ -1,7 +1,11 @@ package net.vulkanmod.render.chunk.build.thread; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import net.vulkanmod.render.PipelineManager; +import net.vulkanmod.render.vertex.CustomVertexFormat; import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; +import net.vulkanmod.render.vertex.VertexBuilder; import java.util.Arrays; import java.util.EnumMap; @@ -12,7 +16,14 @@ public class ThreadBuilderPack { private static Function terrainBuilderConstructor; public static void defaultTerrainBuilderConstructor() { - terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getLayer(renderType).bufferSize()); + terrainBuilderConstructor = renderType -> { + int size = TerrainRenderType.getLayer(renderType) + .bufferSize() / DefaultVertexFormat.BLOCK.getVertexSize(); + + boolean compressedFormat = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN; + VertexBuilder vertexBuilder = compressedFormat ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); + return new TerrainBuilder(size, vertexBuilder); + }; } public static void setTerrainBuilderConstructor(Function constructor) { diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index 7b23ae68cb..90d394915d 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -5,6 +5,7 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import org.apache.logging.log4j.Logger; import org.lwjgl.system.MemoryUtil; @@ -31,14 +32,12 @@ public class TerrainBuilder { private final TerrainBufferBuilder[] bufferBuilders; - public TerrainBuilder(int size) { - // TODO index buffer + public TerrainBuilder(int size, VertexBuilder vertexBuilder) { + this.indexBufferCapacity = size * IndexBuffer.IndexType.UINT32.size; this.indexBufferPtr = ALLOCATOR.malloc(size); - this.indexBufferCapacity = size; this.format = PipelineManager.terrainVertexFormat; - this.vertexBuilder = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN - ? new VertexBuilder.CompressedVertexBuilder() : new VertexBuilder.DefaultVertexBuilder(); + this.vertexBuilder = vertexBuilder; var bufferBuilders = new TerrainBufferBuilder[QuadFacing.COUNT]; for (int i = 0; i < QuadFacing.COUNT; i++) { From d642e77d2c3a433fcfe23cdaade10f06b6213bd1 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 24 Feb 2026 17:05:01 +0100 Subject: [PATCH 152/177] Fix bug on texture binding --- .../render/engine/VkCommandEncoder.java | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java index 5f3215403a..94d1e64e53 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java +++ b/src/main/java/net/vulkanmod/render/engine/VkCommandEncoder.java @@ -809,31 +809,16 @@ public void setupUniforms(VkRenderPass renderPass) { for (ImageDescriptor imageDescriptor : pipeline.getImageDescriptors()) { String uniformName = imageDescriptor.name; - - int samplerIndex; - switch (glProgram.getUniform(uniformName)) { - case Uniform.Sampler(int location, int samplerIndex1): - samplerIndex = samplerIndex1; - break; - case Uniform.Utb( - int location, int samplerIndex1, com.mojang.blaze3d.textures.TextureFormat format, int texture - ): - samplerIndex = samplerIndex1; - break; - case null: - continue; - default: - throw new IllegalStateException("Unexpected value: " + glProgram.getUniform(uniformName)); - } + int samplerIndex = imageDescriptor.imageIdx; VkTextureView textureView = (VkTextureView) renderPass.samplers.get(uniformName); if (textureView == null) { - break; + continue; } VkGpuTexture gpuTexture = textureView.texture(); if (gpuTexture.isClosed()) { - break; + continue; } GlStateManager._activeTexture(33984 + samplerIndex); @@ -841,7 +826,7 @@ public void setupUniforms(VkRenderPass renderPass) { GlStateManager._texParameter(GL11.GL_TEXTURE_2D, 33084, textureView.baseMipLevel()); GlStateManager._texParameter(GL11.GL_TEXTURE_2D, 33085, textureView.baseMipLevel() + textureView.mipLevels() - 1); - gpuTexture.flushModeChanges(GL11.GL_TEXTURE_2D); + gpuTexture.flushModeChanges(); } } From 9417f918be341102452b32d54cc551fbf3ed207d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Mar 2026 15:37:24 +0100 Subject: [PATCH 153/177] Fix bug with texture sampling --- src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java index 400d489106..142769f0cf 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuTexture.java @@ -60,7 +60,10 @@ public void flushModeChanges() { int magFilterVk = magFilter == FilterMode.LINEAR ? VK10.VK_FILTER_LINEAR : VK10.VK_FILTER_NEAREST; int minFilterVk = minFilter == FilterMode.LINEAR ? VK10.VK_FILTER_LINEAR : VK10.VK_FILTER_NEAREST; - long sampler = SamplerManager.getSampler(VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + int addressModeUVk = this.addressModeU == AddressMode.REPEAT ? VK10.VK_SAMPLER_ADDRESS_MODE_REPEAT : VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + int addressModeVVk = this.addressModeV == AddressMode.REPEAT ? VK10.VK_SAMPLER_ADDRESS_MODE_REPEAT : VK10.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + + long sampler = SamplerManager.getSampler(addressModeUVk, addressModeVVk, minFilterVk, magFilterVk, VK10.VK_SAMPLER_MIPMAP_MODE_LINEAR, maxLod, false, 0, -1); From 374ddfc7984194bd0dd6d725d3c01720d0cebb7d Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sun, 1 Mar 2026 15:41:16 +0100 Subject: [PATCH 154/177] Improve terrain rendering command recording - aggregate draw cmds --- .../render/chunk/buffer/AreaBuffer.java | 58 ++++++- .../render/chunk/buffer/DrawBuffers.java | 148 ++++++++++++++---- .../render/chunk/cull/QuadFacing.java | 6 +- .../render/vertex/CustomVertexFormat.java | 13 +- 4 files changed, 181 insertions(+), 44 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java index c2c02db66d..018324a691 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java @@ -52,13 +52,60 @@ private Buffer allocateBuffer() { return buffer; } - public Segment upload(ByteBuffer byteBuffer, int oldOffset, long paramsPtr) { - // Free old segment - if (oldOffset != -1) { + public Segment allocateSegment(int size) { + if (DEBUG && size % elementSize != 0) + throw new RuntimeException("Unaligned buffer"); + + Segment segment = findSegment(size); + + if (segment.size - size > 0) { + Segment s1 = new Segment(segment.offset + size, segment.size - size); + segments++; + + if (segment.next != null) { + s1.bindNext(segment.next); + } else + this.last = s1; + + segment.bindNext(s1); + + segment.size = size; + } + + segment.free = false; + this.usedSegments.put(segment.offset, segment); + + segment.paramsPtr = 0; + + this.used += size; + + return segment; + } + + public void freeSegment(int offset) { + if (offset != -1) { // Need to delay segment freeing since it might be still used by prev frames in flight // this.setSegmentFree(oldOffset); - MemoryManager.getInstance().addToFreeSegment(this, oldOffset); + MemoryManager.getInstance().addToFreeSegment(this, offset); } + } + + public void upload(Segment segment, ByteBuffer byteBuffer, int offset) { + int size = byteBuffer.remaining(); + + if (DEBUG && size % elementSize != 0) + throw new RuntimeException("Unaligned buffer"); + + if (size + offset > segment.size) { + throw new RuntimeException("trying to upload %d at offset %d, but segment size is %d".formatted(size, offset, segment.size)); + } + + Buffer dst = this.buffer; + UploadManager.INSTANCE.recordUpload(dst, segment.offset + offset, size, byteBuffer); + } + + public Segment upload(ByteBuffer byteBuffer, int oldOffset, long paramsPtr) { + freeSegment(oldOffset); int size = byteBuffer.remaining(); @@ -120,7 +167,8 @@ public Segment reallocate(int uploadSize) { int minIncrement = this.size >> 3; minIncrement = (int) Util.align(minIncrement, this.elementSize); - int increment = Math.max(minIncrement, uploadSize << 1); +// int increment = Math.max(minIncrement, uploadSize << 1); + int increment = Math.max(minIncrement, uploadSize); if (increment < uploadSize) throw new RuntimeException(String.format("Size increment %d < %d (Upload size)", increment, uploadSize)); diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 24f3c95503..f48d0583b6 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -26,6 +26,8 @@ public class DrawBuffers { public static final int VERTEX_SIZE = PipelineManager.terrainVertexFormat.getVertexSize(); public static final int INDEX_SIZE = Short.BYTES; + public static final int UNDEFINED_FACING_IDX = QuadFacing.UNDEFINED.ordinal(); + public static final float POS_OFFSET = CustomVertexFormat.getPositionOffset(); private static final int CMD_STRIDE = 32; @@ -43,7 +45,7 @@ public class DrawBuffers { final int[] sectionIndices = new int[512]; final int[] masks = new int[512]; - //Need ugly minHeight Parameter to fix custom world heights (exceeding 384 Blocks in total) + // Need ugly minHeight parameter to fix custom world heights (exceeding 384 Blocks in total) public DrawBuffers(int index, Vector3i origin, int minHeight) { this.index = index; this.origin = origin; @@ -71,10 +73,39 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType return; } + int oldOffset = -1; + int size = 0; for (int i = 0; i < QuadFacing.COUNT; i++) { long paramPtr = DrawParametersBuffer.getParamsPtr(this.drawParamsPtr, section.inAreaIndex, renderType.ordinal(), i); - int vertexOffset = DrawParametersBuffer.getVertexOffset(paramPtr); + + // Only need to get first used offset, as it identifies the whole segment that will be freed + if (oldOffset == -1) { + oldOffset = vertexOffset; + } + + var vertexBuffer = vertexBuffers[i]; + if (vertexBuffer != null) { + size += vertexBuffer.remaining(); + + } + } + + if (size == 0) { + return; + } + + AreaBuffer areaBuffer = this.getAreaBufferOrAlloc(renderType); + areaBuffer.freeSegment(oldOffset); + AreaBuffer.Segment segment = areaBuffer.allocateSegment(size); + + int baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); + + int offset = 0; + for (int i = 0; i < QuadFacing.COUNT; i++) { + long paramPtr = DrawParametersBuffer.getParamsPtr(this.drawParamsPtr, section.inAreaIndex, renderType.ordinal(), i); + + int vertexOffset = -1; int firstIndex = 0; int indexCount = 0; @@ -82,12 +113,10 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType int vertexCount = 0; if (vertexBuffer != null) { - AreaBuffer.Segment segment = this.getAreaBufferOrAlloc(renderType).upload(vertexBuffer, vertexOffset, paramPtr); - vertexOffset = segment.offset / VERTEX_SIZE; - - int baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); - DrawParametersBuffer.setBaseInstance(paramPtr, baseInstance); + areaBuffer.upload(segment, vertexBuffer, offset); + vertexOffset = (segment.offset + offset) / VERTEX_SIZE; + offset += vertexBuffer.remaining(); vertexCount = vertexBuffer.limit() / VERTEX_SIZE; indexCount = vertexCount * 6 / 4; } @@ -97,9 +126,9 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType this.indexBuffer = new AreaBuffer(AreaBuffer.Usage.INDEX, 60000, INDEX_SIZE); } - int oldOffset = DrawParametersBuffer.getIndexCount(paramPtr) > 0 ? DrawParametersBuffer.getFirstIndex(paramPtr) : -1; - AreaBuffer.Segment segment = this.indexBuffer.upload(buffer.getIndexBuffer(), oldOffset, paramPtr); - firstIndex = segment.offset / INDEX_SIZE; + oldOffset = DrawParametersBuffer.getIndexCount(paramPtr) > 0 ? DrawParametersBuffer.getFirstIndex(paramPtr) : -1; + AreaBuffer.Segment ibSegment = this.indexBuffer.upload(buffer.getIndexBuffer(), oldOffset, paramPtr); + firstIndex = ibSegment.offset / INDEX_SIZE; } else { Renderer.getDrawer().getQuadsIndexBuffer().checkCapacity(vertexCount); } @@ -107,6 +136,7 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType DrawParametersBuffer.setIndexCount(paramPtr, indexCount); DrawParametersBuffer.setFirstIndex(paramPtr, firstIndex); DrawParametersBuffer.setVertexOffset(paramPtr, vertexOffset); + DrawParametersBuffer.setBaseInstance(paramPtr, baseInstance); } buffer.release(); @@ -140,9 +170,6 @@ private int encodeSectionOffset(int xOffset, int yOffset, int zOffset) { return yOffset1 << 16 | zOffset1 << 8 | xOffset1; } - // TODO: refactor - public static final float POS_OFFSET = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN ? 4.0f : 0.0f; - private void updateChunkAreaOrigin(VkCommandBuffer commandBuffer, Pipeline pipeline, double camX, double camY, double camZ, MemoryStack stack) { float xOffset = (float) ((this.origin.x) + POS_OFFSET - camX); float yOffset = (float) ((this.origin.y) + POS_OFFSET - camY); @@ -187,26 +214,57 @@ public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuff long drawParamsBasePtr2 = drawParamsBasePtr + (sectionIdx * facingsStride); + int indexCount = 0; + int firstIndex = 0; + int vertexOffset = 0; + int baseInstance = 0; + for (int i = 0; i < QuadFacing.COUNT; i++) { if ((mask & 1 << i) == 0) { drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + + // Flush draw cmd + if (indexCount > 0) { + MemoryUtil.memPutInt(ptr, indexCount); + MemoryUtil.memPutInt(ptr + 4, 1); + MemoryUtil.memPutInt(ptr + 8, firstIndex); + MemoryUtil.memPutInt(ptr + 12, vertexOffset); + MemoryUtil.memPutInt(ptr + 16, baseInstance); + + ptr += CMD_STRIDE; + drawCount++; + } + + indexCount = 0; + firstIndex = 0; + vertexOffset = 0; + baseInstance = 0; + continue; } long drawParamsPtr = drawParamsBasePtr2; - final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); - final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); - final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); - final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); + final int indexCount_i = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex_i = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset_i = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance_i = DrawParametersBuffer.getBaseInstance(drawParamsPtr); - drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; - - if (indexCount <= 0) { - continue; + if (indexCount == 0) { + indexCount = indexCount_i; + firstIndex = firstIndex_i; + vertexOffset = vertexOffset_i; + baseInstance = baseInstance_i; + } + else { + indexCount += indexCount_i; } + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + } + + if (indexCount > 0) { MemoryUtil.memPutInt(ptr, indexCount); MemoryUtil.memPutInt(ptr + 4, 1); MemoryUtil.memPutInt(ptr + 8, firstIndex); @@ -227,8 +285,7 @@ public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuff count++; } - final int facing = 6; - final long facingOffset = facing * DrawParametersBuffer.STRIDE; + final long facingOffset = UNDEFINED_FACING_IDX * DrawParametersBuffer.STRIDE; drawParamsBasePtr += facingOffset; long ptr = bufferPtr; @@ -293,34 +350,57 @@ public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue qu long drawParamsBasePtr2 = drawParamsBasePtr + (sectionIdx * facingsStride); + int indexCount = 0; + int firstIndex = 0; + int vertexOffset = 0; + int baseInstance = 0; + for (int i = 0; i < QuadFacing.COUNT; i++) { if ((mask & 1 << i) == 0) { drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + + // Flush draw cmd + if (indexCount > 0) { + vkCmdDrawIndexed(commandBuffer, indexCount, 1, firstIndex, vertexOffset, baseInstance); + } + + indexCount = 0; + firstIndex = 0; + vertexOffset = 0; + baseInstance = 0; + continue; } long drawParamsPtr = drawParamsBasePtr2; - final int indexCount = DrawParametersBuffer.getIndexCount(drawParamsPtr); - final int firstIndex = DrawParametersBuffer.getFirstIndex(drawParamsPtr); - final int vertexOffset = DrawParametersBuffer.getVertexOffset(drawParamsPtr); - final int baseInstance = DrawParametersBuffer.getBaseInstance(drawParamsPtr); - - drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + final int indexCount_i = DrawParametersBuffer.getIndexCount(drawParamsPtr); + final int firstIndex_i = DrawParametersBuffer.getFirstIndex(drawParamsPtr); + final int vertexOffset_i = DrawParametersBuffer.getVertexOffset(drawParamsPtr); + final int baseInstance_i = DrawParametersBuffer.getBaseInstance(drawParamsPtr); - if (indexCount <= 0) { - continue; + if (indexCount == 0) { + indexCount = indexCount_i; + firstIndex = firstIndex_i; + vertexOffset = vertexOffset_i; + baseInstance = baseInstance_i; + } + else { + indexCount += indexCount_i; } + drawParamsBasePtr2 += DrawParametersBuffer.STRIDE; + } + + if (indexCount > 0) { vkCmdDrawIndexed(commandBuffer, indexCount, 1, firstIndex, vertexOffset, baseInstance); } } } else { - final int facing = 6; - final long facingOffset = facing * DrawParametersBuffer.STRIDE; + final long facingOffset = UNDEFINED_FACING_IDX * DrawParametersBuffer.STRIDE; drawParamsBasePtr += facingOffset; for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { @@ -354,7 +434,7 @@ private int getMask(Vec3 camera, RenderSection section) { final int secY = section.yOffset; final int secZ = section.zOffset; - int mask = 1 << QuadFacing.UNDEFINED.ordinal(); + int mask = 1 << UNDEFINED_FACING_IDX; mask |= camera.x - secX >= 0 ? 1 << QuadFacing.X_POS.ordinal() : 0; mask |= camera.y - secY >= 0 ? 1 << QuadFacing.Y_POS.ordinal() : 0; diff --git a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java index 642fd9bf46..292b69fd15 100644 --- a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java +++ b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java @@ -7,12 +7,12 @@ public enum QuadFacing { X_POS, - X_NEG, Y_POS, - Y_NEG, Z_POS, + X_NEG, Z_NEG, - UNDEFINED; + UNDEFINED, + Y_NEG; public static final QuadFacing[] VALUES = QuadFacing.values(); public static final int COUNT = VALUES.length; diff --git a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java index 437345ff82..7ec452ce56 100644 --- a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java +++ b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java @@ -3,12 +3,13 @@ import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; -public class CustomVertexFormat { - +public abstract class CustomVertexFormat { public static final VertexFormatElement ELEMENT_POSITION = new VertexFormatElement(0, 0,VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.POSITION, 4); public static final VertexFormatElement ELEMENT_COLOR = new VertexFormatElement(1, 0, VertexFormatElement.Type.UINT, VertexFormatElement.Usage.COLOR, 1); public static final VertexFormatElement ELEMENT_UV0 = new VertexFormatElement(2, 0, VertexFormatElement.Type.USHORT, VertexFormatElement.Usage.UV, 2); + private static float POSITION_OFFSET = 4.0f; + public static final VertexFormat COMPRESSED_TERRAIN = VertexFormat.builder() .add("Position", ELEMENT_POSITION) @@ -17,4 +18,12 @@ public class CustomVertexFormat { .build(); public static final VertexFormat NONE = VertexFormat.builder().build(); + + public static void setPositionOffset(float positionOffset) { + POSITION_OFFSET = positionOffset; + } + + public static float getPositionOffset() { + return POSITION_OFFSET; + } } From 37e7ef14efe6b696efc71077ad99ed43ecef2ce5 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 3 Mar 2026 16:46:51 +0100 Subject: [PATCH 155/177] Fix index buffer allocation bug --- .../java/net/vulkanmod/render/vertex/TerrainBuilder.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index 90d394915d..43b547bcc3 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -33,8 +33,9 @@ public class TerrainBuilder { private final TerrainBufferBuilder[] bufferBuilders; public TerrainBuilder(int size, VertexBuilder vertexBuilder) { - this.indexBufferCapacity = size * IndexBuffer.IndexType.UINT32.size; - this.indexBufferPtr = ALLOCATOR.malloc(size); + // FIXME: same size is used for both index and vertex buffers + this.indexBufferCapacity = size; + this.indexBufferPtr = ALLOCATOR.malloc(this.indexBufferCapacity); this.format = PipelineManager.terrainVertexFormat; this.vertexBuilder = vertexBuilder; From a19291b086eeac6b54688cc215ee33ef36681a0a Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 3 Mar 2026 16:48:39 +0100 Subject: [PATCH 156/177] Add update checker --- src/main/java/net/vulkanmod/Initializer.java | 3 + .../net/vulkanmod/config/UpdateChecker.java | 58 +++++++++++++++++++ .../vulkanmod/config/gui/VOptionScreen.java | 30 +++++++--- .../assets/vulkanmod/lang/en_us.json | 1 + 4 files changed, 83 insertions(+), 9 deletions(-) create mode 100644 src/main/java/net/vulkanmod/config/UpdateChecker.java diff --git a/src/main/java/net/vulkanmod/Initializer.java b/src/main/java/net/vulkanmod/Initializer.java index 198d7153a6..b9309e3738 100644 --- a/src/main/java/net/vulkanmod/Initializer.java +++ b/src/main/java/net/vulkanmod/Initializer.java @@ -5,6 +5,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.vulkanmod.config.Config; import net.vulkanmod.config.Platform; +import net.vulkanmod.config.UpdateChecker; import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import org.apache.logging.log4j.LogManager; @@ -39,6 +40,8 @@ public void onInitializeClient() { CONFIG = loadConfig(configPath); Renderer.register(VulkanModRenderer.INSTANCE); + + UpdateChecker.checkForUpdates(); } private static Config loadConfig(Path path) { diff --git a/src/main/java/net/vulkanmod/config/UpdateChecker.java b/src/main/java/net/vulkanmod/config/UpdateChecker.java new file mode 100644 index 0000000000..cb054a84a2 --- /dev/null +++ b/src/main/java/net/vulkanmod/config/UpdateChecker.java @@ -0,0 +1,58 @@ +package net.vulkanmod.config; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.fabricmc.loader.api.Version; +import net.fabricmc.loader.api.VersionParsingException; +import net.fabricmc.loader.impl.util.version.VersionParser; +import net.minecraft.SharedConstants; +import net.vulkanmod.Initializer; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.CompletableFuture; + +public abstract class UpdateChecker { + private static boolean updateAvailable = false; + + public static void checkForUpdates() { + CompletableFuture.supplyAsync(() -> { + try { + String req = "https://api.modrinth.com/v2/project/vulkanmod/version?include_changelog=false"; + String mcVersion = SharedConstants.getCurrentVersion().name(); + req += "&game_versions=%s".formatted(mcVersion); + + URL url = new URL(req); + HttpURLConnection http = (HttpURLConnection)url.openConnection(); + var inputStream = http.getInputStream(); + + JsonObject data = JsonParser.parseString("{ versions: " + new String(inputStream.readAllBytes()) + "}").getAsJsonObject(); + JsonArray versions = data.getAsJsonArray("versions"); + http.disconnect(); + + String version = String.valueOf(versions.get(0).getAsJsonObject().get("version_number")).replace("\"", ""); + + var currentVersion = VersionParser.parseSemantic(Initializer.getVersion()); + updateAvailable = currentVersion.compareTo(Version.parse(version)) < 0; + + if (updateAvailable) { + Initializer.LOGGER.info("Update available!"); + } + } + catch (IOException e) { + Initializer.LOGGER.info("Error occurred, skipping update check."); + } + catch (VersionParsingException e) { + Initializer.LOGGER.info("Unable to parse version, skipping update check."); + } + + return null; + }); + } + + public static boolean isUpdateAvailable() { + return updateAvailable; + } +} diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java index 8f80a0a14b..718b9fa8c4 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java @@ -1,6 +1,7 @@ package net.vulkanmod.config.gui; import com.google.common.collect.Lists; +import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; @@ -12,6 +13,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; import net.vulkanmod.Initializer; +import net.vulkanmod.config.UpdateChecker; import net.vulkanmod.config.gui.render.GuiRenderer; import net.vulkanmod.config.gui.widget.VAbstractWidget; import net.vulkanmod.config.gui.widget.VButtonWidget; @@ -24,6 +26,7 @@ import java.util.List; public class VOptionScreen extends Screen { + public final static int MARGIN = 20; public final static int RED = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 0.8f); final ResourceLocation ICON = ResourceLocation.fromNamespaceAndPath("vulkanmod", "vlogo_transparent.png"); @@ -88,15 +91,13 @@ protected void init() { int bottom = 60; int itemHeight = 20; - int leftMargin = 100; -// int listWidth = (int) (this.width * 0.65f); - int listWidth = Math.min((int) (this.width * 0.65f), 420); + int leftMargin = MARGIN + 90; + int listWidth = Math.min(this.width - leftMargin - MARGIN, 420); int listHeight = this.height - top - bottom; this.buildLists(leftMargin, top, listWidth, listHeight, itemHeight); int x = leftMargin + listWidth + 10; -// int width = Math.min(this.width - this.tooltipX - 10, 200); int width = this.width - x - 10; int y = 50; @@ -147,8 +148,7 @@ private void buildPage() { this.pageButtons.clear(); this.clearWidgets(); -// this.addPageButtons(20, 6, 60, 20, false); - this.addPageButtons(10, 40, 80, 22, true); + this.addPageButtons(MARGIN, 40, 80, 22, true); VOptionList currentList = this.optionPages.get(this.currentListIdx).getOptionList(); this.addWidget(currentList); @@ -197,6 +197,19 @@ private void addButtons() { this.addWidget(this.applyButton); this.addWidget(this.doneButton); this.addWidget(this.supportButton); + + if (UpdateChecker.isUpdateAvailable()) { + buttonWidth = minecraft.font.width(Component.translatable("vulkanmod.options.buttons.update_available")) + 10; + var updateButton = new VButtonWidget( + x0 - buttonWidth - buttonMargin, 6, + buttonWidth, buttonHeight, + Component.translatable("vulkanmod.options.buttons.update_available").withStyle(ChatFormatting.UNDERLINE), + button -> Util.getPlatform().openUri("https://modrinth.com/mod/vulkanmod") + ); + + this.buttons.add(updateButton); + this.addWidget(updateButton); + } } @Override @@ -235,9 +248,8 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) GuiRenderer.guiGraphics = guiGraphics; VRenderSystem.enableBlend(); - int size = minecraft.font.lineHeight * 4; - - guiGraphics.blit(RenderPipelines.GUI_TEXTURED, ICON, 30, 4, 0f, 0f, size, size, size, size); + int size = 36; + guiGraphics.blit(RenderPipelines.GUI_TEXTURED, ICON, MARGIN + 40 - 18, 4, 0f, 0f, size, size, size, size); VOptionList currentList = this.optionPages.get(this.currentListIdx).getOptionList(); currentList.updateState(mouseX, mouseY); diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 09be191c71..ec9addfed0 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -8,6 +8,7 @@ "vulkanmod.options.buttons.apply": "Apply", "vulkanmod.options.buttons.kofi": "Support me", + "vulkanmod.options.buttons.update_available": "Update available!", "vulkanmod.options.advCulling": "Advanced Chunk Culling", "vulkanmod.options.advCulling.aggressive": "Aggressive", From 8c76e02fe2458a92db5f53f8e10aa2ec6cb88782 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 3 Mar 2026 18:29:10 +0100 Subject: [PATCH 157/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index c6367426f0..9ef951ec7f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.5.10-dev +mod_version = 0.6.0-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From 2283870e3f2b9b4286da014a04360252f92b81fd Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Wed, 4 Mar 2026 17:55:44 +0100 Subject: [PATCH 158/177] Fix missed draw parameters update on upload --- .../render/chunk/buffer/DrawBuffers.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index f48d0583b6..f43a5200b4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -91,14 +91,16 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType } } - if (size == 0) { - return; + AreaBuffer areaBuffer = null; + AreaBuffer.Segment segment = null; + boolean doUpload = false; + if (size > 0) { + areaBuffer = this.getAreaBufferOrAlloc(renderType); + areaBuffer.freeSegment(oldOffset); + segment = areaBuffer.allocateSegment(size); + doUpload = true; } - AreaBuffer areaBuffer = this.getAreaBufferOrAlloc(renderType); - areaBuffer.freeSegment(oldOffset); - AreaBuffer.Segment segment = areaBuffer.allocateSegment(size); - int baseInstance = encodeSectionOffset(section.xOffset(), section.yOffset(), section.zOffset()); int offset = 0; @@ -112,7 +114,7 @@ public void upload(RenderSection section, UploadBuffer buffer, TerrainRenderType var vertexBuffer = vertexBuffers[i]; int vertexCount = 0; - if (vertexBuffer != null) { + if (vertexBuffer != null && doUpload) { areaBuffer.upload(segment, vertexBuffer, offset); vertexOffset = (segment.offset + offset) / VERTEX_SIZE; From 62a5106a5112d7c36df305964334aaff2c2c0e02 Mon Sep 17 00:00:00 2001 From: whitebelyash Date: Mon, 16 Mar 2026 17:58:23 +0400 Subject: [PATCH 159/177] Add another AMD device id --- src/main/java/net/vulkanmod/vulkan/device/Device.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/device/Device.java b/src/main/java/net/vulkanmod/vulkan/device/Device.java index da850d3b9d..1d30312130 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/Device.java +++ b/src/main/java/net/vulkanmod/vulkan/device/Device.java @@ -72,7 +72,8 @@ public Device(VkPhysicalDevice device) { private static String decodeVendor(int i) { return switch (i) { case (0x10DE) -> "Nvidia"; - case (0x1022) -> "AMD"; + // AMD has two deviceIds, apparently + case (0x1022), (0x1002) -> "AMD"; case (0x8086) -> "Intel"; default -> "undef"; //Either AMD or Unknown Driver version/vendor and.or Encoding Scheme }; @@ -90,7 +91,7 @@ static String decDefVersion(int v) { private static String decodeDvrVersion(int v, int i) { return switch (i) { case (0x10DE) -> decodeNvidia(v); //Nvidia - case (0x1022) -> decDefVersion(v); //AMD + case (0x1022), (0x1002) -> decDefVersion(v); //AMD case (0x8086) -> decIntelVersion(v); //Intel default -> decDefVersion(v); //Either AMD or Unknown Driver Encoding Scheme }; @@ -149,7 +150,7 @@ public boolean isDrawIndirectSupported() { // Added these to allow detecting GPU vendor, to allow handling vendor specific circumstances: // (e.g. such as in case we encounter a vendor specific driver bug) public boolean isAMD() { - return vendorId == 0x1022; + return vendorId == 0x1022 || vendorId == 0x1002; } public boolean isNvidia() { From 13e925f06f132d05f129e7928334848fa92070fd Mon Sep 17 00:00:00 2001 From: whitebelyash Date: Mon, 16 Mar 2026 18:11:05 +0400 Subject: [PATCH 160/177] Add vendor ids for non-PC/exotic vendors Some are used on PC (like Qualcomm on WoA or Apple Silicon), so might be useful. Haven't touched the driver version detection logic. --- src/main/java/net/vulkanmod/vulkan/device/Device.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/device/Device.java b/src/main/java/net/vulkanmod/vulkan/device/Device.java index 1d30312130..a286ecfb9e 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/Device.java +++ b/src/main/java/net/vulkanmod/vulkan/device/Device.java @@ -72,9 +72,15 @@ public Device(VkPhysicalDevice device) { private static String decodeVendor(int i) { return switch (i) { case (0x10DE) -> "Nvidia"; - // AMD has two deviceIds, apparently - case (0x1022), (0x1002) -> "AMD"; + case (0x1022), (0x1002) -> "AMD"; // AMD has two deviceIds, apparently case (0x8086) -> "Intel"; + case (0x1010) -> "Imagination Technologies"; + case (0x13B5) -> "ARM"; + case (0x5143) -> "Qualcomm"; + case (0x106B) -> "Apple"; + case (0x14E4) -> "Broadcom"; + case (0x1AE0) -> "Google"; // Not sure about this, SwiftShader devices have this id + case (0x10005) -> "Mesa"; // Honeykrisp on Apple devices has this vendorId for some reason default -> "undef"; //Either AMD or Unknown Driver version/vendor and.or Encoding Scheme }; } From 0e2447fa92f291d8e7d77d640cfdd158343883fa Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 19 Mar 2026 18:12:08 +0100 Subject: [PATCH 161/177] Add device name to debug system specs --- .../mixin/debug/DebugEntrySystemSpecsM.java | 49 +++++++++++++++++++ .../vulkanmod/render/engine/VkGpuDevice.java | 2 +- src/main/resources/vulkanmod.mixins.json | 1 + 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/main/java/net/vulkanmod/mixin/debug/DebugEntrySystemSpecsM.java diff --git a/src/main/java/net/vulkanmod/mixin/debug/DebugEntrySystemSpecsM.java b/src/main/java/net/vulkanmod/mixin/debug/DebugEntrySystemSpecsM.java new file mode 100644 index 0000000000..2c8d18ebf7 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/debug/DebugEntrySystemSpecsM.java @@ -0,0 +1,49 @@ +package net.vulkanmod.mixin.debug; + +import com.mojang.blaze3d.platform.GLX; +import com.mojang.blaze3d.systems.GpuDevice; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.debug.DebugEntrySystemSpecs; +import net.minecraft.client.gui.components.debug.DebugScreenDisplayer; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.LevelChunk; +import net.vulkanmod.Initializer; +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; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; +import java.util.Locale; + +@Mixin(DebugEntrySystemSpecs.class) +public class DebugEntrySystemSpecsM { + + @Shadow @Final private static ResourceLocation GROUP; + + @Inject(method = "display", at = @At("HEAD"), cancellable = true) + private void display(DebugScreenDisplayer debugScreenDisplayer, Level level, LevelChunk levelChunk, + LevelChunk levelChunk2, CallbackInfo ci) { + GpuDevice gpuDevice = RenderSystem.getDevice(); + debugScreenDisplayer.addToGroup( + GROUP, + List.of( + String.format(Locale.ROOT, "Java: %s", System.getProperty("java.version")), + String.format(Locale.ROOT, "CPU: %s", GLX._getCpuInfo()), + String.format( + Locale.ROOT, "Display: %dx%d (%s)", Minecraft.getInstance().getWindow().getWidth(), Minecraft.getInstance().getWindow().getHeight(), gpuDevice.getVendor() + ), + gpuDevice.getRenderer(), + String.format(Locale.ROOT, "%s %s", gpuDevice.getBackendName(), gpuDevice.getVersion()), + String.format(Locale.ROOT, "VulkanMod %s", Initializer.getVersion()) + ) + ); + + ci.cancel(); + } + +} diff --git a/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java index 78cf830a6b..6d5ec560d1 100644 --- a/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java +++ b/src/main/java/net/vulkanmod/render/engine/VkGpuDevice.java @@ -182,7 +182,7 @@ public boolean isDebuggingEnabled() { @Override public String getRenderer() { - return "VulkanMod %s".formatted(Initializer.getVersion()) ; + return DeviceManager.device.deviceName; } @Override diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index fee540ab0f..bd8e25bd2c 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -26,6 +26,7 @@ "debug.crash_report.SystemReportM", "debug.DebugEntryMemoryM", + "debug.DebugEntrySystemSpecsM", "debug.DebugScreenEntriesM", "debug.KeyboardHandlerM", From 687e0688ee46c57983ccf0ea21172eeb31d135fb Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Thu, 19 Mar 2026 18:16:23 +0100 Subject: [PATCH 162/177] Update Framebuffer - add level param - fix bug with RenderPass --- .../vulkan/framebuffer/Framebuffer.java | 75 +++++++++++++++---- .../vulkan/framebuffer/RenderPass.java | 15 ++-- 2 files changed, 68 insertions(+), 22 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java index 047da14368..d34fb50ac3 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java @@ -18,8 +18,7 @@ public class Framebuffer { public static final int DEFAULT_FORMAT = VK_FORMAT_R8G8B8A8_UNORM; -// private long id; - + public final String name; protected int format; protected int depthFormat; protected int width, height; @@ -33,12 +32,17 @@ public class Framebuffer { private VulkanImage colorAttachment; protected VulkanImage depthAttachment; + private int level; + private final Reference2LongArrayMap renderpassToFramebufferMap = new Reference2LongArrayMap<>(); - //SwapChain - protected Framebuffer() {} + // SwapChain + protected Framebuffer() { + this.name = null; + } public Framebuffer(Builder builder) { + this.name = builder.name; this.format = builder.format; this.depthFormat = builder.depthFormat; this.width = builder.width; @@ -54,22 +58,30 @@ public Framebuffer(Builder builder) { this.colorAttachment = builder.colorAttachment; this.depthAttachment = builder.depthAttachment; } + + this.level = builder.level; } public void createImages() { if (this.hasColorAttachment) { - this.colorAttachment = VulkanImage.builder(this.width, this.height) - .setFormat(format) - .setUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) - .setLinearFiltering(linearFiltering) - .setClamp(true) - .createVulkanImage(); + this.colorAttachment = + VulkanImage.builder(this.width, this.height) + .setName(this.name != null ? String.format("%s Color", this.name) : null) + .setFormat(format) + .setUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) + .setLinearFiltering(linearFiltering) + .setClamp(true) + .createVulkanImage(); } if (this.hasDepthAttachment) { - this.depthAttachment = VulkanImage.createDepthImage(depthFormat, this.width, this.height, - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - depthLinearFiltering, true); + this.depthAttachment = VulkanImage.builder(width, height) + .setName(this.name != null ? String.format("%s Depth", this.name) : null) + .setFormat(depthFormat) + .setUsage(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) + .setLinearFiltering(depthLinearFiltering) + .setClamp(true) + .createVulkanImage(); this.attachmentCount++; } @@ -85,7 +97,6 @@ public void resize(int newWidth, int newHeight) { } private long createFramebuffer(RenderPass renderPass) { - try (MemoryStack stack = MemoryStack.stackPush()) { LongBuffer attachments; @@ -116,10 +127,13 @@ private long createFramebuffer(RenderPass renderPass) { } public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass, MemoryStack stack) { + renderPass.setFramebuffer(this); + if (!DYNAMIC_RENDERING) { long framebufferId = this.getFramebufferId(renderPass); renderPass.beginRenderPass(commandBuffer, framebufferId, stack); - } else { + } + else { renderPass.beginDynamicRendering(commandBuffer, stack); } } @@ -173,6 +187,17 @@ public void cleanUp(boolean cleanImages) { renderpassToFramebufferMap.clear(); } + public void setLevel(int level) { + int maxLevel = this.colorAttachment.mipLevels - 1; + if (level > maxLevel) { + throw new IllegalStateException( + "Requested mip level (%d) greater than color attachments max mip level (%d)" + .formatted(level, maxLevel)); + } + + this.level = level; + } + public long getDepthImageView() { return depthAttachment.getImageView(); } @@ -185,6 +210,10 @@ public VulkanImage getColorAttachment() { return colorAttachment; } + public long getColorAttachmentView() { + return colorAttachment.getLevelImageView(level); + } + public int getWidth() { return this.width; } @@ -210,6 +239,7 @@ public static Builder builder(VulkanImage colorAttachment, VulkanImage depthAtta } public static class Builder { + final String name; final boolean createImages; final int width, height; int format, depthFormat; @@ -217,19 +247,25 @@ public static class Builder { VulkanImage colorAttachment; VulkanImage depthAttachment; -// int colorAttachments; boolean hasColorAttachment; boolean hasDepthAttachment; boolean linearFiltering; boolean depthLinearFiltering; + int level = 0; + public Builder(int width, int height, int colorAttachments, boolean hasDepthAttachment) { + this(null, width, height, colorAttachments, hasDepthAttachment); + } + + public Builder(String name, int width, int height, int colorAttachments, boolean hasDepthAttachment) { Validate.isTrue(colorAttachments > 0 || hasDepthAttachment, "At least 1 attachment needed"); //TODO multi color attachments Validate.isTrue(colorAttachments <= 1, "Not supported"); + this.name = name; this.createImages = true; this.format = DEFAULT_FORMAT; this.depthFormat = Vulkan.getDefaultDepthFormat(); @@ -243,6 +279,7 @@ public Builder(int width, int height, int colorAttachments, boolean hasDepthAtta } public Builder(VulkanImage colorAttachment, VulkanImage depthAttachment) { + this.name = null; this.createImages = false; this.colorAttachment = colorAttachment; this.depthAttachment = depthAttachment; @@ -263,6 +300,12 @@ public Framebuffer build() { return new Framebuffer(this); } + public Builder setLevel(int level) { + this.level = level; + + return this; + } + public Builder setFormat(int format) { this.format = format; diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java index 3172e51b0c..62e237c560 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java @@ -263,13 +263,16 @@ public Framebuffer getFramebuffer() { return framebuffer; } - public void cleanUp() { - //TODO - - if (!Vulkan.DYNAMIC_RENDERING) - MemoryManager.getInstance().addFrameOp( - () -> vkDestroyRenderPass(Vulkan.getVkDevice(), this.id, null)); + public void setFramebuffer(Framebuffer framebuffer) { + this.framebuffer = framebuffer; + } + public void cleanUp() { + if (!Vulkan.DYNAMIC_RENDERING) { + MemoryManager.getInstance() + .addFrameOp( + () -> vkDestroyRenderPass(Vulkan.getVkDevice(), this.id, null)); + } } public long getId() { From 681391a443cc49b9ac73e274369957e77aa3f1cd Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 21 Mar 2026 15:58:14 +0100 Subject: [PATCH 163/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 9ef951ec7f..c928beb4e7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.6.0-dev +mod_version = 0.6.1-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From ca548ce379fa6e2766a90cffdf0b24cf7951006b Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 23 Mar 2026 00:29:30 +0100 Subject: [PATCH 164/177] Improve glsl translation - fix bugs --- .../vulkan/shader/converter/GLSLParser.java | 47 +++++++++++++++++-- .../vulkan/shader/converter/Lexer.java | 34 ++++++++++++-- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java index 8a0fafbaf3..49c5b592cc 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GLSLParser.java @@ -254,6 +254,16 @@ private void parseUniformBlock() { private void parseAttribute() { this.state = State.ATTRIBUTE; + Token prevToken = this.prevToken(true); + + // Check if we are at the beginning of a statement + if (prevToken != null && prevToken.type != Token.TokenType.SPACING && + prevToken.type != Token.TokenType.SEMICOLON && prevToken.type != Token.TokenType.RIGHT_BRACE && + !(prevToken.type == Token.TokenType.IDENTIFIER && Objects.equals(prevToken.value, "flat"))) + { + return; + } + String ioType = this.currentToken.value; nextToken(true); @@ -373,15 +383,44 @@ private void nextToken(boolean skipSpace) { } } + private Token prevToken(boolean skipSpace) { + int tokenIdx = this.currentTokenIdx - 1; + Token token; + + if (tokenIdx == 0) { + return null; + } + + tokenIdx--; + token = this.tokens.get(tokenIdx); + + while (skipSpace && tokenIdx != 0 && + (token.type == Token.TokenType.SPACING || token.type == Token.TokenType.PREPROCESSOR || token.type == Token.TokenType.COMMENT)) + { + tokenIdx--; + token = this.tokens.get(tokenIdx); + } + + if (skipSpace && (token.type == Token.TokenType.SPACING || token.type == Token.TokenType.COMMENT || token.type == Token.TokenType.PREPROCESSOR)) { + return null; + } + + return token; + } + private void appendToken(Token token) { this.appendNode(Node.fromToken(token)); } private void appendNode(Node node) { - switch (this.stage) { - case VERTEX -> this.vsStream.add(node); - case FRAGMENT -> this.fsStream.add(node); - } + this.getNodeStream().add(node); + } + + private LinkedList getNodeStream() { + return switch (this.stage) { + case VERTEX -> this.vsStream; + case FRAGMENT -> this.fsStream; + }; } public String getOutput(Stage stage) { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java index c6c2abca63..1a443e726c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/Lexer.java @@ -66,9 +66,13 @@ public Token nextToken() { // Comment if (currentChar == '/') { - if (peek() == '/') { - advance(2); - return this.comment(); + switch (peek()) { + case '/' -> { + return this.lineComment(); + } + case '*' -> { + return this.multiLineComment(); + } } } @@ -157,7 +161,7 @@ public Token nextToken() { }; if (token == null) { - if (Character.isLetter(currentChar)) { + if (Character.isJavaIdentifierStart(currentChar)) { return identifier(); } @@ -179,9 +183,11 @@ public Token nextToken() { return token; } - private Token comment() { + private Token lineComment() { StringBuilder sb = new StringBuilder(); sb.append("//"); + this.advance(2); + while (checkEOF() && currentChar != '\n') { sb.append(currentChar); advance(); @@ -193,6 +199,24 @@ private Token comment() { return new Token(Token.TokenType.COMMENT, value); } + private Token multiLineComment() { + StringBuilder sb = new StringBuilder(); + sb.append("/*"); + this.advance(2); + + while (checkEOF() && currentChar != '*' && this.peek() != '/') { + sb.append(currentChar); + advance(); + } + sb.append(currentChar); + advance(); + sb.append(currentChar); + advance(); + + String value = sb.toString(); + return new Token(Token.TokenType.COMMENT, value); + } + private Token identifier() { StringBuilder sb = new StringBuilder(); while (checkEOF() && Character.isJavaIdentifierPart(currentChar)) { From 6b2db6eb9846a6e6b4a89429e617e84458d97dbc Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Mon, 23 Mar 2026 00:32:07 +0100 Subject: [PATCH 165/177] Fix out of stack memory error on layout transitions --- .../vulkanmod/render/texture/SpriteUpdateUtil.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index 681629f89e..23cb63bcaf 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -31,9 +31,14 @@ public static void transitionLayouts() { VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer().handle; - try (MemoryStack stack = MemoryStack.stackPush()) { - transitionedLayouts.forEach(image -> image.readOnlyLayout(stack, commandBuffer)); - transitionedLayouts.clear(); - } + transitionedLayouts.forEach( + image -> + { + try (MemoryStack stack = MemoryStack.stackPush()) { + image.readOnlyLayout(stack, commandBuffer); + } + + }); + transitionedLayouts.clear(); } } From 7a1e52083b1d5d3742bba183bd86249c6dabdc91 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 24 Mar 2026 12:26:39 +0100 Subject: [PATCH 166/177] Add int index type for lines render type --- .../java/net/vulkanmod/vulkan/Drawer.java | 2 +- .../memory/buffer/index/AutoIndexBuffer.java | 30 ++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index fd2ae33f81..f71363c0c1 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -112,7 +112,7 @@ public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode if (autoIndexBuffer != null) { int indexCount = autoIndexBuffer.getIndexCount(vertexCount); - autoIndexBuffer.checkCapacity(indexCount); + autoIndexBuffer.checkCapacity(vertexCount); drawIndexed(vertexBuffer, autoIndexBuffer.getIndexBuffer(), indexCount); } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java index 6fead50d26..d4aaa0a81d 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java @@ -44,7 +44,13 @@ private void createIndexBuffer(int vertexCount) { } case TRIANGLE_FAN -> buffer = genTriangleFanIndices(vertexCount); case TRIANGLE_STRIP -> buffer = genTriangleStripIndices(vertexCount); - case LINES -> buffer = genLinesIndices(vertexCount); + case LINES -> { + if (indexType == IndexBuffer.IndexType.UINT16) + buffer = genLinesIndices(vertexCount); + else { + buffer = genIntLinesIndices(vertexCount); + } + } case DEBUG_LINE_STRIP -> buffer = genDebugLineStripIndices(vertexCount); default -> throw new IllegalArgumentException("Unsupported drawType: %s".formatted(this.drawType)); } @@ -167,6 +173,28 @@ public static ByteBuffer genLinesIndices(int vertexCount) { return buffer; } + public static ByteBuffer genIntLinesIndices(int vertexCount) { + int indexCount = vertexCount * 3 / 2; + indexCount = roundUpToDivisible(indexCount, 6); + + ByteBuffer buffer = MemoryUtil.memAlloc(indexCount * Integer.BYTES); + IntBuffer idxs = buffer.asIntBuffer(); + + int j = 0; + for (int i = 0; i < vertexCount; i += 4) { + idxs.put(j + 0, (i)); + idxs.put(j + 1, (i + 1)); + idxs.put(j + 2, (i + 2)); + idxs.put(j + 3, (i + 3)); + idxs.put(j + 4, (i + 2)); + idxs.put(j + 5, (i + 1)); + + j += 6; + } + + return buffer; + } + public static ByteBuffer genTriangleFanIndices(int vertexCount) { int indexCount = (vertexCount - 2) * 3; ByteBuffer buffer = MemoryUtil.memAlloc(indexCount * Short.BYTES); From 1502f635e81836bf6fd3dfe98cdb88c2cad2cc34 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Tue, 24 Mar 2026 18:25:46 +0100 Subject: [PATCH 167/177] Add missing gl mixin --- .../java/net/vulkanmod/mixin/compatibility/gl/GL11M.java | 6 ++++++ src/main/resources/vulkanmod.mixins.json | 1 + 2 files changed, 7 insertions(+) diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index 7793470bfc..33c7cbbb2d 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -4,6 +4,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL11C; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; @@ -100,6 +101,11 @@ public static void glClearColor(@NativeType("GLfloat") float red, @NativeType("G VRenderSystem.setClearColor(red, green, blue, alpha); } + @Overwrite(remap = false) + public static void glDepthFunc(@NativeType("GLenum") int func) { + VRenderSystem.depthFunc(func); + } + /** * @author * @reason diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index bd8e25bd2c..8c6d503890 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -21,6 +21,7 @@ "chunk.VisibilitySetMixin", "compatibility.gl.GL11M", + "compatibility.gl.GL14M", "compatibility.gl.GL15M", "compatibility.gl.GL30M", From 29802329d6154ac4c55ff8ee0508ee81703e4834 Mon Sep 17 00:00:00 2001 From: xCollateral <103696619+xCollateral@users.noreply.github.com> Date: Sat, 28 Mar 2026 15:39:23 +0100 Subject: [PATCH 168/177] Bump version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index c928beb4e7..4a0a13c961 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.6.1-dev +mod_version = 0.6.2-dev maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From 56d4ef2b9c76cb7586ce753950ea46fa517caaec Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:23:26 +0800 Subject: [PATCH 169/177] Add files via upload --- src/main/java/net/vulkanmod/vulkan/Vulkan.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index f2f0a16462..31152a2a80 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -34,7 +34,7 @@ import static org.lwjgl.vulkan.KHRDynamicRendering.VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME; import static org.lwjgl.vulkan.KHRSwapchain.VK_KHR_SWAPCHAIN_EXTENSION_NAME; import static org.lwjgl.vulkan.VK10.*; -import static org.lwjgl.vulkan.VK12.VK_API_VERSION_1_2; +import static org.lwjgl.vulkan.VK11.VK_API_VERSION_1_1; public class Vulkan { @@ -216,7 +216,7 @@ private static void createInstance() { appInfo.applicationVersion(VK_MAKE_VERSION(1, 0, 0)); appInfo.pEngineName(stack.UTF8Safe("VulkanMod Engine")); appInfo.engineVersion(VK_MAKE_VERSION(1, 0, 0)); - appInfo.apiVersion(VK_API_VERSION_1_2); + appInfo.apiVersion(VK_API_VERSION_1_1); VkInstanceCreateInfo createInfo = VkInstanceCreateInfo.calloc(stack); @@ -329,7 +329,7 @@ private static void createVma() { allocatorCreateInfo.device(DeviceManager.vkDevice); allocatorCreateInfo.pVulkanFunctions(vulkanFunctions); allocatorCreateInfo.instance(instance); - allocatorCreateInfo.vulkanApiVersion(VK_API_VERSION_1_2); + allocatorCreateInfo.vulkanApiVersion(VK_API_VERSION_1_1); PointerBuffer pAllocator = stack.pointers(VK_NULL_HANDLE); From bb3f4051e6254c81429659d5ca13387fa3c5fb97 Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:24:50 +0800 Subject: [PATCH 170/177] Add files via upload --- src/main/java/net/vulkanmod/vulkan/device/Device.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/vulkanmod/vulkan/device/Device.java b/src/main/java/net/vulkanmod/vulkan/device/Device.java index a286ecfb9e..a8ab2b70c8 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/Device.java +++ b/src/main/java/net/vulkanmod/vulkan/device/Device.java @@ -120,9 +120,9 @@ static int getVkVer() { var a = stack.mallocInt(1); vkEnumerateInstanceVersion(a); int vkVer1 = a.get(0); - if (VK_VERSION_MINOR(vkVer1) < 2) { + /* if (VK_VERSION_MINOR(vkVer1) < 2) { throw new RuntimeException("Vulkan 1.2 not supported: Only Has: %s".formatted(decDefVersion(vkVer1))); - } + }*/ return vkVer1; } } From 683a683529e416a5bd647113f31605b147479604 Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:26:12 +0800 Subject: [PATCH 171/177] Add files via upload --- src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index a45379fde8..6e4c72f666 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -58,7 +58,7 @@ private static void initCompiler() { if (DEBUG) shaderc_compile_options_set_generate_debug_info(options); - shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_2, VK12.VK_API_VERSION_1_2); + shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_1, VK12.VK_API_VERSION_1_1); shaderc_compile_options_set_include_callbacks(options, SHADER_INCLUDER, SHADER_RELEASER, pUserData); includePaths = new ObjectArrayList<>(); From e5367f6c959bad1354f9432d3435a0ee22325a5b Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:30:31 +0800 Subject: [PATCH 172/177] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20buildvk11.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/buildvk11.yml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 .github/workflows/buildvk11.yml diff --git a/.github/workflows/buildvk11.yml b/.github/workflows/buildvk11.yml new file mode 100644 index 0000000000..6b0dbbc9ed --- /dev/null +++ b/.github/workflows/buildvk11.yml @@ -0,0 +1,33 @@ +name: Build Mod for Multiple Versions + +on: + push: + branches: [ main ] # 或指定 0.6.2 对应的分支 + workflow_dispatch: # 支持手动触发 + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + mc_version: [1.20.1, 1.21, 1.21.1] # 修改为你需要的版本列表 + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + - name: Build with Gradle + run: | + # 尝试通过命令行参数覆盖 Minecraft 版本 + # 具体参数需要根据 build.gradle 的逻辑来定,通常需修改 gradle.properties + sed -i "s/minecraft_version=.*/minecraft_version=${{ matrix.mc_version }}/" gradle.properties + chmod +x gradlew + ./gradlew build + - name: Upload JAR + uses: actions/upload-artifact@v4 + with: + name: VulkanMod-${{ matrix.mc_version }} + path: build/libs/*.jar \ No newline at end of file From 7a16cc580914b8ccd885f1eae9e675b4ec63067a Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:32:36 +0800 Subject: [PATCH 173/177] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20gradle.properties?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 4a0a13c961..5674cebd24 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,6 +12,6 @@ loader_version = 0.17.3 fabric_version = 0.138.0+1.21.10 # Mod Properties -mod_version = 0.6.2-dev +mod_version = 0.6.2 maven_group = net.vulkanmod archives_base_name = VulkanMod_1.21.10 From a3be7c8fcaad9660614b478e9daa28a5b838b43e Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:37:00 +0800 Subject: [PATCH 174/177] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20build=5Frelease.ym?= =?UTF-8?q?l?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build_release.yml | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 .github/workflows/build_release.yml diff --git a/.github/workflows/build_release.yml b/.github/workflows/build_release.yml new file mode 100644 index 0000000000..df885563d3 --- /dev/null +++ b/.github/workflows/build_release.yml @@ -0,0 +1,62 @@ +name: Build and Release from dev + +on: + push: + branches: + - dev + workflow_dispatch: # 支持手动触发 + +permissions: + contents: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + + steps: + - name: 检出 dev 分支 + uses: actions/checkout@v4 + with: + ref: dev + + - name: 设置 JDK 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: temurin + + - name: 构建 Mod JAR + run: | + chmod +x gradlew + ./gradlew build + + - name: 查找生成的 JAR 文件 + id: find_jar + run: | + JAR_PATH=$(find build/libs -name "*.jar" ! -name "*-sources.jar" ! -name "*-dev.jar" | head -n 1) + echo "jar_path=$JAR_PATH" >> $GITHUB_OUTPUT + echo "找到 JAR: $JAR_PATH" + + - name: 获取版本号(从 gradle.properties 读取) + id: version + run: | + VERSION=$(grep "^mod_version" gradle.properties | cut -d'=' -f2 | tr -d ' ') + echo "tag=v$VERSION" >> $GITHUB_OUTPUT + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "版本号: $VERSION" + + - name: 创建 Release 并上传 JAR + uses: softprops/action-gh-release@v1 + with: + tag_name: ${{ steps.version.outputs.tag }} + name: VulkanMod ${{ steps.version.outputs.version }} + body: | + ✅ 来自 dev 分支的自动构建 + + - 版本号: ${{ steps.version.outputs.version }} + - 基于最新 dev 分支代码 + files: ${{ steps.find_jar.outputs.jar_path }} + draft: false + prerelease: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file From d3fd51536f3601dcc86fa721e61471f21f884aaf Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:40:35 +0800 Subject: [PATCH 175/177] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20build=5Frelease.ym?= =?UTF-8?q?l?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build_release.yml | 68 ++++++++++------------------- 1 file changed, 22 insertions(+), 46 deletions(-) diff --git a/.github/workflows/build_release.yml b/.github/workflows/build_release.yml index df885563d3..195b8544c3 100644 --- a/.github/workflows/build_release.yml +++ b/.github/workflows/build_release.yml @@ -1,62 +1,38 @@ -name: Build and Release from dev +name: Build Specific MC Version on: - push: - branches: - - dev - workflow_dispatch: # 支持手动触发 - -permissions: - contents: write + workflow_dispatch: + inputs: + branch: + description: '分支名(如 1.21.4)' + required: true + default: '1.21.4' + mc_version: + description: 'Minecraft 版本(用于 Release 名称)' + required: true + default: '1.21.4' jobs: - build-and-release: + build: runs-on: ubuntu-latest - steps: - - name: 检出 dev 分支 - uses: actions/checkout@v4 + - uses: actions/checkout@v4 with: - ref: dev - + ref: ${{ github.event.inputs.branch }} + - name: 设置 JDK 21 uses: actions/setup-java@v4 with: java-version: 21 distribution: temurin - - - name: 构建 Mod JAR + + - name: 构建 run: | chmod +x gradlew ./gradlew build - - - name: 查找生成的 JAR 文件 - id: find_jar - run: | - JAR_PATH=$(find build/libs -name "*.jar" ! -name "*-sources.jar" ! -name "*-dev.jar" | head -n 1) - echo "jar_path=$JAR_PATH" >> $GITHUB_OUTPUT - echo "找到 JAR: $JAR_PATH" - - - name: 获取版本号(从 gradle.properties 读取) - id: version - run: | - VERSION=$(grep "^mod_version" gradle.properties | cut -d'=' -f2 | tr -d ' ') - echo "tag=v$VERSION" >> $GITHUB_OUTPUT - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "版本号: $VERSION" - - - name: 创建 Release 并上传 JAR - uses: softprops/action-gh-release@v1 + + - name: 上传 JAR + uses: actions/upload-artifact@v4 with: - tag_name: ${{ steps.version.outputs.tag }} - name: VulkanMod ${{ steps.version.outputs.version }} - body: | - ✅ 来自 dev 分支的自动构建 - - - 版本号: ${{ steps.version.outputs.version }} - - 基于最新 dev 分支代码 - files: ${{ steps.find_jar.outputs.jar_path }} - draft: false - prerelease: false - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + name: VulkanMod-${{ github.event.inputs.mc_version }} + path: build/libs/*.jar \ No newline at end of file From aebcc10571f434f14597610ece2b6711fad34837 Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 11:44:19 +0800 Subject: [PATCH 176/177] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20build=5Fall.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build_all.yml | 78 +++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 .github/workflows/build_all.yml diff --git a/.github/workflows/build_all.yml b/.github/workflows/build_all.yml new file mode 100644 index 0000000000..a55571b9d6 --- /dev/null +++ b/.github/workflows/build_all.yml @@ -0,0 +1,78 @@ +name: Build All Minecraft Versions + +on: + workflow_dispatch: # 手动触发 + inputs: + version: + description: 'VulkanMod 版本号(如 0.6.2)' + required: true + default: '0.6.2' + +permissions: + contents: write + +jobs: + build-all: + runs-on: ubuntu-latest + strategy: + matrix: + mc_version: + - 1.18.2 + - 1.19.2 + - 1.19.4 + - 1.20.x + - 1.21 + fail-fast: false # 一个失败不影响其他版本 + + steps: + - name: 检出 ${{ matrix.mc_version }} 分支 + uses: actions/checkout@v4 + with: + ref: ${{ matrix.mc_version }} + + - name: 设置 JDK 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: temurin + + - name: 修改版本号为 ${{ github.event.inputs.version }} + run: | + # 修改 gradle.properties 中的版本号 + sed -i 's/^mod_version=.*/mod_version=${{ github.event.inputs.version }}/' gradle.properties 2>/dev/null || \ + sed -i 's/^version=.*/version=${{ github.event.inputs.version }}/' gradle.properties 2>/dev/null || \ + echo "未找到版本号字段,请检查 gradle.properties" + cat gradle.properties | grep -E "mod_version|version" || echo "警告:未找到版本号定义" + + - name: 赋予 gradlew 执行权限 + run: chmod +x gradlew + + - name: 构建 Mod JAR + run: ./gradlew build + + - name: 查找生成的 JAR + id: find_jar + run: | + JAR_PATH=$(find build/libs -name "*.jar" ! -name "*-sources.jar" ! -name "*-dev.jar" | head -n 1) + if [ -z "$JAR_PATH" ]; then + # 如果没有排除 sources/dev,就取第一个 jar + JAR_PATH=$(find build/libs -name "*.jar" | head -n 1) + fi + echo "jar_path=$JAR_PATH" >> $GITHUB_OUTPUT + echo "找到 JAR: $JAR_PATH" + + - name: 上传到 GitHub Release(每个 MC 版本单独 Release) + uses: softprops/action-gh-release@v1 + with: + tag_name: v${{ github.event.inputs.version }}-${{ matrix.mc_version }} + name: VulkanMod ${{ github.event.inputs.version }} (MC ${{ matrix.mc_version }}) + body: | + 🚀 VulkanMod ${{ github.event.inputs.version }} for Minecraft ${{ matrix.mc_version }} + + - 基于分支: ${{ matrix.mc_version }} + - 自动构建时间: ${{ github.server_time }} + files: ${{ steps.find_jar.outputs.jar_path }} + draft: false + prerelease: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file From 9be5494ddc1b4513a8dbdae05c1722252b689e87 Mon Sep 17 00:00:00 2001 From: ssbtt114514 Date: Sun, 5 Apr 2026 19:15:24 +0800 Subject: [PATCH 177/177] --- README.md | 76 +------------------------------------------------------ 1 file changed, 1 insertion(+), 75 deletions(-) diff --git a/README.md b/README.md index ef4118897b..332745eeeb 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,3 @@ # VulkanMod -This is a fabric mod that introduces a brand new **Vulkan** based voxel rendering engine to **Minecraft java** in order to both replace the default OpenGL renderer and bring performance improvements. - -### Why? -- Highly experimental project that overhauls and modernizes the internal renderer for Minecraft.
-- Updates the renderer from OpenGL 3.2 to Vulkan 1.2.
-- Provides a potential reference for a future-proof Vulkan codebase for Minecraft Java.
-- Utilizes the VulkanAPI to allow for capabilities not always possible with OpenGL.
-- Including reduced CPU Overhead and use of newer, modern hardware capabilities.
- -### Demonstration Video: - -[![Demostration Video](http://img.youtube.com/vi/sbr7UxcAmOE/0.jpg)](https://youtu.be/sbr7UxcAmOE) - -## FAQ -- Remember to check the [Wiki](https://github.com/xCollateral/VulkanMod/wiki) we wrote before asking for support! - -## Installation - -### Download Links: - -- [![CurseForge](https://cf.way2muchnoise.eu/full_635429_downloads.svg?badge_style=flat)](https://www.curseforge.com/minecraft/mc-mods/vulkanmod) - -- [![Modrinth Downloads](https://img.shields.io/modrinth/dt/JYQhtZtO?logo=modrinth&label=Modrinth%20Downloads)](https://modrinth.com/mod/vulkanmod/versions) - -- [![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/xCollateral/VulkanMod/total?style=flat-square&logo=github&label=Github%20Downloads)](https://github.com/xCollateral/VulkanMod/releases) - -### Install guide: ->1) Install the [fabric modloader](https://fabricmc.net). ->1) Download and put the `Vulkanmod.jar` file into `.minecraft/mods` ->1) Enjoy ! - -## Useful links - - - - - - - - - -
Discord server Ko-Fi
- - Discord - - - - Static Badge - -
- - -## Features - -### Optimizations: ->- [x] Multiple chunk culling algorithms ->- [x] Reduced CPU overhead ->- [x] Improved GPU performance ->- [x] Indirect Draw mode (reduces CPU overhead) ->- [x] Chunk rendering optimizations - -### New changes: ->- [x] Native Wayland support ->- [x] GPU selector ->- [x] Windowed fullscreen mode ->- [x] Revamped graphic settings menu ->- [x] Resizable render frame queue ->- [ ] Shader support ->- [ ] Removed Herobrine - - -## Notes -- This mod is still in development, please report issues in the [issue tab](https://github.com/xCollateral/VulkanMod/issues) with logs attached! -- This mode isn't just "minecraft on vulkan" (e.g: [zink](https://docs.mesa3d.org/drivers/zink.html) ), it is a full rewrite of the minecraft renderer. - +这是一个专门用于给vulkan1.1做适配的版本