swift+GLKit 绘制立方体

1,294 阅读3分钟

背景

为了简化基于OpenGLOpenGL ES的应⽤开发。 苹果提供了GLKit框架可以省去书写着色器代码的烦恼。本篇即用GLKit框架完成立方体的绘制。基础代码注释见上篇使用OpenGLES实现UIImageView显示效果

代码

因上一篇使用oc完成,本篇采用了swift,对于指针的操作二者还是存在差异的。详细代码如下


import UIKit
import OpenGLES
import GLKit

struct CubeVertex {
    var positionCoord: GLKVector3 //顶点坐标
    var textureCoord: GLKVector2  //纹理坐标
}

class ViewController: UIViewController {

    lazy var glkView: GLKView = {
        let glkView = GLKView(frame: CGRect(x: 0, y: 200, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width))
        glkView.backgroundColor = .purple
        //使用深度缓存
        glkView.drawableDepthFormat = GLKViewDrawableDepthFormat.format24
        glkView.delegate = self
        view.addSubview(glkView)
        return glkView
    }()
    
    lazy var baseEffect: GLKBaseEffect = {
        let baseEffect = GLKBaseEffect()
        return baseEffect
    }()
    
    //顶点数
    let kCoordCount = 36
    
    lazy var vertices: UnsafeMutablePointer<CubeVertex> = {
        let verticesSize = MemoryLayout<CubeVertex>.size * kCoordCount
        let vertices = UnsafeMutablePointer<CubeVertex>.allocate(capacity: verticesSize)
        return vertices
    }()
    
    lazy var displayLink: CADisplayLink = {
        let displayLink = CADisplayLink(target: self, selector: #selector(glkViewDisplay))
        return displayLink
    }()
    
    var angle = 0
    var vertexBuffer = GLuint()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupContext()
        setupEffect()
        setupVertexData()
        addDisplayLink()
    }


    private func setupContext() {
        if let context = EAGLContext(api: EAGLRenderingAPI.openGLES3) {
            EAGLContext.setCurrent(context)
            glkView.context = context
        }
    }
    
    private func setupEffect() {
       
        guard  let imagePath = Bundle.main.path(forResource: "me", ofType: "png", inDirectory: nil),
                   let image = UIImage(contentsOfFile: imagePath)?.cgImage
            else { return  }
        
        //设置纹理参数
        let options = [GLKTextureLoaderOriginBottomLeft : NSNumber(value: true)]
        let textureInfo = try? GLKTextureLoader.texture(with: image, options: options)
        if let textureInfo = textureInfo, let target = GLKTextureTarget(rawValue: textureInfo.target) {
            baseEffect.texture2d0.name = textureInfo.name
            baseEffect.texture2d0.target = target
        }
       
    }
    
    private func setupVertexData() {
        // 前面
        self.vertices[0] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[1] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 0)))
        self.vertices[2] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))

        self.vertices[3] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 0)))
        self.vertices[4] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[5] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (1, 0)))
        
        // 上面
        self.vertices[6] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[7] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[8] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        
        self.vertices[9] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[10] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        self.vertices[11] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))

        // 下面
        self.vertices[12] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[13] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[14] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        
        self.vertices[15] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[16] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        self.vertices[17] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))

        // 左面
        self.vertices[18] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[19] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[20] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        
        self.vertices[21] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[22] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        self.vertices[23] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))

        // 右面
        self.vertices[24] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, 0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[25] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[26] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        
        self.vertices[27] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, 0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[28] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))
        self.vertices[29] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))

        // 后面
        self.vertices[30] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (0, 1)))
        self.vertices[31] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))
        self.vertices[32] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 1)))
        
        self.vertices[33] = CubeVertex(positionCoord: GLKVector3(v: (-0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (0, 0)))
        self.vertices[34] = CubeVertex(positionCoord: GLKVector3(v: (0.5, 0.5, -0.5)), textureCoord: GLKVector2(v: (1, 1)))
        self.vertices[35] = CubeVertex(positionCoord: GLKVector3(v: (0.5, -0.5, -0.5)), textureCoord: GLKVector2(v: (1, 0)))

        //开辟缓存区
        glGenBuffers(1, &vertexBuffer)
        glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer)
        let bufferSize = MemoryLayout<CubeVertex>.size * kCoordCount
        glBufferData(GLenum(GL_ARRAY_BUFFER), bufferSize, self.vertices, GLenum(GL_STATIC_DRAW))

        //顶点数据
        glEnableVertexAttribArray(GLuint(GLKVertexAttrib.position.rawValue))
        glVertexAttribPointer(GLuint(GLKVertexAttrib.position.rawValue), 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<CubeVertex>.size), BUFFER_OFFSET(0))

        //纹理数据
        glEnableVertexAttribArray(GLuint(GLKVertexAttrib.texCoord0.rawValue))
        glVertexAttribPointer(GLuint(GLKVertexAttrib.texCoord0.rawValue), 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<CubeVertex>.size), BUFFER_OFFSET(MemoryLayout<GLKVector3>.size + 4))

    }
    
    private func BUFFER_OFFSET(_ i: Int) -> UnsafeRawPointer? {
        return UnsafeRawPointer(bitPattern: i)
    }
    
    private func addDisplayLink() {
        displayLink.add(to: RunLoop.main, forMode: .common)
    }
    
    @objc private   func glkViewDisplay() {
        angle = (angle + 3) % 360
        let radians = GLKMathDegreesToRadians(Float(angle))
        //模型视图矩阵变换
        baseEffect.transform.modelviewMatrix = GLKMatrix4MakeRotation(radians, 0.5, 0.3, 0.4)
        glkView.display()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        displayLink.invalidate()
    }
    deinit {
        if EAGLContext.current() == glkView.context {
            EAGLContext.setCurrent(nil)
        }
        
       vertices.deallocate()
       glDeleteBuffers(1, &vertexBuffer)
        
    }
}

extension ViewController: GLKViewDelegate {
    func glkView(_ view: GLKView, drawIn rect: CGRect) {
        glEnable(GLenum(GL_DEPTH_TEST))
        glClear(GLbitfield(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT))
        baseEffect.prepareToDraw()
        glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(kCoordCount))
    }
}

代码解析

上述代码对顶点和纹理坐标数据的使用采用了指针操作,具体使用方式可参考我上篇文章iOS 指针与数组

还有一点就是在结构体CubeVertex中,根据偏移取纹理坐标GLKVector2的值:

BUFFER_OFFSET(MemoryLayout<GLKVector3>.size + 4)

这个地方加4是因为苹果对部分包含vector类型数据的结构体加了一个padding,此处这个padding等于4个字节。CubeVertex24个字节,而不是5float所占的20个字节,具体参见sizeof() returns wrong size for struct which contains GLKVector3, GLKVector4 variable

效果