From 32725a604d3187c1fa748f2e8e17c1f8d90936fd Mon Sep 17 00:00:00 2001 From: xCollateral <> Date: Mon, 11 Sep 2023 16:31:06 +0200 Subject: [PATCH] Refactor --- src/main/java/net/vulkanmod/Initializer.java | 1 - src/main/java/net/vulkanmod/gl/Util.java | 8 +- .../net/vulkanmod/interfaces/ShaderMixed.java | 4 +- .../mixin/chunk/LevelRendererMixin.java | 69 ++- .../mixin/compatibility/EffectInstanceM.java | 4 +- .../mixin/compatibility/ProgramM.java | 4 +- .../mixin/render/BufferUploaderM.java | 5 +- .../mixin/render/ShaderInstanceM.java | 13 +- .../mixin/texture/MTextureManager.java | 22 +- src/main/java/net/vulkanmod/render/VBO.java | 5 +- .../vulkanmod/render/chunk/AreaBuffer.java | 3 +- .../render/chunk/AreaUploadManager.java | 8 +- .../vulkanmod/render/chunk/DrawBuffers.java | 7 +- .../render/chunk/TerrainShaderManager.java | 69 +++ .../vulkanmod/render/chunk/WorldRenderer.java | 20 +- .../render/chunk/build/ChunkTask.java | 8 +- .../render/vertex/TerrainBufferBuilder.java | 10 +- .../java/net/vulkanmod/vulkan/Device.java | 58 +- .../java/net/vulkanmod/vulkan/Renderer.java | 19 +- .../java/net/vulkanmod/vulkan/Vulkan.java | 14 +- .../vulkan/memory/IndirectBuffer.java | 4 +- .../vulkan/memory/MemoryManager.java | 3 +- .../vulkanmod/vulkan/memory/MemoryTypes.java | 6 +- .../vulkan/memory/UniformBuffers.java | 4 +- .../vulkanmod/vulkan/queue/ComputeQueue.java | 10 + .../vulkanmod/vulkan/queue/GraphicsQueue.java | 20 +- .../vulkanmod/vulkan/queue/PresentQueue.java | 10 + .../net/vulkanmod/vulkan/queue/Queue.java | 37 +- .../vulkanmod/vulkan/queue/TransferQueue.java | 29 +- .../vulkan/shader/GraphicsPipeline.java | 334 +++++++++++ .../net/vulkanmod/vulkan/shader/Pipeline.java | 551 ++++-------------- ...{ShaderSPIRVUtils.java => SPIRVUtils.java} | 22 +- .../vulkan/shader/ShaderManager.java | 64 -- .../vulkan/shader/descriptor/Descriptor.java | 10 + .../vulkan/shader/descriptor/Image.java | 40 ++ .../shader/{ => descriptor}/ManualUBO.java | 8 +- .../vulkan/shader/descriptor/UBO.java | 33 ++ .../vulkan/shader/layout/AlignedStruct.java | 24 +- .../vulkanmod/vulkan/shader/layout/Field.java | 21 +- .../vulkanmod/vulkan/shader/layout/Mat4f.java | 14 +- .../vulkanmod/vulkan/shader/layout/UBO.java | 28 - .../vulkanmod/vulkan/shader/layout/Vec1f.java | 26 +- .../vulkanmod/vulkan/shader/layout/Vec1i.java | 26 +- .../vulkanmod/vulkan/shader/layout/Vec2f.java | 12 +- .../vulkanmod/vulkan/shader/layout/Vec3f.java | 13 +- .../vulkanmod/vulkan/shader/layout/Vec4f.java | 16 +- .../vulkan/shader/parser/GlslConverter.java | 5 +- .../vulkan/shader/parser/UniformParser.java | 25 +- .../vulkanmod/vulkan/texture/VulkanImage.java | 22 +- .../terrain_indirect.fsh} | 0 .../terrain_indirect.json} | 0 .../terrain_indirect.vsh} | 33 +- 52 files changed, 932 insertions(+), 869 deletions(-) create mode 100644 src/main/java/net/vulkanmod/render/chunk/TerrainShaderManager.java create mode 100644 src/main/java/net/vulkanmod/vulkan/queue/ComputeQueue.java create mode 100644 src/main/java/net/vulkanmod/vulkan/queue/PresentQueue.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java rename src/main/java/net/vulkanmod/vulkan/shader/{ShaderSPIRVUtils.java => SPIRVUtils.java} (83%) delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/ShaderManager.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/descriptor/Image.java rename src/main/java/net/vulkanmod/vulkan/shader/{ => descriptor}/ManualUBO.java (71%) create mode 100644 src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java delete mode 100644 src/main/java/net/vulkanmod/vulkan/shader/layout/UBO.java rename src/main/resources/assets/vulkanmod/shaders/basic/{terrain/terrain.fsh => terrain_indirect/terrain_indirect.fsh} (100%) rename src/main/resources/assets/vulkanmod/shaders/basic/{terrain/terrain.json => terrain_indirect/terrain_indirect.json} (100%) rename src/main/resources/assets/vulkanmod/shaders/basic/{terrain/terrain.vsh => terrain_indirect/terrain_indirect.vsh} (68%) diff --git a/src/main/java/net/vulkanmod/Initializer.java b/src/main/java/net/vulkanmod/Initializer.java index 88f2a9581..390ae24ae 100644 --- a/src/main/java/net/vulkanmod/Initializer.java +++ b/src/main/java/net/vulkanmod/Initializer.java @@ -1,7 +1,6 @@ package net.vulkanmod; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.vulkanmod.config.Config; import net.vulkanmod.config.VideoResolution; diff --git a/src/main/java/net/vulkanmod/gl/Util.java b/src/main/java/net/vulkanmod/gl/Util.java index 05b8b44b4..b7b475b82 100644 --- a/src/main/java/net/vulkanmod/gl/Util.java +++ b/src/main/java/net/vulkanmod/gl/Util.java @@ -1,13 +1,13 @@ package net.vulkanmod.gl; -import net.vulkanmod.vulkan.shader.ShaderSPIRVUtils; +import net.vulkanmod.vulkan.shader.SPIRVUtils; public class Util { - public static ShaderSPIRVUtils.ShaderKind extToShaderKind(String in) { + public static SPIRVUtils.ShaderKind extToShaderKind(String in) { return switch (in) { - case ".vsh" -> ShaderSPIRVUtils.ShaderKind.VERTEX_SHADER; - case ".fsh" -> ShaderSPIRVUtils.ShaderKind.FRAGMENT_SHADER; + case ".vsh" -> SPIRVUtils.ShaderKind.VERTEX_SHADER; + case ".fsh" -> SPIRVUtils.ShaderKind.FRAGMENT_SHADER; default -> throw new RuntimeException("unknown shader type: " + in); }; } diff --git a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java b/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java index 28f9121fe..e1676144f 100644 --- a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java +++ b/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java @@ -1,8 +1,8 @@ package net.vulkanmod.interfaces; -import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; public interface ShaderMixed { - Pipeline getPipeline(); + GraphicsPipeline getPipeline(); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java index 798b15314..a303b383a 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java @@ -47,13 +47,17 @@ public abstract class LevelRendererMixin { @Shadow private boolean generateClouds; @Shadow @Final private EntityRenderDispatcher entityRenderDispatcher; + @Shadow protected abstract boolean shouldShowEntityOutlines(); + + @Shadow public abstract void needsUpdate(); + + @Shadow public abstract void renderLevel(PoseStack poseStack, float f, long l, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f); + private WorldRenderer worldRenderer; @Unique private Object2ReferenceOpenHashMap, ObjectArrayList>> entitiesMap = new Object2ReferenceOpenHashMap<>(); - //TODO clear VBOs - @Inject(method = "", at = @At("RETURN")) private void init(Minecraft minecraft, EntityRenderDispatcher entityRenderDispatcher, BlockEntityRenderDispatcher blockEntityRenderDispatcher, RenderBuffers renderBuffers, CallbackInfo ci) { this.worldRenderer = WorldRenderer.init(this.renderBuffers); @@ -192,11 +196,10 @@ private void popProfiler3(PoseStack poseStack, float f, long l, boolean bl, Came */ @Overwrite private void renderEntity(Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) { - //Entity lists optimization if(!Initializer.CONFIG.entityCulling) { - double h = Mth.lerp(g, entity.xOld, entity.getX()); - double i = Mth.lerp(g, entity.yOld, entity.getY()); - double j = Mth.lerp(g, entity.zOld, entity.getZ()); + double h = Mth.lerp((double)g, entity.xOld, entity.getX()); + double i = Mth.lerp((double)g, entity.yOld, entity.getY()); + double j = Mth.lerp((double)g, entity.zOld, entity.getZ()); float k = Mth.lerp(g, entity.yRotO, entity.getYRot()); this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, k, g, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, g)); return; @@ -238,4 +241,58 @@ private void renderEntities(PoseStack poseStack, float partialTicks, long l, boo } } +// @Redirect(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/ClientLevel;entitiesForRendering()Ljava/lang/Iterable;")) +// private Iterable replaceIterator(ClientLevel instance) { +// +// return () -> new Iterator() { +// @Override +// public boolean hasNext() { +// return false; +// } +// +// @Override +// public Entity next() { +// return null; +// } +// }; +// } +// +// @Inject(method = "renderLevel", at = @At(value = "INVOKE", +// target = "Lnet/minecraft/client/multiplayer/ClientLevel;entitiesForRendering()Ljava/lang/Iterable;", +// shift = At.Shift.AFTER), +// locals = LocalCapture.CAPTURE_FAILHARD +// ) +// private void renderEntities(PoseStack poseStack, float f, long l, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, CallbackInfo ci) { +// for(Entity entity : this.level.entitiesForRendering()) { +// if (this.entityRenderDispatcher.shouldRender(entity, frustum, d0, d1, d2) || entity.hasIndirectPassenger(this.minecraft.player)) { +// BlockPos blockpos = entity.blockPosition(); +// if ((this.level.isOutsideBuildHeight(blockpos.getY()) || this.isChunkCompiled(blockpos)) && (entity != p_109604_.getEntity() || p_109604_.isDetached() || p_109604_.getEntity() instanceof LivingEntity && ((LivingEntity)p_109604_.getEntity()).isSleeping()) && (!(entity instanceof LocalPlayer) || p_109604_.getEntity() == entity)) { +// ++this.renderedEntities; +// if (entity.tickCount == 0) { +// entity.xOld = entity.getX(); +// entity.yOld = entity.getY(); +// entity.zOld = entity.getZ(); +// } +// +// MultiBufferSource multibuffersource; +// if (this.shouldShowEntityOutlines() && this.minecraft.shouldEntityAppearGlowing(entity)) { +// flag3 = true; +// OutlineBufferSource outlinebuffersource = this.renderBuffers.outlineBufferSource(); +// multibuffersource = outlinebuffersource; +// int i = entity.getTeamColor(); +// int j = 255; +// int k = i >> 16 & 255; +// int l = i >> 8 & 255; +// int i1 = i & 255; +// outlinebuffersource.setColor(k, l, i1, 255); +// } else { +// multibuffersource = bu; +// } +// +// this.renderEntity(entity, d0, d1, d2, p_109601_, p_109600_, multibuffersource); +// } +// } +// } +// } + } diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java index aa1e841d6..12c2eadd3 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java @@ -11,7 +11,7 @@ import net.minecraft.server.packs.resources.ResourceManager; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.layout.Field; -import net.vulkanmod.vulkan.shader.layout.UBO; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.parser.GlslConverter; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.io.IOUtils; @@ -102,7 +102,7 @@ private void createShaders(ResourceManager resourceManager, String vertexShader, builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); builder.compileShaders(converter.getVshConverted(), converter.getFshConverted()); - this.pipeline = builder.createPipeline(); + this.pipeline = builder.createGraphicsPipeline(); } catch (IOException e) { throw new RuntimeException(e); diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java b/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java index 891ea0b66..2eed96df2 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java @@ -3,7 +3,7 @@ import com.mojang.blaze3d.preprocessor.GlslPreprocessor; import com.mojang.blaze3d.shaders.Program; import net.vulkanmod.gl.Util; -import net.vulkanmod.vulkan.shader.ShaderSPIRVUtils; +import net.vulkanmod.vulkan.shader.SPIRVUtils; import org.apache.commons.io.IOUtils; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -37,7 +37,7 @@ public static int compileShaderInternal(Program.Type type, String string, InputS //TODO glslPreprocessor.process(string3); - ShaderSPIRVUtils.compileShader(string2 + ":" + string, string3, Util.extToShaderKind(type.getExtension())); + SPIRVUtils.compileShader(string2 + ":" + string, string3, Util.extToShaderKind(type.getExtension())); } return 0; } diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java index c200305a0..1d3cc0ade 100644 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java @@ -5,6 +5,7 @@ import com.mojang.blaze3d.vertex.BufferUploader; import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -33,8 +34,8 @@ public static void drawWithShader(BufferBuilder.RenderedBuffer buffer) { if(parameters.vertexCount() <= 0) return; - Pipeline pipeline = ((ShaderMixed)(RenderSystem.getShader())).getPipeline(); - renderer.bindPipeline(pipeline); + GraphicsPipeline pipeline = ((ShaderMixed)(RenderSystem.getShader())).getPipeline(); + renderer.bindGraphicsPipeline(pipeline); renderer.uploadAndBindUBOs(pipeline); Renderer.getDrawer().draw(buffer.vertexBuffer(), 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 df6932229..a90f86280 100644 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java @@ -1,12 +1,10 @@ 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.shaders.Uniform; 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.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; @@ -14,9 +12,10 @@ import net.minecraft.util.GsonHelper; import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ShaderMixed; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.shader.layout.Field; -import net.vulkanmod.vulkan.shader.layout.UBO; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.shader.parser.GlslConverter; import net.vulkanmod.vulkan.util.MappedBuffer; import org.apache.commons.io.IOUtils; @@ -50,11 +49,11 @@ public class ShaderInstanceM implements ShaderMixed { @Shadow @Final @Nullable public Uniform PROJECTION_MATRIX; @Shadow @Final @Nullable public Uniform COLOR_MODULATOR; @Shadow @Final @Nullable public Uniform LINE_WIDTH; - private Pipeline pipeline; + private GraphicsPipeline pipeline; boolean isLegacy = false; - public Pipeline getPipeline() { + public GraphicsPipeline getPipeline() { return pipeline; } @@ -69,7 +68,7 @@ private void create(ResourceProvider resourceProvider, String name, VertexFormat Pipeline.Builder pipelineBuilder = new Pipeline.Builder(format, path); pipelineBuilder.parseBindingsJSON(); pipelineBuilder.compileShaders(); - this.pipeline = pipelineBuilder.createPipeline(); + this.pipeline = pipelineBuilder.createGraphicsPipeline(); } @Inject(method = "getOrCreate", at = @At("HEAD"), cancellable = true) @@ -194,7 +193,7 @@ private void createLegacyShader(ResourceProvider resourceProvider, ResourceLocat builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); builder.compileShaders(converter.getVshConverted(), converter.getFshConverted()); - this.pipeline = builder.createPipeline(); + this.pipeline = builder.createGraphicsPipeline(); this.isLegacy = true; } catch (Throwable throwable) { diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java index c6747dcdb..dfcca58bc 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java +++ b/src/main/java/net/vulkanmod/mixin/texture/MTextureManager.java @@ -5,6 +5,8 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.Tickable; import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.render.texture.SpriteUtil; +import net.vulkanmod.vulkan.Device; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -31,16 +33,16 @@ public void tick() { return; //Debug D -// if(SpriteUtil.shouldUpload()) -// GraphicsQueue.getInstance().startRecording(); -// for (Tickable tickable : this.tickableTextures) { -// tickable.tick(); -// } -// if(SpriteUtil.shouldUpload()) { -// SpriteUtil.transitionLayouts(GraphicsQueue.getInstance().getCommandBuffer()); -// GraphicsQueue.getInstance().endRecordingAndSubmit(); -//// Synchronization.INSTANCE.waitFences(); -// } + if(SpriteUtil.shouldUpload()) + Device.getGraphicsQueue().startRecording(); + for (Tickable tickable : this.tickableTextures) { + tickable.tick(); + } + if(SpriteUtil.shouldUpload()) { + SpriteUtil.transitionLayouts(Device.getGraphicsQueue().getCommandBuffer()); + Device.getGraphicsQueue().endRecordingAndSubmit(); +// Synchronization.INSTANCE.waitFences(); + } } /** diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 8cf3415b3..df32109b0 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -10,6 +10,7 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; import org.joml.Matrix4f; @@ -105,14 +106,14 @@ public void drawWithShader(Matrix4f MV, Matrix4f P, ShaderInstance shader) { } } - public void drawWithShader(Matrix4f MV, Matrix4f P, Pipeline pipeline) { + public void drawWithShader(Matrix4f MV, Matrix4f P, GraphicsPipeline pipeline) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); VRenderSystem.applyMVP(MV, P); Renderer renderer = Renderer.getInstance(); - renderer.bindPipeline(pipeline); + renderer.bindGraphicsPipeline(pipeline); renderer.uploadAndBindUBOs(pipeline); if(indexBuffer != null) diff --git a/src/main/java/net/vulkanmod/render/chunk/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/AreaBuffer.java index 7c68726ee..70b3247ed 100644 --- a/src/main/java/net/vulkanmod/render/chunk/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/AreaBuffer.java @@ -2,6 +2,7 @@ import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import net.vulkanmod.render.chunk.util.Util; +import net.vulkanmod.vulkan.Device; import net.vulkanmod.vulkan.memory.*; import net.vulkanmod.vulkan.queue.TransferQueue; @@ -122,7 +123,7 @@ public Segment reallocate(int uploadSize) { AreaUploadManager.INSTANCE.waitAllUploads(); //Sync upload - TransferQueue.getInstance().uploadBufferImmediate(this.buffer.getId(), 0, buffer.getId(), 0, this.buffer.getBufferSize()); + Device.getTransferQueue().uploadBufferImmediate(this.buffer.getId(), 0, buffer.getId(), 0, this.buffer.getBufferSize()); this.buffer.freeBuffer(); this.buffer = buffer; diff --git a/src/main/java/net/vulkanmod/render/chunk/AreaUploadManager.java b/src/main/java/net/vulkanmod/render/chunk/AreaUploadManager.java index 258bf735a..73601d63d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/AreaUploadManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/AreaUploadManager.java @@ -45,15 +45,15 @@ public synchronized void submitUploads() { if(this.recordedUploads[this.currentFrame].isEmpty()) return; - TransferQueue.getInstance().submitCommands(this.commandBuffers[currentFrame]); + Device.getTransferQueue().submitCommands(this.commandBuffers[currentFrame]); } public void uploadAsync(AreaBuffer.Segment uploadSegment, long bufferId, long dstOffset, long bufferSize, ByteBuffer src) { Validate.isTrue(currentFrame == Renderer.getCurrentFrame()); if(commandBuffers[currentFrame] == null) - this.commandBuffers[currentFrame] = TransferQueue.getInstance().beginCommands(); -// this.commandBuffers[currentFrame] = GraphicsQueue.getInstance().beginCommands(); + this.commandBuffers[currentFrame] = Device.getTransferQueue().beginCommands(); +// this.commandBuffers[currentFrame] = Device.getGraphicsQueue().beginCommands(); StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(this.currentFrame); stagingBuffer.copyBuffer((int) bufferSize, src); @@ -77,7 +77,7 @@ public void copy(Buffer src, Buffer dst) { } if(commandBuffers[currentFrame] == null) - this.commandBuffers[currentFrame] = TransferQueue.getInstance().beginCommands(); + this.commandBuffers[currentFrame] = Device.getTransferQueue().beginCommands(); TransferQueue.uploadBufferCmd(this.commandBuffers[currentFrame], src.getId(), 0, dst.getId(), 0, src.getBufferSize()); } diff --git a/src/main/java/net/vulkanmod/render/chunk/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/DrawBuffers.java index 481b74bfb..580697713 100644 --- a/src/main/java/net/vulkanmod/render/chunk/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/DrawBuffers.java @@ -7,7 +7,6 @@ import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.memory.IndirectBuffer; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.ShaderManager; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.VkCommandBuffer; @@ -19,7 +18,7 @@ public class DrawBuffers { - private static final int VERTEX_SIZE = ShaderManager.TERRAIN_VERTEX_FORMAT.getVertexSize(); + private static final int VERTEX_SIZE = TerrainShaderManager.TERRAIN_VERTEX_FORMAT.getVertexSize(); private static final int INDEX_SIZE = Short.BYTES; private boolean allocated = false; @@ -85,7 +84,7 @@ public int buildDrawBatchesIndirect(IndirectBuffer indirectBuffer, ChunkArea chu terrainRenderType.setCutoutUniform(); boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; - Pipeline pipeline = ShaderManager.getInstance().getTerrainIndirectShader(renderType); + Pipeline pipeline = TerrainShaderManager.getTerrainIndirectShader(renderType); if(isTranslucent) { vkCmdBindIndexBuffer(Renderer.getCommandBuffer(), this.indexBuffer.getId(), 0, VK_INDEX_TYPE_UINT16); @@ -168,7 +167,7 @@ public int buildDrawBatchesIndirect(IndirectBuffer indirectBuffer, ChunkArea chu } private static void fakeIndirectCmd(VkCommandBuffer commandBuffer, IndirectBuffer indirectBuffer, int drawCount, ByteBuffer offsetBuffer) { - Pipeline pipeline = ShaderManager.shaderManager.terrainDirectShader; + Pipeline pipeline = TerrainShaderManager.getTerrainDirectShader(null); // Drawer.getInstance().bindPipeline(pipeline); pipeline.bindDescriptorSets(Renderer.getCommandBuffer(), Renderer.getCurrentFrame()); // pipeline.bindDescriptorSets(Drawer.getCommandBuffer(), WorldRenderer.getInstance().getUniformBuffers(), Drawer.getCurrentFrame()); diff --git a/src/main/java/net/vulkanmod/render/chunk/TerrainShaderManager.java b/src/main/java/net/vulkanmod/render/chunk/TerrainShaderManager.java new file mode 100644 index 000000000..affbeeea8 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/TerrainShaderManager.java @@ -0,0 +1,69 @@ +package net.vulkanmod.render.chunk; + +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderType; +import net.vulkanmod.Initializer; +import net.vulkanmod.render.vertex.CustomVertexFormat; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; + +import java.util.function.Consumer; +import java.util.function.Function; + +public abstract class TerrainShaderManager { + public static VertexFormat TERRAIN_VERTEX_FORMAT; + + public static void setTerrainVertexFormat(VertexFormat format) { + TERRAIN_VERTEX_FORMAT = format; + } + + static GraphicsPipeline terrainIndirectShader; + public static GraphicsPipeline terrainDirectShader; + + private static Function shaderGetter; + + public static void init() { + setTerrainVertexFormat(CustomVertexFormat.COMPRESSED_TERRAIN); + createBasicPipelines(); + setDefaultShader(); + } + + public static void setDefaultShader() { + setShaderGetter(renderType -> Initializer.CONFIG.indirectDraw ? terrainIndirectShader : terrainDirectShader); + } + + private static void createBasicPipelines() { + terrainIndirectShader = createPipeline("terrain_indirect"); + terrainDirectShader = createPipeline("terrain_direct"); + } + + private static GraphicsPipeline createPipeline(String name) { + String path = String.format("basic/%s/%s", name, name); + + Pipeline.Builder pipelineBuilder = new Pipeline.Builder(CustomVertexFormat.COMPRESSED_TERRAIN, path); + pipelineBuilder.parseBindingsJSON(); + pipelineBuilder.compileShaders(); + return pipelineBuilder.createGraphicsPipeline(); + } + + public static GraphicsPipeline getTerrainShader(RenderType renderType) { + return shaderGetter.apply(renderType); + } + + public static void setShaderGetter(Function consumer) { + shaderGetter = consumer; + } + + public static GraphicsPipeline getTerrainDirectShader(RenderType renderType) { + return terrainDirectShader; + } + + public static GraphicsPipeline getTerrainIndirectShader(RenderType renderType) { + return terrainIndirectShader; + } + + public static void destroyPipelines() { + terrainIndirectShader.cleanUp(); + terrainDirectShader.cleanUp(); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index b181f920f..2fb75499e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -3,10 +3,7 @@ import com.google.common.collect.Lists; 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; -import com.mojang.blaze3d.vertex.VertexMultiConsumer; +import com.mojang.blaze3d.vertex.*; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.Camera; @@ -30,11 +27,11 @@ import net.vulkanmod.interfaces.FrustumMixed; import net.vulkanmod.render.chunk.build.ChunkTask; import net.vulkanmod.render.chunk.build.TaskDispatcher; +import net.vulkanmod.render.profiling.Profiler; +import net.vulkanmod.render.profiling.Profiler2; import net.vulkanmod.render.chunk.util.AreaSetQueue; import net.vulkanmod.render.chunk.util.ResettableQueue; import net.vulkanmod.render.chunk.util.Util; -import net.vulkanmod.render.profiling.Profiler; -import net.vulkanmod.render.profiling.Profiler2; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; @@ -42,7 +39,7 @@ import net.vulkanmod.vulkan.memory.Buffer; import net.vulkanmod.vulkan.memory.IndirectBuffer; import net.vulkanmod.vulkan.memory.MemoryTypes; -import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; import org.joml.FrustumIntersection; import org.joml.Matrix4f; @@ -196,7 +193,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus if (!isCapturedFrustum) { //Debug -// this.needsUpdate = true; + this.needsUpdate = true; // this.needsUpdate = false; if (this.needsUpdate) { @@ -215,6 +212,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus this.minecraft.getProfiler().push("partial_update"); this.chunkQueue.clear(); + this.initUpdate(); this.initializeQueueForFullUpdate(camera); this.renderRegionCache = new RenderRegionCache(); @@ -298,7 +296,7 @@ private void resetUpdateQueues() { private void updateRenderChunks() { int maxDirectionsChanges = Initializer.CONFIG.advCulling; - this.initUpdate(); +// this.initUpdate(); int rebuildLimit = taskDispatcher.getIdleThreadsCount(); // int rebuildLimit = 32; @@ -585,8 +583,8 @@ else if(layerName.equals("translucent")) VRenderSystem.applyMVP(poseStack.last().pose(), projection); Renderer renderer = Renderer.getInstance(); - Pipeline pipeline = TerrainShaderManager.getInstance().getTerrainShader(renderType); - renderer.bindPipeline(pipeline); + GraphicsPipeline pipeline = TerrainShaderManager.getTerrainShader(renderType); + renderer.bindGraphicsPipeline(pipeline); Renderer.getDrawer().bindAutoIndexBuffer(Renderer.getCommandBuffer(), 7); p.push("draw batches"); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/ChunkTask.java b/src/main/java/net/vulkanmod/render/chunk/build/ChunkTask.java index 1ebd40f2c..b2c36508f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/ChunkTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/ChunkTask.java @@ -25,7 +25,7 @@ import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.vertex.TerrainBufferBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; -import net.vulkanmod.vulkan.shader.ShaderManager; +import net.vulkanmod.render.chunk.TerrainShaderManager; import javax.annotation.Nullable; import java.util.*; @@ -167,7 +167,7 @@ private CompileResults compile(float camX, float camY, float camZ, ThreadBuilder bufferBuilder = chunkBufferBuilderPack.builder(renderType); if (set.add(renderType)) { - bufferBuilder.begin(VertexFormat.Mode.QUADS, ShaderManager.TERRAIN_VERTEX_FORMAT); + bufferBuilder.begin(VertexFormat.Mode.QUADS, TerrainShaderManager.TERRAIN_VERTEX_FORMAT); } blockRenderDispatcher.renderLiquid(blockPos3, renderChunkRegion, bufferBuilder, blockState2, fluidState); @@ -181,7 +181,7 @@ private CompileResults compile(float camX, float camY, float camZ, ThreadBuilder bufferBuilder = chunkBufferBuilderPack.builder(renderType); if (set.add(renderType)) { - bufferBuilder.begin(VertexFormat.Mode.QUADS, ShaderManager.TERRAIN_VERTEX_FORMAT); + bufferBuilder.begin(VertexFormat.Mode.QUADS, TerrainShaderManager.TERRAIN_VERTEX_FORMAT); } poseStack.pushPose(); @@ -291,7 +291,7 @@ public CompletableFuture doTask(ThreadBuilderPack builderPack) { TerrainBufferBuilder.SortState transparencyState = this.compiledSection.transparencyState; if (transparencyState != null && this.compiledSection.renderTypes.contains(TerrainRenderType.TRANSLUCENT)) { TerrainBufferBuilder bufferbuilder = builderPack.builder(RenderType.translucent()); - bufferbuilder.begin(VertexFormat.Mode.QUADS, ShaderManager.TERRAIN_VERTEX_FORMAT); + bufferbuilder.begin(VertexFormat.Mode.QUADS, TerrainShaderManager.TERRAIN_VERTEX_FORMAT); bufferbuilder.restoreSortState(transparencyState); // bufferbuilder.setQuadSortOrigin(f - (float) this.renderSection.origin.getX(), f1 - (float) renderSection.origin.getY(), f2 - (float) renderSection.origin.getZ()); bufferbuilder.setQuadSortOrigin(f - (float) this.renderSection.xOffset(), f1 - (float) renderSection.yOffset(), f2 - (float) renderSection.zOffset()); diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java index da40c704e..064adfb60 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java @@ -1,21 +1,15 @@ package net.vulkanmod.render.vertex; import com.google.common.collect.ImmutableList; -import com.google.common.primitives.Floats; import com.mojang.blaze3d.platform.MemoryTracker; import com.mojang.blaze3d.vertex.*; import com.mojang.logging.LogUtils; -import it.unimi.dsi.fastutil.ints.IntArrays; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Vec3i; import net.minecraft.util.Mth; import net.vulkanmod.render.util.SortUtil; -import net.vulkanmod.vulkan.shader.ShaderManager; +import net.vulkanmod.render.chunk.TerrainShaderManager; import org.apache.commons.lang3.mutable.MutableInt; import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; import org.joml.Vector3f; -import org.joml.Vector4f; import org.lwjgl.system.MemoryUtil; import org.slf4j.Logger; @@ -59,7 +53,7 @@ public TerrainBufferBuilder(int i) { this.buffer = MemoryTracker.create(i * 6); this.bufferPtr = MemoryUtil.memAddress0(this.buffer); - this.vertexBuilder = ShaderManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN ? new CompressedVertexBuilder() : new DefaultVertexBuilder(); + this.vertexBuilder = TerrainShaderManager.TERRAIN_VERTEX_FORMAT == CustomVertexFormat.COMPRESSED_TERRAIN ? new CompressedVertexBuilder() : new DefaultVertexBuilder(); } private void ensureVertexCapacity() { diff --git a/src/main/java/net/vulkanmod/vulkan/Device.java b/src/main/java/net/vulkanmod/vulkan/Device.java index 9ed864cf5..52ae3c64e 100644 --- a/src/main/java/net/vulkanmod/vulkan/Device.java +++ b/src/main/java/net/vulkanmod/vulkan/Device.java @@ -1,7 +1,7 @@ package net.vulkanmod.vulkan; import net.vulkanmod.Initializer; -import net.vulkanmod.vulkan.queue.Queue; +import net.vulkanmod.vulkan.queue.*; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.*; @@ -33,9 +33,10 @@ public class Device { public static SurfaceProperties surfaceProperties; - static VkQueue graphicsQueue; - static VkQueue presentQueue; - static VkQueue transferQueue; + static GraphicsQueue graphicsQueue; + static PresentQueue presentQueue; + static TransferQueue transferQueue; + static ComputeQueue computeQueue; static void pickPhysicalDevice(VkInstance instance) { @@ -176,16 +177,25 @@ static void createLogicalDevice() { device = new VkDevice(pDevice.get(0), physicalDevice, createInfo, VK_API_VERSION_1_2); - PointerBuffer pQueue = stack.pointers(VK_NULL_HANDLE); - - vkGetDeviceQueue(device, indices.graphicsFamily, 0, pQueue); - graphicsQueue = new VkQueue(pQueue.get(0), device); +// PointerBuffer pQueue = stack.pointers(VK_NULL_HANDLE); +// +// vkGetDeviceQueue(device, indices.graphicsFamily, 0, pQueue); +// graphicsQueue = new VkQueue(pQueue.get(0), device); +// +// vkGetDeviceQueue(device, indices.presentFamily, 0, pQueue); +// presentQueue = new VkQueue(pQueue.get(0), device); +// +// vkGetDeviceQueue(device, indices.transferFamily, 0, pQueue); +// transferQueue = new VkQueue(pQueue.get(0), device); - vkGetDeviceQueue(device, indices.presentFamily, 0, pQueue); - presentQueue = new VkQueue(pQueue.get(0), device); + graphicsQueue = new GraphicsQueue(stack, indices.graphicsFamily); + transferQueue = new TransferQueue(stack, indices.transferFamily); + presentQueue = new PresentQueue(stack, indices.presentFamily); + computeQueue = new ComputeQueue(stack, indices.computeFamily); - vkGetDeviceQueue(device, indices.transferFamily, 0, pQueue); - transferQueue = new VkQueue(pQueue.get(0), device); +// GraphicsQueue.createInstance(stack, indices.graphicsFamily); +// TransferQueue.createInstance(stack, indices.transferFamily); +// PresentQueue.createInstance(stack, indices.presentFamily); } } @@ -290,6 +300,30 @@ private static int findSupportedFormat(IntBuffer formatCandidates, int tiling, i throw new RuntimeException("Failed to find supported format"); } + public static void destroy() { + graphicsQueue.cleanUp(); + transferQueue.cleanUp(); + computeQueue.cleanUp(); + + vkDestroyDevice(device, null); + } + + public static GraphicsQueue getGraphicsQueue() { + return graphicsQueue; + } + + public static PresentQueue getPresentQueue() { + return presentQueue; + } + + public static TransferQueue getTransferQueue() { + return transferQueue; + } + + public static ComputeQueue getComputeQueue() { + return computeQueue; + } + public static SurfaceProperties querySurfaceProperties(VkPhysicalDevice device, MemoryStack stack) { long surface = Vulkan.getSurface(); diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 6c832edfb..f6598ab8d 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -4,16 +4,14 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.client.Minecraft; import net.vulkanmod.render.chunk.AreaUploadManager; +import net.vulkanmod.render.chunk.TerrainShaderManager; import net.vulkanmod.render.profiling.Profiler2; import net.vulkanmod.vulkan.framebuffer.Framebuffer; import net.vulkanmod.vulkan.framebuffer.RenderPass; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.passes.DefaultMainPass; import net.vulkanmod.vulkan.passes.MainPass; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.PipelineState; -import net.vulkanmod.vulkan.shader.ShaderManager; -import net.vulkanmod.vulkan.shader.Uniforms; +import net.vulkanmod.vulkan.shader.*; import net.vulkanmod.vulkan.shader.layout.PushConstants; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.util.VUtil; @@ -76,7 +74,7 @@ public Renderer() { device = Vulkan.getDevice(); Uniforms.setupDefaultUniforms(); - ShaderManager.init(); + TerrainShaderManager.init(); AreaUploadManager.createInstance(); framesNum = getSwapChainImages().size(); @@ -321,7 +319,7 @@ private void submitFrame() { Synchronization.INSTANCE.waitFences(); - if((vkResult = vkQueueSubmit(getGraphicsQueue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { + if((vkResult = vkQueueSubmit(Device.getGraphicsQueue().queue(), submitInfo, inFlightFences.get(currentFrame))) != VK_SUCCESS) { vkResetFences(device, stackGet().longs(inFlightFences.get(currentFrame))); throw new RuntimeException("Failed to submit draw command buffer: " + vkResult); } @@ -336,7 +334,7 @@ private void submitFrame() { presentInfo.pImageIndices(pImageIndex); - vkResult = vkQueuePresentKHR(getPresentQueue(), presentInfo); + vkResult = vkQueuePresentKHR(Device.getPresentQueue().queue(), presentInfo); if(vkResult == VK_ERROR_OUT_OF_DATE_KHR || vkResult == VK_SUBOPTIMAL_KHR || swapCahinUpdate) { swapCahinUpdate = true; @@ -363,7 +361,7 @@ void waitForSwapChain() .pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))) .pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); - vkQueueSubmit(getGraphicsQueue(), info, inFlightFences.get(currentFrame)); + vkQueueSubmit(Device.getGraphicsQueue().queue(), info, inFlightFences.get(currentFrame)); vkWaitForFences(device, inFlightFences.get(currentFrame), true, -1); } } @@ -412,7 +410,7 @@ public void cleanUpResources() { drawer.cleanUpResources(); - ShaderManager.getInstance().destroyPipelines(); + TerrainShaderManager.destroyPipelines(); VTextureSelector.getWhiteTexture().free(); } @@ -438,10 +436,9 @@ public void addOnResizeCallback(Runnable runnable) { this.onResizeCallbacks.add(runnable); } - public void bindPipeline(Pipeline pipeline) { + public void bindGraphicsPipeline(GraphicsPipeline pipeline) { VkCommandBuffer commandBuffer = currentCmdBuffer; -// PipelineState currentState = new PipelineState(currentBlendState, currentDepthState, currentLogicOpState, currentColorMask, boundRenderPass); PipelineState currentState = PipelineState.getCurrentPipelineState(boundRenderPass); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getHandle(currentState)); diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 52ed957d7..27e67cc56 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -145,7 +145,6 @@ public static void initVulkan(long window) { createVma(); MemoryTypes.createMemoryTypes(); - Queue.initQueues(); createCommandPool(); allocateImmediateCmdBuffer(); @@ -194,9 +193,6 @@ public static void cleanUp() { vkDestroyCommandPool(Device.device, commandPool, null); vkDestroyFence(Device.device, immediateFence, null); - GraphicsQueue.INSTANCE.cleanUp(); - TransferQueue.INSTANCE.cleanUp(); - Pipeline.destroyPipelineCache(); swapChain.cleanUp(); @@ -211,7 +207,7 @@ public static void cleanUp() { vmaDestroyAllocator(allocator); - vkDestroyDevice(Device.device, null); + Device.destroy(); destroyDebugUtilsMessengerEXT(instance, debugMessenger, null); KHRSurface.vkDestroySurfaceKHR(instance, surface, null); vkDestroyInstance(instance, null); @@ -421,7 +417,7 @@ public static void endImmediateCmd() { submitInfo.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO); submitInfo.pCommandBuffers(stack.pointers(immediateCmdBuffer)); - vkQueueSubmit(Device.graphicsQueue, submitInfo, immediateFence); + vkQueueSubmit(Device.getGraphicsQueue().queue(), submitInfo, immediateFence); vkWaitForFences(Device.device, immediateFence, true, VUtil.UINT64_MAX); vkResetFences(Device.device, immediateFence); @@ -459,12 +455,6 @@ public static void setVsync(boolean b) { public static long getSurface() { return surface; } - public static VkQueue getPresentQueue() { return Device.presentQueue; } - - public static VkQueue getGraphicsQueue() { return Device.graphicsQueue; } - - public static VkQueue getTransferQueue() { return Device.transferQueue; } - public static SwapChain getSwapChain() { return swapChain; } public static VkExtent2D getSwapchainExtent() diff --git a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java index aa795c916..76f96d82d 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/IndirectBuffer.java @@ -28,7 +28,7 @@ public void recordCopyCmd(ByteBuffer byteBuffer) { } else { if(commandBuffer == null) - commandBuffer = TransferQueue.getInstance().beginCommands(); + commandBuffer = Device.getTransferQueue().beginCommands(); StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(Renderer.getCurrentFrame()); stagingBuffer.copyBuffer(size, byteBuffer); @@ -51,7 +51,7 @@ public void submitUploads() { if(commandBuffer == null) return; - TransferQueue.getInstance().submitCommands(commandBuffer); + Device.getTransferQueue().submitCommands(commandBuffer); Synchronization.INSTANCE.addCommandBuffer(commandBuffer); commandBuffer = null; } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java index 89275a084..af824a349 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java @@ -160,6 +160,7 @@ 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 imageInfo.pQueueFamilyIndices(stack.ints(0,1)); VmaAllocationCreateInfo allocationInfo = VmaAllocationCreateInfo.callocStack(stack); @@ -267,7 +268,7 @@ private void freeImages() { List bufferList = freeableImages[currentFrame]; for(VulkanImage image : bufferList) { - image.doFree(this); + image.doFree(); } bufferList.clear(); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java index ad1ba9939..0b8724693 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryTypes.java @@ -68,7 +68,7 @@ void copyToBuffer(Buffer buffer, long bufferSize, ByteBuffer byteBuffer) { StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(Renderer.getCurrentFrame()); stagingBuffer.copyBuffer((int) bufferSize, byteBuffer); - TransferQueue.INSTANCE.copyBufferCmd(stagingBuffer.id, stagingBuffer.offset, buffer.getId(), buffer.getUsedBytes(), bufferSize); + Device.getTransferQueue().copyBufferCmd(stagingBuffer.id, stagingBuffer.offset, buffer.getId(), buffer.getUsedBytes(), bufferSize); } @Override @@ -81,7 +81,7 @@ public long copyBuffer(Buffer src, Buffer dst) { throw new IllegalArgumentException("dst size is less than src size."); } - return TransferQueue.INSTANCE.copyBufferCmd(src.getId(), 0, dst.getId(), 0, src.bufferSize); + return Device.getTransferQueue().copyBufferCmd(src.getId(), 0, dst.getId(), 0, src.bufferSize); } @Override @@ -90,7 +90,7 @@ void uploadBuffer(Buffer buffer, ByteBuffer byteBuffer) { StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(Renderer.getCurrentFrame()); stagingBuffer.copyBuffer(bufferSize, byteBuffer); - TransferQueue.INSTANCE.copyBufferCmd(stagingBuffer.id, stagingBuffer.offset, buffer.getId(), 0, bufferSize); + Device.getTransferQueue().copyBufferCmd(stagingBuffer.id, stagingBuffer.offset, buffer.getId(), 0, bufferSize); } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffers.java b/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffers.java index e8ca97e6d..a93c4a37e 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffers.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/UniformBuffers.java @@ -83,7 +83,7 @@ public void submitUploads() { if(commandBuffer == null) return; - TransferQueue.getInstance().submitCommands(commandBuffer); + Device.getTransferQueue().submitCommands(commandBuffer); Synchronization.INSTANCE.addCommandBuffer(commandBuffer); commandBuffer = null; } @@ -123,7 +123,7 @@ public void uploadUBO(ByteBuffer buffer, int offset) { } else { if(commandBuffer == null) - commandBuffer = TransferQueue.getInstance().beginCommands(); + commandBuffer = Device.getTransferQueue().beginCommands(); int size = buffer.remaining(); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/ComputeQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/ComputeQueue.java new file mode 100644 index 000000000..1c0d7c025 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/queue/ComputeQueue.java @@ -0,0 +1,10 @@ +package net.vulkanmod.vulkan.queue; + +import org.lwjgl.system.MemoryStack; + +public class ComputeQueue extends Queue { + + public ComputeQueue(MemoryStack stack, int familyIndex) { + super(stack, familyIndex); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java index f27c3a797..e449f617b 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java @@ -4,27 +4,18 @@ import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.util.VUtil; +import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.*; import static org.lwjgl.vulkan.VK10.*; public class GraphicsQueue extends Queue { - private static final VkDevice DEVICE = Vulkan.getDevice(); - public static GraphicsQueue INSTANCE; - public static void createInstance() { - INSTANCE = new GraphicsQueue(); - } - - public static GraphicsQueue getInstance() { - return INSTANCE; - } - private static CommandPool.CommandBuffer currentCmdBuffer; - protected GraphicsQueue() { - this.commandPool = new CommandPool(getQueueFamilies().graphicsFamily); + public GraphicsQueue(MemoryStack stack, int familyIndex) { + super(stack, familyIndex); } public void startRecording() { @@ -54,9 +45,4 @@ public long endIfNeeded(CommandPool.CommandBuffer commandBuffer) { } } - public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { - - return this.commandPool.submitCommands(commandBuffer, Vulkan.getGraphicsQueue()); - } - } diff --git a/src/main/java/net/vulkanmod/vulkan/queue/PresentQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/PresentQueue.java new file mode 100644 index 000000000..0997e72a4 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/queue/PresentQueue.java @@ -0,0 +1,10 @@ +package net.vulkanmod.vulkan.queue; + +import org.lwjgl.system.MemoryStack; + +public class PresentQueue extends Queue { + + public PresentQueue(MemoryStack stack, int familyIndex) { + super(stack, familyIndex, false); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index 46e525da5..b9cbbf8fe 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -1,11 +1,12 @@ package net.vulkanmod.vulkan.queue; +import net.vulkanmod.vulkan.Device; import net.vulkanmod.vulkan.Vulkan; +import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.*; import java.nio.IntBuffer; -import java.util.ArrayDeque; import java.util.stream.IntStream; import static org.lwjgl.system.MemoryStack.stackPush; @@ -18,15 +19,38 @@ public abstract class Queue { private static QueueFamilyIndices queueFamilyIndices; protected CommandPool commandPool; - public synchronized CommandPool.CommandBuffer beginCommands() { + private final VkQueue queue; + public synchronized CommandPool.CommandBuffer beginCommands() { return this.commandPool.beginCommands(); } - public abstract long submitCommands(CommandPool.CommandBuffer commandBuffer); + Queue(MemoryStack stack, int familyIndex) { + this(stack, familyIndex, true); + } + + Queue(MemoryStack stack, int familyIndex, boolean initCommandPool) { + PointerBuffer pQueue = stack.mallocPointer(1); + vkGetDeviceQueue(Device.device, familyIndex, 0, pQueue); + this.queue = new VkQueue(pQueue.get(0), Device.device); + + if(initCommandPool) + this.commandPool = new CommandPool(familyIndex); + } + + public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { + return this.commandPool.submitCommands(commandBuffer, queue); + } + + public VkQueue queue() { return this.queue; } public void cleanUp() { - commandPool.cleanUp(); + if(commandPool != null) + commandPool.cleanUp(); + } + + public void waitIdle() { + vkQueueWaitIdle(queue); } public enum Family { @@ -35,11 +59,6 @@ public enum Family { Compute } - public static void initQueues() { - GraphicsQueue.createInstance(); - TransferQueue.createInstance(); - } - public static QueueFamilyIndices getQueueFamilies() { if(DEVICE == null) DEVICE = Vulkan.getDevice(); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java index aeeae9bcb..3a27c0453 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java @@ -14,18 +14,8 @@ public class TransferQueue extends Queue { private static final VkDevice DEVICE = Vulkan.getDevice(); - public static TransferQueue INSTANCE; - - public static void createInstance() { - INSTANCE = new TransferQueue(); - } - - public static TransferQueue getInstance() { - return INSTANCE; - } - - protected TransferQueue() { - commandPool = new CommandPool(getQueueFamilies().transferFamily); + public TransferQueue(MemoryStack stack, int familyIndex) { + super(stack, familyIndex); } public long copyBufferCmd(long srcBuffer, long srcOffset, long dstBuffer, long dstOffset, long size) { @@ -34,7 +24,7 @@ public long copyBufferCmd(long srcBuffer, long srcOffset, long dstBuffer, long d CommandPool.CommandBuffer commandBuffer = beginCommands(); - VkBufferCopy.Buffer copyRegion = VkBufferCopy.callocStack(1, stack); + VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); copyRegion.size(size); copyRegion.srcOffset(srcOffset); copyRegion.dstOffset(dstOffset); @@ -53,7 +43,7 @@ public void uploadBufferImmediate(long srcBuffer, long srcOffset, long dstBuffer try(MemoryStack stack = stackPush()) { CommandPool.CommandBuffer commandBuffer = this.beginCommands(); - VkBufferCopy.Buffer copyRegion = VkBufferCopy.callocStack(1, stack); + VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); copyRegion.size(size); copyRegion.srcOffset(srcOffset); copyRegion.dstOffset(dstOffset); @@ -66,16 +56,11 @@ public void uploadBufferImmediate(long srcBuffer, long srcOffset, long dstBuffer } } - public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { - - return this.commandPool.submitCommands(commandBuffer, Vulkan.getTransferQueue()); - } - public static void uploadBufferCmd(CommandPool.CommandBuffer commandBuffer, long srcBuffer, long srcOffset, long dstBuffer, long dstOffset, long size) { try(MemoryStack stack = stackPush()) { - VkBufferCopy.Buffer copyRegion = VkBufferCopy.callocStack(1, stack); + VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); copyRegion.size(size); copyRegion.srcOffset(srcOffset); copyRegion.dstOffset(dstOffset); @@ -83,9 +68,5 @@ public static void uploadBufferCmd(CommandPool.CommandBuffer commandBuffer, long vkCmdCopyBuffer(commandBuffer.getHandle(), srcBuffer, dstBuffer, copyRegion); } } - - public static void waitIdle() { - vkQueueWaitIdle(Vulkan.getTransferQueue()); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java new file mode 100644 index 000000000..3fe15a346 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -0,0 +1,334 @@ +package net.vulkanmod.vulkan.shader; + +import com.google.common.collect.ImmutableList; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import net.vulkanmod.interfaces.VertexFormatMixed; +import net.vulkanmod.vulkan.Device; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.Vulkan; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.vulkan.*; + +import java.nio.ByteBuffer; +import java.nio.LongBuffer; +import java.util.HashMap; +import java.util.Map; + +import static net.vulkanmod.vulkan.shader.PipelineState.*; +import static net.vulkanmod.vulkan.shader.PipelineState.DEFAULT_COLORMASK; +import static org.lwjgl.system.MemoryStack.stackGet; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK10.vkDestroyPipelineLayout; + +public class GraphicsPipeline extends Pipeline { + + private final Map graphicsPipelines = new HashMap<>(); + private final VertexFormat vertexFormat; + + private long vertShaderModule = 0; + private long fragShaderModule = 0; + + GraphicsPipeline(Builder builder) { + super(builder.shaderPath); + this.buffers = builder.UBOs; + this.manualUBO = builder.manualUBO; + this.images = builder.images; + this.pushConstants = builder.pushConstants; + this.vertexFormat = builder.vertexFormat; + + 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), + this::createGraphicsPipeline); + + createDescriptorSets(Vulkan.getSwapChainImages().size()); + + PIPELINES.add(this); + } + + public long getHandle(PipelineState state) { + return graphicsPipelines.computeIfAbsent(state, this::createGraphicsPipeline); + } + + private long createGraphicsPipeline(PipelineState state) { + + try(MemoryStack stack = stackPush()) { + + ByteBuffer entryPoint = stack.UTF8("main"); + + VkPipelineShaderStageCreateInfo.Buffer shaderStages = VkPipelineShaderStageCreateInfo.calloc(2, stack); + + 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); + + 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); + + // ===> VERTEX STAGE <=== + + VkPipelineVertexInputStateCreateInfo vertexInputInfo = VkPipelineVertexInputStateCreateInfo.calloc(stack); + vertexInputInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO); + vertexInputInfo.pVertexBindingDescriptions(getBindingDescription(vertexFormat)); + vertexInputInfo.pVertexAttributeDescriptions(getAttributeDescriptions(vertexFormat)); + + // ===> ASSEMBLY STAGE <=== + + VkPipelineInputAssemblyStateCreateInfo inputAssembly = VkPipelineInputAssemblyStateCreateInfo.calloc(stack); + inputAssembly.sType(VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO); + inputAssembly.topology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); + inputAssembly.primitiveRestartEnable(false); + + // ===> VIEWPORT & SCISSOR + + VkPipelineViewportStateCreateInfo viewportState = VkPipelineViewportStateCreateInfo.calloc(stack); + viewportState.sType(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO); + + viewportState.viewportCount(1); + viewportState.scissorCount(1); + + // ===> RASTERIZATION STAGE <=== + + VkPipelineRasterizationStateCreateInfo rasterizer = VkPipelineRasterizationStateCreateInfo.calloc(stack); + rasterizer.sType(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO); + rasterizer.depthClampEnable(false); + rasterizer.rasterizerDiscardEnable(false); + rasterizer.polygonMode(VK_POLYGON_MODE_FILL); + rasterizer.lineWidth(1.0f); + + if(state.cullState) + rasterizer.cullMode(VK_CULL_MODE_BACK_BIT); + else + rasterizer.cullMode(VK_CULL_MODE_NONE); + + rasterizer.frontFace(VK_FRONT_FACE_COUNTER_CLOCKWISE); + rasterizer.depthBiasEnable(true); + + // ===> MULTISAMPLING <=== + + VkPipelineMultisampleStateCreateInfo multisampling = VkPipelineMultisampleStateCreateInfo.calloc(stack); + multisampling.sType(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO); + multisampling.sampleShadingEnable(false); + multisampling.rasterizationSamples(VK_SAMPLE_COUNT_1_BIT); + + // ===> DEPTH TEST <=== + + VkPipelineDepthStencilStateCreateInfo depthStencil = VkPipelineDepthStencilStateCreateInfo.calloc(stack); + depthStencil.sType(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO); + depthStencil.depthTestEnable(state.depthState.depthTest); + depthStencil.depthWriteEnable(state.depthState.depthMask); + depthStencil.depthCompareOp(state.depthState.function); + depthStencil.depthBoundsTestEnable(false); + depthStencil.minDepthBounds(0.0f); // Optional + depthStencil.maxDepthBounds(1.0f); // Optional + depthStencil.stencilTestEnable(false); + + // ===> COLOR BLENDING <=== + + VkPipelineColorBlendAttachmentState.Buffer colorBlendAttachment = VkPipelineColorBlendAttachmentState.calloc(1, stack); + colorBlendAttachment.colorWriteMask(state.colorMask.colorMask); + + if(state.blendState.enabled) { + colorBlendAttachment.blendEnable(true); + colorBlendAttachment.srcColorBlendFactor(state.blendState.srcRgbFactor); + colorBlendAttachment.dstColorBlendFactor(state.blendState.dstRgbFactor); + colorBlendAttachment.colorBlendOp(VK_BLEND_OP_ADD); + colorBlendAttachment.srcAlphaBlendFactor(state.blendState.srcAlphaFactor); + colorBlendAttachment.dstAlphaBlendFactor(state.blendState.dstAlphaFactor); + colorBlendAttachment.alphaBlendOp(VK_BLEND_OP_ADD); + } + else { + colorBlendAttachment.blendEnable(false); + } + + VkPipelineColorBlendStateCreateInfo colorBlending = VkPipelineColorBlendStateCreateInfo.calloc(stack); + colorBlending.sType(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO); + colorBlending.logicOpEnable(state.logicOpState.enabled); + colorBlending.logicOp(state.logicOpState.getLogicOp()); + colorBlending.pAttachments(colorBlendAttachment); + colorBlending.blendConstants(stack.floats(0.0f, 0.0f, 0.0f, 0.0f)); + + // ===> DYNAMIC STATES <=== + + VkPipelineDynamicStateCreateInfo dynamicStates = VkPipelineDynamicStateCreateInfo.calloc(stack); + dynamicStates.sType(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); + 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); + pipelineInfo.pStages(shaderStages); + pipelineInfo.pVertexInputState(vertexInputInfo); + pipelineInfo.pInputAssemblyState(inputAssembly); + pipelineInfo.pViewportState(viewportState); + pipelineInfo.pRasterizationState(rasterizer); + pipelineInfo.pMultisampleState(multisampling); + pipelineInfo.pDepthStencilState(depthStencil); + pipelineInfo.pColorBlendState(colorBlending); + pipelineInfo.pDynamicState(dynamicStates); + pipelineInfo.layout(pipelineLayout); + pipelineInfo.basePipelineHandle(VK_NULL_HANDLE); + pipelineInfo.basePipelineIndex(-1); + + if(!Vulkan.DYNAMIC_RENDERING) { + pipelineInfo.renderPass(state.renderPass.getId()); + pipelineInfo.subpass(0); + } + else { + //dyn-rendering + VkPipelineRenderingCreateInfoKHR renderingInfo = VkPipelineRenderingCreateInfoKHR.calloc(stack); + renderingInfo.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); + renderingInfo.pColorAttachmentFormats(stack.ints(state.renderPass.getFramebuffer().getFormat())); + renderingInfo.depthAttachmentFormat(state.renderPass.getFramebuffer().getDepthFormat()); + pipelineInfo.pNext(renderingInfo); + } + + LongBuffer pGraphicsPipeline = stack.mallocLong(1); + + if(vkCreateGraphicsPipelines(Device.device, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline) != VK_SUCCESS) { + throw new RuntimeException("Failed to create graphics pipeline"); + } + + return pGraphicsPipeline.get(0); + } + } + + private void createShaderModules(SPIRVUtils.SPIRV vertSpirv, SPIRVUtils.SPIRV fragSpirv) { + this.vertShaderModule = createShaderModule(vertSpirv.bytecode()); + this.fragShaderModule = createShaderModule(fragSpirv.bytecode()); + } + + private static VkVertexInputBindingDescription.Buffer getBindingDescription(VertexFormat vertexFormat) { + + VkVertexInputBindingDescription.Buffer bindingDescription = + VkVertexInputBindingDescription.calloc(1); + + bindingDescription.binding(0); + bindingDescription.stride(vertexFormat.getVertexSize()); + bindingDescription.inputRate(VK_VERTEX_INPUT_RATE_VERTEX); + + return bindingDescription; + } + + private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions(VertexFormat vertexFormat) { + + ImmutableList elements = vertexFormat.getElements(); + + int size = elements.size(); + if(elements.stream().anyMatch(vertexFormatElement -> vertexFormatElement.getUsage() == VertexFormatElement.Usage.PADDING)) { + size--; + } + + VkVertexInputAttributeDescription.Buffer attributeDescriptions = + VkVertexInputAttributeDescription.calloc(size, stackGet()); + + int offset = 0; + + for(int i = 0; i < size; ++i) { + VkVertexInputAttributeDescription posDescription = attributeDescriptions.get(i); + posDescription.binding(0); + posDescription.location(i); + + VertexFormatElement formatElement = elements.get(i); + VertexFormatElement.Usage usage = formatElement.getUsage(); + VertexFormatElement.Type type = formatElement.getType(); + switch (usage) { + case POSITION : + if(type == VertexFormatElement.Type.FLOAT) { + posDescription.format(VK_FORMAT_R32G32B32_SFLOAT); + posDescription.offset(offset); + + offset += 12; + } + else if (type == VertexFormatElement.Type.SHORT) { + posDescription.format(VK_FORMAT_R16G16B16A16_SINT); + posDescription.offset(offset); + + offset += 8; + } + else if (type == VertexFormatElement.Type.BYTE) { + posDescription.format(VK_FORMAT_R8G8B8A8_SINT); + posDescription.offset(offset); + + offset += 4; + } + + break; + + case COLOR: + posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); + posDescription.offset(offset); + +// offset += 16; + offset += 4; + break; + + case UV: + if(type == VertexFormatElement.Type.FLOAT){ + posDescription.format(VK_FORMAT_R32G32_SFLOAT); + posDescription.offset(offset); + + offset += 8; + } + else if(type == VertexFormatElement.Type.SHORT){ + posDescription.format(VK_FORMAT_R16G16_SINT); + posDescription.offset(offset); + + offset += 4; + } + else if(type == VertexFormatElement.Type.USHORT){ + posDescription.format(VK_FORMAT_R16G16_UINT); + posDescription.offset(offset); + + offset += 4; + } + break; + + case NORMAL: + posDescription.format(VK_FORMAT_R8G8B8A8_SNORM); + posDescription.offset(offset); + + offset += 4; + break; + + case PADDING: + + default: + throw new RuntimeException(String.format("Unknown format: %s", usage)); + } + + posDescription.offset(((VertexFormatMixed)(vertexFormat)).getOffset(i)); + } + + return attributeDescriptions.rewind(); + } + + public void cleanUp() { + vkDestroyShaderModule(Device.device, vertShaderModule, null); + vkDestroyShaderModule(Device.device, fragShaderModule, null); + + destroyDescriptorSets(); + + graphicsPipelines.forEach((state, pipeline) -> { + vkDestroyPipeline(Device.device, pipeline, null); + }); + graphicsPipelines.clear(); + + vkDestroyDescriptorSetLayout(Device.device, descriptorSetLayout, null); + vkDestroyPipelineLayout(Device.device, pipelineLayout, null); + + PIPELINES.remove(this); + Renderer.getInstance().removeUsedPipeline(this); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 91b55c44b..23732bd73 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -1,22 +1,21 @@ package net.vulkanmod.vulkan.shader; -import com.google.common.collect.ImmutableList; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; import net.minecraft.util.GsonHelper; -import net.vulkanmod.interfaces.VertexFormatMixed; import net.vulkanmod.vulkan.*; import net.vulkanmod.vulkan.framebuffer.RenderPass; -import net.vulkanmod.vulkan.shader.ShaderSPIRVUtils.SPIRV; -import net.vulkanmod.vulkan.shader.ShaderSPIRVUtils.ShaderKind; +import net.vulkanmod.vulkan.shader.SPIRVUtils.SPIRV; +import net.vulkanmod.vulkan.shader.SPIRVUtils.ShaderKind; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.UniformBuffers; +import net.vulkanmod.vulkan.shader.descriptor.Image; +import net.vulkanmod.vulkan.shader.descriptor.ManualUBO; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; import net.vulkanmod.vulkan.shader.layout.PushConstants; -import net.vulkanmod.vulkan.shader.layout.UBO; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.texture.VulkanImage; import org.apache.commons.lang3.Validate; @@ -32,260 +31,106 @@ import java.nio.charset.StandardCharsets; import java.util.*; -import static net.vulkanmod.vulkan.shader.ShaderSPIRVUtils.compileShader; -import static net.vulkanmod.vulkan.shader.ShaderSPIRVUtils.compileShaderFile; -import static net.vulkanmod.vulkan.shader.PipelineState.*; +import static net.vulkanmod.vulkan.shader.SPIRVUtils.*; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.VK10.*; -public class Pipeline { +public abstract class Pipeline { private static final VkDevice DEVICE = Vulkan.getDevice(); - private static final long PIPELINE_CACHE = createPipelineCache(); - private static final List PIPELINES = new LinkedList<>(); - - public static void recreateDescriptorSets(int frames) { - PIPELINES.forEach(pipeline -> { - pipeline.destroyDescriptorSets(); - pipeline.createDescriptorSets(frames); - }); - } - - private long descriptorSetLayout; - private long pipelineLayout; - private final Map graphicsPipelines = new HashMap<>(); - private final VertexFormat vertexFormat; - - private DescriptorSets[] descriptorSets; - private final List UBOs; - private final ManualUBO manualUBO; - private final List samplers; - private final PushConstants pushConstants; - - private long vertShaderModule = 0; - private long fragShaderModule = 0; - - public Pipeline(VertexFormat vertexFormat, RenderPass renderPass, List UBOs, ManualUBO manualUBO, List samplers, PushConstants pushConstants, SPIRV vertSpirv, SPIRV fragSpirv) { - this.UBOs = UBOs; - this.manualUBO = manualUBO; - this.samplers = samplers; - this.pushConstants = pushConstants; - this.vertexFormat = vertexFormat; - - createDescriptorSetLayout(); - createPipelineLayout(); - createShaderModules(vertSpirv, fragSpirv); - - if(renderPass != null) - graphicsPipelines.computeIfAbsent(new PipelineState(DEFAULT_BLEND_STATE, DEFAULT_DEPTH_STATE, DEFAULT_LOGICOP_STATE, DEFAULT_COLORMASK, renderPass), - this::createGraphicsPipeline); - - createDescriptorSets(Vulkan.getSwapChainImages().size()); - - PIPELINES.add(this); - } - - private long createGraphicsPipeline(PipelineState state) { + protected static final long PIPELINE_CACHE = createPipelineCache(); + protected static final List PIPELINES = new LinkedList<>(); + private static long createPipelineCache() { try(MemoryStack stack = stackPush()) { - ByteBuffer entryPoint = stack.UTF8("main"); - - VkPipelineShaderStageCreateInfo.Buffer shaderStages = VkPipelineShaderStageCreateInfo.callocStack(2, stack); - - 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); - - 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); - - // ===> VERTEX STAGE <=== - - VkPipelineVertexInputStateCreateInfo vertexInputInfo = VkPipelineVertexInputStateCreateInfo.callocStack(stack); - vertexInputInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO); - vertexInputInfo.pVertexBindingDescriptions(getBindingDescription(vertexFormat)); - vertexInputInfo.pVertexAttributeDescriptions(getAttributeDescriptions(vertexFormat)); - - // ===> ASSEMBLY STAGE <=== - - VkPipelineInputAssemblyStateCreateInfo inputAssembly = VkPipelineInputAssemblyStateCreateInfo.callocStack(stack); - inputAssembly.sType(VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO); - inputAssembly.topology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); - inputAssembly.primitiveRestartEnable(false); - - // ===> VIEWPORT & SCISSOR - - VkPipelineViewportStateCreateInfo viewportState = VkPipelineViewportStateCreateInfo.callocStack(stack); - viewportState.sType(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO); - - viewportState.viewportCount(1); - viewportState.scissorCount(1); - - // ===> RASTERIZATION STAGE <=== - - VkPipelineRasterizationStateCreateInfo rasterizer = VkPipelineRasterizationStateCreateInfo.callocStack(stack); - rasterizer.sType(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO); - rasterizer.depthClampEnable(false); - rasterizer.rasterizerDiscardEnable(false); - rasterizer.polygonMode(VK_POLYGON_MODE_FILL); - rasterizer.lineWidth(1.0f); - - if(state.cullState) - rasterizer.cullMode(VK_CULL_MODE_BACK_BIT); - else - rasterizer.cullMode(VK_CULL_MODE_NONE); - - rasterizer.frontFace(VK_FRONT_FACE_COUNTER_CLOCKWISE); - rasterizer.depthBiasEnable(true); - - // ===> MULTISAMPLING <=== - - VkPipelineMultisampleStateCreateInfo multisampling = VkPipelineMultisampleStateCreateInfo.callocStack(stack); - multisampling.sType(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO); - multisampling.sampleShadingEnable(false); - multisampling.rasterizationSamples(VK_SAMPLE_COUNT_1_BIT); + VkPipelineCacheCreateInfo cacheCreateInfo = VkPipelineCacheCreateInfo.calloc(stack); + cacheCreateInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO); - // ===> DEPTH TEST <=== + LongBuffer pPipelineCache = stack.mallocLong(1); - VkPipelineDepthStencilStateCreateInfo depthStencil = VkPipelineDepthStencilStateCreateInfo.callocStack(stack); - depthStencil.sType(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO); - depthStencil.depthTestEnable(state.depthState.depthTest); - depthStencil.depthWriteEnable(state.depthState.depthMask); - depthStencil.depthCompareOp(state.depthState.function); - depthStencil.depthBoundsTestEnable(false); - depthStencil.minDepthBounds(0.0f); // Optional - depthStencil.maxDepthBounds(1.0f); // Optional - depthStencil.stencilTestEnable(false); + if(vkCreatePipelineCache(DEVICE, cacheCreateInfo, null, pPipelineCache) != VK_SUCCESS) { + throw new RuntimeException("Failed to create graphics pipeline"); + } - // ===> COLOR BLENDING <=== + return pPipelineCache.get(0); + } + } - VkPipelineColorBlendAttachmentState.Buffer colorBlendAttachment = VkPipelineColorBlendAttachmentState.callocStack(1, stack); - colorBlendAttachment.colorWriteMask(state.colorMask.colorMask); + public static void destroyPipelineCache() { + vkDestroyPipelineCache(DEVICE, PIPELINE_CACHE, null); + } - if(state.blendState.enabled) { - colorBlendAttachment.blendEnable(true); - colorBlendAttachment.srcColorBlendFactor(state.blendState.srcRgbFactor); - colorBlendAttachment.dstColorBlendFactor(state.blendState.dstRgbFactor); - colorBlendAttachment.colorBlendOp(VK_BLEND_OP_ADD); - colorBlendAttachment.srcAlphaBlendFactor(state.blendState.srcAlphaFactor); - colorBlendAttachment.dstAlphaBlendFactor(state.blendState.dstAlphaFactor); - colorBlendAttachment.alphaBlendOp(VK_BLEND_OP_ADD); - } - else { - colorBlendAttachment.blendEnable(false); - } + public static void recreateDescriptorSets(int frames) { + PIPELINES.forEach(pipeline -> { + pipeline.destroyDescriptorSets(); + pipeline.createDescriptorSets(frames); + }); + } - VkPipelineColorBlendStateCreateInfo colorBlending = VkPipelineColorBlendStateCreateInfo.callocStack(stack); - colorBlending.sType(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO); - colorBlending.logicOpEnable(state.logicOpState.enabled); - colorBlending.logicOp(state.logicOpState.getLogicOp()); - colorBlending.pAttachments(colorBlendAttachment); - colorBlending.blendConstants(stack.floats(0.0f, 0.0f, 0.0f, 0.0f)); - - // ===> DYNAMIC STATES <=== - - VkPipelineDynamicStateCreateInfo dynamicStates = VkPipelineDynamicStateCreateInfo.callocStack(stack); - dynamicStates.sType(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); - dynamicStates.pDynamicStates(stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR)); - - VkGraphicsPipelineCreateInfo.Buffer pipelineInfo = VkGraphicsPipelineCreateInfo.callocStack(1, stack); - pipelineInfo.sType(VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO); - pipelineInfo.pStages(shaderStages); - pipelineInfo.pVertexInputState(vertexInputInfo); - pipelineInfo.pInputAssemblyState(inputAssembly); - pipelineInfo.pViewportState(viewportState); - pipelineInfo.pRasterizationState(rasterizer); - pipelineInfo.pMultisampleState(multisampling); - pipelineInfo.pDepthStencilState(depthStencil); - pipelineInfo.pColorBlendState(colorBlending); - pipelineInfo.pDynamicState(dynamicStates); - pipelineInfo.layout(pipelineLayout); - pipelineInfo.basePipelineHandle(VK_NULL_HANDLE); - pipelineInfo.basePipelineIndex(-1); - - if(!Vulkan.DYNAMIC_RENDERING) { - pipelineInfo.renderPass(state.renderPass.getId()); - pipelineInfo.subpass(0); - } - else { - //dyn-rendering - VkPipelineRenderingCreateInfoKHR renderingInfo = VkPipelineRenderingCreateInfoKHR.calloc(stack); - renderingInfo.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); - renderingInfo.pColorAttachmentFormats(stack.ints(state.renderPass.getFramebuffer().getFormat())); - renderingInfo.depthAttachmentFormat(state.renderPass.getFramebuffer().getDepthFormat()); - pipelineInfo.pNext(renderingInfo); - } + public final String name; - LongBuffer pGraphicsPipeline = stack.mallocLong(1); + protected long descriptorSetLayout; + protected long pipelineLayout; - if(vkCreateGraphicsPipelines(DEVICE, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline) != VK_SUCCESS) { - throw new RuntimeException("Failed to create graphics pipeline"); - } + protected DescriptorSets[] descriptorSets; + protected List buffers; + protected ManualUBO manualUBO; + protected List images; + protected PushConstants pushConstants; - return pGraphicsPipeline.get(0); - } + public Pipeline(String name) { + this.name = name; } - private void createDescriptorSetLayout() { + protected void createDescriptorSetLayout() { try(MemoryStack stack = stackPush()) { - int bindingsSize = this.UBOs.size() + samplers.size(); + int bindingsSize = this.buffers.size() + images.size(); - VkDescriptorSetLayoutBinding.Buffer bindings = VkDescriptorSetLayoutBinding.callocStack(bindingsSize, stack); + VkDescriptorSetLayoutBinding.Buffer bindings = VkDescriptorSetLayoutBinding.calloc(bindingsSize, stack); - for(UBO ubo : this.UBOs) { + for(UBO ubo : this.buffers) { VkDescriptorSetLayoutBinding uboLayoutBinding = bindings.get(ubo.getBinding()); uboLayoutBinding.binding(ubo.getBinding()); uboLayoutBinding.descriptorCount(1); - uboLayoutBinding.descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC); + uboLayoutBinding.descriptorType(ubo.getType()); uboLayoutBinding.pImmutableSamplers(null); - uboLayoutBinding.stageFlags(ubo.getFlags()); - + uboLayoutBinding.stageFlags(ubo.getStages()); } - for(Sampler sampler : this.samplers) { - VkDescriptorSetLayoutBinding samplerLayoutBinding = bindings.get(sampler.binding); - samplerLayoutBinding.binding(sampler.binding); + for(Image image : this.images) { + VkDescriptorSetLayoutBinding samplerLayoutBinding = bindings.get(image.getBinding()); + samplerLayoutBinding.binding(image.getBinding()); samplerLayoutBinding.descriptorCount(1); - samplerLayoutBinding.descriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); + samplerLayoutBinding.descriptorType(image.getType()); samplerLayoutBinding.pImmutableSamplers(null); - samplerLayoutBinding.stageFlags(VK_SHADER_STAGE_ALL_GRAPHICS); - -// ++i; + samplerLayoutBinding.stageFlags(image.getStages()); } - VkDescriptorSetLayoutCreateInfo layoutInfo = VkDescriptorSetLayoutCreateInfo.callocStack(stack); + VkDescriptorSetLayoutCreateInfo layoutInfo = VkDescriptorSetLayoutCreateInfo.calloc(stack); layoutInfo.sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO); layoutInfo.pBindings(bindings); LongBuffer pDescriptorSetLayout = stack.mallocLong(1); - if(vkCreateDescriptorSetLayout(DEVICE, layoutInfo, null, pDescriptorSetLayout) != VK_SUCCESS) { + if(vkCreateDescriptorSetLayout(Device.device, layoutInfo, null, pDescriptorSetLayout) != VK_SUCCESS) { throw new RuntimeException("Failed to create descriptor set layout"); } -// this.descriptorSetLayout.put(0, pDescriptorSetLayout.get(0)); this.descriptorSetLayout = pDescriptorSetLayout.get(0); } } - private void createPipelineLayout() { + protected void createPipelineLayout() { try(MemoryStack stack = stackPush()) { // ===> PIPELINE LAYOUT CREATION <=== - VkPipelineLayoutCreateInfo pipelineLayoutInfo = VkPipelineLayoutCreateInfo.callocStack(stack); + VkPipelineLayoutCreateInfo pipelineLayoutInfo = VkPipelineLayoutCreateInfo.calloc(stack); pipelineLayoutInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO); pipelineLayoutInfo.pSetLayouts(stack.longs(this.descriptorSetLayout)); if(this.pushConstants != null) { - VkPushConstantRange.Buffer pushConstantRange = VkPushConstantRange.callocStack(1, stack); + VkPushConstantRange.Buffer pushConstantRange = VkPushConstantRange.calloc(1, stack); pushConstantRange.size(this.pushConstants.getSize()); pushConstantRange.offset(0); pushConstantRange.stageFlags(VK_SHADER_STAGE_VERTEX_BIT); @@ -303,37 +148,16 @@ private void createPipelineLayout() { } } - private void createDescriptorSets(int frames) { + protected void createDescriptorSets(int frames) { descriptorSets = new DescriptorSets[frames]; for(int i = 0; i < frames; ++i) { descriptorSets[i] = new DescriptorSets(i); } } - private void createShaderModules(SPIRV vertSpirv, SPIRV fragSpirv) { - this.vertShaderModule = createShaderModule(vertSpirv.bytecode()); - this.fragShaderModule = createShaderModule(fragSpirv.bytecode()); - } - - public void cleanUp() { - vkDestroyShaderModule(DEVICE, vertShaderModule, null); - vkDestroyShaderModule(DEVICE, fragShaderModule, null); - - destroyDescriptorSets(); - - graphicsPipelines.forEach((state, pipeline) -> { - vkDestroyPipeline(DEVICE, pipeline, null); - }); - graphicsPipelines.clear(); - - vkDestroyDescriptorSetLayout(DEVICE, descriptorSetLayout, null); - vkDestroyPipelineLayout(DEVICE, pipelineLayout, null); + public abstract void cleanUp(); - PIPELINES.remove(this); - Renderer.getInstance().removeUsedPipeline(this); - } - - private void destroyDescriptorSets() { + void destroyDescriptorSets() { for(DescriptorSets descriptorSets : this.descriptorSets) { descriptorSets.cleanUp(); } @@ -343,116 +167,30 @@ private void destroyDescriptorSets() { public ManualUBO getManualUBO() { return this.manualUBO; } - private static VkVertexInputBindingDescription.Buffer getBindingDescription(VertexFormat vertexFormat) { - - VkVertexInputBindingDescription.Buffer bindingDescription = - VkVertexInputBindingDescription.callocStack(1); - - bindingDescription.binding(0); - bindingDescription.stride(vertexFormat.getVertexSize()); - bindingDescription.inputRate(VK_VERTEX_INPUT_RATE_VERTEX); + public void resetDescriptorPool(int i) { + if(this.descriptorSets != null) + this.descriptorSets[i].resetIdx(); - return bindingDescription; } - private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions(VertexFormat vertexFormat) { - - ImmutableList elements = vertexFormat.getElements(); - - int size = elements.size(); - if(elements.stream().anyMatch(vertexFormatElement -> vertexFormatElement.getUsage() == VertexFormatElement.Usage.PADDING)) { - size--; - } - - VkVertexInputAttributeDescription.Buffer attributeDescriptions = - VkVertexInputAttributeDescription.callocStack(size); - - int offset = 0; - - for(int i = 0; i < size; ++i) { - VkVertexInputAttributeDescription posDescription = attributeDescriptions.get(i); - posDescription.binding(0); - posDescription.location(i); - - VertexFormatElement formatElement = elements.get(i); - VertexFormatElement.Usage usage = formatElement.getUsage(); - VertexFormatElement.Type type = formatElement.getType(); - switch (usage) { - case POSITION : - if(type == VertexFormatElement.Type.FLOAT) { - posDescription.format(VK_FORMAT_R32G32B32_SFLOAT); - posDescription.offset(offset); - - offset += 12; - } - else if (type == VertexFormatElement.Type.SHORT) { - posDescription.format(VK_FORMAT_R16G16B16A16_SINT); - posDescription.offset(offset); - - offset += 8; - } - else if (type == VertexFormatElement.Type.BYTE) { - posDescription.format(VK_FORMAT_R8G8B8A8_SINT); - posDescription.offset(offset); - - offset += 4; - } - - break; - - case COLOR: - posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); - posDescription.offset(offset); - -// offset += 16; - offset += 4; - break; - - case UV: - if(type == VertexFormatElement.Type.FLOAT){ - posDescription.format(VK_FORMAT_R32G32_SFLOAT); - posDescription.offset(offset); - - offset += 8; - } - else if(type == VertexFormatElement.Type.SHORT){ - posDescription.format(VK_FORMAT_R16G16_SINT); - posDescription.offset(offset); - - offset += 4; - } - else if(type == VertexFormatElement.Type.USHORT){ - posDescription.format(VK_FORMAT_R16G16_UINT); - posDescription.offset(offset); - - offset += 4; - } - break; - - case NORMAL: - posDescription.format(VK_FORMAT_R8G8B8A8_SNORM); - posDescription.offset(offset); - - offset += 4; - break; - - case PADDING: + public PushConstants getPushConstants() { return this.pushConstants; } - default: - throw new RuntimeException(String.format("Unknown format: %s", usage)); - } + public long getLayout() { return pipelineLayout; } - posDescription.offset(((VertexFormatMixed)(vertexFormat)).getOffset(i)); - } + public void bindDescriptorSets(VkCommandBuffer commandBuffer, int frame) { + UniformBuffers uniformBuffers = Renderer.getDrawer().getUniformBuffers(); + this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffers); + } - return attributeDescriptions.rewind(); + public void bindDescriptorSets(VkCommandBuffer commandBuffer, UniformBuffers uniformBuffers, int frame) { + this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffers); } - private static long createShaderModule(ByteBuffer spirvCode) { + static long createShaderModule(ByteBuffer spirvCode) { try(MemoryStack stack = stackPush()) { - VkShaderModuleCreateInfo createInfo = VkShaderModuleCreateInfo.callocStack(stack); + VkShaderModuleCreateInfo createInfo = VkShaderModuleCreateInfo.calloc(stack); createInfo.sType(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); createInfo.pCode(spirvCode); @@ -467,51 +205,6 @@ private static long createShaderModule(ByteBuffer spirvCode) { } } - private static long createPipelineCache() { - try(MemoryStack stack = stackPush()) { - - VkPipelineCacheCreateInfo cacheCreateInfo = VkPipelineCacheCreateInfo.callocStack(stack); - cacheCreateInfo.sType(VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO); - - LongBuffer pPipelineCache = stack.mallocLong(1); - - if(vkCreatePipelineCache(DEVICE, cacheCreateInfo, null, pPipelineCache) != VK_SUCCESS) { - throw new RuntimeException("Failed to create graphics pipeline"); - } - - return pPipelineCache.get(0); - } - } - - public static void destroyPipelineCache() { - vkDestroyPipelineCache(DEVICE, PIPELINE_CACHE, null); - } - - public void resetDescriptorPool(int i) { - if(this.descriptorSets != null) - this.descriptorSets[i].resetIdx(); - - } - - public long getHandle(PipelineState state) { - return graphicsPipelines.computeIfAbsent(state, this::createGraphicsPipeline); - } - - public PushConstants getPushConstants() { return this.pushConstants; } - - public long getLayout() { return pipelineLayout; } - - public record Sampler(int binding, String type, String name) {} - - public void bindDescriptorSets(VkCommandBuffer commandBuffer, int frame) { - UniformBuffers uniformBuffers = Renderer.getDrawer().getUniformBuffers(); - this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffers); - } - - public void bindDescriptorSets(VkCommandBuffer commandBuffer, UniformBuffers uniformBuffers, int frame) { - this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffers); - } - private class DescriptorSets { private int poolSize = 10; private long descriptorPool; @@ -521,8 +214,8 @@ private class DescriptorSets { private int currentIdx = -1; private final int frame; - private final VulkanImage.Sampler[] boundTextures = new VulkanImage.Sampler[samplers.size()]; - private final IntBuffer dynamicOffsets = MemoryUtil.memAllocInt(UBOs.size());; + private final VulkanImage.Sampler[] boundTextures = new VulkanImage.Sampler[images.size()]; + private final IntBuffer dynamicOffsets = MemoryUtil.memAllocInt(buffers.size());; DescriptorSets(int frame) { this.frame = frame; @@ -548,7 +241,7 @@ private void updateUniforms(UniformBuffers uniformBuffers) { int currentOffset = uniformBuffers.getUsedBytes(); int i = 0; - for(UBO ubo : UBOs) { + for(UBO ubo : buffers) { // ubo.update(); // uniformBuffers.uploadUBO(ubo.getBuffer(), currentOffset, frame); @@ -570,10 +263,10 @@ private void updateUniforms(UniformBuffers uniformBuffers) { private void updateDescriptorSet(MemoryStack stack, UniformBuffers uniformBuffers) { boolean changed = false; - for(int j = 0; j < samplers.size(); ++j) { - Sampler sampler = samplers.get(j); + for(int j = 0; j < images.size(); ++j) { + Image image = images.get(j); - VulkanImage.Sampler texture = VTextureSelector.getTexture(sampler.name()).getTextureSampler(); + VulkanImage.Sampler texture = VTextureSelector.getTexture(image.name).getTextureSampler(); texture.image().readOnlyLayout(); if(this.boundTextures[j] != texture) { changed = true; @@ -605,14 +298,14 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffers uniformBuffer this.currentSet = this.sets.get(this.currentIdx); - VkWriteDescriptorSet.Buffer descriptorWrites = VkWriteDescriptorSet.calloc(UBOs.size() + samplers.size(), stack); - VkDescriptorBufferInfo.Buffer[] bufferInfos = new VkDescriptorBufferInfo.Buffer[UBOs.size()]; + VkWriteDescriptorSet.Buffer descriptorWrites = VkWriteDescriptorSet.calloc(buffers.size() + images.size(), stack); + VkDescriptorBufferInfo.Buffer[] bufferInfos = new VkDescriptorBufferInfo.Buffer[buffers.size()]; //TODO maybe ubo update is not needed everytime int i = 0; - for(UBO ubo : UBOs) { + for(UBO ubo : buffers) { - bufferInfos[i] = VkDescriptorBufferInfo.callocStack(1, stack); + bufferInfos[i] = VkDescriptorBufferInfo.calloc(1, stack); bufferInfos[i].buffer(this.uniformBufferId); bufferInfos[i].range(ubo.getSize()); @@ -620,7 +313,7 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffers uniformBuffer uboDescriptorWrite.sType$Default(); uboDescriptorWrite.dstBinding(ubo.getBinding()); uboDescriptorWrite.dstArrayElement(0); - uboDescriptorWrite.descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC); + uboDescriptorWrite.descriptorType(ubo.getType()); uboDescriptorWrite.descriptorCount(1); uboDescriptorWrite.pBufferInfo(bufferInfos[i]); uboDescriptorWrite.dstSet(currentSet); @@ -628,15 +321,15 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffers uniformBuffer ++i; } - VkDescriptorImageInfo.Buffer[] imageInfo = new VkDescriptorImageInfo.Buffer[samplers.size()]; + VkDescriptorImageInfo.Buffer[] imageInfo = new VkDescriptorImageInfo.Buffer[images.size()]; - for(int j = 0; j < samplers.size(); ++j) { - Sampler sampler = samplers.get(j); - VulkanImage texture = VTextureSelector.getTexture(sampler.name()); + for(int j = 0; j < images.size(); ++j) { + Image image = images.get(j); + VulkanImage texture = VTextureSelector.getTexture(image.name); VulkanImage.Sampler textureSampler = texture.getTextureSampler(); texture.readOnlyLayout(); - imageInfo[j] = VkDescriptorImageInfo.callocStack(1, stack); + imageInfo[j] = VkDescriptorImageInfo.calloc(1, stack); imageInfo[j].imageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); imageInfo[j].imageView(texture.getImageView()); @@ -644,9 +337,9 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffers uniformBuffer VkWriteDescriptorSet samplerDescriptorWrite = descriptorWrites.get(i); samplerDescriptorWrite.sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET); - samplerDescriptorWrite.dstBinding(sampler.binding()); + samplerDescriptorWrite.dstBinding(image.getBinding()); samplerDescriptorWrite.dstArrayElement(0); - samplerDescriptorWrite.descriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); + samplerDescriptorWrite.descriptorType(image.getType()); samplerDescriptorWrite.descriptorCount(1); samplerDescriptorWrite.pImageInfo(imageInfo[j]); samplerDescriptorWrite.dstSet(currentSet); @@ -666,7 +359,7 @@ private void createDescriptorSets(MemoryStack stack) { layout.put(i, descriptorSetLayout); } - VkDescriptorSetAllocateInfo allocInfo = VkDescriptorSetAllocateInfo.callocStack(stack); + VkDescriptorSetAllocateInfo allocInfo = VkDescriptorSetAllocateInfo.calloc(stack); allocInfo.sType$Default(); allocInfo.descriptorPool(descriptorPool); allocInfo.pSetLayouts(layout); @@ -680,25 +373,25 @@ private void createDescriptorSets(MemoryStack stack) { } private void createDescriptorPool(MemoryStack stack) { - int size = UBOs.size() + samplers.size(); + int size = buffers.size() + images.size(); - VkDescriptorPoolSize.Buffer poolSizes = VkDescriptorPoolSize.callocStack(size, stack); + VkDescriptorPoolSize.Buffer poolSizes = VkDescriptorPoolSize.calloc(size, stack); int i; - for(i = 0; i < UBOs.size(); ++i) { + for(i = 0; i < 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 < UBOs.size() + samplers.size(); ++i) { + for(; i < buffers.size() + images.size(); ++i) { VkDescriptorPoolSize textureSamplerPoolSize = poolSizes.get(i); textureSamplerPoolSize.type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); textureSamplerPoolSize.descriptorCount(this.poolSize); } - VkDescriptorPoolCreateInfo poolInfo = VkDescriptorPoolCreateInfo.callocStack(stack); + VkDescriptorPoolCreateInfo poolInfo = VkDescriptorPoolCreateInfo.calloc(stack); poolInfo.sType(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO); poolInfo.pPoolSizes(poolSizes); poolInfo.maxSets(this.poolSize); @@ -730,25 +423,25 @@ private void cleanUp() { public static class Builder { - public static Pipeline create(VertexFormat format, String path) { + public static GraphicsPipeline createGraphicsPipeline(VertexFormat format, String path) { Pipeline.Builder pipelineBuilder = new Pipeline.Builder(format, path); pipelineBuilder.parseBindingsJSON(); pipelineBuilder.compileShaders(); - return pipelineBuilder.createPipeline(); + return pipelineBuilder.createGraphicsPipeline(); } - private final VertexFormat vertexFormat; - private final String shaderPath; - private List UBOs; - private ManualUBO manualUBO; - private PushConstants pushConstants; - private List samplers; - private int currentBinding; + final VertexFormat vertexFormat; + final String shaderPath; + List UBOs; + ManualUBO manualUBO; + PushConstants pushConstants; + List images; + int currentBinding; - private SPIRV vertShaderSPIRV; - private SPIRV fragShaderSPIRV; + SPIRV vertShaderSPIRV; + SPIRV fragShaderSPIRV; - private RenderPass renderPass; + RenderPass renderPass; public Builder(VertexFormat vertexFormat, String path) { this.vertexFormat = vertexFormat; @@ -759,26 +452,27 @@ public Builder(VertexFormat vertexFormat) { this(vertexFormat, null); } - public Pipeline createPipeline() { - Validate.isTrue(this.samplers != null && this.UBOs != null + public GraphicsPipeline createGraphicsPipeline() { + Validate.isTrue(this.images != null && this.UBOs != null && this.vertShaderSPIRV != null && this.fragShaderSPIRV != null, "Cannot create Pipeline: resources missing"); if(this.manualUBO != null) this.UBOs.add(this.manualUBO); - return new Pipeline(this.vertexFormat, this.renderPass, - this.UBOs, this.manualUBO, this.samplers, this.pushConstants, this.vertShaderSPIRV, this.fragShaderSPIRV); + return new GraphicsPipeline(this); } - public void setUniforms(List UBOs, List samplers) { + public void setUniforms(List UBOs, List images) { this.UBOs = UBOs; - this.samplers = samplers; + this.images = images; } public void compileShaders() { - this.vertShaderSPIRV = compileShaderFile(this.shaderPath + ".vsh", ShaderKind.VERTEX_SHADER); - this.fragShaderSPIRV = compileShaderFile(this.shaderPath + ".fsh", ShaderKind.FRAGMENT_SHADER); + 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 vsh, String fsh) { @@ -790,7 +484,7 @@ public void parseBindingsJSON() { Validate.notNull(this.shaderPath, "Cannot parse bindings: shaderPath is null"); this.UBOs = new ArrayList<>(); - this.samplers = new ArrayList<>(); + this.images = new ArrayList<>(); JsonObject jsonObject; @@ -831,7 +525,7 @@ public void parseBindingsJSON() { private void parseUboNode(JsonElement jsonelement) { JsonObject jsonobject = GsonHelper.convertToJsonObject(jsonelement, "UBO"); int binding = GsonHelper.getAsInt(jsonobject, "binding"); - int type = getTypeFromString(GsonHelper.getAsString(jsonobject, "type")); + int type = getStageFromString(GsonHelper.getAsString(jsonobject, "type")); JsonArray fields = GsonHelper.getAsJsonArray(jsonobject, "fields"); AlignedStruct.Builder builder = new AlignedStruct.Builder(); @@ -857,22 +551,22 @@ private void parseUboNode(JsonElement jsonelement) { private void parseManualUboNode(JsonElement jsonelement) { JsonObject jsonobject = GsonHelper.convertToJsonObject(jsonelement, "ManualUBO"); int binding = GsonHelper.getAsInt(jsonobject, "binding"); - int type = getTypeFromString(GsonHelper.getAsString(jsonobject, "type")); + int stage = getStageFromString(GsonHelper.getAsString(jsonobject, "type")); int size = GsonHelper.getAsInt(jsonobject, "size"); if(binding > this.currentBinding) this.currentBinding = binding; - this.manualUBO = new ManualUBO(binding, type, size); + this.manualUBO = new ManualUBO(binding, stage, size); } private void parseSamplerNode(JsonElement jsonelement) { - JsonObject jsonobject = GsonHelper.convertToJsonObject(jsonelement, "UBO"); + JsonObject jsonobject = GsonHelper.convertToJsonObject(jsonelement, "Sampler"); String name = GsonHelper.getAsString(jsonobject, "name"); this.currentBinding++; - this.samplers.add(new Sampler(this.currentBinding, "sampler2D", name)); + this.images.add(new Image(this.currentBinding, "sampler2D", name)); } private void parsePushConstantNode(JsonArray jsonArray) { @@ -891,11 +585,12 @@ private void parsePushConstantNode(JsonArray jsonArray) { this.pushConstants = builder.buildPushConstant(); } - public static int getTypeFromString(String s) { + public static int getStageFromString(String s) { return switch (s) { case "vertex" -> VK_SHADER_STAGE_VERTEX_BIT; case "fragment" -> VK_SHADER_STAGE_FRAGMENT_BIT; case "all" -> VK_SHADER_STAGE_ALL_GRAPHICS; + case "compute" -> VK_SHADER_STAGE_COMPUTE_BIT; default -> throw new RuntimeException("cannot identify type.."); }; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/ShaderSPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java similarity index 83% rename from src/main/java/net/vulkanmod/vulkan/shader/ShaderSPIRVUtils.java rename to src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index b809fdab8..8238611c2 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/ShaderSPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -14,14 +14,11 @@ import static org.lwjgl.system.MemoryUtil.NULL; import static org.lwjgl.util.shaderc.Shaderc.*; -public class ShaderSPIRVUtils { - private static long compiler; +public class SPIRVUtils { + private static final boolean DEBUG = true; + private static final boolean OPTIMIZATIONS = false; - public static SPIRV compileShaderFile(String shaderFile, ShaderKind shaderKind) { - //TODO name out - String path = ShaderSPIRVUtils.class.getResource("/assets/vulkanmod/shaders/" + shaderFile).toExternalForm(); - return compileShaderAbsoluteFile(path, shaderKind); - } + private static long compiler; public static SPIRV compileShaderAbsoluteFile(String shaderFile, ShaderKind shaderKind) { try { @@ -47,9 +44,11 @@ public static SPIRV compileShader(String filename, String source, ShaderKind sha throw new RuntimeException("Failed to create compiler options"); } -// shaderc_compile_options_set_optimization_level(options, shaderc_optimization_level_performance); + if(OPTIMIZATIONS) + shaderc_compile_options_set_optimization_level(options, shaderc_optimization_level_performance); - shaderc_compile_options_set_generate_debug_info(options); + if(DEBUG) + shaderc_compile_options_set_generate_debug_info(options); long result = shaderc_compile_into_spv(compiler, source, shaderKind.kind, filename, "main", options); @@ -61,8 +60,6 @@ public static SPIRV compileShader(String filename, String source, ShaderKind sha throw new RuntimeException("Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message(result)); } -// shaderc_compiler_release(compiler); - return new SPIRV(result, shaderc_result_get_bytes(result)); } @@ -83,7 +80,8 @@ private static SPIRV readFromStream(InputStream inputStream) { public enum ShaderKind { VERTEX_SHADER(shaderc_glsl_vertex_shader), GEOMETRY_SHADER(shaderc_glsl_geometry_shader), - FRAGMENT_SHADER(shaderc_glsl_fragment_shader); + FRAGMENT_SHADER(shaderc_glsl_fragment_shader), + COMPUTE_SHADER(shaderc_glsl_compute_shader); private final int kind; diff --git a/src/main/java/net/vulkanmod/vulkan/shader/ShaderManager.java b/src/main/java/net/vulkanmod/vulkan/shader/ShaderManager.java deleted file mode 100644 index 89682f17a..000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/ShaderManager.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.vulkanmod.vulkan.shader; - -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderType; -import net.vulkanmod.Initializer; -import net.vulkanmod.render.vertex.CustomVertexFormat; - -public class ShaderManager { - public static VertexFormat TERRAIN_VERTEX_FORMAT; - - public static ShaderManager shaderManager; - - public static void init() { - setTerrainVertexFormat(CustomVertexFormat.COMPRESSED_TERRAIN); - shaderManager = new ShaderManager(); - } - - public static void setTerrainVertexFormat(VertexFormat format) { - TERRAIN_VERTEX_FORMAT = format; - } - - public static ShaderManager getInstance() { return shaderManager; } - - Pipeline terrainIndirectShader; - public Pipeline terrainDirectShader; - - public ShaderManager() { - createBasicPipelines(); - } - - private void createBasicPipelines() { - this.terrainIndirectShader = createPipeline("terrain"); - - this.terrainDirectShader = createPipeline("terrain_direct"); - } - - private Pipeline createPipeline(String name) { - String path = String.format("basic/%s/%s", name, name); - - Pipeline.Builder pipelineBuilder = new Pipeline.Builder(CustomVertexFormat.COMPRESSED_TERRAIN, path); - pipelineBuilder.parseBindingsJSON(); - pipelineBuilder.compileShaders(); - return pipelineBuilder.createPipeline(); - } - - public Pipeline getTerrainShader(RenderType renderType) { - if(Initializer.CONFIG.indirectDraw) { - return this.terrainIndirectShader; - } - else { - return this.terrainDirectShader; - } - - } - - public Pipeline getTerrainIndirectShader(RenderType renderType) { - return terrainIndirectShader; - } - - public void destroyPipelines() { - this.terrainIndirectShader.cleanUp(); - this.terrainDirectShader.cleanUp(); - } -} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java new file mode 100644 index 000000000..2685ccd0e --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java @@ -0,0 +1,10 @@ +package net.vulkanmod.vulkan.shader.descriptor; + +public interface Descriptor { + + int getBinding(); + + int getType(); + + int getStages(); +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Image.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Image.java new file mode 100644 index 000000000..f96be3ef8 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Image.java @@ -0,0 +1,40 @@ +package net.vulkanmod.vulkan.shader.descriptor; + +import static org.lwjgl.vulkan.VK10.*; + +public class Image implements Descriptor { + + private final int descriptorType; + private final int binding; + public final String qualifier; + public final String name; + public final boolean useSampler; + + public Image(int binding, String type, String name) { + this(binding, type, name, true); + } + + public Image(int binding, String type, String name, boolean useSampler) { + this.binding = binding; + this.qualifier = type; + this.name = name; + this.useSampler = useSampler; + + descriptorType = useSampler ? VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + } + + @Override + public int getBinding() { + return binding; + } + + @Override + public int getType() { + return descriptorType; + } + + @Override + public int getStages() { + return VK_SHADER_STAGE_ALL_GRAPHICS; + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/ManualUBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java similarity index 71% rename from src/main/java/net/vulkanmod/vulkan/shader/ManualUBO.java rename to src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java index e685ce6d5..45ca1841c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/ManualUBO.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ManualUBO.java @@ -1,7 +1,5 @@ -package net.vulkanmod.vulkan.shader; +package net.vulkanmod.vulkan.shader.descriptor; -import net.vulkanmod.vulkan.shader.layout.Field; -import net.vulkanmod.vulkan.shader.layout.UBO; import org.lwjgl.system.MemoryUtil; public class ManualUBO extends UBO { @@ -13,10 +11,6 @@ public ManualUBO(int binding, int type, int size) { super(binding, type, size * 4, null); } - public void update() { - //update manually - } - @Override public void update(long ptr) { //update manually diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java new file mode 100644 index 000000000..039b14799 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/UBO.java @@ -0,0 +1,33 @@ +package net.vulkanmod.vulkan.shader.descriptor; + +import net.vulkanmod.vulkan.shader.layout.AlignedStruct; +import net.vulkanmod.vulkan.shader.layout.Field; + +import java.util.List; + +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 UBO(int binding, int stages, int size, List infoList) { + super(infoList, size); + this.binding = binding; + this.stages = stages; + } + + public int getBinding() { + return binding; + } + + @Override + public int getType() { + return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + } + + public int getStages() { + return stages; + } + +} 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 0ff0a3541..9daf680a4 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java @@ -1,40 +1,28 @@ package net.vulkanmod.vulkan.shader.layout; -import net.vulkanmod.vulkan.shader.ManualUBO; -import net.vulkanmod.vulkan.util.MappedBuffer; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import java.util.ArrayList; import java.util.List; public abstract class AlignedStruct { - @Deprecated - protected MappedBuffer buffer; protected List fields = new ArrayList<>(); protected int size; protected AlignedStruct(List infoList, int size) { this.size = size; - this.buffer = new MappedBuffer(size); if(infoList == null) return; for(Field.FieldInfo fieldInfo : infoList) { - Field field = Field.createField(fieldInfo, this.buffer.ptr); + Field field = Field.createField(fieldInfo); this.fields.add(field); } } - @Deprecated - public void update() { - for(Field field : this.fields) { - field.update(); - } - - } - public void update(long ptr) { for(Field field : this.fields) { field.update(ptr); @@ -45,10 +33,6 @@ public List getFields() { return this.fields; } - public long getBufferPtr() { - return this.buffer.ptr; - } - public int getSize() { return size; } @@ -74,9 +58,9 @@ public void addFieldInfo(String type, String name) { this.fields.add(fieldInfo); } - public UBO buildUBO(int binding, int type) { + public UBO buildUBO(int binding, int stages) { //offset is expressed in floats/ints - return new UBO(binding, type, this.currentOffset * 4, this.fields); + return new UBO(binding, stages, this.currentOffset * 4, this.fields); } public PushConstants buildPushConstant() { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Field.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Field.java index 4d0ea41af..47a49f04f 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Field.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Field.java @@ -3,20 +3,17 @@ import net.vulkanmod.vulkan.util.MappedBuffer; import org.lwjgl.system.MemoryUtil; -import java.nio.ByteBuffer; import java.util.function.Supplier; public abstract class Field { protected Supplier values; FieldInfo fieldInfo; - protected long basePtr; protected long offset; protected int size; - Field(FieldInfo fieldInfo, long ptr) { + Field(FieldInfo fieldInfo) { this.fieldInfo = fieldInfo; - this.basePtr = ptr + (fieldInfo.offset * 4L); this.offset = fieldInfo.offset * 4L; this.size = fieldInfo.size * 4; this.setSupplier(); @@ -32,22 +29,20 @@ public String getName() { return this.fieldInfo.name; } - abstract void update(); - void update(long ptr) { MappedBuffer src = values.get(); MemoryUtil.memCopy(src.ptr, ptr + this.offset, this.size); } - public static Field createField(FieldInfo info, long ptr) { + public static Field createField(FieldInfo info) { return switch (info.type) { - case "mat4" -> new Mat4f(info, ptr); - case "vec4" -> new Vec4f(info, ptr); - case "vec3" -> new Vec3f(info, ptr); - case "vec2" -> new Vec2f(info, ptr); - case "float" -> new Vec1f(info, ptr); - case "int" -> new Vec1i(info, ptr); + case "mat4" -> new Mat4f(info); + case "vec4" -> new Vec4f(info); + case "vec3" -> new Vec3f(info); + case "vec2" -> new Vec2f(info); + case "float" -> new Vec1f(info); + case "int" -> new Vec1i(info); default -> throw new RuntimeException("not admitted type: " + info.type); }; } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Mat4f.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Mat4f.java index d564ecb57..503cf8b19 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Mat4f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Mat4f.java @@ -1,13 +1,11 @@ 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; public class Mat4f extends Field { - public Mat4f(FieldInfo info, long ptr) { - super(info, ptr); + public Mat4f(FieldInfo info) { + super(info); } protected void setSupplier() { @@ -16,12 +14,4 @@ protected void setSupplier() { Validate.notNull(this.values, "Field name not found: " + this.fieldInfo.name); } - void update() { - MappedBuffer src = values.get(); - -// float[] floats = new float[16]; -// src.asFloatBuffer().get(floats); - - MemoryUtil.memCopy(src.buffer, MemoryUtil.memByteBuffer(this.basePtr, 64)); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/UBO.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/UBO.java deleted file mode 100644 index 1bfb0dd44..000000000 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/UBO.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.vulkanmod.vulkan.shader.layout; - -import java.nio.ByteBuffer; -import java.util.List; - -public class UBO extends AlignedStruct { - private final int binding; - private final int flags; - - protected UBO(int binding, int type, int size, List infoList) { - super(infoList, size); - this.binding = binding; - this.flags = type; - } - - public int getBinding() { - return binding; - } - - public int getFlags() { - return flags; - } - - public ByteBuffer getBuffer() { - return buffer.buffer; - } - -} 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 4835c0946..2207f9ed3 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1f.java @@ -9,8 +9,8 @@ public class Vec1f extends Field { private Supplier floatSupplier; - public Vec1f(FieldInfo fieldInfo, long ptr) { - super(fieldInfo, ptr); + public Vec1f(FieldInfo fieldInfo) { + super(fieldInfo); } void setSupplier() { @@ -19,26 +19,8 @@ void setSupplier() { Validate.notNull(this.floatSupplier, "Field name not found: " + this.fieldInfo.name); } - void update() { - if(this.floatSupplier != null) { - float f = this.floatSupplier.get(); - MemoryUtil.memPutFloat(this.basePtr, f); - } - else { - //TODO -// MappedBuffer buffer = this.values.get(); -// -// MemoryUtil.memPutFloat(this.basePtr, buffer.getFloat(0)); - } - } - void update(long ptr) { - if(this.floatSupplier != null) { - float f = this.floatSupplier.get(); - MemoryUtil.memPutFloat(ptr + this.offset, f); - } - else { - //TODO - } + float f = this.floatSupplier.get(); + MemoryUtil.memPutFloat(ptr + this.offset, f); } } 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 bfaab6b9c..a63fdc146 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java @@ -1,7 +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; @@ -10,8 +9,8 @@ public class Vec1i extends Field { private Supplier intSupplier; - public Vec1i(FieldInfo fieldInfo, long ptr) { - super(fieldInfo, ptr); + public Vec1i(FieldInfo fieldInfo) { + super(fieldInfo); } void setSupplier() { @@ -20,25 +19,8 @@ void setSupplier() { Validate.notNull(this.intSupplier, "Field name not found: " + this.fieldInfo.name); } - void update() { - if(this.intSupplier != null) { - int i = this.intSupplier.get(); - MemoryUtil.memPutInt(this.basePtr, i); - } - else { - MappedBuffer buffer = this.values.get(); - - MemoryUtil.memPutInt(this.basePtr, buffer.getInt(0)); - } - } - void update(long ptr) { - if(this.intSupplier != null) { - int i = this.intSupplier.get(); - MemoryUtil.memPutInt(ptr + this.offset, i); - } - else { - //TODO - } + int i = this.intSupplier.get(); + MemoryUtil.memPutInt(ptr + this.offset, i); } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec2f.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec2f.java index d858a5fc3..f7143c760 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec2f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec2f.java @@ -1,14 +1,12 @@ 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; public class Vec2f extends Field { - public Vec2f(FieldInfo fieldInfo, long ptr) { - super(fieldInfo, ptr); + public Vec2f(FieldInfo fieldInfo) { + super(fieldInfo); } void setSupplier() { @@ -17,10 +15,4 @@ void setSupplier() { Validate.notNull(this.values, "Field name not found: " + this.fieldInfo.name); } - void update() { - MappedBuffer buffer = this.values.get(); - - MemoryUtil.memPutFloat(this.basePtr, buffer.getFloat(0)); - MemoryUtil.memPutFloat(this.basePtr + 4, buffer.getFloat(4)); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec3f.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec3f.java index 6656354c4..f4c31e1c4 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec3f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec3f.java @@ -1,14 +1,12 @@ package net.vulkanmod.vulkan.shader.layout; import net.vulkanmod.vulkan.shader.Uniforms; -import net.vulkanmod.vulkan.util.MappedBuffer; -import net.vulkanmod.vulkan.util.VUtil; import org.apache.commons.lang3.Validate; public class Vec3f extends Field { - public Vec3f(FieldInfo fieldInfo, long ptr) { - super(fieldInfo, ptr); + public Vec3f(FieldInfo fieldInfo) { + super(fieldInfo); } void setSupplier() { @@ -17,11 +15,4 @@ void setSupplier() { Validate.notNull(this.values, "Field name not found: " + this.fieldInfo.name); } - void update() { - MappedBuffer src = this.values.get(); - - VUtil.UNSAFE.putFloat(this.basePtr, VUtil.UNSAFE.getFloat(src.ptr)); - VUtil.UNSAFE.putFloat(this.basePtr + 4, VUtil.UNSAFE.getFloat(src.ptr + 4)); - VUtil.UNSAFE.putFloat(this.basePtr + 8, VUtil.UNSAFE.getFloat(src.ptr + 8)); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec4f.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec4f.java index 1bc12df0d..b75a747a5 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec4f.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec4f.java @@ -1,14 +1,12 @@ 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; public class Vec4f extends Field { - public Vec4f(FieldInfo fieldInfo, long ptr) { - super(fieldInfo, ptr); + public Vec4f(FieldInfo fieldInfo) { + super(fieldInfo); } void setSupplier() { @@ -17,14 +15,4 @@ void setSupplier() { Validate.notNull(this.values, "Field name not found: " + this.fieldInfo.name); } - void update() { - MappedBuffer buffer = this.values.get(); - - MemoryUtil.memPutFloat(this.basePtr, buffer.getFloat(0)); - MemoryUtil.memPutFloat(this.basePtr + 4, buffer.getFloat(4)); - MemoryUtil.memPutFloat(this.basePtr + 8, buffer.getFloat(8)); - MemoryUtil.memPutFloat(this.basePtr + 12, buffer.getFloat(12)); - - } - } 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 40ae1bc54..1ca9895c7 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/parser/GlslConverter.java @@ -2,7 +2,8 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.layout.UBO; +import net.vulkanmod.vulkan.shader.descriptor.Image; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import java.util.Arrays; import java.util.List; @@ -143,7 +144,7 @@ public UBO getUBO() { return this.uniformParser.getUbo(); } - public List getSamplerList() { + public List getSamplerList() { return this.uniformParser.getSamplers(); } 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 e6cdfd7f9..1909bc563 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/parser/UniformParser.java @@ -2,8 +2,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.descriptor.Image; import net.vulkanmod.vulkan.shader.layout.AlignedStruct; -import net.vulkanmod.vulkan.shader.layout.UBO; +import net.vulkanmod.vulkan.shader.descriptor.UBO; import java.util.ArrayList; import java.util.List; @@ -19,7 +20,7 @@ public class UniformParser { private String name; private UBO ubo; - private List samplers; + private List images; public UniformParser(GlslConverter converterInstance) { this.converterInstance = converterInstance; @@ -86,10 +87,10 @@ public String createUniformsCode() { public String createSamplersCode(GlslConverter.ShaderStage shaderStage) { StringBuilder builder = new StringBuilder(); - this.samplers = createSamplerList(); + this.images = createSamplerList(); - for(Pipeline.Sampler sampler : this.samplers) { - builder.append(String.format("layout(binding = %d) uniform %s %s;\n", sampler.binding(), sampler.type(), sampler.name())); + for(Image image : this.images) { + builder.append(String.format("layout(binding = %d) uniform %s %s;\n", image.getBinding(), image.qualifier, image.name)); } builder.append("\n"); @@ -104,22 +105,22 @@ private UBO createUBO() { } //hardcoded 0 binding as it should always be 0 in this case - return builder.buildUBO(0, Pipeline.Builder.getTypeFromString("all")); + return builder.buildUBO(0, Pipeline.Builder.getStageFromString("all")); } - private List createSamplerList() { + private List createSamplerList() { int currentLocation = 1; - List samplers = new ObjectArrayList<>(); + List images = new ObjectArrayList<>(); for(StageUniforms stageUniforms : this.stageUniforms) { for(Uniform uniform : stageUniforms.samplers) { - samplers.add(new Pipeline.Sampler(currentLocation, uniform.type, uniform.name)); + images.add(new Image(currentLocation, uniform.type, uniform.name)); currentLocation++; } } - return samplers; + return images; } public static String removeSemicolon(String s) { @@ -133,8 +134,8 @@ public UBO getUbo() { return this.ubo; } - public List getSamplers() { - return this.samplers; + public List getSamplers() { + return this.images; } public record Uniform(String type, String name) {} diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index 9a8b34f04..c2a231d75 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -104,7 +104,7 @@ private void createImage(int mipLevels, int width, int height, int format, int u LongBuffer pTextureImage = stack.mallocLong(1); PointerBuffer pAllocation = stack.pointers(0L); - MemoryManager.getInstance().createImage(width, height, mipLevels, + MemoryManager.createImage(width, height, mipLevels, format, VK_IMAGE_TILING_OPTIMAL, usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, @@ -114,7 +114,7 @@ private void createImage(int mipLevels, int width, int height, int format, int u id = pTextureImage.get(0); allocation = pAllocation.get(0); - MemoryManager.getInstance().addImage(this); + MemoryManager.addImage(this); } catch (Exception e) { e.printStackTrace(); @@ -149,7 +149,7 @@ 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 = GraphicsQueue.getInstance().getCommandBuffer(); + CommandPool.CommandBuffer commandBuffer = Device.getGraphicsQueue().getCommandBuffer(); transferDstLayout(commandBuffer); StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(Renderer.getCurrentFrame()); @@ -160,7 +160,7 @@ public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffs copyBufferToImageCmd(commandBuffer, stagingBuffer.getId(), id, mipLevel, width, height, xOffset, yOffset, (int) (stagingBuffer.getOffset() + (unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize), unpackRowLength, height); - long fence = GraphicsQueue.getInstance().endIfNeeded(commandBuffer); + long fence = Device.getGraphicsQueue().endIfNeeded(commandBuffer); if (fence != VK_NULL_HANDLE) // Synchronization.INSTANCE.addFence(fence); Synchronization.INSTANCE.addCommandBuffer(commandBuffer); @@ -184,7 +184,7 @@ public static void downloadTexture(int width, int height, int formatSize, ByteBu (data) -> VUtil.memcpy(data.getByteBuffer(0, (int)imageSize), buffer) ); - MemoryManager.getInstance().freeBuffer(pStagingBuffer.get(0), pStagingAllocation.get(0)); + MemoryManager.freeBuffer(pStagingBuffer.get(0), pStagingAllocation.get(0)); } } @@ -237,9 +237,9 @@ public void readOnlyLayout() { if (this.currentLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) return; - CommandPool.CommandBuffer commandBuffer = GraphicsQueue.getInstance().getCommandBuffer(); + CommandPool.CommandBuffer commandBuffer = Device.getGraphicsQueue().getCommandBuffer(); readOnlyLayout(commandBuffer); - GraphicsQueue.getInstance().submitCommands(commandBuffer); + Device.getGraphicsQueue().submitCommands(commandBuffer); Synchronization.INSTANCE.addCommandBuffer(commandBuffer); } @@ -374,7 +374,7 @@ private static void copyImageToBuffer(long buffer, long image, int mipLevel, int try(MemoryStack stack = stackPush()) { - CommandPool.CommandBuffer commandBuffer = GraphicsQueue.getInstance().beginCommands(); + CommandPool.CommandBuffer commandBuffer = Device.getGraphicsQueue().beginCommands(); VkBufferImageCopy.Buffer region = VkBufferImageCopy.callocStack(1, stack); region.bufferOffset(bufferOffset); @@ -389,7 +389,7 @@ private static void copyImageToBuffer(long buffer, long image, int mipLevel, int vkCmdCopyImageToBuffer(commandBuffer.getHandle(), image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, region); - long fence = GraphicsQueue.getInstance().submitCommands(commandBuffer); + long fence = Device.getGraphicsQueue().submitCommands(commandBuffer); vkWaitForFences(device, fence, true, VUtil.UINT64_MAX); } @@ -490,8 +490,8 @@ public void free() { MemoryManager.getInstance().addToFreeable(this); } - public void doFree(MemoryManager memoryManager) { - memoryManager.freeImage(this.id, this.allocation); + public void doFree() { + MemoryManager.freeImage(this.id, this.allocation); vkDestroyImageView(Vulkan.getDevice(), this.imageView, null); diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.fsh similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.fsh rename to src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.fsh diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.json similarity index 100% rename from src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json rename to src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.json diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.vsh similarity index 68% rename from src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh rename to src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.vsh index 8eb698335..17b12036d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.vsh +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_indirect/terrain_indirect.vsh @@ -22,8 +22,7 @@ layout(location = 1) out vec4 vertexColor; layout(location = 2) out vec2 texCoord0; //layout(location = 3) out vec4 normal; -#define COMPRESSED_VERTEX -#ifdef COMPRESSED_VERTEX +//Compressed Vertex const float UV_INV = 1.0 / 65536.0; const float POSITION_INV = 1.0 / 1900.0; @@ -44,21 +43,19 @@ void main() { // normal = MVP * vec4(Normal, 0.0); } -#else +//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() { - gl_Position = MVP * vec4(Position + ChunkOffset[gl_DrawID], 1.0); - - vertexDistance = length((ModelViewMat * vec4(Position + ChunkOffset[gl_DrawID], 1.0)).xyz); - vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); - texCoord0 = UV0; - normal = MVP * vec4(Normal, 0.0); -} +//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 \ No newline at end of file +//void main() { +// gl_Position = MVP * vec4(Position + ChunkOffset[gl_DrawID], 1.0); +// +// vertexDistance = length((ModelViewMat * vec4(Position + ChunkOffset[gl_DrawID], 1.0)).xyz); +// vertexColor = Color * minecraft_sample_lightmap(Sampler2, UV2); +// texCoord0 = UV0; +// normal = MVP * vec4(Normal, 0.0); +//} \ No newline at end of file