Skip to content

Instantly share code, notes, and snippets.

@TheoBendixson
Last active June 14, 2021 22:59
Show Gist options
  • Save TheoBendixson/cb1478e3d82118e2c65be5e287cdd594 to your computer and use it in GitHub Desktop.
Save TheoBendixson/cb1478e3d82118e2c65be5e287cdd594 to your computer and use it in GitHub Desktop.
2D Scaling Pixel Art Vertex Shader (Metal)
typedef enum MacVertexInputIndex
{
MacVertexInputIndexVertices = 0,
MacVertexInputIndexViewportSize = 1,
MacVertexInputIndexTextureSize = 2
} MacVertexInputIndex;
vertex RasterizerData
vertexShader(uint vertexID [[ vertex_id ]],
constant MacTextureShaderVertex *vertexArray [[ buffer(MacVertexInputIndexVertices) ]],
constant vector_uint2 *viewportSizePointer [[ buffer(MacVertexInputIndexViewportSize) ]],
constant MacTextureSize *textureSize [[buffer(MacVertexInputIndexTextureSize) ]])
{
RasterizerData out;
// Index into the array of positions to get the current vertex.
// Positions are specified in pixel dimensions (i.e. a value of 100 is 100 pixels from
// the origin)
float2 pixelSpacePosition = vertexArray[vertexID].position.xy;
// Get the viewport size and cast to float.
float2 viewportSize = float2(*viewportSizePointer);
// To convert from positions in pixel space to positions in clip-space,
// divide the pixel coordinates by half the size of the viewport.
// Z is set to 0.0 and w to 1.0 because this is 2D sample.
out.position = vector_float4(0.0, 0.0, 0.0, 1.0);
// NOTE: (Ted) This would be the Open GL equivalent of mapping the projection matrix to
// the game's screen coordinates. This is a 2D game.
out.position.xy = (pixelSpacePosition / (viewportSize / 2.0)) - 1;
out.textureCoordinate = vertexArray[vertexID].textureCoordinate;
out.textureSize = float2(textureSize->Width, textureSize->Height);
out.vUv = out.textureSize*out.textureCoordinate;
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment