iOS OpenGL ES3.0入门实践

一、效果图 

入门实践,做的东西比较简单,效果如下:

二、关于顶点坐标和纹理坐标

绘制图片需要设置顶点坐标和纹理坐标并加载像素数据,之所以要指定两组坐标是因为纹理和顶点使用不同的坐标系,就是告诉OpenGL:把图像的某一区域绘制到屏幕的某一区域,3个点能确定一个三角形区域,我们把一张图分成4个三角形,分别是中心点和每条边点两个顶点组成的三角形,如下图,它图能够帮助你理解后面代码 GLImage.m 中的两组顶点为什么是那样子设置的

三、关于坐标轴方向、投影和坐标映射

具体参考我的另一篇文章Android OpenGL ES 2.0入门实践,主要也是参考的Android官方文档,好在iOS都有对应的函数,就没再仔细看iOS官方文档了。 

四、代码

OpenGL在iOS12 就已经不推荐使用了,官方推荐使用Metal,最近在学习OpenGL ES就在Android和iOS上分别实践了一下,iOS端最简单的方式就是使用GLKit,主要使用GLKViewController这个现成的绘制环境,有了这个环境,就可以直接使用OpenGL的接口进行编码了,平台有更简单易用的 GLKBaseEffect,我没有使用,还是沿用了最基本的流程,使用GL着色器,下面是主要代码:

GlUtil.h

#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLUtil : NSObject+(GLuint)createProgram:(NSString*)vertexShaderCode :(NSString*)fragmentShaderCode;+(void)printActiveUniforms:(GLuint)program;@endNS_ASSUME_NONNULL_END

GLUtil.m

#import "GLUtil.h"@implementation GLUtil+ (NSString *)readShaderSource:(NSString *)bundleFileName {NSString* path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleFileName];NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@", content);return content;
}+ (GLuint)loadShader:(GLenum)type :(const char *)shaderCode {GLuint shader = glCreateShader(type);glShaderSource(shader, 1, &shaderCode, NULL);glCompileShader(shader);GLint commpiled;glGetShaderiv(shader, GL_COMPILE_STATUS, &commpiled);if(!commpiled) {GLint infoLen = 0;glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);if(infoLen > 0) {char* infoLog = malloc(infoLen);glGetShaderInfoLog(shader, infoLen, NULL, infoLog);NSLog(@"%s", infoLog);free(infoLog);glDeleteShader(shader);return 0;}}return shader;
}+ (GLuint)createProgram:(NSString *)vertexShaderFileName :(NSString *)fragmentShaderFileName {GLuint program = glCreateProgram();const char* vertexShaderCode = [[GLUtil readShaderSource:vertexShaderFileName] UTF8String];const char* fragmentShaderCode = [[GLUtil readShaderSource:fragmentShaderFileName] UTF8String];GLuint vertexShader = [self loadShader:GL_VERTEX_SHADER:vertexShaderCode];GLuint fragmentShader = [self loadShader:GL_FRAGMENT_SHADER:fragmentShaderCode];if (vertexShader == 0 || fragmentShader == 0) {return 0;}glAttachShader(program, vertexShader);glAttachShader(program, fragmentShader);glLinkProgram(program);GLint linked;glGetProgramiv(program, GL_LINK_STATUS, &linked);if(!linked) {GLint infoLen = 0;glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);if(infoLen > 0) {char* infoLog = malloc(infoLen);glGetProgramInfoLog(program, infoLen, NULL, infoLog);NSLog(@"%s", infoLog);free(infoLog);glDeleteProgram(program);return 0;}}glDeleteShader(vertexShader);glDeleteShader(fragmentShader);return program;
}+ (void)printActiveUniforms:(GLuint)program {GLint maxUniformLen;//变量名的最大长度GLint numUniforms;//变量个数char* uniformName;//变量名glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numUniforms);glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformLen);uniformName = malloc(maxUniformLen);for (GLint index = 0; index < numUniforms; index++) {GLint size;GLenum type;GLint location;glGetActiveUniform(program, index, maxUniformLen, NULL, &size, &type, uniformName);location = glGetUniformLocation(program, uniformName);NSString* typeStr;switch (type) {case GL_FLOAT:typeStr = (@"GL_FLOAT");break;case GL_FLOAT_VEC2:typeStr = (@"GL_FLOAT_VEC2");break;case GL_FLOAT_VEC3:typeStr = (@"GL_FLOAT_VEC3");break;case GL_FLOAT_VEC4:typeStr = (@"GL_FLOAT_VEC4");break;case GL_FLOAT_MAT4:typeStr = (@"GL_FLOAT_MAT4");break;case GL_BOOL:typeStr = (@"GL_BOOL");break;case GL_SAMPLER_2D:typeStr = (@"GL_SAMPLER_2D");break;default:typeStr = [NSString stringWithFormat:@"变量类型:0x%X", type];break;}NSLog(@"index=%d, name=%s, size=%d, type=%@, location=%d", index, uniformName, size, typeStr, location);}free(uniformName);
}@end

vertexShader.glsl

顶点着色器代码 vertexShader.glsl

#version 300 es
uniform mat4 uMVPMatrix;
uniform mat4 translateMatrix;
uniform bool isTranslate;
layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec2 aTextureCoord;
out vec2 vTexCoord;
void main() {if (isTranslate) {gl_Position = uMVPMatrix * translateMatrix * vPosition;} else {gl_Position = uMVPMatrix * vPosition;}vTexCoord = aTextureCoord;
}

fragmentShader.glsl

片段着色器代码 fragmentShader.glsl

#version 300 es
precision mediump float;
uniform bool isTexture;
uniform vec4 vColor;
uniform sampler2D uTextureUnit;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {if(isTexture) {fragColor = texture(uTextureUnit,vTexCoord);} else {fragColor = vColor;}
}

绘制2D纹理的类 GLImage

GLImage.h

#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLImage : NSObject-(void)loadTexture:(NSString*)imageName;-(void)draw:(int)positionHandle :(int)textureHandle :(GLuint*)vbo;@endNS_ASSUME_NONNULL_END

GLImage.m

#import "GLImage.h"
#import <UIKit/UIKit.h>//原文链接:https://blog.csdn.net/gongxiaoou/article/details/89344561//图片尺寸:2385 × 3623
static const float POSITION_VERTEX[]  = {0.0f, 0.0f,     //顶点坐标V01.0f, 1.52f,   //顶点坐标V1-1.0f, 1.52f,   //顶点坐标V2-1.0f, -1.52f,  //顶点坐标V31.0f, -1.52f     //顶点坐标V4
};static const float TEX_VERTEX[]  = {0.5f, 0.5f, //纹理坐标V01.0f, 1.0f,     //纹理坐标V10.0f, 1.0f,     //纹理坐标V20.0f, 0.0f,   //纹理坐标V31.0f, 0.0f    //纹理坐标V4
};static const short VERTEX_INDEX[]  = {0, 1, 2,  //V0,V1,V2 三个顶点组成一个三角形0, 2, 3,  //V0,V2,V3 三个顶点组成一个三角形0, 3, 4,  //V0,V3,V4 三个顶点组成一个三角形0, 4, 1   //V0,V4,V1 三个顶点组成一个三角形
};@interface GLImage()
{GLuint textureID;
}@end@implementation GLImage//原文链接:https://blog.csdn.net/qq_30513483/article/details/101538967
- (void)loadTexture:(NSString *)imageName {UIImage *image = [UIImage imageNamed:imageName];// 将 UIImage 转换为 CGImageRefCGImageRef cgImageRef = [image CGImage];GLuint width = (GLuint)CGImageGetWidth(cgImageRef);GLuint height = (GLuint)CGImageGetHeight(cgImageRef);CGRect rect = CGRectMake(0, 0, width, height);// 绘制图片CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();void *imageData = malloc(width * height * 4);CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8, width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);CGContextTranslateCTM(context, 0, height);CGContextScaleCTM(context, 1.0f, -1.0f);CGColorSpaceRelease(colorSpace);CGContextClearRect(context, rect);CGContextDrawImage(context, rect, cgImageRef);// 生成纹理glGenTextures(1, &textureID);glBindTexture(GL_TEXTURE_2D, textureID);// 将图片数据写入纹理缓存glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);// 设置如何把纹素映射成像素glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);// 解绑glBindTexture(GL_TEXTURE_2D, 0);// 释放内存CGContextRelease(context);free(imageData);
}- (void)draw:(int)positionHandle :(int)textureHandle :(GLuint*)vbo {//顶点坐标glEnableVertexAttribArray(positionHandle);glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);glBufferData(GL_ARRAY_BUFFER, sizeof(POSITION_VERTEX), POSITION_VERTEX, GL_STATIC_DRAW);glVertexAttribPointer(positionHandle, 2, GL_FLOAT, GL_FALSE, 0, 0);//纹理坐标glEnableVertexAttribArray(textureHandle);glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);glBufferData(GL_ARRAY_BUFFER, sizeof(TEX_VERTEX), TEX_VERTEX, GL_STATIC_DRAW);glVertexAttribPointer(textureHandle, 2, GL_FLOAT, GL_FALSE, 0, 0);//激活纹理glActiveTexture(GL_TEXTURE0);//绑定纹理glBindTexture(GL_TEXTURE_2D, textureID);//绘制glDrawElements(GL_TRIANGLES, sizeof(VERTEX_INDEX)/sizeof(short), GL_UNSIGNED_SHORT, VERTEX_INDEX);
}@end

GLViewController.h

#import <GLKit/GLKit.h>NS_ASSUME_NONNULL_BEGIN@interface GLViewController : GLKViewController {
}@endNS_ASSUME_NONNULL_END

GLViewController.m

#import "GLViewController.h"
#import "GLUtil.h"
#import "GLImage.h"const int VBO_NUM = 2;static const GLfloat vertices[] = {0.0f,  0.5f, 0.0f,-0.5f, -0.5f, 0.0f,0.5f, -0.5f, 0.0f};@interface GLViewController ()
{GLuint program;int muMVPMatrixHandle;int translateMatrixHandle;int isTranslateHandle;int isTextureHandle;int colorHandle;GLKMatrix4 vMatrix;GLKMatrix4 projMatrix;GLKMatrix4 vPMatrix;GLKMatrix4 translateMatrix;GLuint vbo[VBO_NUM];GLImage* glImage;
}@end@implementation GLViewController- (void)initGL{program = [GLUtil createProgram:@"vertexShader.glsl" :@"fragmentShader.glsl"];glUseProgram(program);muMVPMatrixHandle = glGetUniformLocation(program, "uMVPMatrix");translateMatrixHandle = glGetUniformLocation(program, "translateMatrix");isTranslateHandle = glGetUniformLocation(program, "isTranslate");isTextureHandle = glGetUniformLocation(program, "isTexture");colorHandle = glGetUniformLocation(program, "vColor");glGenBuffers(VBO_NUM, vbo);[GLUtil printActiveUniforms:program];
}- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.GLKView* glView = (GLKView*)self.view;glView.context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES3];[EAGLContext setCurrentContext:glView.context];//这句必须得有,不然画不出来图形[self initGL];glImage = [GLImage new];[glImage loadTexture:@"dog.jpg"];// Combine the projection and camera view matricesvMatrix = GLKMatrix4MakeLookAt(0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}- (void) onSurfaceChange:(float)width :(float)height {NSLog(@"%fx%f", width, height);glViewport(0, 0, width, height);//投影矩阵if (width > height) {float ratio = width / height;projMatrix = GLKMatrix4MakeFrustum(-ratio, ratio, -1.0f, 1.0f, 3.0f, 7.0f);} else {float ratio = height / width;projMatrix = GLKMatrix4MakeFrustum(-1.0f, 1.0f, -ratio, ratio, 3.0f, 7.0f);}// Combine the projection and camera view matricesvPMatrix = GLKMatrix4Multiply(projMatrix, vMatrix);
}- (void)viewWillLayoutSubviews {[super viewWillLayoutSubviews];float width = self.view.frame.size.width;float height = self.view.frame.size.height;NSLog(@"%s %fx%f", __func__, width, height);[self onSurfaceChange:width :height];
}- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
//    NSLog(@"%s %f", __func__, [[NSDate new] timeIntervalSince1970]);// Apply the combined projection and camera view transformationsglUniformMatrix4fv(muMVPMatrixHandle, 1, false, (float*)&vPMatrix);glClearColor(0.9f, 0.9f, 0.9f, 1.0f);//背景色glClear(GL_COLOR_BUFFER_BIT);//画图片glUniform1i(isTranslateHandle, 0);//禁用矩阵偏移glUniform1i(isTextureHandle, 1);//启用纹理[glImage draw:0 :1 :vbo];double degrees = (long)([[NSDate new] timeIntervalSince1970] * 50) % 360;double radians = degrees * M_PI / 180.0;
//    NSLog(@"degrees=%f", degrees);translateMatrix = GLKMatrix4Translate(GLKMatrix4Identity, cos(radians), sin(radians), 0.0f);glUniformMatrix4fv(translateMatrixHandle, 1, GL_FALSE, (float*)&translateMatrix);glUniform1i(isTranslateHandle, 1);//启用矩阵偏移glUniform1i(isTextureHandle, 0);//禁用纹理glUniform4f(colorHandle, 0.0f, 0.5f, 1.0f, 1.0f);glEnableVertexAttribArray(0);glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);glDrawArrays(GL_TRIANGLES, 0, 3);
}@end

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/176065.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

GZ038 物联网应用开发赛题第3套

2023年全国职业院校技能大赛 高职组 物联网应用开发 任 务 书 &#xff08;第3套卷&#xff09; 工位号&#xff1a;______________ 第一部分 竞赛须知 一、竞赛要求 1、正确使用工具&#xff0c;操作安全规范&#xff1b; 2、竞赛过程中如有异议&#xff0c;可向现场考评…

【LIUNX】配置缓存DNS服务

配置缓存DNS服务 A.安装bind bind-utils1.尝试修改named.conf配置文件2.测试nslookup B.修改named.conf配置文件1.配置文件2.再次测试 缓存DNS服务器&#xff1a;只提供域名解析结果的缓存功能&#xff0c;目的在于提高数据查询速度和效率&#xff0c;但是没有自己控制的区域地…

后台系统更改主题【el-color-picker】

Element el-color-picker 颜色选择器的使用 设置的页面 <script setup lang"ts"> import { getThemeColor } from "../../utils/colorChange"; import { useUserStore } from "/store/index"; import { reactive } from "vue"…

高防IP可以抵御哪些恶意攻击

高防IP协议可以隐藏用户的站点&#xff0c;使得攻击者无法发现恶意攻击的目标网络资源&#xff0c;从而提高了源站的安全性。能够有效抵御常见的恶意攻击类型ICMPFlood、UDPFlood、 TCPFlood、SYNFlood、ACKFlood等&#xff0c;帮助游戏、金 融、电子商务、互联网、政企等行业抵…

Linux---(五)三大工具yum、vim、gcc/g++

文章目录 一、yum工具1.Linux中安装软件的方法&#xff1a;2.什么是yum?3.yum源更新 二、Linux编辑器--vim1.IDE例子2.vim&#xff08;1&#xff09;vim的常用模式及切换模式&#xff08;2&#xff09;底层模式常用命令&#xff08;3&#xff09;插入模式常用命令&#xff08;…

Mac安装与配置eclipse

目录 一、安装Java&#xff1a;Mac环境配置&#xff08;Java&#xff09;----使用bash_profile进行配置&#xff08;附下载地址&#xff09; 二、下载和安装eclipse 1、进入eclipse的官网 (1)、点击“Download Packages ”​ (2)、找到macOS选择符合自己电脑的框架选项&am…

比较LeNet、AlexNet、VGG和ResNet模型及其优缺点的实际实验。

一、说明 卷积神经网络&#xff0c;有很多种类&#xff0c;这不仅仅是各种试验或尝试。而且是已经设计好的网络存在若干不尽人意之处&#xff0c;需要弥补和改进。因此&#xff0c;本文就是记录这些网络的优缺点&#xff0c;从新意上说&#xff0c;本文全无&#xff0c;但是从启…

Java学习笔记(七)——面向对象编程(中级)

一、IDEA &#xff08;一&#xff09;常用的快捷键 &#xff08;二&#xff09;模版/自定义模版 二、包 &#xff08;一&#xff09;包的命名 &#xff08;二&#xff09;常用的包 &#xff08;三&#xff09;如何引入&#xff08;导入&#xff09;包 &#xff08;四&am…

spring cloud之网关

Gateway网关(*) 什么是网关 # 1.说明 - 网关统一服务入口&#xff0c;可方便实现对平台众多服务接口进行管控。 - 网关 路由转发 过滤器路由转发&#xff1a;接收一切外界请求&#xff0c;转发到后端的微服务上去过滤器&#xff1a;在服务网关中可以完成一系列的横切功能&a…

react Antd3以下实现年份选择器 YearPicker

项目antd版本低&#xff0c;没有直接可使用的年份选择器&#xff0c;参考此篇&#xff08;使用antd实现年份选择器控件 - 掘金&#xff09; 一开始在state里设置了time&#xff1a; this.state {isopen: false,time: null } 在类似onChange事件里this.setState({time: valu…

Ubuntu 17.10 “Artful Aardvark” 发布首个 Beta

Ubuntu 17.10 “Artful Aardvark” 首个 Beta 版已发布。 按照 Ubuntu 17.10 的发布日程 &#xff0c;Ubuntu 17.10 首个 beta 版按时发布了。不过参与本次测试版的没有 Ubuntu 官方风味版本&#xff08;要尝试的话可以考虑每日构建 ISO&#xff09;&#xff0c;包括了 Kubunt…

Android R.fraction

来源 我是在看Android10原生代码&#xff0c;绘制状态栏蓝牙电量相关类中第一次看到R.fraction的&#xff0c;如类BatteryMeterDrawable <fraction name"battery_button_height_fraction">10%</fraction> mButtonHeightFraction context.getResources(…