iOS 8.0起,Apple为了更充分地发挥GPU的潜力,引入了Metal框架,Metal基于C++设计,开发者可以用它来编写在GPU上执行的图形渲染逻辑代码和通用并行计算逻辑代码,目前的Metal框架中可以使用三种着色器——Vertex Shader、Fragment Shader以及Compute Shader。
1、先创建MTLCreateSystemDefaultDevice和CAMetalLayer
2、确定顶点数据,中心点是原点(x, y, z)和顶点缓冲区MTLBuffer
let vertexData: [Float] = [
0.5, 0.5, 0.0,
-0.5, 0.5, 0.0,
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0
]
2.1、您需要以字节为单位获取顶点数据的大小。您可以通过将第一个元素的大小乘以数组中元素的计数来实现这一点
let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0])
2.2、在GPU上创建一个新的缓冲区,从CPU传入数据。为默认配置传递一个空数组
vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: [])
3、创建Metal文件
vertex float4 basic_vertex(
const device packed_float3* vertex_array [[ buffer(0) ]],
unsigned int vid [[ vertex_id ]]) {
return float4(vertex_array[vid], 1.0);
}
fragment half4 basic_fragment() {
return half4(1.0);
}
3.1、按名称查找每个着色器
let defaultLibrary = device.makeDefaultLibrary()!
let fragmentProgram = defaultLibrary.makeFunction(name: "basic_fragment") //片段
let vertexProgram = defaultLibrary.makeFunction(name: "basic_vertex")
4、创建渲染管道MTLRenderPipelineState
let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
pipelineStateDescriptor.vertexFunction = vertexProgram
pipelineStateDescriptor.fragmentFunction = fragmentProgram;
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)
5、创建MTLCommandQueue和CADisplayLink
commandQueue = device.makeCommandQueue()
timer = CADisplayLink.init(target: self, selector: #selector(gameloop))
timer.add(to: RunLoop.main, forMode: .default)
在gameloop方法里面写相应的需求