iOS 16.1, Xcode 14.1, Swift 5, Playground 환경에서 진행했습니다.
삼각형의 좌표를 저장하는 [Float] 배열을 만들고, 삼각형의 좌표를 구성하는 Buffer를 생성합니다.
let vertices: [Float] = [
0, 1, 0,
-1, -1, 0,
1, -1, 0
]
let vertexBuffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<Float>.size)
Shader Function은 GPU를 돌리기 위한 작은 프로그램입니다. Shader Function을 작성하기 위하여 Metal Shading Laungage(MSL)을 사용해야합니다. MSL은 C++로 구성되어 있습니다. .metal 확장자에 Shader Function을 작성하지만, playground 환경에서 여러줄의 문자열로 작성하겠습니다.
let shader = """
#include <metal_stdlib>
using namespace metal;
vertex float4 vertex_main(const device packed_float3 *vertices [[ buffer(0) ]],
uint vertexId [[ vertex_id ]]) {
return float4(vertices[vertexId], 1);
}
fragment float4 fragment_main() {
return float4(1, 0, 0, 1);
}
"""
let library = try device.makeLibrary(source: shader, options: nil)
let vertexFunction = library.makeFunction(name: "vertex_main")
let fragmentFunction = library.makeFunction(name: "fragment_main")
메탈에서는 GPU를 사용하기 위해 pipeline state를 사용합니다. pipeline state가 설정이 되면, 효율적으로 동작할 수 있습니다.
pipeline state에 위에서 생성한 vertex function과 fragment function을 설정합니다.
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor)
화면을 구성하는 Encoder에 pipeline state 정보를 입력하고, vertexBuffer를 출력합니다.
commandEncoder?.setRenderPipelineState(pipelineState!)
commandEncoder?.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
commandEncoder?.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertices.count)
완성 !
참조 :
https://www.kodeco.com/books/metal-by-tutorials
https://www.youtube.com/watch?v=948OYW6-7ek&list=PL23Revp-82LJG3vcDPm8w7b5HTKjBOY0W&index=3
https://developer.apple.com/documentation/metal/using_a_render_pipeline_to_render_primitives
'iOS > 라이브러리' 카테고리의 다른 글
[iOS, Metal] Metal에서 Image를 MTKView에 올리는 방법 (0) | 2023.03.21 |
---|---|
[Library, Metal] shader 사용방법 (0) | 2023.02.06 |
[Library, Metal] vertex를 index로 메모리 절약하기 (0) | 2023.02.03 |
[Library, Metal] MetalView 그리기 (0) | 2023.02.03 |