Skip to content

Commit

Permalink
Add renderFog Spec Constant + Animations and renderSky options
Browse files Browse the repository at this point in the history
  • Loading branch information
thr3343 committed Jan 12, 2024
1 parent 1357817 commit 78b6120
Show file tree
Hide file tree
Showing 24 changed files with 194 additions and 33 deletions.
5 changes: 5 additions & 0 deletions src/main/java/net/vulkanmod/config/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public class Config {
public boolean uniqueOpaqueLayer = true;
public boolean entityCulling = true;
public int device = -1;
public boolean animations = true;
public boolean renderSky = true;


private static Path path;

Expand All @@ -29,6 +32,8 @@ public class Config {
.excludeFieldsWithModifiers(Modifier.PRIVATE)
.create();

public boolean renderFog = true;

public static Config load(Path path) {
Config config;
Config.path = path;
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/net/vulkanmod/config/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,18 @@ public static Option<?>[] getGraphicsOpts() {
new RangeOption("Entity Distance", 50, 500, 25,
value -> minecraftOptions.entityDistanceScaling().set(value * 0.01),
() -> minecraftOptions.entityDistanceScaling().get().intValue() * 100),
new SwitchOption("Animations",
value -> config.animations = value,
() -> config.animations),
new SwitchOption("Render Sky",
value -> config.renderSky = value,
() -> config.renderSky),
new SwitchOption("RenderFog",
value -> {
config.renderFog = value;
Renderer.recomp=true;
},
() -> config.renderFog),
new CyclingOption<>("Mipmap Levels",
new Integer[]{0, 1, 2, 3, 4},
value -> Component.nullToEmpty(value.toString()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.VertexBuffer;
import net.minecraft.client.renderer.ShaderInstance;
import net.vulkanmod.Initializer;
import net.vulkanmod.render.VBO;
import org.joml.Matrix4f;
import org.spongepowered.asm.mixin.Mixin;
Expand Down Expand Up @@ -57,7 +58,8 @@ public void upload(BufferBuilder.RenderedBuffer buffer) {
*/
@Overwrite
public void drawWithShader(Matrix4f viewMatrix, Matrix4f projectionMatrix, ShaderInstance shader) {
vbo.drawWithShader(viewMatrix, projectionMatrix, shader);
if(Initializer.CONFIG.renderSky)
vbo.drawWithShader(viewMatrix, projectionMatrix, shader);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.Tickable;
import net.minecraft.resources.ResourceLocation;
import net.vulkanmod.Initializer;
import net.vulkanmod.render.texture.SpriteUtil;
import net.vulkanmod.vulkan.DeviceManager;
import net.vulkanmod.vulkan.Renderer;
Expand All @@ -29,7 +30,7 @@ public abstract class MTextureManager {
*/
@Overwrite
public void tick() {
if(Renderer.skipRendering)
if(Renderer.skipRendering|| !Initializer.CONFIG.animations)
return;

//Debug D
Expand Down
14 changes: 12 additions & 2 deletions src/main/java/net/vulkanmod/vulkan/Renderer.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public class Renderer {

private static boolean swapChainUpdate = false;
public static boolean skipRendering = false;
public static boolean recomp;

public static void initRenderer() {
INSTANCE = new Renderer();
INSTANCE.init();
Expand All @@ -57,7 +59,7 @@ public static void initRenderer() {

public static int getCurrentImage() { return imageIndex; }

private final Set<Pipeline> usedPipelines = new ObjectOpenHashSet<>();
private final Set<GraphicsPipeline> usedPipelines = new ObjectOpenHashSet<>();

private Drawer drawer;

Expand Down Expand Up @@ -172,6 +174,14 @@ public void beginFrame() {
p.pop();
p.push("Frame_fence");

if(recomp)
{
waitIdle();
usedPipelines.forEach(graphicsPipeline -> graphicsPipeline.updateSpecConstant(SPIRVUtils.SpecConstant.USE_FOG));
recomp=false;
}


if(swapChainUpdate) {
recreateSwapChain();
swapChainUpdate = false;
Expand Down Expand Up @@ -363,7 +373,7 @@ public void resetBuffers() {
Vulkan.getStagingBuffer().reset();
}

public void addUsedPipeline(Pipeline pipeline) {
public void addUsedPipeline(GraphicsPipeline pipeline) {
usedPipelines.add(pipeline);
}

Expand Down
70 changes: 67 additions & 3 deletions src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -26,9 +27,11 @@ public class GraphicsPipeline extends Pipeline {

private final Map<PipelineState, Long> graphicsPipelines = new HashMap<>();
private final VertexFormat vertexFormat;
private final EnumSet<SPIRVUtils.SpecConstant> specConstants;

private long vertShaderModule = 0;
private long fragShaderModule = 0;
private PipelineState state;

GraphicsPipeline(Builder builder) {
super(builder.shaderPath);
Expand All @@ -37,14 +40,17 @@ public class GraphicsPipeline extends Pipeline {
this.imageDescriptors = builder.imageDescriptors;
this.pushConstants = builder.pushConstants;
this.vertexFormat = builder.vertexFormat;
this.specConstants = builder.specConstants;

createDescriptorSetLayout();
createPipelineLayout();
createShaderModules(builder.vertShaderSPIRV, builder.fragShaderSPIRV);

if(builder.renderPass != null)
graphicsPipelines.computeIfAbsent(new PipelineState(DEFAULT_BLEND_STATE, DEFAULT_DEPTH_STATE, DEFAULT_LOGICOP_STATE, DEFAULT_COLORMASK, builder.renderPass),
if(builder.renderPass != null) {
this.state = new PipelineState(DEFAULT_BLEND_STATE, DEFAULT_DEPTH_STATE, DEFAULT_LOGICOP_STATE, DEFAULT_COLORMASK, builder.renderPass);
graphicsPipelines.computeIfAbsent(state,
this::createGraphicsPipeline);
}

createDescriptorSets(Renderer.getFramesNum());

Expand All @@ -56,26 +62,38 @@ public long getHandle(PipelineState state) {
}

private long createGraphicsPipeline(PipelineState state) {

this.state=state;
try(MemoryStack stack = stackPush()) {

ByteBuffer entryPoint = stack.UTF8("main");

VkPipelineShaderStageCreateInfo.Buffer shaderStages = VkPipelineShaderStageCreateInfo.calloc(2, stack);


VkSpecializationMapEntry.Buffer specEntrySet = VkSpecializationMapEntry.malloc(specConstants.size(), stack);


boolean equals = !this.specConstants.isEmpty();
VkSpecializationInfo specInfo = equals ? VkSpecializationInfo.malloc(stack)
.pMapEntries(specEntrySet)
.pData(enumSpecConstants(stack, specEntrySet)) : null;


VkPipelineShaderStageCreateInfo vertShaderStageInfo = shaderStages.get(0);

vertShaderStageInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO);
vertShaderStageInfo.stage(VK_SHADER_STAGE_VERTEX_BIT);
vertShaderStageInfo.module(vertShaderModule);
vertShaderStageInfo.pName(entryPoint);
vertShaderStageInfo.pSpecializationInfo(specInfo);

VkPipelineShaderStageCreateInfo fragShaderStageInfo = shaderStages.get(1);

fragShaderStageInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO);
fragShaderStageInfo.stage(VK_SHADER_STAGE_FRAGMENT_BIT);
fragShaderStageInfo.module(fragShaderModule);
fragShaderStageInfo.pName(entryPoint);
fragShaderStageInfo.pSpecializationInfo(specInfo);

// ===> VERTEX STAGE <===

Expand Down Expand Up @@ -204,6 +222,30 @@ private long createGraphicsPipeline(PipelineState state) {
}
}


private ByteBuffer enumSpecConstants(MemoryStack stack, VkSpecializationMapEntry.Buffer specEntrySet) {
int i = 0;
int x = 0;
ByteBuffer byteBuffer = stack.malloc(specConstants.size()*Integer.BYTES);

for(var specDef : specConstants)
{
specEntrySet.get(i)
.constantID(specDef.ordinal())
.offset(x)
.size(4);

byteBuffer.putInt(i, specDef.getValue());
i++; x+=4;
}
return byteBuffer;
}

//Vulkan spec mandates that VkBool32 must always be aligned to uint32_t, which is 4 Bytes
private static ByteBuffer alignedVkBool32(MemoryStack stack, int i) {
return stack.malloc(Integer.BYTES).putInt(0, i); //Malloc as Int is always Unaligned, so asIntBuffer doesn't help here afaik
}

private void createShaderModules(SPIRVUtils.SPIRV vertSpirv, SPIRVUtils.SPIRV fragSpirv) {
this.vertShaderModule = createShaderModule(vertSpirv.bytecode());
this.fragShaderModule = createShaderModule(fragSpirv.bytecode());
Expand Down Expand Up @@ -338,6 +380,28 @@ else if (type == VertexFormatElement.Type.INT && elementCount == 1) {
return attributeDescriptions.rewind();
}

// SpecConstants can be set to be unique per Pipeline
// but that would involve adding boilerplate to PipelineState
// So to simplify the code, SpecConstants are limited to "Static Global State" rn
public void updateSpecConstant(SPIRVUtils.SpecConstant specConstant)
{

if(this.specConstants.contains(specConstant))
{
if(graphicsPipelines.size()>1)
{
graphicsPipelines.values().forEach(pipeline -> vkDestroyPipeline(DeviceManager.device, pipeline, null));
graphicsPipelines.clear();
}
this.graphicsPipelines.put(this.state, this.createGraphicsPipeline(this.state));
}
// PIPELINES.remove(this);
// Renderer.getInstance().removeUsedPipeline(this);
// this.graphicsPipelines.remove(this.state);
// PIPELINES.add(this);
// Renderer.getInstance().addUsedPipeline(this);
}

public void cleanUp() {
vkDestroyShaderModule(DeviceManager.device, vertShaderModule, null);
vkDestroyShaderModule(DeviceManager.device, fragShaderModule, null);
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,8 @@ private void cleanUp() {

public static class Builder {

final EnumSet<SpecConstant> specConstants = EnumSet.noneOf(SpecConstant.class);

public static GraphicsPipeline createGraphicsPipeline(VertexFormat format, String path) {
Pipeline.Builder pipelineBuilder = new Pipeline.Builder(format, path);
pipelineBuilder.parseBindingsJSON();
Expand Down Expand Up @@ -516,6 +518,7 @@ public void parseBindingsJSON() {
JsonArray jsonManualUbos = GsonHelper.getAsJsonArray(jsonObject, "ManualUBOs", null);
JsonArray jsonSamplers = GsonHelper.getAsJsonArray(jsonObject, "samplers", null);
JsonArray jsonPushConstants = GsonHelper.getAsJsonArray(jsonObject, "PushConstants", null);
JsonArray jsonSpecConstants = GsonHelper.getAsJsonArray(jsonObject, "SpecConstants", null);

if (jsonUbos != null) {
for (JsonElement jsonelement : jsonUbos) {
Expand All @@ -536,6 +539,24 @@ public void parseBindingsJSON() {
if(jsonPushConstants != null) {
this.parsePushConstantNode(jsonPushConstants);
}
if(jsonSpecConstants != null) {
this.parseSpecConstantNode(jsonSpecConstants);
}
}

private void parseSpecConstantNode(JsonArray jsonSpecConstants) {
// AlignedStruct.Builder builder = new AlignedStruct.Builder();

for(JsonElement jsonelement : jsonSpecConstants) {
JsonObject jsonobject2 = GsonHelper.convertToJsonObject(jsonelement, "SC");

String name = GsonHelper.getAsString(jsonobject2, "name");
// String type2 = GsonHelper.getAsString(jsonobject2, "type");


this.specConstants.add(SpecConstant.getNamed(name));
}

}

private void parseUboNode(JsonElement jsonelement) {
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package net.vulkanmod.vulkan.shader;

import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.vulkanmod.Initializer;
import net.vulkanmod.vulkan.VRenderSystem;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.system.NativeResource;
Expand Down Expand Up @@ -118,6 +120,37 @@ private static SPIRV readFromStream(InputStream inputStream) {
throw new RuntimeException("unable to read inputStream");
}



public enum SpecConstant
{
USE_FOG(Boolean.class),
ALPHA_CUTOUT(Float.class);

SpecConstant(Object floatClass) {

}

public static SpecConstant getNamed(String name) {
return switch (name)
{
case "USE_FOG" -> USE_FOG;
case "ALPHA_CUTOUT" -> ALPHA_CUTOUT;
default -> null;
};
}

//Vulkan spec mandates that VkBool32 must always be aligned to uint32_t, which is 4 Bytes
public int getValue()
{
return switch (this){
case USE_FOG -> Initializer.CONFIG.renderFog ? 1 : 0;
case ALPHA_CUTOUT -> Float.floatToRawIntBits(VRenderSystem.alphaCutout);
};
}
}


public enum ShaderKind {
VERTEX_SHADER(shaderc_glsl_vertex_shader),
GEOMETRY_SHADER(shaderc_glsl_geometry_shader),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#version 450

layout (constant_id = 0) const bool USE_FOG = true;
#include "light.glsl"

layout(binding = 2) uniform sampler2D Sampler0;
Expand All @@ -24,5 +24,5 @@ void main() {
if (color.a < AlphaCutout) {
discard;
}
fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor);
fragColor = USE_FOG ? linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor) : color; //Optimised out by Driver
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#version 460

layout (constant_id = 0) const bool USE_FOG = true;
#include "light.glsl"

layout(binding = 0) uniform UniformBufferObject {
Expand Down Expand Up @@ -31,8 +31,7 @@ const float POSITION_INV = 1.0 / 1900.0;
void main() {
vec3 pos = (Position * POSITION_INV);
gl_Position = MVP * vec4(pos + ChunkOffset, 1.0);

vertexDistance = length((ModelViewMat * vec4(pos + ChunkOffset, 1.0)).xyz);
vertexDistance = USE_FOG ? length((ModelViewMat * vec4(pos + ChunkOffset, 1.0)).xyz) : 0.0f; //Optimised out by Driver
vertexColor = Color * sample_lightmap(Sampler2, UV2);
texCoord0 = UV0 * UV_INV;
// normal = MVP * vec4(Normal, 0.0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#version 450

layout (constant_id = 0) const bool USE_FOG = true;
#include "light.glsl"

layout(binding = 3) uniform sampler2D Sampler0;
Expand All @@ -24,5 +24,5 @@ void main() {
if (color.a < AlphaCutout) {
discard;
}
fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor);
fragColor = USE_FOG ? linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor) : color; //Optimised out by Driver
}
Loading

0 comments on commit 78b6120

Please sign in to comment.