Last active
October 10, 2019 23:21
-
-
Save btipling/fa0ab7bd514d8a319c886def0980ccfc to your computer and use it in GitHub Desktop.
Keep your MTLBuffer struct buffer size aligned with this easy to use function
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
/* | |
* `bufferSize` is the total size of your buffer when adding up the sizes of your struct's properties (not alignments) | |
* `alignment` is the largest alignment for your struct. That is one of your struct's properties will have the largest | |
* alignment value out of all the alignment values for each of your structs properties. Use that value for the second | |
* argument. | |
* | |
* To see the alignment of types see here: https://developer.apple.com/library/ios/documentation/Metal/Reference/MetalShadingLanguageGuide/data-types/data-types.html#//apple_ref/doc/uid/TP40014364-CH2-SW15 | |
* | |
* Example: | |
* | |
* In swift you may have the following struct: | |
* | |
* struct RenderData { | |
* var resolution: [Float32] | |
* var cameraMatrix: [Float32] | |
* } | |
* | |
* In metal it will look like this: | |
* | |
* struct RenderData { | |
* packed_float2 resolution; | |
* float4x4 cameraMatrix; | |
* } | |
* | |
* `resolution` is a packed_float2 and has a size of 8 bytes and an alignment of 4 bytes. | |
* `cameraMatrix` is a float4x4 matrix with a size of 64 bytes and an alignment of 16 bytes. | |
* | |
* The largest alignment in this struct is 16. The total size of the MTLBuffer must be a multiple of 16. | |
* The total struct size will be 64 + 8 = 72, but 72 % 16 != 0 and this will blow up. | |
* | |
* let bufferSize = 64 + 8; | |
* let matrixAlignment = 16; | |
* let totalBufferSize = alignBufferSize(bufferSize, matrixAlignment); | |
* | |
* `totalBufferSize` will be 80. | |
* | |
* Now use this value to make your MTLBuffer: | |
* | |
* let buffer = device.makeBuffer(length: totalBufferSize, options: []) | |
* | |
*/ | |
func alignBufferSize(bufferSize: Int, alignment: Int) -> Int { | |
let alignmentError = bufferSize % alignment; | |
if (alignmentError == 0) { | |
return bufferSize | |
} | |
return bufferSize + (alignment - alignmentError) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment