Android OpenGL ES3.0 入门
# EGL
# 初始化
选择的 EGL 版本为 EGL1.4 版本,对应了 AndroidSdk 中的  EGL14 
 创建可以等到 Surface 初始化完成后进行,比如在 SurfaceHolder 的 surfaceCreate 方法中去初始化。
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
 //必须要一个surface对象来创建窗口表面
fun initEGL(surface: Surface) : Boolean{  4
	//第一步,获取一个EGLDisplay表面,用来建立与设备的窗口系统通信信道,建立连接
    egldisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);  
    if(egldisplay == EGL14.EGL_NO_DISPLAY){  
        Log.d(TAG, "eglGetDisplay fail $egldisplay")  
        return false  
    }  
  	//初始化EGL,返回EGL的主版本号的次版本号
    if(!EGL14.eglInitialize( egldisplay,versions,0,versions,1)){  
        Log.d(TAG, "eglInitialize fail $egldisplay")  
        return false  
    }  
    val config : Array<EGLConfig?> = arrayOfNulls(1)  
    var configNum = intArrayOf(EGL14.EGL_NONE)  
	//选择设备窗口系统支持的EGL配置列表
    if(!EGL14.eglChooseConfig(egldisplay,configAttribe,0,  
            config,0,1, configNum,0)) {  
        Log.d(TAG, "eglChooseConfig fail $config")  
        return false;  
    }  
    if(config[0] == null){  
        Log.d(TAG, "config choose fail $config")  
        return false;  
    }  
	//创建一个窗口,作为屏幕上的渲染区域
    eglSurface = EGL14.eglCreateWindowSurface(egldisplay,config[0],surface,  
        intArrayOf(EGL14.EGL_NONE),0)  
    if(eglSurface == EGL14.EGL_NO_SURFACE){  
        Log.d(TAG, "eglCreateWindowSurface fail $eglSurface")  
        return false;  
    }  
	//创建渲染上下文
    val eglContext = EGL14.eglCreateContext(egldisplay,config[0],  
        EGL14.EGL_NO_CONTEXT,contextAttribe,0)  
    if(eglContext == EGL14.EGL_NO_CONTEXT){  
        Log.d(TAG, "eglCreateContext fail $eglContext")  
        return false;  
    }  
  	//将上一步创建的上下文与渲染表面进行关联
    if(!EGL14.eglMakeCurrent(egldisplay,eglSurface,eglSurface,eglContext)){  
        Log.d(TAG, "eglMakeCurrent fail $egldisplay")  
        return false;  
    }  
    return true;  
}
# 运行
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//这里是放在一个子线程的run方法体中,执行一个无限循环去渲染OpenGL ES3.0API输出的数据。
override fun run() {  
    super.run()  
    if(!init()){  
        Log.d(TAG,"EGL init fail")  
        return  
    }  
    try {  
        while (true){  
            for(draw in drawers){  
                draw.draw()  
                swapBuffer(egldisplay,eglSurface)  
            }  
            sleep(20)  
        }  
    }catch (e:Exception){  
        e.printStackTrace()  
    }  
    for(draw in drawers){  
        draw.release()  
    }  
  
}
private fun swapBuffer (display: EGLDisplay,surface:EGLSurface){  
    EGL14.eglSwapBuffers(display,surface)  
}
