美文网首页
Metal 三角形

Metal 三角形

作者: HChase | 来源:发表于2019-06-24 16:28 被阅读0次

    一,设置MTKView

    • 将ViewController的view设置为MTKView
       var metalView: MTKView {
            return view as! MTKView
        }
    
    • 获取默认的 MTLDevice
        let d = MTLCreateSystemDefaultDevice()
    
    • 设置 ** MTKView** 属性;
        metalView.device = device
        metalView.clearColor = MTLClearColorMake(0.3, 0.3, 0.3, 1)
        renderer = Render(device: device)
        metalView.delegate = renderer
    

    二,设置管道状态MTLRenderPipelineState

    • 使用GPU设备(MTLDevice)创建命令管道;
       self.commandQueue = device.makeCommandQueue()!
    
    • 创建顶点缓存区(MTLBuffer)
        self.vertexBuffer = device.makeBuffer(bytes: verters,
                                                  length: verters.count * MemoryLayout<Float>.size, options: [])
    
    • 设置管道状态:配置顶点着色器、片元着色器,设置颜色的像素格式
        let libary = device.makeDefaultLibrary()
        let vertextFuncion = libary?.makeFunction(name: "vertex_shader") // 设置顶点着色器
        let fragmentFuncion = libary?.makeFunction(name: "fragment_shader") // 设置片元着色器
            
        let pipelineDescriptor = MTLRenderPipelineDescriptor()
        pipelineDescriptor.vertexFunction = vertextFuncion
        pipelineDescriptor.fragmentFunction = fragmentFuncion
        pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm // 设置颜色的像素格式为32位
            
        do {
           pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor)
        } catch let error as NSError {
           print("error: \(error.localizedDescription)")
        }
    

    三、绘制模型

    • 遵守MTKViewDelegate协议,实现其方法;
    // 每帧回调
        func draw(in view: MTKView) {
            guard let drawable = view.currentDrawable,
                let pipelineState = pipelineState,
                let descriptor = view.currentRenderPassDescriptor else {return}
            
            //  创建命令缓存区 / 命令编码器
            let commandBuffer = commandQueue.makeCommandBuffer()
            let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: descriptor) // 描述符
            
            commandEncoder?.setRenderPipelineState(pipelineState)
            commandEncoder?.setVertexBuffer(vertexBuffer, offset: 0, index: 0)  // 设置如何从缓存数组读取顶点到命令缓存区
            commandEncoder?.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: verters.count)
            commandEncoder?.endEncoding()
            
            commandBuffer?.present(drawable) //
            commandBuffer?.commit() // 
        }
    

    源代码Metal_Triangle

    相关文章

      网友评论

          本文标题:Metal 三角形

          本文链接:https://www.haomeiwen.com/subject/bnjoqctx.html