ARKit & OpenGL ES - OpenGL实现

作者: handyTOOL | 来源:发表于2017-06-19 11:39 被阅读1110次

点击获取本文示例代码

如果你想了解ATRKit的基础知识,请访问ARKit & OpenGL ES - ARKit原理篇
如果你想了解更多关于OpenGL ES的知识,请移步至OpenGL ES相关文章目录

本文所用OpenGL基础代码来自OpenGL ES系列,具备渲染几何体,纹理等基础功能,实现细节将不赘述。

集成ARKit的关键代码都在ARGLBaseViewController中。我们来看一下它的代码。

处理ARFrame

- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame {
    // 同步YUV信息到 yTexture 和 uvTexture
    CVPixelBufferRef pixelBuffer = frame.capturedImage;
    GLsizei imageWidth = (GLsizei)CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
    GLsizei imageHeight = (GLsizei)CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
    void * baseAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
    
    glBindTexture(GL_TEXTURE_2D, self.yTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, imageWidth, imageHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, baseAddress);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    imageWidth = (GLsizei)CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
    imageHeight = (GLsizei)CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
    void *laAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
    glBindTexture(GL_TEXTURE_2D, self.uvTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, imageWidth, imageHeight, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, laAddress);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    self.videoPlane.yuv_yTexture = self.yTexture;
    self.videoPlane.yuv_uvTexture = self.uvTexture;
    [self setupViewport: CGSizeMake(imageHeight, imageWidth)];
    
    // 同步摄像机
    matrix_float4x4 cameraMatrix = matrix_invert([frame.camera transform]);
    GLKMatrix4 newCameraMatrix = GLKMatrix4Identity;
    for (int col = 0; col < 4; ++col) {
        for (int row = 0; row < 4; ++row) {
            newCameraMatrix.m[col * 4 + row] = cameraMatrix.columns[col][row];
        }
    }
    
    self.cameraMatrix = newCameraMatrix;
    GLKVector3 forward = GLKVector3Make(-self.cameraMatrix.m13, -self.cameraMatrix.m23, -self.cameraMatrix.m33);
    GLKMatrix4 rotationMatrix = GLKMatrix4MakeRotation(M_PI / 2, forward.x, forward.y, forward.z);
    self.cameraMatrix = GLKMatrix4Multiply(rotationMatrix, newCameraMatrix);
}

上面的代码展示了如何处理ARKit捕捉的ARFrame,ARFramecapturedImage存储了摄像头捕捉的图片信息,类型是CVPixelBufferRef。默认情况下,图片信息的格式是YUV,通过两个Plane来存储,也可以理解为两张图片。一张格式是Y(Luminance),保存了明度信息,另一张是UV(Chrominance、Chroma),保存了色度和浓度。我们需要把这两张图分别绑定到不同的纹理上,然后在Shader中利用算法将YUV转换成RGB。下面是处理纹理的Fragment Shader,利用公式进行颜色转换。

precision highp float;

varying vec3 fragNormal;
varying vec2 fragUV;

uniform float elapsedTime;
uniform mat4 normalMatrix;
uniform sampler2D yMap;
uniform sampler2D uvMap;

void main(void) {
    vec4 Y_planeColor = texture2D(yMap, fragUV);
    vec4 CbCr_planeColor = texture2D(uvMap, fragUV);
    
    float Cb, Cr, Y;
    float R ,G, B;
    Y = Y_planeColor.r * 255.0;
    Cb = CbCr_planeColor.r * 255.0 - 128.0;
    Cr = CbCr_planeColor.a * 255.0 - 128.0;
    
    R = 1.402 * Cr + Y;
    G = -0.344 * Cb - 0.714 * Cr + Y;
    B = 1.772 * Cb + Y;
    
    
    vec4 videoColor = vec4(R / 255.0, G / 255.0, B / 255.0, 1.0);
    gl_FragColor = videoColor;
}

处理并绑定好纹理后,为了保证不同屏幕尺寸下,纹理不被非等比拉伸,所以对viewport进行重了新计算[self setupViewport: CGSizeMake(imageHeight, imageWidth)];。接下来将ARKit计算出来的摄像机的变换赋值给self.cameraMatrix。注意ARKit捕捉的图片需要旋转90度后才能正常显示,所以在设置Viewport时特意颠倒了宽和高,并在最后对摄像机进行了旋转。

VideoPlane

VideoPlane是为了显示视频编写的几何体,它能够接收两个纹理,Y和UV。

@interface VideoPlane : GLObject
@property (assign, nonatomic) GLuint yuv_yTexture;
@property (assign, nonatomic) GLuint yuv_uvTexture;
- (instancetype)initWithGLContext:(GLContext *)context;
- (void)update:(NSTimeInterval)timeSinceLastUpdate;
- (void)draw:(GLContext *)glContext;
@end

...

- (void)draw:(GLContext *)glContext {
    [glContext setUniformMatrix4fv:@"modelMatrix" value:self.modelMatrix];
    bool canInvert;
    GLKMatrix4 normalMatrix = GLKMatrix4InvertAndTranspose(self.modelMatrix, &canInvert);
    [glContext setUniformMatrix4fv:@"normalMatrix" value:canInvert ? normalMatrix : GLKMatrix4Identity];
    [glContext bindTextureName:self.yuv_yTexture to:GL_TEXTURE0 uniformName:@"yMap"];
    [glContext bindTextureName:self.yuv_uvTexture to:GL_TEXTURE1 uniformName:@"uvMap"];
    [glContext drawTrianglesWithVAO:vao vertexCount:6];
}

其他的功能很简单,就是绘制一个正方形,最终配合显示视频的Shader,渲染YUV格式的数据。

透视投影矩阵

在ARFrame可以获取渲染需要的纹理和摄像机矩阵,除了这些,和真实摄像头匹配的透视投影矩阵也是必须的。它能够让渲染出来的3D物体透视看起来很自然。

- (void)session:(ARSession *)session cameraDidChangeTrackingState:(ARCamera *)camera {
    matrix_float4x4 projectionMatrix = [camera projectionMatrixWithViewportSize:self.viewport.size orientation:UIInterfaceOrientationPortrait zNear:0.1 zFar:1000];
    GLKMatrix4 newWorldProjectionMatrix = GLKMatrix4Identity;
    for (int col = 0; col < 4; ++col) {
        for (int row = 0; row < 4; ++row) {
           newWorldProjectionMatrix.m[col * 4 + row] = projectionMatrix.columns[col][row];
        }
    }
    self.worldProjectionMatrix = newWorldProjectionMatrix;
}

上面的代码演示了如何通过ARKit获取3D透视投影矩阵,有了透视投影矩阵和摄像机矩阵,就可以很方便的利用OpenGL渲染物体了。

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    [super glkView:view drawInRect:rect];
    
    [self.objects enumerateObjectsUsingBlock:^(GLObject *obj, NSUInteger idx, BOOL *stop) {
        [obj.context active];
        [obj.context setUniform1f:@"elapsedTime" value:(GLfloat)self.elapsedTime];
        [obj.context setUniformMatrix4fv:@"projectionMatrix" value:self.worldProjectionMatrix];
        [obj.context setUniformMatrix4fv:@"cameraMatrix" value:self.cameraMatrix];
        
        [obj.context setUniform3fv:@"lightDirection" value:self.lightDirection];
        [obj draw:obj.context];
    }];
}

本文主要介绍了OpenGL ES渲染ARKit的基本思路,没有对OpenGL ES技术细节描述太多。如果你有兴趣,可以直接阅读示例中的代码深入了解。

相关文章

网友评论

  • Genie_GY:你好,没有在GitHub上找到本篇的相关代码哦
  • 以霏之名:摄像机矩阵那块没咋看懂,为啥需要matrix_invert后,还需要旋转90度呢?是因为和opengl的坐标系不符合么?
  • 皮皮Warrior:没有在你的GitHub上找到代码
  • a4e01f3250ae:請問[frame.camera transform], camera的三个轴 x_axis=(cam.m00, cam10, cam20), y_axis=(cam01, cam02, cam03), z_axis=(-cam.m02, -cam.m12. -cam.m22), 这样对吗? 如果我想求这个相机的reflection, 如果用这个 z_axis作为入射角,求其反射角度, 这样会出错吗? 按一些网上的教材,是把camera往下位移 2d, 然后在把三个轴 旋转 2*反射角(按z_axis作为入射角求出的)的rotation matrix, 这样有问题吗? 因为结果总是不对,所以想知道一开始把 z_axis 作为入射角是不是就是错的。 谢谢
  • a4e01f3250ae:请问在这个框架中还可以让model使用它们自己的 PBR shader 吗?
    b11826b79430:@handyTOOL scenekit版本可以使用opengl渲染吗?还是只能用metal?
    handyTOOL:我这篇文章主要演示的是如何使用OpenGL ES去对接ARKit,因为苹果的官方只给了Metal和SceneKit版本, 光照模型都比较简单。如果你想要更加真实3D渲染效果,可以去寻找或者自己制作shader。不管是使用图片做环境光还是模拟其他光照特性,都是Shader可以解决的事情,你可以随意修改示例项目中的Shader来达到你的效果。如果你不了解Shader,那就只能去使用SceneKit或者其他OpenGL的开源库来达到你的目的了。
  • a4e01f3250ae:请问在这个构架中如何获取实时的光线方向? 如何使用 let environment = UIImage(named: "IBL.png")
    scene.lightingEnvironment.contents = environment
    scene.lightingEnvironment.intensity = 2.0

    有没有办法实时获取并使用 SphericalHarmnicsEfficient?
    https://medium.com/@avihay/amazing-physically-based-rendering-using-the-new-ios-10-scenekit-2489e43f7021
  • nil_c6af: // 同步摄像机
    matrix_float4x4 cameraMatrix = matrix_invert([frame.camera transform]);

    作者你好,请问这里为什么要对相机旋转矩阵做取逆操作,我在好几个demo中都看到这个取逆操作,但不知道为什么,还请大神指点一下。
    以霏之名:@handyTOOL 为啥作顶点变换的矩阵和摄像机自身的变换矩阵是互逆的?一脸懵逼,求介绍一下
    nil_c6af:@handyTOOL 好的,感谢回复
    handyTOOL:@nil_c6af OpenGL 中摄像机是一个虚拟的概念,它一般是一个矩阵,在顶点着色器中作用于顶点。举个简单的例子,一个在z轴坐标为3处的摄像机,实际上的含义是它所代表的矩阵会把顶点沿z轴平移-3。这里用作顶点变换的矩阵和摄像机自身的变换矩阵是互逆的。如果你想更深入的了解,可以去看看OpenGL的一些基本概念,这些概念有很多在其他渲染系统中也通用。
  • c064b2b405b2:基于您的这篇博客,我为 Unity3D 写了一下 ARKit OpenGL 的渲染支持,并把过程整理了一篇博客。如果有时间,麻烦您看一下,指点一二。

    http://chendi.me/2017/07/21/unity-arkit-plugin-opengl/
    handyTOOL:@三鹿_8d87 指点不敢当,有时间我会去看下的,刚好拓展一下u3d方面的知识:grin:

本文标题:ARKit & OpenGL ES - OpenGL实现

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