如何封装 opengl 流程 -- 以为android-opengl-canvas例

我们在 OpenGL绘制一张图片的流程--以android-openGL-canvas为例
里看到,要使用opengl进行绘制,要实现的流程相当地繁琐,那么我们能不能对其进行封装,使绘制更加简单呢?
接下来还是以 android-openGL-canvas 为例子进行说明。

OpenGL绘制一张图片的流程--以android-openGL-canvas为例 里面,提到了实现的3个流程,其中第一和第二个流程是初始化的流程,基本上只需要走一遍,所以我们可以考虑将这两个流程进行封装。
封装后的类就是
EglHelper
GLThread

EglHelper

EglHelper封装了 创建 eglContext 和 创建 surface 的功能,主要的实现代码是:

    public EGLContext start(EGLContext eglContext) {
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
        }
        /*
         * Get an EGL instance
         */
        mEgl = (EGL10) EGLContext.getEGL();

        /*
         * Get to the default display.
         */
        mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

        if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
            throw new RuntimeException("eglGetDisplay failed");
        }

        /*
         * We can now initialize EGL for that display
         */
        int[] version = new int[2];
        if (!mEgl.eglInitialize(mEglDisplay, version)) {
            throw new RuntimeException("eglInitialize failed");
        }
        mEglConfig = eglConfigChooser.chooseConfig(mEgl, mEglDisplay);

            /*
            * Create an EGL context. We want to do this as rarely as we can, because an
            * EGL context is a somewhat heavy object.
            */
        mEglContext = eglContextFactory.createContext(mEgl, mEglDisplay, mEglConfig, eglContext);
        if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
            mEglContext = null;
            throwEglException("createContext");
        }
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
        }

        mEglSurface = null;

        return mEglContext;
    }


    public boolean createSurface(Object surface) {
        if (GLThread.LOG_EGL) {
            Log.w("EglHelper", "createSurface()  tid=" + Thread.currentThread().getId());
        }
        /*
         * Check preconditions.
         */
        if (mEgl == null) {
            throw new RuntimeException("egl not initialized");
        }
        if (mEglDisplay == null) {
            throw new RuntimeException("eglDisplay not initialized");
        }
        if (mEglConfig == null) {
            throw new RuntimeException("mEglConfig not initialized");
        }

        /*
         *  The window size has changed, so we need to create a new
         *  surface.
         */
        destroySurfaceImp();

        /*
         * Create an EGL surface we can render into.
         */
        mEglSurface = eglWindowSurfaceFactory.createWindowSurface(mEgl,
                mEglDisplay, mEglConfig, surface);

        if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
            int error = mEgl.eglGetError();
            if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
            }
            return false;
        }

        /*
         * Before we can issue GL commands, we need to make sure
         * the context is current and bound to a surface.
         */
        if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
            /*
             * Could not make the context current, probably because the underlying
             * SurfaceView surface has been destroyed.
             */
            logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError());
            return false;
        }

        return true;
    }

可以看到两个方法的参数,说明EGLContext 和 surface 可以从外部传入。也就是说,可以和其它线程共享一个EGLContext,这样就可以使用其它线程绑定的texture了。而surface,是绘制的东西的承载者,可以是TextureView的SurfaceTexture,可以是GLSurfaceView的surfaceHolder,可以是MediaCodec的surface(用于录制视频);所以surface的类型是Object。

GLThread

GLThread是一个继承Thread的类,我们可以不在主线程进行绘制。

主要的运行代码如下:

            while (true) {
                synchronized (sGLThreadManager) {
                    while (true) {
                        ...
                        mEglContext = mEglHelper.start(mEglContext);
                        ...
                        sGLThreadManager.wait();
                        ...
                    }
                } 
                ...
                mEglHelper.createSurface(mSurface))
                ...
                mRenderer.onSurfaceCreated(gl, mEglHelper.getEglConfig()); // OpenGL第三步流程,绘制流程
                ...
                mRenderer.onSurfaceChanged(gl, w, h); // OpenGL第三步流程,绘制流程
                ...
                mRenderer.onDrawFrame(gl); // OpenGL第三步流程,绘制流程
                ...
            }
  • 为了支持持续不断地刷新界面,也就是RENDERMODE_CONTINUOUSLY的renderMode模式,需要在这个线程里while(true)无限循环地运行
  • 为了支持需要时才刷新界面,也就是RENDERMODE_WHEN_DIRTY的renderMode模式,需要sGLThreadManager.wait();
    public void requestRender() {
        synchronized (sGLThreadManager) {
            mRequestRender = true;
            sGLThreadManager.notifyAll();
        }
    }
  • 其中synchronized (sGLThreadManager)的部分是用于线程之间通信,外部线程可以停止和恢复这个线程
    public void onResume() {
        synchronized (sGLThreadManager) {
            if (LOG_PAUSE_RESUME) {
                Log.i("GLThread", "onResume tid=" + getId());
            }
            mRequestPaused = false;
            mRequestRender = true;
            mRenderComplete = false;
            sGLThreadManager.notifyAll();
            while ((!mExited) && mPaused && (!mRenderComplete)) {
                if (LOG_PAUSE_RESUME) {
                    Log.i("Main thread", "onResume waiting for !mPaused.");
                }
                try {
                    sGLThreadManager.wait();
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public void onPause() {
        synchronized (sGLThreadManager) {
            if (LOG_PAUSE_RESUME) {
                Log.i("GLThread", "onPause tid=" + getId());
            }
            mRequestPaused = true;
            sGLThreadManager.notifyAll();
            while ((!mExited) && (!mPaused)) {
                if (LOG_PAUSE_RESUME) {
                    Log.i("Main thread", "onPause waiting for mPaused.");
                }
                try {
                    sGLThreadManager.wait();
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
  • 前文中提及的 EglHelper 和 GLThread 都是由GLSurfaceView里的内部类修改而来的,增加了从外部传入EGLContext和surface等功能,所以此处使用Builder模式,能够定制化地create一个GLThread对象。
    public static class Builder {
        private EGLConfigChooser configChooser;
        private EGLContextFactory eglContextFactory;
        private EGLWindowSurfaceFactory eglWindowSurfaceFactory;
        private GLSurfaceView.Renderer renderer;
        private GLWrapper mGLWrapper = null;
        private int eglContextClientVersion = 2;
        private int debugFlags = 0;
        private int renderMode = RENDERMODE_WHEN_DIRTY;
        private Object surface;
        private EGLContext eglContext = EGL10.EGL_NO_CONTEXT;

        public Builder setSurface(Object surface) {
            this.surface = surface;
            return this;
        }


        public Builder setEGLConfigChooser(boolean needDepth) {
            setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth, eglContextClientVersion));
            return this;
        }


        public Builder setEGLConfigChooser(EGLConfigChooser configChooser) {
            this.configChooser = configChooser;
            return this;
        }

        public Builder setEGLConfigChooser(int redSize, int greenSize, int blueSize,
                                           int alphaSize, int depthSize, int stencilSize) {
            setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
                    blueSize, alphaSize, depthSize, stencilSize, eglContextClientVersion));
            return this;
        }

        public Builder setEglContextFactory(EGLContextFactory eglContextFactory) {
            this.eglContextFactory = eglContextFactory;
            return this;
        }

        public Builder setEglWindowSurfaceFactory(EGLWindowSurfaceFactory eglWindowSurfaceFactory) {
            this.eglWindowSurfaceFactory = eglWindowSurfaceFactory;
            return this;
        }

        public Builder setRenderer(GLSurfaceView.Renderer renderer) {
            this.renderer = renderer;
            return this;
        }

        public Builder setmGLWrapper(GLWrapper mGLWrapper) {
            this.mGLWrapper = mGLWrapper;
            return this;
        }

        public Builder setEglContextClientVersion(int eglContextClientVersion) {
            this.eglContextClientVersion = eglContextClientVersion;
            return this;
        }

        public Builder setDebugFlags(int debugFlags) {
            this.debugFlags = debugFlags;
            return this;
        }

        public Builder setRenderMode(int renderMode) {
            this.renderMode = renderMode;
            return this;
        }

        public void setSharedEglContext(@NonNull EGLContext sharedEglContext) {
            this.eglContext = sharedEglContext;
        }

        public GLThread createGLThread() {
            if (renderer == null) {
                throw new NullPointerException("renderer has not been set");
            }
            if (surface == null && eglWindowSurfaceFactory == null) {
                throw new NullPointerException("surface has not been set");
            }
            if (configChooser == null) {
                configChooser = new SimpleEGLConfigChooser(true, eglContextClientVersion);
            }
            if (eglContextFactory == null) {
                eglContextFactory = new DefaultContextFactory(eglContextClientVersion);
            }
            if (eglWindowSurfaceFactory == null) {
                eglWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
            }
            return new GLThread(configChooser, eglContextFactory, eglWindowSurfaceFactory, renderer, mGLWrapper, debugFlags, renderMode, surface, eglContext);
        }
    }

主要关注点是configChooser, eglContextFactory, eglWindowSurfaceFactory,这3个变量分别定义了EGLConfig, EGLContext, EGLSurface。
以上就是第一第二步流程地封装。至于第三步流程,其实在 OpenGL绘制一张图片的流程--以android-openGL-canvas为例 里也已经引用了相关代码,总结就是封装成了GLES20Canvas ,有兴趣地可以进去查看。

下一篇文章会讲如何使用封装好的GLThread -- 实现一个代替GLSurfaceView的GLTextureView。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容