From c30ba9a5caed363e3042b0f6071ff11059846c6a Mon Sep 17 00:00:00 2001 From: a dinosaur Date: Tue, 6 Aug 2024 16:51:29 +1000 Subject: [PATCH] use shader uniforms for scaling cube --- Sources/Voxelotl/Renderer.swift | 8 ++++++++ Sources/Voxelotl/shader.metal | 8 ++++++-- Sources/Voxelotl/shadertypes.h | 8 +++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Sources/Voxelotl/Renderer.swift b/Sources/Voxelotl/Renderer.swift index 6af0536..7ff7d63 100644 --- a/Sources/Voxelotl/Renderer.swift +++ b/Sources/Voxelotl/Renderer.swift @@ -218,6 +218,10 @@ class Renderer { } func paint() throws { + var uniforms = ShaderUniforms( + model: .init(diagonal: .init(0.5, 0.5, 0.5, 1.0)), + projView: matrix_identity_float4x4) + guard let rt = layer.nextDrawable() else { throw RendererError.drawFailure("Failed to get next drawable render target") } @@ -239,6 +243,10 @@ class Renderer { encoder.setVertexBuffer(vtxBuffer, offset: 0, index: ShaderInputIdx.vertices.rawValue) + // Ideal as long as our uniforms total 4 KB or less + encoder.setVertexBytes(&uniforms, + length: MemoryLayout.stride, + index: ShaderInputIdx.uniforms.rawValue) encoder.drawIndexedPrimitives( type: .triangle, indexCount: cubeIndices.count, diff --git a/Sources/Voxelotl/shader.metal b/Sources/Voxelotl/shader.metal index 266d0aa..88b6bf3 100644 --- a/Sources/Voxelotl/shader.metal +++ b/Sources/Voxelotl/shader.metal @@ -12,10 +12,14 @@ struct FragmentInput { vertex FragmentInput vertexMain( uint vertexID [[vertex_id]], - device const ShaderVertex* vtx [[buffer(ShaderInputIdxVertices)]] + device const ShaderVertex* vtx [[buffer(ShaderInputIdxVertices)]], + constant ShaderUniforms& u [[buffer(ShaderInputIdxUniforms)]] ) { + auto position = vtx[vertexID].position; + position = u.projView * u.model * position; + FragmentInput out; - out.position = vtx[vertexID].position * float4(0.5, 0.5, 0.5, 1.0); + out.position = position; out.normal = vtx[vertexID].normal; out.texCoord = vtx[vertexID].texCoord; return out; diff --git a/Sources/Voxelotl/shadertypes.h b/Sources/Voxelotl/shadertypes.h index 1299f95..6f3e3a6 100644 --- a/Sources/Voxelotl/shadertypes.h +++ b/Sources/Voxelotl/shadertypes.h @@ -11,7 +11,8 @@ #include typedef NS_ENUM(NSInteger, ShaderInputIdx) { - ShaderInputIdxVertices = 0 + ShaderInputIdxVertices = 0, + ShaderInputIdxUniforms = 1 }; typedef struct { @@ -20,4 +21,9 @@ typedef struct { vector_float2 texCoord; } ShaderVertex; +typedef struct { + matrix_float4x4 model; + matrix_float4x4 projView; +} ShaderUniforms; + #endif//SHADERTYPES_H