Last active
June 14, 2021 22:34
-
-
Save TheoBendixson/0de67f42b6e32ebdfb8b5914f696a93e to your computer and use it in GitHub Desktop.
2D Scaling Pixel Art Shader (Metal) - Passing Texture Size Into The Vertex Shader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple struct representing the size of the texture in terms of | |
// texels. | |
typedef struct | |
{ | |
real32 Width; | |
real32 Height; | |
} MacTextureSize; | |
// PRETEND THIS IS INSIDE OF A RENDERING FUNCTION | |
// An example of how you might pass this struct into MTLRenderEncoder | |
// while setting up a render pass. The specifics don't matter so much | |
// as the line where the texture size is passed in using setVertexBytes: | |
[RenderEncoder setFragmentTexture: [self GameCharacterTextureAtlas] | |
atIndex: 0]; | |
// This assumes a triple buffered setup where there are three vertex buffers | |
// and your renderer tracks the current frame. | |
id<MTLBuffer> VertexBuffer = [[self VertexBuffers] objectAtIndex: _currentFrameIndex]; | |
[RenderEncoder setVertexBuffer: VertexBuffer offset: 0 atIndex: 0]; | |
// If you use a 2D texture array, you will probably know this ahead of time. | |
// For example, my game character array has the game character at 32x32 texels/frame. | |
MacTextureSize TextureSize = {}; | |
TextureSize.Width = 32; | |
TextureSize.Height = 32; | |
// The index you use is kind of arbitrary. If you pass other parameters into the | |
// vertex shader, it will depend on those. Mine uses two params before the texture | |
// size parameter. | |
[RenderEncoder setVertexBytes:&TextureSize | |
length:sizeof(TextureSize) | |
atIndex:2]; | |
// Do the rest of your drawing as normal. | |
[RenderEncoder drawPrimitives: MTLPrimitiveTypeTriangle | |
vertexStart: 0 | |
vertexCount: VertexCount]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment