傲视苍穹iOS《Objective-C》VIP专题IOSIOS个人开发

Metal框架详细解析(五十) —— 将项目从OpenGL转化到

2019-01-19  本文已影响39人  刀客传奇

版本记录

版本号 时间
V1.0 2019.01.19 星期六

前言

很多做视频和图像的,相信对这个框架都不是很陌生,它渲染高级3D图形,并使用GPU执行数据并行计算。接下来的几篇我们就详细的解析这个框架。感兴趣的看下面几篇文章。
1. Metal框架详细解析(一)—— 基本概览
2. Metal框架详细解析(二) —— 器件和命令(一)
3. Metal框架详细解析(三) —— 渲染简单的2D三角形(一)
4. Metal框架详细解析(四) —— 关于GPU Family 4(一)
5. Metal框架详细解析(五) —— 关于GPU Family 4之关于Imageblocks(二)
6. Metal框架详细解析(六) —— 关于GPU Family 4之关于Tile Shading(三)
7. Metal框架详细解析(七) —— 关于GPU Family 4之关于光栅顺序组(四)
8. Metal框架详细解析(八) —— 关于GPU Family 4之关于增强的MSAA和Imageblock采样覆盖控制(五)
9. Metal框架详细解析(九) —— 关于GPU Family 4之关于线程组共享(六)
10. Metal框架详细解析(十) —— 基本组件(一)
11. Metal框架详细解析(十一) —— 基本组件之器件选择 - 图形渲染的器件选择(二)
12. Metal框架详细解析(十二) —— 基本组件之器件选择 - 计算处理的设备选择(三)
13. Metal框架详细解析(十三) —— 计算处理(一)
14. Metal框架详细解析(十四) —— 计算处理之你好,计算(二)
15. Metal框架详细解析(十五) —— 计算处理之关于线程和线程组(三)
16. Metal框架详细解析(十六) —— 计算处理之计算线程组和网格大小(四)
17. Metal框架详细解析(十七) —— 工具、分析和调试(一)
18. Metal框架详细解析(十八) —— 工具、分析和调试之Metal GPU Capture(二)
19. Metal框架详细解析(十九) —— 工具、分析和调试之GPU活动监视器(三)
20. Metal框架详细解析(二十) —— 工具、分析和调试之关于Metal着色语言文件名扩展名、使用Metal的命令行工具构建库和标记Metal对象和命令(四)
21. Metal框架详细解析(二十一) —— 基本课程之基本缓冲区(一)
22. Metal框架详细解析(二十二) —— 基本课程之基本纹理(二)
23. Metal框架详细解析(二十三) —— 基本课程之CPU和GPU同步(三)
24. Metal框架详细解析(二十四) —— 基本课程之参数缓冲 - 基本参数缓冲(四)
25. Metal框架详细解析(二十五) —— 基本课程之参数缓冲 - 带有数组和资源堆的参数缓冲区(五)
26. Metal框架详细解析(二十六) —— 基本课程之参数缓冲 - 具有GPU编码的参数缓冲区(六)
27. Metal框架详细解析(二十七) —— 高级技术之图层选择的反射(一)
28. Metal框架详细解析(二十八) —— 高级技术之使用专用函数的LOD(一)
29. Metal框架详细解析(二十九) —— 高级技术之具有参数缓冲区的动态地形(一)
30. Metal框架详细解析(三十) —— 延迟照明(一)
31. Metal框架详细解析(三十一) —— 在视图中混合Metal和OpenGL渲染(一)
32. Metal框架详细解析(三十二) —— Metal渲染管道教程(一)
33. Metal框架详细解析(三十三) —— Metal渲染管道教程(二)
34. Metal框架详细解析(三十四) —— Hello Metal! 一个简单的三角形的实现(一)
35. Metal框架详细解析(三十五) —— Hello Metal! 一个简单的三角形的实现(二)
36. Metal框架详细解析(三十六) —— Metal编程指南之概览(一)
37. Metal框架详细解析(三十七) —— Metal编程指南之基本Metal概念(二)
38. Metal框架详细解析(三十八) —— Metal编程指南之命令组织和执行模型(三)
39. Metal框架详细解析(三十九) —— Metal编程指南之资源对象:缓冲区和纹理(四)
40. Metal框架详细解析(四十) —— Metal编程指南之函数和库(五)
41. Metal框架详细解析(四十一) —— Metal编程指南之图形渲染:渲染命令编码器之Part 1(六)
42. Metal框架详细解析(四十二) —— Metal编程指南之图形渲染:渲染命令编码器之Part 2(七)
43. Metal框架详细解析(四十三) —— Metal编程指南之数据并行计算处理:计算命令编码器(八)
44. Metal框架详细解析(四十四) —— Metal编程指南之缓冲和纹理操作:Blit命令编码器(九)
45. Metal框架详细解析(四十五) —— Metal编程指南之Metal工具(十)
46. Metal框架详细解析(四十六) —— Metal编程指南之Tessellation(十一)
47. Metal框架详细解析(四十七) —— Metal编程指南之资源堆(十二)
48. Metal框架详细解析(四十八) —— 将项目从OpenGL转化到Metal(一)
49. Metal框架详细解析(四十九) —— 将项目从OpenGL转化到Metal(二)

源码

1. Swift

OpenGL源码

首先看下工程组织结构

接着看一下sb文件

下面就是源码了

1. Array+Helpers.swift
import Foundation

//
// MARK: - Array Helpers
//

/// Array extension to help with size/memory calculations when working with OpenGL.
extension Array {
  //
  // MARK: - Instance Methods
  //
  
  /// Returns the memory size/footprint (in bytes) of a given array.
  ///
  /// - Returns: Integer value representing the memory size the array.
  func size() -> Int {
    return count * MemoryLayout.size(ofValue: self[0])
  }
}
2. Vertex.swift
import GLKit

//
// MARK: - Vertex
//

/// Structure to hold a vertex's position and color data.
struct Vertex {
  /// Stores the X coordinate of a vertex.
  var x: GLfloat
  /// Stores the Y coordinate of a vertex.
  var y: GLfloat
  /// Stores the Z coordinate of a vertex.
  var z: GLfloat
  /// Stores the red color value of a vertex.
  var r: GLfloat
  /// Stores the green color value of a vertex.
  var g: GLfloat
  /// Stores the blue color value of a vertex.
  var b: GLfloat
  /// Stores the alpha value of a vertex.
  var a: GLfloat
}
3. ViewController.swift
import GLKit

final class ViewController: GLKViewController {
  var Vertices = [
    Vertex(x:  1, y: -1, z: 0, r: 1, g: 0, b: 0, a: 1),
    Vertex(x:  1, y:  1, z: 0, r: 0, g: 1, b: 0, a: 1),
    Vertex(x: -1, y:  1, z: 0, r: 0, g: 0, b: 1, a: 1),
    Vertex(x: -1, y: -1, z: 0, r: 0, g: 0, b: 0, a: 1),
    ]
  
  var Indices: [GLubyte] = [0, 1, 2, 2, 3, 0]
  
  private var context: EAGLContext?
  private var effect = GLKBaseEffect()
  private var rotation: Float = 0.0
  private var ebo = GLuint()
  private var vbo = GLuint()
  private var vao = GLuint()
  
  deinit {
    tearDownGL()
  }
  
  private func setupGL() {
    context = EAGLContext(api: .openGLES3)
    EAGLContext.setCurrent(context)
    
    if let view = view as? GLKView, let context = context {
      view.context = context
      delegate = self
    }
    
    // Helper variables to identify the position and color attributes for OpenGL calls.
    let vertexAttribColor = GLuint(GLKVertexAttrib.color.rawValue)
    let vertexAttribPosition = GLuint(GLKVertexAttrib.position.rawValue)
    
    // The size, in memory, of a Vertex structure.
    let vertexSize = MemoryLayout<Vertex>.stride
    let colorOffset = MemoryLayout<GLfloat>.stride * 3
    let colorOffsetPointer = UnsafeRawPointer(bitPattern: colorOffset)
    
    // VAO
    
    // Generate and bind a vertex array object.
    glGenVertexArraysOES(1, &vao)
    glBindVertexArrayOES(vao)
    
    // VBO
    glGenBuffers(1, &vbo)
    glBindBuffer(GLenum(GL_ARRAY_BUFFER), vbo)
    glBufferData(GLenum(GL_ARRAY_BUFFER), Vertices.size(), Vertices, GLenum(GL_STATIC_DRAW))
    glEnableVertexAttribArray(vertexAttribPosition)
    glVertexAttribPointer(vertexAttribPosition, 3, GLenum(GL_FLOAT), GLboolean(UInt8(GL_FALSE)), GLsizei(vertexSize), nil)
    
    // Enable the colors vertex attribute to then specify information about how the color of a vertex is stored.
    glEnableVertexAttribArray(vertexAttribColor)
    glVertexAttribPointer(vertexAttribColor, 4, GLenum(GL_FLOAT), GLboolean(UInt8(GL_FALSE)), GLsizei(vertexSize), colorOffsetPointer)
    
    // EBO
    glGenBuffers(1, &ebo)
    glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), ebo)
    glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), Indices.size(), Indices, GLenum(GL_STATIC_DRAW))
    glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0)
    glBindVertexArrayOES(0)
  }
  
  /// Perform cleanup, and delete buffers and memory.
  private func tearDownGL() {
    EAGLContext.setCurrent(context)
    
    glDeleteBuffers(1, &vao)
    glDeleteBuffers(1, &vbo)
    glDeleteBuffers(1, &ebo)
    
    EAGLContext.setCurrent(nil)
    context = nil
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    setupGL()
  }
}

extension ViewController: GLKViewControllerDelegate {
  func glkViewControllerUpdate(_ controller: GLKViewController) {
    let aspect = fabsf(Float(view.bounds.size.width) / Float(view.bounds.size.height))
    let projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0), aspect, 4.0, 10.0)
    effect.transform.projectionMatrix = projectionMatrix
    
    var modelViewMatrix = GLKMatrix4MakeTranslation(0.0, 0.0, -6.0)
    rotation += 90 * Float(timeSinceLastUpdate)
    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, GLKMathDegreesToRadians(rotation), 0, 0, 1)
    effect.transform.modelviewMatrix = modelViewMatrix
  }

  override func glkView(_ view: GLKView, drawIn rect: CGRect) {
    glClearColor(0.85, 0.85, 0.85, 1.0)
    glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
    
    effect.prepareToDraw()
    glBindVertexArrayOES(vao)
    glDrawElements(GLenum(GL_TRIANGLES), GLsizei(Indices.count), GLenum(GL_UNSIGNED_BYTE), nil)
    glBindVertexArrayOES(0)
  }
}

下面看一下实现效果

Metal源码

首先还是看下工程组织结构

接着看sb中的内容

下面就是源码了

1. Array+Helpers.swift
import Foundation

// MARK: - Array Helpers

/// Array extension to help with size/memory calculations when working with OpenGL.
extension Array {
  // MARK: - Instance Methods
  
  /// Returns the memory size/footprint (in bytes) of a given array.
  ///
  /// - Returns: Integer value representing the memory size the array.
  func size() -> Int {
    return count * MemoryLayout.size(ofValue: self[0])
  }
}
2. Vertex.swift
import GLKit

//
// MARK: - Vertex
//

/// Structure to hold a vertex's position and color data.
struct Vertex {
  /// Stores the X coordinate of a vertex.
  var x: GLfloat
  /// Stores the Y coordinate of a vertex.
  var y: GLfloat
  /// Stores the Z coordinate of a vertex.
  var z: GLfloat
  /// Stores the red color value of a vertex.
  var r: GLfloat
  /// Stores the green color value of a vertex.
  var g: GLfloat
  /// Stores the blue color value of a vertex.
  var b: GLfloat
  /// Stores the alpha value of a vertex.
  var a: GLfloat
}

struct SceneMatrices {
  var projectionMatrix: GLKMatrix4 = GLKMatrix4Identity
  var modelviewMatrix: GLKMatrix4 = GLKMatrix4Identity
}
3. ViewController.swift
import GLKit
import MetalKit
final class ViewController: UIViewController {
  @IBOutlet weak var metalView: MTKView!

  private var vertexBuffer: MTLBuffer!
  private var indicesBuffer: MTLBuffer!
  private var metalDevice: MTLDevice!
  private var metalCommandQueue: MTLCommandQueue!
  private var pipelineState: MTLRenderPipelineState!

  var Vertices = [
    Vertex(x:  1, y: -1, z: 0, r: 1, g: 0, b: 0, a: 1),
    Vertex(x:  1, y:  1, z: 0, r: 0, g: 1, b: 0, a: 1),
    Vertex(x: -1, y:  1, z: 0, r: 0, g: 0, b: 1, a: 1),
    Vertex(x: -1, y: -1, z: 0, r: 0, g: 0, b: 0, a: 1),
    ]
  
  var Indices: [UInt32] = [0, 1, 2, 2, 3, 0]
  
  private var rotation: Float = 0.0
  private var ebo = GLuint()
  private var vbo = GLuint()
  private var vao = GLuint()

  private var sceneMatrices = SceneMatrices()
  private var uniformBuffer: MTLBuffer!
  private var lastUpdateDate = Date()
  
  private func setupMetal() {
    metalDevice = MTLCreateSystemDefaultDevice()  // 1
    metalCommandQueue = metalDevice.makeCommandQueue()  // 2
    metalView.device = metalDevice // 3
    metalView.delegate = self // 4

    let vertexBufferSize = Vertices.size()
    vertexBuffer = metalDevice.makeBuffer(bytes: &Vertices, length: vertexBufferSize, options: .storageModeShared)

    let indicesBufferSize = Indices.size()
    indicesBuffer = metalDevice.makeBuffer(bytes: &Indices, length: indicesBufferSize, options: .storageModeShared)

    let defaultLibrary = metalDevice.makeDefaultLibrary()!
    let fragmentProgram = defaultLibrary.makeFunction(name: "basic_fragment")
    let vertexProgram = defaultLibrary.makeFunction(name: "basic_vertex") // 1

    let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
    pipelineStateDescriptor.vertexFunction = vertexProgram
    pipelineStateDescriptor.fragmentFunction = fragmentProgram
    pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm // 2

    pipelineState = try! metalDevice.makeRenderPipelineState(descriptor: pipelineStateDescriptor) // 3
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    setupMetal()
  }
}

// MARK: - MTKView Delegate Extension
extension ViewController: MTKViewDelegate {
  // 1
  func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
    let aspect = fabsf(Float(size.width) / Float(size.height))  // 1
    let projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0), aspect, 4.0, 10.0)  // 2
    sceneMatrices.projectionMatrix = projectionMatrix  // 3
  }

  // 2
  func draw(in view: MTKView) {
    // 1
    guard let drawable = view.currentDrawable else {
      return
    }

    let renderPassDescriptor = MTLRenderPassDescriptor() // 2
    renderPassDescriptor.colorAttachments[0].texture = drawable.texture // 3
    renderPassDescriptor.colorAttachments[0].loadAction = .clear // 4
    renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0) // 5

    // 6
    guard let commandBuffer = metalCommandQueue.makeCommandBuffer() else {
      return
    }

    // 7
    guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else {
      return
    }

    // Frame drawing goes here
    renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)  // 1
    // Update logic
    var modelViewMatrix = GLKMatrix4MakeTranslation(0.0, 0.0, -6.0)
    let timeSinceLastUpdate = lastUpdateDate.timeIntervalSince(Date())
    rotation += 90 * Float(timeSinceLastUpdate) // 1
    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, GLKMathDegreesToRadians(rotation), 0, 0, 1)  // 2
    sceneMatrices.modelviewMatrix = modelViewMatrix

    // Set uniform buffer
    let uniformBufferSize = MemoryLayout.size(ofValue: sceneMatrices)
    uniformBuffer = metalDevice.makeBuffer(bytes: &sceneMatrices, length: uniformBufferSize, options: .storageModeShared) // 2
    renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, index: 1)  // 3

    renderEncoder.setRenderPipelineState(pipelineState)
    renderEncoder.drawIndexedPrimitives(type: .triangle, indexCount: Indices.count, indexType: .uint32, indexBuffer: indicesBuffer, indexBufferOffset: 0) // 2

    renderEncoder.endEncoding() // 8
    commandBuffer.addCompletedHandler { _ in
      self.lastUpdateDate = Date()
    }
    commandBuffer.present(drawable) // 9
    commandBuffer.commit() // 10
  }
}

具体效果同OpenGL一样,这里就不展示了。

后记

本篇主要讲述了将项目从OpenGL转化到Metal,感兴趣的给个赞或者关注~~~

上一篇下一篇

猜你喜欢

热点阅读