OpenGL ES - 地球月亮渲染案例

思维导图

长截图   2019-03-25 下午04.58.39.jpg

处理ArrayBuffer封装

创建顶点缓存数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 此方法在当前的OpenGL ES上下文中创建一个顶点属性数组缓冲区,用于调用此方法的线程.
- (id)initWithAttribStride:(GLsizeiptr)aStride
numberOfVertices:(GLsizei)count
bytes:(const GLvoid *)dataPtr
usage:(GLenum)usage;
{
NSParameterAssert(0 < aStride);
NSAssert((0 < count && NULL != dataPtr) ||
(0 == count && NULL == dataPtr),
@"data must not be NULL or count > 0");

if(nil != (self = [super init]))
{
stride = aStride;
bufferSizeBytes = stride * count;
// 第一步
glGenBuffers(1,
&name);
// 第二步
glBindBuffer(GL_ARRAY_BUFFER,
self.name);

// 第三步
glBufferData(
GL_ARRAY_BUFFER, // 初始化缓存区的内容
bufferSizeBytes, // 要复制的字节数
dataPtr, // 要复制的字节地址
usage); //GPU内存中的缓存

NSAssert(0 != name, @"Failed to generate name");
}

return self;
}

分配顶点数据,准备绘制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 当应用程序希望使用缓冲区呈现任何几何图形时,必须准备一个顶点属性数组缓冲区。当你的应用程序准备一个缓冲区时,一些OpenGL ES状态被改变,允许绑定缓冲区和配置指针。
- (void)prepareToDrawWithAttrib:(GLuint)index
numberOfCoordinates:(GLint)count
attribOffset:(GLsizeiptr)offset
shouldEnable:(BOOL)shouldEnable
{
NSParameterAssert((0 < count) && (count < 4));
NSParameterAssert(offset < self.stride);
NSAssert(0 != name, @"Invalid name");

glBindBuffer(GL_ARRAY_BUFFER,
self.name);

if(shouldEnable)
{
glEnableVertexAttribArray(index);
}

glVertexAttribPointer(
index,
count,
GL_FLOAT,
GL_FALSE,
self.stride,
NULL + offset);

#ifdef DEBUG
{
GLenum error = glGetError();
if(GL_NO_ERROR != error)
{
NSLog(@"GL Error: 0x%x", error);
}
}
#endif
}

绘制

1
2
3
4
5
6
7
// 提交由模式标识的绘图命令,并指示OpenGL ES从准备好的缓冲区中的顶点开始,从先前准备好的缓冲区中使用计数顶点。
+ (void)drawPreparedArraysWithMode:(GLenum)mode
startVertexIndex:(GLint)first
numberOfVertices:(GLsizei)count;
{
glDrawArrays(mode, first, count);
}

重新缓存顶点数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 此方法加载由接收器存储的数据
- (void)reinitWithAttribStride:(GLsizeiptr)aStride
numberOfVertices:(GLsizei)count
bytes:(const GLvoid *)dataPtr;
{
NSParameterAssert(0 < aStride);
NSParameterAssert(0 < count);
NSParameterAssert(NULL != dataPtr);
NSAssert(0 != name, @"Invalid name");

self.stride = aStride;
self.bufferSizeBytes = aStride * count;

// 第二步
glBindBuffer(GL_ARRAY_BUFFER,
self.name);
// 第三步
glBufferData(
GL_ARRAY_BUFFER,
bufferSizeBytes,
dataPtr,
GL_DYNAMIC_DRAW);
}

ViewDidLoad

新建opengles上下文及GLKView配置

1
2
3
4
5
6
7
8
9
10
//1.新建OpenGL ES 上下文
self.mContext = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2];

//2.获取GLKView
GLKView *view = (GLKView *)self.view;
view.context = self.mContext;
view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

[EAGLContext setCurrentContext:self.mContext];

配置baseEffect光照信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//创建GLKBaseEffect 只能有3个光照、2个纹理
self.baseEffect = [[GLKBaseEffect alloc]init];

-(void)configureLight
{

//1.是否开启light0光照
self.baseEffect.light0.enabled = GL_TRUE;

/*
union _GLKVector4
{
struct { float x, y, z, w; };
struct { float r, g, b, a; };
struct { float s, t, p, q; };
float v[4];
} __attribute__((aligned(16)));
typedef union _GLKVector4 GLKVector4;

union共用体
有3个结构体,
比如表示顶点坐标的x,y,z,w
比如表示颜色的,RGBA;
表示纹理的stpq

*/
//2.设置漫射光颜色
self.baseEffect.light0.diffuseColor = GLKVector4Make(
1.0f,//Red
1.0f,//Green
1.0f,//Blue
1.0f);//Alpha
/*
The position of the light in world coordinates.
世界坐标中的光的位置。
If the w component of the position is 0.0, the light is calculated using the directional light formula. The x, y, and z components of the vector specify the direction the light shines. The light is assumed to be infinitely far away; attenuation and spotlight properties are ignored.
如果位置的w分量为0,则使用定向光公式计算光。向量的x、y和z分量指定光的方向。光被认为是无限远的,衰减和聚光灯属性被忽略。
If the w component of the position is a non-zero value, the coordinates specify the position of the light in homogenous coordinates, and the light is either calculated as a point light or a spotlight, depending on the value of the spotCutoff property.
如果该位置的W组件是一个非零的值,指定的坐标的光在齐次坐标的位置,和光是一个点光源和聚光灯计算,根据不同的spotcutoff属性的值
The default value is [0.0, 0.0, 1.0, 0.0].
默认值[0.0f,0.0f,1.0f,0.0f];
*/

self.baseEffect.light0.position = GLKVector4Make(
1.0f, //x
0.0f, //y
0.8f, //z
0.0f);//w

//光的环境部分
self.baseEffect.light0.ambientColor = GLKVector4Make(
0.2f,//Red
0.2f,//Green
0.2f,//Blue
1.0f);//Alpha

}

