-
-
Save karosLi/c1712e32531c5a49ac0b28ad277692cf to your computer and use it in GitHub Desktop.
Metal compute shader example
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
import MetalKit | |
let device = MTLCreateSystemDefaultDevice()! | |
let commandQueue = device.makeCommandQueue()! | |
let library = try device.makeLibrary(filepath: "compute.metallib") | |
let commandBuffer = commandQueue.makeCommandBuffer()! | |
let encoder = commandBuffer.makeComputeCommandEncoder()! | |
encoder.setComputePipelineState(try device.makeComputePipelineState(function: library.makeFunction(name: "add")!)) | |
let input: [Float] = [1.0, 2.0] | |
encoder.setBuffer(device.makeBuffer(bytes: input as [Float], length: MemoryLayout<Float>.stride * input.count, options: []), | |
offset: 0, index: 0) | |
let outputBuffer = device.makeBuffer(length: MemoryLayout<Float>.stride, options: [])! | |
encoder.setBuffer(outputBuffer, offset: 0, index: 1) | |
let numThreadgroups = MTLSize(width: 1, height: 1, depth: 1) | |
let threadsPerThreadgroup = MTLSize(width: 1, height: 1, depth: 1) | |
encoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerThreadgroup) | |
encoder.endEncoding() | |
commandBuffer.commit() | |
commandBuffer.waitUntilCompleted() | |
let result = outputBuffer.contents().load(as: Float.self) | |
print(String(format: "%f + %f = %f", input[0], input[1], result)) |
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
SDK = xcrun -sdk macosx | |
all: compute.metallib compute | |
compute.metallib: Compute.metal | |
# Metal intermediate representation (.air) | |
$(SDK) metal -c -Wall -Wextra -std=osx-metal2.0 -o /tmp/Compute.air $^ | |
# Metal library (.metallib) | |
$(SDK) metallib -o $@ /tmp/Compute.air | |
compute: compute.swift | |
$(SDK) swiftc -o $@ $^ | |
clean: | |
rm -f compute.metallib compute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment