use shader uniforms for scaling cube

This commit is contained in:
a dinosaur 2024-08-06 16:51:29 +10:00
parent 10d7f8281c
commit c30ba9a5ca
3 changed files with 21 additions and 3 deletions

View File

@ -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<ShaderUniforms>.stride,
index: ShaderInputIdx.uniforms.rawValue)
encoder.drawIndexedPrimitives(
type: .triangle,
indexCount: cubeIndices.count,

View File

@ -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;

View File

@ -11,7 +11,8 @@
#include <simd/simd.h>
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