设置模型矩阵,投影矩阵

1
2
3
4
5
6
7
8
//获取屏幕纵横比
GLfloat aspectRatio = self.view.bounds.size.width / self.view.bounds.size.height;

//4.创建投影矩阵 -> 透视投影
self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(-1.0 * aspectRatio, 1.0 * aspectRatio, -1.0, 1.0, 1.0, 120.0f);

//5.设置模型矩阵 -5.0f表示往屏幕内移动-5.0f距离
self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -5.0f);

处理顶点数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-(void)bufferData
{
//1、GLKMatrixStackCreate()创建一个新的空矩阵
self.modelViewMatrixStack = GLKMatrixStackCreate(kCFAllocatorDefault);

//2、为将要缓存区数据开辟空间
//sphereVerts 在sphere.h文件中存在
/*
参数1:数据大小 3个GLFloat类型,x,y,z
参数2:有多少个数据,count
参数3:数据大小
参数4:用途 GL_STATIC_DRAW,
*/
//顶点数据缓存,顶点数据从sphere.h文件的sphereVerts数组中获取顶点数据x,y,z
self.vertexPositionBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(3 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereVerts)/(3 * sizeof(GLfloat)) bytes:sphereVerts usage:GL_STATIC_DRAW];

//法线,光照坐标 sphereNormals数组 x,y,z
self.vertexNormalBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(3 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereNormals)/(3 * sizeof(GLfloat)) bytes:sphereNormals usage:GL_STATIC_DRAW];

//纹理坐标 sphereTexCoords数组 x,y
self.vertextTextureCoordBuffer = [[AGLKVertexAttribArrayBuffer alloc]initWithAttribStride:(2 * sizeof(GLfloat)) numberOfVertices:sizeof(sphereTexCoords)/ (2 * sizeof(GLfloat)) bytes:sphereTexCoords usage:GL_STATIC_DRAW];


//3.获取地球纹理
CGImageRef earthImageRef = [UIImage imageNamed:@"Earth512x256.jpg"].CGImage;

//控制图像加载方式的选项
NSDictionary *earthOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],GLKTextureLoaderOriginBottomLeft, nil];

//将纹理图片加载到纹理数据对象earchTextureInfo中
/*
参数1:加载的纹理图片
参数2:控制图像加载的方式的选项-字典
参数3:错误信息
*/
self.earchTextureInfo = [GLKTextureLoader textureWithCGImage:earthImageRef options:earthOptions error:NULL];

//4.获取月亮纹理
CGImageRef moonImageRef = [UIImage imageNamed:@"Moon256x128"].CGImage;

NSDictionary *moonOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],GLKTextureLoaderOriginBottomLeft, nil];

self.moomTextureInfo = [GLKTextureLoader textureWithCGImage:moonImageRef options:moonOptions error:NULL];

//矩阵堆
//用所提供的矩阵替换最顶层矩阵,将self.baseEffect.transform.modelviewMatrix,替换self.modelViewMatrixStack
GLKMatrixStackLoadMatrix4(self.modelViewMatrixStack, self.baseEffect.transform.modelviewMatrix);

//初始化在轨道上月球位置
self.moonRotationAngleDegress = -20.0f;


}

渲染场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#pragma mark - drawRect
//渲染场景
-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
//设置清屏颜色
glClearColor(0.3f, 0.3f, 0.3f, 1.0f);

//清空颜色缓存区和深度缓存区
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//地球旋转角度
_earthRotationAngleDegress += 360.0f/60.0f;
//月球旋转角度
_moonRotationAngleDegress += (360.0f/60.0f)/SceneDaysPerMoonOrbit;

//2、准备绘制
/*
其实就是把数据传递过去,然后指定读取方式
参数1:数据是做什么用的
参数2:数据读取个数
参数3:数据读取索引
参数4:是否调用glEnableVertexAttribArray

着色器能否读取到数据,由是否启用了对应的属性决定,这就是glEnableVertexAttribArray的功能,允许顶点着色器读取GPU(服务器端)数据。


默认情况下,出于性能考虑,所有顶点着色器的属性(Attribute)变量都是关闭的,意味着数据在着色器端是不可见的,哪怕数据已经上传到GPU,由glEnableVertexAttribArray启用指定属性,才可在顶点着色器中访问逐顶点的属性数据。glVertexAttribPointer或VBO只是建立CPU和GPU之间的逻辑连接,从而实现了CPU数据上传至GPU。但是,数据在GPU端是否可见,即,着色器能否读取到数据,由是否启用了对应的属性决定,这就是glEnableVertexAttribArray的功能,允许顶点着色器读取GPU(服务器端)数据。

那么,glEnableVertexAttribArray应该在glVertexAttribPointer之前还是之后调用?答案是都可以,只要在绘图调用(glDraw*系列函数)前调用即可。
*/
[self.vertexPositionBuffer prepareToDrawWithAttrib:GLKVertexAttribPosition numberOfCoordinates:3 attribOffset:0 shouldEnable:YES];
[self.vertexNormalBuffer prepareToDrawWithAttrib:GLKVertexAttribNormal numberOfCoordinates:3 attribOffset:0 shouldEnable:YES];
[self.vertextTextureCoordBuffer prepareToDrawWithAttrib:GLKVertexAttribTexCoord0 numberOfCoordinates:2 attribOffset:0 shouldEnable:YES];

//3.开始绘制
[self drawEarth];
[self drawMoon];

}

绘制地球

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
-(void)drawEarth
{
//获取纹理的name、target
self.baseEffect.texture2d0.name = self.earchTextureInfo.name;
self.baseEffect.texture2d0.target = self.earchTextureInfo.target;

/*
current matrix:
1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 0.000000
0.000000 0.000000 -5.000000 1.000000

为什么?因为你在viewDidLoad中设置的
//5.设置模型矩形 -5.0f表示往屏幕内移动-5.0f距离
self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -5.0f);
*/

//将当前的modelViewMatrixStack 压栈
GLKMatrixStackPush(self.modelViewMatrixStack);

//在指定的轴上旋转最上面的矩阵。
GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(SceneEarthAxialTiltDeg), 1.0f, 0.0f, 0.0f);


/*
current matrix:
1.000000 0.000000 0.000000 0.000000
0.000000 0.917060 0.398749 0.000000
0.000000 -0.398749 0.917060 0.000000
0.000000 0.000000 -5.000000 1.000000

为什么?
将矩阵与围绕X旋转的旋转矩阵相乘,即可得上述结果
*/
self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);

//准备绘制
[self.baseEffect prepareToDraw];

//调用AGLKVertexAttribArrayBuffer,绘制图形
/*
参数1:绘制的方式,三角形
参数2:绘制数据读取的索引
参数3:绘制数据的大小
*/

[AGLKVertexAttribArrayBuffer drawPreparedArraysWithMode:GL_TRIANGLES startVertexIndex:0 numberOfVertices:sphereNumVerts];

//绘制完毕,则出栈
/*
current matrix:
0.994522 0.041681 -0.095859 0.000000
0.000000 0.917060 0.398749 0.000000
0.104528 -0.396565 0.912036 0.000000
0.000000 0.000000 -5.000000 1.000000
*/
GLKMatrixStackPop(self.modelViewMatrixStack);

/*
current matrix:
1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 0.000000
0.000000 0.000000 -5.000000 1.000000
*/
self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);

}

绘制月球

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-(void)drawMoon
{
//获取纹理的name、target
self.baseEffect.texture2d0.name = self.moomTextureInfo.name;
self.baseEffect.texture2d0.target = self.moomTextureInfo.target;

//压栈
GLKMatrixStackPush(self.modelViewMatrixStack);

//围绕Y轴旋转moonRotationAngleDegress角度
//自转
GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(self.moonRotationAngleDegress), 0.0f, 1.0f, 0.0f);

//平移 -月球距离地球的距离
GLKMatrixStackTranslate(self.modelViewMatrixStack, 0.0f, 0.0f, SceneMoonDistanceFromEarth);

//缩放,把月球缩放
GLKMatrixStackScale(self.modelViewMatrixStack, SceneMoonRadiusFractionOfEarth, SceneMoonRadiusFractionOfEarth, SceneMoonRadiusFractionOfEarth);

//旋转 围绕Y轴旋转
GLKMatrixStackRotate(self.modelViewMatrixStack, GLKMathDegreesToRadians(self.moonRotationAngleDegress), 0.0f, 1.0f, 0.0f);
self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);

[self.baseEffect prepareToDraw];

[AGLKVertexAttribArrayBuffer drawPreparedArraysWithMode:GL_TRIANGLES startVertexIndex:0 numberOfVertices:sphereNumVerts];

GLKMatrixStackPop(self.modelViewMatrixStack);

self.baseEffect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(self.modelViewMatrixStack);
}

切换投影方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma mark -Switch Click
//切换正投影效果或透视投影效果
- (IBAction)switchClick:(UISwitch *)sender {

GLfloat aspect = self.view.bounds.size.width / self.view.bounds.size.height;

if ([sender isOn]) {

//正投影
self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeFrustum(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, 2.0, 120.0);

}else
{
//透视投影
self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, 2.0, 120.0);
}

}

效果图

12.gif

13.gif

谢谢你赏我糖果吃