GLSurfaceView.java revision 2b3bf720bf28584f700ad8ebb5e8e31a0e466f29
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.opengl;
18
19import java.io.Writer;
20import java.lang.ref.WeakReference;
21import java.util.ArrayList;
22
23import javax.microedition.khronos.egl.EGL10;
24import javax.microedition.khronos.egl.EGL11;
25import javax.microedition.khronos.egl.EGLConfig;
26import javax.microedition.khronos.egl.EGLContext;
27import javax.microedition.khronos.egl.EGLDisplay;
28import javax.microedition.khronos.egl.EGLSurface;
29import javax.microedition.khronos.opengles.GL;
30import javax.microedition.khronos.opengles.GL10;
31
32import android.content.Context;
33import android.content.pm.ConfigurationInfo;
34import android.os.SystemProperties;
35import android.os.Trace;
36import android.util.AttributeSet;
37import android.util.Log;
38import android.view.SurfaceHolder;
39import android.view.SurfaceView;
40
41/**
42 * An implementation of SurfaceView that uses the dedicated surface for
43 * displaying OpenGL rendering.
44 * <p>
45 * A GLSurfaceView provides the following features:
46 * <p>
47 * <ul>
48 * <li>Manages a surface, which is a special piece of memory that can be
49 * composited into the Android view system.
50 * <li>Manages an EGL display, which enables OpenGL to render into a surface.
51 * <li>Accepts a user-provided Renderer object that does the actual rendering.
52 * <li>Renders on a dedicated thread to decouple rendering performance from the
53 * UI thread.
54 * <li>Supports both on-demand and continuous rendering.
55 * <li>Optionally wraps, traces, and/or error-checks the renderer's OpenGL calls.
56 * </ul>
57 *
58 * <div class="special reference">
59 * <h3>Developer Guides</h3>
60 * <p>For more information about how to use OpenGL, read the
61 * <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a> developer guide.</p>
62 * </div>
63 *
64 * <h3>Using GLSurfaceView</h3>
65 * <p>
66 * Typically you use GLSurfaceView by subclassing it and overriding one or more of the
67 * View system input event methods. If your application does not need to override event
68 * methods then GLSurfaceView can be used as-is. For the most part
69 * GLSurfaceView behavior is customized by calling "set" methods rather than by subclassing.
70 * For example, unlike a regular View, drawing is delegated to a separate Renderer object which
71 * is registered with the GLSurfaceView
72 * using the {@link #setRenderer(Renderer)} call.
73 * <p>
74 * <h3>Initializing GLSurfaceView</h3>
75 * All you have to do to initialize a GLSurfaceView is call {@link #setRenderer(Renderer)}.
76 * However, if desired, you can modify the default behavior of GLSurfaceView by calling one or
77 * more of these methods before calling setRenderer:
78 * <ul>
79 * <li>{@link #setDebugFlags(int)}
80 * <li>{@link #setEGLConfigChooser(boolean)}
81 * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
82 * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
83 * <li>{@link #setGLWrapper(GLWrapper)}
84 * </ul>
85 * <p>
86 * <h4>Specifying the android.view.Surface</h4>
87 * By default GLSurfaceView will create a PixelFormat.RGB_888 format surface. If a translucent
88 * surface is required, call getHolder().setFormat(PixelFormat.TRANSLUCENT).
89 * The exact format of a TRANSLUCENT surface is device dependent, but it will be
90 * a 32-bit-per-pixel surface with 8 bits per component.
91 * <p>
92 * <h4>Choosing an EGL Configuration</h4>
93 * A given Android device may support multiple EGLConfig rendering configurations.
94 * The available configurations may differ in how may channels of data are present, as
95 * well as how many bits are allocated to each channel. Therefore, the first thing
96 * GLSurfaceView has to do when starting to render is choose what EGLConfig to use.
97 * <p>
98 * By default GLSurfaceView chooses a EGLConfig that has an RGB_888 pixel format,
99 * with at least a 16-bit depth buffer and no stencil.
100 * <p>
101 * If you would prefer a different EGLConfig
102 * you can override the default behavior by calling one of the
103 * setEGLConfigChooser methods.
104 * <p>
105 * <h4>Debug Behavior</h4>
106 * You can optionally modify the behavior of GLSurfaceView by calling
107 * one or more of the debugging methods {@link #setDebugFlags(int)},
108 * and {@link #setGLWrapper}. These methods may be called before and/or after setRenderer, but
109 * typically they are called before setRenderer so that they take effect immediately.
110 * <p>
111 * <h4>Setting a Renderer</h4>
112 * Finally, you must call {@link #setRenderer} to register a {@link Renderer}.
113 * The renderer is
114 * responsible for doing the actual OpenGL rendering.
115 * <p>
116 * <h3>Rendering Mode</h3>
117 * Once the renderer is set, you can control whether the renderer draws
118 * continuously or on-demand by calling
119 * {@link #setRenderMode}. The default is continuous rendering.
120 * <p>
121 * <h3>Activity Life-cycle</h3>
122 * A GLSurfaceView must be notified when the activity is paused and resumed. GLSurfaceView clients
123 * are required to call {@link #onPause()} when the activity pauses and
124 * {@link #onResume()} when the activity resumes. These calls allow GLSurfaceView to
125 * pause and resume the rendering thread, and also allow GLSurfaceView to release and recreate
126 * the OpenGL display.
127 * <p>
128 * <h3>Handling events</h3>
129 * <p>
130 * To handle an event you will typically subclass GLSurfaceView and override the
131 * appropriate method, just as you would with any other View. However, when handling
132 * the event, you may need to communicate with the Renderer object
133 * that's running in the rendering thread. You can do this using any
134 * standard Java cross-thread communication mechanism. In addition,
135 * one relatively easy way to communicate with your renderer is
136 * to call
137 * {@link #queueEvent(Runnable)}. For example:
138 * <pre class="prettyprint">
139 * class MyGLSurfaceView extends GLSurfaceView {
140 *
141 *     private MyRenderer mMyRenderer;
142 *
143 *     public void start() {
144 *         mMyRenderer = ...;
145 *         setRenderer(mMyRenderer);
146 *     }
147 *
148 *     public boolean onKeyDown(int keyCode, KeyEvent event) {
149 *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
150 *             queueEvent(new Runnable() {
151 *                 // This method will be called on the rendering
152 *                 // thread:
153 *                 public void run() {
154 *                     mMyRenderer.handleDpadCenter();
155 *                 }});
156 *             return true;
157 *         }
158 *         return super.onKeyDown(keyCode, event);
159 *     }
160 * }
161 * </pre>
162 *
163 */
164public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback2 {
165    private final static String TAG = "GLSurfaceView";
166    private final static boolean LOG_ATTACH_DETACH = false;
167    private final static boolean LOG_THREADS = false;
168    private final static boolean LOG_PAUSE_RESUME = false;
169    private final static boolean LOG_SURFACE = false;
170    private final static boolean LOG_RENDERER = false;
171    private final static boolean LOG_RENDERER_DRAW_FRAME = false;
172    private final static boolean LOG_EGL = false;
173    /**
174     * The renderer only renders
175     * when the surface is created, or when {@link #requestRender} is called.
176     *
177     * @see #getRenderMode()
178     * @see #setRenderMode(int)
179     * @see #requestRender()
180     */
181    public final static int RENDERMODE_WHEN_DIRTY = 0;
182    /**
183     * The renderer is called
184     * continuously to re-render the scene.
185     *
186     * @see #getRenderMode()
187     * @see #setRenderMode(int)
188     */
189    public final static int RENDERMODE_CONTINUOUSLY = 1;
190
191    /**
192     * Check glError() after every GL call and throw an exception if glError indicates
193     * that an error has occurred. This can be used to help track down which OpenGL ES call
194     * is causing an error.
195     *
196     * @see #getDebugFlags
197     * @see #setDebugFlags
198     */
199    public final static int DEBUG_CHECK_GL_ERROR = 1;
200
201    /**
202     * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".
203     *
204     * @see #getDebugFlags
205     * @see #setDebugFlags
206     */
207    public final static int DEBUG_LOG_GL_CALLS = 2;
208
209    /**
210     * Standard View constructor. In order to render something, you
211     * must call {@link #setRenderer} to register a renderer.
212     */
213    public GLSurfaceView(Context context) {
214        super(context);
215        init();
216    }
217
218    /**
219     * Standard View constructor. In order to render something, you
220     * must call {@link #setRenderer} to register a renderer.
221     */
222    public GLSurfaceView(Context context, AttributeSet attrs) {
223        super(context, attrs);
224        init();
225    }
226
227    @Override
228    protected void finalize() throws Throwable {
229        try {
230            if (mGLThread != null) {
231                // GLThread may still be running if this view was never
232                // attached to a window.
233                mGLThread.requestExitAndWait();
234            }
235        } finally {
236            super.finalize();
237        }
238    }
239
240    private void init() {
241        // Install a SurfaceHolder.Callback so we get notified when the
242        // underlying surface is created and destroyed
243        SurfaceHolder holder = getHolder();
244        holder.addCallback(this);
245        // setFormat is done by SurfaceView in SDK 2.3 and newer. Uncomment
246        // this statement if back-porting to 2.2 or older:
247        // holder.setFormat(PixelFormat.RGB_565);
248        //
249        // setType is not needed for SDK 2.0 or newer. Uncomment this
250        // statement if back-porting this code to older SDKs.
251        // holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
252    }
253
254    /**
255     * Set the glWrapper. If the glWrapper is not null, its
256     * {@link GLWrapper#wrap(GL)} method is called
257     * whenever a surface is created. A GLWrapper can be used to wrap
258     * the GL object that's passed to the renderer. Wrapping a GL
259     * object enables examining and modifying the behavior of the
260     * GL calls made by the renderer.
261     * <p>
262     * Wrapping is typically used for debugging purposes.
263     * <p>
264     * The default value is null.
265     * @param glWrapper the new GLWrapper
266     */
267    public void setGLWrapper(GLWrapper glWrapper) {
268        mGLWrapper = glWrapper;
269    }
270
271    /**
272     * Set the debug flags to a new value. The value is
273     * constructed by OR-together zero or more
274     * of the DEBUG_CHECK_* constants. The debug flags take effect
275     * whenever a surface is created. The default value is zero.
276     * @param debugFlags the new debug flags
277     * @see #DEBUG_CHECK_GL_ERROR
278     * @see #DEBUG_LOG_GL_CALLS
279     */
280    public void setDebugFlags(int debugFlags) {
281        mDebugFlags = debugFlags;
282    }
283
284    /**
285     * Get the current value of the debug flags.
286     * @return the current value of the debug flags.
287     */
288    public int getDebugFlags() {
289        return mDebugFlags;
290    }
291
292    /**
293     * Control whether the EGL context is preserved when the GLSurfaceView is paused and
294     * resumed.
295     * <p>
296     * If set to true, then the EGL context may be preserved when the GLSurfaceView is paused.
297     * Whether the EGL context is actually preserved or not depends upon whether the
298     * Android device that the program is running on can support an arbitrary number of EGL
299     * contexts or not. Devices that can only support a limited number of EGL contexts must
300     * release the  EGL context in order to allow multiple applications to share the GPU.
301     * <p>
302     * If set to false, the EGL context will be released when the GLSurfaceView is paused,
303     * and recreated when the GLSurfaceView is resumed.
304     * <p>
305     *
306     * The default is false.
307     *
308     * @param preserveOnPause preserve the EGL context when paused
309     */
310    public void setPreserveEGLContextOnPause(boolean preserveOnPause) {
311        mPreserveEGLContextOnPause = preserveOnPause;
312    }
313
314    /**
315     * @return true if the EGL context will be preserved when paused
316     */
317    public boolean getPreserveEGLContextOnPause() {
318        return mPreserveEGLContextOnPause;
319    }
320
321    /**
322     * Set the renderer associated with this view. Also starts the thread that
323     * will call the renderer, which in turn causes the rendering to start.
324     * <p>This method should be called once and only once in the life-cycle of
325     * a GLSurfaceView.
326     * <p>The following GLSurfaceView methods can only be called <em>before</em>
327     * setRenderer is called:
328     * <ul>
329     * <li>{@link #setEGLConfigChooser(boolean)}
330     * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
331     * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
332     * </ul>
333     * <p>
334     * The following GLSurfaceView methods can only be called <em>after</em>
335     * setRenderer is called:
336     * <ul>
337     * <li>{@link #getRenderMode()}
338     * <li>{@link #onPause()}
339     * <li>{@link #onResume()}
340     * <li>{@link #queueEvent(Runnable)}
341     * <li>{@link #requestRender()}
342     * <li>{@link #setRenderMode(int)}
343     * </ul>
344     *
345     * @param renderer the renderer to use to perform OpenGL drawing.
346     */
347    public void setRenderer(Renderer renderer) {
348        checkRenderThreadState();
349        if (mEGLConfigChooser == null) {
350            mEGLConfigChooser = new SimpleEGLConfigChooser(true);
351        }
352        if (mEGLContextFactory == null) {
353            mEGLContextFactory = new DefaultContextFactory();
354        }
355        if (mEGLWindowSurfaceFactory == null) {
356            mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
357        }
358        mRenderer = renderer;
359        mGLThread = new GLThread(mThisWeakRef);
360        mGLThread.start();
361    }
362
363    /**
364     * Install a custom EGLContextFactory.
365     * <p>If this method is
366     * called, it must be called before {@link #setRenderer(Renderer)}
367     * is called.
368     * <p>
369     * If this method is not called, then by default
370     * a context will be created with no shared context and
371     * with a null attribute list.
372     */
373    public void setEGLContextFactory(EGLContextFactory factory) {
374        checkRenderThreadState();
375        mEGLContextFactory = factory;
376    }
377
378    /**
379     * Install a custom EGLWindowSurfaceFactory.
380     * <p>If this method is
381     * called, it must be called before {@link #setRenderer(Renderer)}
382     * is called.
383     * <p>
384     * If this method is not called, then by default
385     * a window surface will be created with a null attribute list.
386     */
387    public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
388        checkRenderThreadState();
389        mEGLWindowSurfaceFactory = factory;
390    }
391
392    /**
393     * Install a custom EGLConfigChooser.
394     * <p>If this method is
395     * called, it must be called before {@link #setRenderer(Renderer)}
396     * is called.
397     * <p>
398     * If no setEGLConfigChooser method is called, then by default the
399     * view will choose an EGLConfig that is compatible with the current
400     * android.view.Surface, with a depth buffer depth of
401     * at least 16 bits.
402     * @param configChooser
403     */
404    public void setEGLConfigChooser(EGLConfigChooser configChooser) {
405        checkRenderThreadState();
406        mEGLConfigChooser = configChooser;
407    }
408
409    /**
410     * Install a config chooser which will choose a config
411     * as close to 16-bit RGB as possible, with or without an optional depth
412     * buffer as close to 16-bits as possible.
413     * <p>If this method is
414     * called, it must be called before {@link #setRenderer(Renderer)}
415     * is called.
416     * <p>
417     * If no setEGLConfigChooser method is called, then by default the
418     * view will choose an RGB_888 surface with a depth buffer depth of
419     * at least 16 bits.
420     *
421     * @param needDepth
422     */
423    public void setEGLConfigChooser(boolean needDepth) {
424        setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
425    }
426
427    /**
428     * Install a config chooser which will choose a config
429     * with at least the specified depthSize and stencilSize,
430     * and exactly the specified redSize, greenSize, blueSize and alphaSize.
431     * <p>If this method is
432     * called, it must be called before {@link #setRenderer(Renderer)}
433     * is called.
434     * <p>
435     * If no setEGLConfigChooser method is called, then by default the
436     * view will choose an RGB_888 surface with a depth buffer depth of
437     * at least 16 bits.
438     *
439     */
440    public void setEGLConfigChooser(int redSize, int greenSize, int blueSize,
441            int alphaSize, int depthSize, int stencilSize) {
442        setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
443                blueSize, alphaSize, depthSize, stencilSize));
444    }
445
446    /**
447     * Inform the default EGLContextFactory and default EGLConfigChooser
448     * which EGLContext client version to pick.
449     * <p>Use this method to create an OpenGL ES 2.0-compatible context.
450     * Example:
451     * <pre class="prettyprint">
452     *     public MyView(Context context) {
453     *         super(context);
454     *         setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
455     *         setRenderer(new MyRenderer());
456     *     }
457     * </pre>
458     * <p>Note: Activities which require OpenGL ES 2.0 should indicate this by
459     * setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the activity's
460     * AndroidManifest.xml file.
461     * <p>If this method is called, it must be called before {@link #setRenderer(Renderer)}
462     * is called.
463     * <p>This method only affects the behavior of the default EGLContexFactory and the
464     * default EGLConfigChooser. If
465     * {@link #setEGLContextFactory(EGLContextFactory)} has been called, then the supplied
466     * EGLContextFactory is responsible for creating an OpenGL ES 2.0-compatible context.
467     * If
468     * {@link #setEGLConfigChooser(EGLConfigChooser)} has been called, then the supplied
469     * EGLConfigChooser is responsible for choosing an OpenGL ES 2.0-compatible config.
470     * @param version The EGLContext client version to choose. Use 2 for OpenGL ES 2.0
471     */
472    public void setEGLContextClientVersion(int version) {
473        checkRenderThreadState();
474        mEGLContextClientVersion = version;
475    }
476
477    /**
478     * Set the rendering mode. When renderMode is
479     * RENDERMODE_CONTINUOUSLY, the renderer is called
480     * repeatedly to re-render the scene. When renderMode
481     * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface
482     * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY.
483     * <p>
484     * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance
485     * by allowing the GPU and CPU to idle when the view does not need to be updated.
486     * <p>
487     * This method can only be called after {@link #setRenderer(Renderer)}
488     *
489     * @param renderMode one of the RENDERMODE_X constants
490     * @see #RENDERMODE_CONTINUOUSLY
491     * @see #RENDERMODE_WHEN_DIRTY
492     */
493    public void setRenderMode(int renderMode) {
494        mGLThread.setRenderMode(renderMode);
495    }
496
497    /**
498     * Get the current rendering mode. May be called
499     * from any thread. Must not be called before a renderer has been set.
500     * @return the current rendering mode.
501     * @see #RENDERMODE_CONTINUOUSLY
502     * @see #RENDERMODE_WHEN_DIRTY
503     */
504    public int getRenderMode() {
505        return mGLThread.getRenderMode();
506    }
507
508    /**
509     * Request that the renderer render a frame.
510     * This method is typically used when the render mode has been set to
511     * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand.
512     * May be called
513     * from any thread. Must not be called before a renderer has been set.
514     */
515    public void requestRender() {
516        mGLThread.requestRender();
517    }
518
519    /**
520     * This method is part of the SurfaceHolder.Callback interface, and is
521     * not normally called or subclassed by clients of GLSurfaceView.
522     */
523    public void surfaceCreated(SurfaceHolder holder) {
524        mGLThread.surfaceCreated();
525    }
526
527    /**
528     * This method is part of the SurfaceHolder.Callback interface, and is
529     * not normally called or subclassed by clients of GLSurfaceView.
530     */
531    public void surfaceDestroyed(SurfaceHolder holder) {
532        // Surface will be destroyed when we return
533        mGLThread.surfaceDestroyed();
534    }
535
536    /**
537     * This method is part of the SurfaceHolder.Callback interface, and is
538     * not normally called or subclassed by clients of GLSurfaceView.
539     */
540    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
541        mGLThread.onWindowResize(w, h);
542    }
543
544    /**
545     * This method is part of the SurfaceHolder.Callback interface, and is
546     * not normally called or subclassed by clients of GLSurfaceView.
547     */
548    @Override
549    public void surfaceRedrawNeeded(SurfaceHolder holder) {
550        mGLThread.requestRenderAndWait();
551    }
552
553
554    /**
555     * Inform the view that the activity is paused. The owner of this view must
556     * call this method when the activity is paused. Calling this method will
557     * pause the rendering thread.
558     * Must not be called before a renderer has been set.
559     */
560    public void onPause() {
561        mGLThread.onPause();
562    }
563
564    /**
565     * Inform the view that the activity is resumed. The owner of this view must
566     * call this method when the activity is resumed. Calling this method will
567     * recreate the OpenGL display and resume the rendering
568     * thread.
569     * Must not be called before a renderer has been set.
570     */
571    public void onResume() {
572        mGLThread.onResume();
573    }
574
575    /**
576     * Queue a runnable to be run on the GL rendering thread. This can be used
577     * to communicate with the Renderer on the rendering thread.
578     * Must not be called before a renderer has been set.
579     * @param r the runnable to be run on the GL rendering thread.
580     */
581    public void queueEvent(Runnable r) {
582        mGLThread.queueEvent(r);
583    }
584
585    /**
586     * This method is used as part of the View class and is not normally
587     * called or subclassed by clients of GLSurfaceView.
588     */
589    @Override
590    protected void onAttachedToWindow() {
591        super.onAttachedToWindow();
592        if (LOG_ATTACH_DETACH) {
593            Log.d(TAG, "onAttachedToWindow reattach =" + mDetached);
594        }
595        if (mDetached && (mRenderer != null)) {
596            int renderMode = RENDERMODE_CONTINUOUSLY;
597            if (mGLThread != null) {
598                renderMode = mGLThread.getRenderMode();
599            }
600            mGLThread = new GLThread(mThisWeakRef);
601            if (renderMode != RENDERMODE_CONTINUOUSLY) {
602                mGLThread.setRenderMode(renderMode);
603            }
604            mGLThread.start();
605        }
606        mDetached = false;
607    }
608
609    @Override
610    protected void onDetachedFromWindow() {
611        if (LOG_ATTACH_DETACH) {
612            Log.d(TAG, "onDetachedFromWindow");
613        }
614        if (mGLThread != null) {
615            mGLThread.requestExitAndWait();
616        }
617        mDetached = true;
618        super.onDetachedFromWindow();
619    }
620
621    // ----------------------------------------------------------------------
622
623    /**
624     * An interface used to wrap a GL interface.
625     * <p>Typically
626     * used for implementing debugging and tracing on top of the default
627     * GL interface. You would typically use this by creating your own class
628     * that implemented all the GL methods by delegating to another GL instance.
629     * Then you could add your own behavior before or after calling the
630     * delegate. All the GLWrapper would do was instantiate and return the
631     * wrapper GL instance:
632     * <pre class="prettyprint">
633     * class MyGLWrapper implements GLWrapper {
634     *     GL wrap(GL gl) {
635     *         return new MyGLImplementation(gl);
636     *     }
637     *     static class MyGLImplementation implements GL,GL10,GL11,... {
638     *         ...
639     *     }
640     * }
641     * </pre>
642     * @see #setGLWrapper(GLWrapper)
643     */
644    public interface GLWrapper {
645        /**
646         * Wraps a gl interface in another gl interface.
647         * @param gl a GL interface that is to be wrapped.
648         * @return either the input argument or another GL object that wraps the input argument.
649         */
650        GL wrap(GL gl);
651    }
652
653    /**
654     * A generic renderer interface.
655     * <p>
656     * The renderer is responsible for making OpenGL calls to render a frame.
657     * <p>
658     * GLSurfaceView clients typically create their own classes that implement
659     * this interface, and then call {@link GLSurfaceView#setRenderer} to
660     * register the renderer with the GLSurfaceView.
661     * <p>
662     *
663     * <div class="special reference">
664     * <h3>Developer Guides</h3>
665     * <p>For more information about how to use OpenGL, read the
666     * <a href="{@docRoot}guide/topics/graphics/opengl.html">OpenGL</a> developer guide.</p>
667     * </div>
668     *
669     * <h3>Threading</h3>
670     * The renderer will be called on a separate thread, so that rendering
671     * performance is decoupled from the UI thread. Clients typically need to
672     * communicate with the renderer from the UI thread, because that's where
673     * input events are received. Clients can communicate using any of the
674     * standard Java techniques for cross-thread communication, or they can
675     * use the {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
676     * <p>
677     * <h3>EGL Context Lost</h3>
678     * There are situations where the EGL rendering context will be lost. This
679     * typically happens when device wakes up after going to sleep. When
680     * the EGL context is lost, all OpenGL resources (such as textures) that are
681     * associated with that context will be automatically deleted. In order to
682     * keep rendering correctly, a renderer must recreate any lost resources
683     * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} method
684     * is a convenient place to do this.
685     *
686     *
687     * @see #setRenderer(Renderer)
688     */
689    public interface Renderer {
690        /**
691         * Called when the surface is created or recreated.
692         * <p>
693         * Called when the rendering thread
694         * starts and whenever the EGL context is lost. The EGL context will typically
695         * be lost when the Android device awakes after going to sleep.
696         * <p>
697         * Since this method is called at the beginning of rendering, as well as
698         * every time the EGL context is lost, this method is a convenient place to put
699         * code to create resources that need to be created when the rendering
700         * starts, and that need to be recreated when the EGL context is lost.
701         * Textures are an example of a resource that you might want to create
702         * here.
703         * <p>
704         * Note that when the EGL context is lost, all OpenGL resources associated
705         * with that context will be automatically deleted. You do not need to call
706         * the corresponding "glDelete" methods such as glDeleteTextures to
707         * manually delete these lost resources.
708         * <p>
709         * @param gl the GL interface. Use <code>instanceof</code> to
710         * test if the interface supports GL11 or higher interfaces.
711         * @param config the EGLConfig of the created surface. Can be used
712         * to create matching pbuffers.
713         */
714        void onSurfaceCreated(GL10 gl, EGLConfig config);
715
716        /**
717         * Called when the surface changed size.
718         * <p>
719         * Called after the surface is created and whenever
720         * the OpenGL ES surface size changes.
721         * <p>
722         * Typically you will set your viewport here. If your camera
723         * is fixed then you could also set your projection matrix here:
724         * <pre class="prettyprint">
725         * void onSurfaceChanged(GL10 gl, int width, int height) {
726         *     gl.glViewport(0, 0, width, height);
727         *     // for a fixed camera, set the projection too
728         *     float ratio = (float) width / height;
729         *     gl.glMatrixMode(GL10.GL_PROJECTION);
730         *     gl.glLoadIdentity();
731         *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
732         * }
733         * </pre>
734         * @param gl the GL interface. Use <code>instanceof</code> to
735         * test if the interface supports GL11 or higher interfaces.
736         * @param width
737         * @param height
738         */
739        void onSurfaceChanged(GL10 gl, int width, int height);
740
741        /**
742         * Called to draw the current frame.
743         * <p>
744         * This method is responsible for drawing the current frame.
745         * <p>
746         * The implementation of this method typically looks like this:
747         * <pre class="prettyprint">
748         * void onDrawFrame(GL10 gl) {
749         *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
750         *     //... other gl calls to render the scene ...
751         * }
752         * </pre>
753         * @param gl the GL interface. Use <code>instanceof</code> to
754         * test if the interface supports GL11 or higher interfaces.
755         */
756        void onDrawFrame(GL10 gl);
757    }
758
759    /**
760     * An interface for customizing the eglCreateContext and eglDestroyContext calls.
761     * <p>
762     * This interface must be implemented by clients wishing to call
763     * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
764     */
765    public interface EGLContextFactory {
766        EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
767        void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
768    }
769
770    private class DefaultContextFactory implements EGLContextFactory {
771        private int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
772
773        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
774            int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion,
775                    EGL10.EGL_NONE };
776
777            return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
778                    mEGLContextClientVersion != 0 ? attrib_list : null);
779        }
780
781        public void destroyContext(EGL10 egl, EGLDisplay display,
782                EGLContext context) {
783            if (!egl.eglDestroyContext(display, context)) {
784                Log.e("DefaultContextFactory", "display:" + display + " context: " + context);
785                if (LOG_THREADS) {
786                    Log.i("DefaultContextFactory", "tid=" + Thread.currentThread().getId());
787                }
788                EglHelper.throwEglException("eglDestroyContex", egl.eglGetError());
789            }
790        }
791    }
792
793    /**
794     * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
795     * <p>
796     * This interface must be implemented by clients wishing to call
797     * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
798     */
799    public interface EGLWindowSurfaceFactory {
800        /**
801         *  @return null if the surface cannot be constructed.
802         */
803        EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
804                Object nativeWindow);
805        void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
806    }
807
808    private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
809
810        public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
811                EGLConfig config, Object nativeWindow) {
812            EGLSurface result = null;
813            try {
814                result = egl.eglCreateWindowSurface(display, config, nativeWindow, null);
815            } catch (IllegalArgumentException e) {
816                // This exception indicates that the surface flinger surface
817                // is not valid. This can happen if the surface flinger surface has
818                // been torn down, but the application has not yet been
819                // notified via SurfaceHolder.Callback.surfaceDestroyed.
820                // In theory the application should be notified first,
821                // but in practice sometimes it is not. See b/4588890
822                Log.e(TAG, "eglCreateWindowSurface", e);
823            }
824            return result;
825        }
826
827        public void destroySurface(EGL10 egl, EGLDisplay display,
828                EGLSurface surface) {
829            egl.eglDestroySurface(display, surface);
830        }
831    }
832
833    /**
834     * An interface for choosing an EGLConfig configuration from a list of
835     * potential configurations.
836     * <p>
837     * This interface must be implemented by clients wishing to call
838     * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
839     */
840    public interface EGLConfigChooser {
841        /**
842         * Choose a configuration from the list. Implementors typically
843         * implement this method by calling
844         * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the
845         * EGL specification available from The Khronos Group to learn how to call eglChooseConfig.
846         * @param egl the EGL10 for the current display.
847         * @param display the current display.
848         * @return the chosen configuration.
849         */
850        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
851    }
852
853    private abstract class BaseConfigChooser
854            implements EGLConfigChooser {
855        public BaseConfigChooser(int[] configSpec) {
856            mConfigSpec = filterConfigSpec(configSpec);
857        }
858
859        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
860            int[] num_config = new int[1];
861            if (!egl.eglChooseConfig(display, mConfigSpec, null, 0,
862                    num_config)) {
863                throw new IllegalArgumentException("eglChooseConfig failed");
864            }
865
866            int numConfigs = num_config[0];
867
868            if (numConfigs <= 0) {
869                throw new IllegalArgumentException(
870                        "No configs match configSpec");
871            }
872
873            EGLConfig[] configs = new EGLConfig[numConfigs];
874            if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
875                    num_config)) {
876                throw new IllegalArgumentException("eglChooseConfig#2 failed");
877            }
878            EGLConfig config = chooseConfig(egl, display, configs);
879            if (config == null) {
880                throw new IllegalArgumentException("No config chosen");
881            }
882            return config;
883        }
884
885        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
886                EGLConfig[] configs);
887
888        protected int[] mConfigSpec;
889
890        private int[] filterConfigSpec(int[] configSpec) {
891            if (mEGLContextClientVersion != 2 && mEGLContextClientVersion != 3) {
892                return configSpec;
893            }
894            /* We know none of the subclasses define EGL_RENDERABLE_TYPE.
895             * And we know the configSpec is well formed.
896             */
897            int len = configSpec.length;
898            int[] newConfigSpec = new int[len + 2];
899            System.arraycopy(configSpec, 0, newConfigSpec, 0, len-1);
900            newConfigSpec[len-1] = EGL10.EGL_RENDERABLE_TYPE;
901            if (mEGLContextClientVersion == 2) {
902                newConfigSpec[len] = EGL14.EGL_OPENGL_ES2_BIT;  /* EGL_OPENGL_ES2_BIT */
903            } else {
904                newConfigSpec[len] = EGLExt.EGL_OPENGL_ES3_BIT_KHR; /* EGL_OPENGL_ES3_BIT_KHR */
905            }
906            newConfigSpec[len+1] = EGL10.EGL_NONE;
907            return newConfigSpec;
908        }
909    }
910
911    /**
912     * Choose a configuration with exactly the specified r,g,b,a sizes,
913     * and at least the specified depth and stencil sizes.
914     */
915    private class ComponentSizeChooser extends BaseConfigChooser {
916        public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
917                int alphaSize, int depthSize, int stencilSize) {
918            super(new int[] {
919                    EGL10.EGL_RED_SIZE, redSize,
920                    EGL10.EGL_GREEN_SIZE, greenSize,
921                    EGL10.EGL_BLUE_SIZE, blueSize,
922                    EGL10.EGL_ALPHA_SIZE, alphaSize,
923                    EGL10.EGL_DEPTH_SIZE, depthSize,
924                    EGL10.EGL_STENCIL_SIZE, stencilSize,
925                    EGL10.EGL_NONE});
926            mValue = new int[1];
927            mRedSize = redSize;
928            mGreenSize = greenSize;
929            mBlueSize = blueSize;
930            mAlphaSize = alphaSize;
931            mDepthSize = depthSize;
932            mStencilSize = stencilSize;
933       }
934
935        @Override
936        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
937                EGLConfig[] configs) {
938            for (EGLConfig config : configs) {
939                int d = findConfigAttrib(egl, display, config,
940                        EGL10.EGL_DEPTH_SIZE, 0);
941                int s = findConfigAttrib(egl, display, config,
942                        EGL10.EGL_STENCIL_SIZE, 0);
943                if ((d >= mDepthSize) && (s >= mStencilSize)) {
944                    int r = findConfigAttrib(egl, display, config,
945                            EGL10.EGL_RED_SIZE, 0);
946                    int g = findConfigAttrib(egl, display, config,
947                             EGL10.EGL_GREEN_SIZE, 0);
948                    int b = findConfigAttrib(egl, display, config,
949                              EGL10.EGL_BLUE_SIZE, 0);
950                    int a = findConfigAttrib(egl, display, config,
951                            EGL10.EGL_ALPHA_SIZE, 0);
952                    if ((r == mRedSize) && (g == mGreenSize)
953                            && (b == mBlueSize) && (a == mAlphaSize)) {
954                        return config;
955                    }
956                }
957            }
958            return null;
959        }
960
961        private int findConfigAttrib(EGL10 egl, EGLDisplay display,
962                EGLConfig config, int attribute, int defaultValue) {
963
964            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
965                return mValue[0];
966            }
967            return defaultValue;
968        }
969
970        private int[] mValue;
971        // Subclasses can adjust these values:
972        protected int mRedSize;
973        protected int mGreenSize;
974        protected int mBlueSize;
975        protected int mAlphaSize;
976        protected int mDepthSize;
977        protected int mStencilSize;
978        }
979
980    /**
981     * This class will choose a RGB_888 surface with
982     * or without a depth buffer.
983     *
984     */
985    private class SimpleEGLConfigChooser extends ComponentSizeChooser {
986        public SimpleEGLConfigChooser(boolean withDepthBuffer) {
987            super(8, 8, 8, 0, withDepthBuffer ? 16 : 0, 0);
988        }
989    }
990
991    /**
992     * An EGL helper class.
993     */
994
995    private static class EglHelper {
996        public EglHelper(WeakReference<GLSurfaceView> glSurfaceViewWeakRef) {
997            mGLSurfaceViewWeakRef = glSurfaceViewWeakRef;
998        }
999
1000        /**
1001         * Initialize EGL for a given configuration spec.
1002         * @param configSpec
1003         */
1004        public void start() {
1005            if (LOG_EGL) {
1006                Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
1007            }
1008            /*
1009             * Get an EGL instance
1010             */
1011            mEgl = (EGL10) EGLContext.getEGL();
1012
1013            /*
1014             * Get to the default display.
1015             */
1016            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
1017
1018            if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
1019                throw new RuntimeException("eglGetDisplay failed");
1020            }
1021
1022            /*
1023             * We can now initialize EGL for that display
1024             */
1025            int[] version = new int[2];
1026            if(!mEgl.eglInitialize(mEglDisplay, version)) {
1027                throw new RuntimeException("eglInitialize failed");
1028            }
1029            GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1030            if (view == null) {
1031                mEglConfig = null;
1032                mEglContext = null;
1033            } else {
1034                mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
1035
1036                /*
1037                * Create an EGL context. We want to do this as rarely as we can, because an
1038                * EGL context is a somewhat heavy object.
1039                */
1040                mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
1041            }
1042            if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
1043                mEglContext = null;
1044                throwEglException("createContext");
1045            }
1046            if (LOG_EGL) {
1047                Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
1048            }
1049
1050            mEglSurface = null;
1051        }
1052
1053        /**
1054         * Create an egl surface for the current SurfaceHolder surface. If a surface
1055         * already exists, destroy it before creating the new surface.
1056         *
1057         * @return true if the surface was created successfully.
1058         */
1059        public boolean createSurface() {
1060            if (LOG_EGL) {
1061                Log.w("EglHelper", "createSurface()  tid=" + Thread.currentThread().getId());
1062            }
1063            /*
1064             * Check preconditions.
1065             */
1066            if (mEgl == null) {
1067                throw new RuntimeException("egl not initialized");
1068            }
1069            if (mEglDisplay == null) {
1070                throw new RuntimeException("eglDisplay not initialized");
1071            }
1072            if (mEglConfig == null) {
1073                throw new RuntimeException("mEglConfig not initialized");
1074            }
1075
1076            /*
1077             *  The window size has changed, so we need to create a new
1078             *  surface.
1079             */
1080            destroySurfaceImp();
1081
1082            /*
1083             * Create an EGL surface we can render into.
1084             */
1085            GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1086            if (view != null) {
1087                mEglSurface = view.mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
1088                        mEglDisplay, mEglConfig, view.getHolder());
1089            } else {
1090                mEglSurface = null;
1091            }
1092
1093            if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
1094                int error = mEgl.eglGetError();
1095                if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
1096                    Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
1097                }
1098                return false;
1099            }
1100
1101            /*
1102             * Before we can issue GL commands, we need to make sure
1103             * the context is current and bound to a surface.
1104             */
1105            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
1106                /*
1107                 * Could not make the context current, probably because the underlying
1108                 * SurfaceView surface has been destroyed.
1109                 */
1110                logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError());
1111                return false;
1112            }
1113
1114            return true;
1115        }
1116
1117        /**
1118         * Create a GL object for the current EGL context.
1119         * @return
1120         */
1121        GL createGL() {
1122
1123            GL gl = mEglContext.getGL();
1124            GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1125            if (view != null) {
1126                if (view.mGLWrapper != null) {
1127                    gl = view.mGLWrapper.wrap(gl);
1128                }
1129
1130                if ((view.mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
1131                    int configFlags = 0;
1132                    Writer log = null;
1133                    if ((view.mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
1134                        configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
1135                    }
1136                    if ((view.mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
1137                        log = new LogWriter();
1138                    }
1139                    gl = GLDebugHelper.wrap(gl, configFlags, log);
1140                }
1141            }
1142            return gl;
1143        }
1144
1145        /**
1146         * Display the current render surface.
1147         * @return the EGL error code from eglSwapBuffers.
1148         */
1149        public int swap() {
1150            if (! mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
1151                return mEgl.eglGetError();
1152            }
1153            return EGL10.EGL_SUCCESS;
1154        }
1155
1156        public void destroySurface() {
1157            if (LOG_EGL) {
1158                Log.w("EglHelper", "destroySurface()  tid=" + Thread.currentThread().getId());
1159            }
1160            destroySurfaceImp();
1161        }
1162
1163        private void destroySurfaceImp() {
1164            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
1165                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
1166                        EGL10.EGL_NO_SURFACE,
1167                        EGL10.EGL_NO_CONTEXT);
1168                GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1169                if (view != null) {
1170                    view.mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
1171                }
1172                mEglSurface = null;
1173            }
1174        }
1175
1176        public void finish() {
1177            if (LOG_EGL) {
1178                Log.w("EglHelper", "finish() tid=" + Thread.currentThread().getId());
1179            }
1180            if (mEglContext != null) {
1181                GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1182                if (view != null) {
1183                    view.mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
1184                }
1185                mEglContext = null;
1186            }
1187            if (mEglDisplay != null) {
1188                mEgl.eglTerminate(mEglDisplay);
1189                mEglDisplay = null;
1190            }
1191        }
1192
1193        private void throwEglException(String function) {
1194            throwEglException(function, mEgl.eglGetError());
1195        }
1196
1197        public static void throwEglException(String function, int error) {
1198            String message = formatEglError(function, error);
1199            if (LOG_THREADS) {
1200                Log.e("EglHelper", "throwEglException tid=" + Thread.currentThread().getId() + " "
1201                        + message);
1202            }
1203            throw new RuntimeException(message);
1204        }
1205
1206        public static void logEglErrorAsWarning(String tag, String function, int error) {
1207            Log.w(tag, formatEglError(function, error));
1208        }
1209
1210        public static String formatEglError(String function, int error) {
1211            return function + " failed: " + EGLLogWrapper.getErrorString(error);
1212        }
1213
1214        private WeakReference<GLSurfaceView> mGLSurfaceViewWeakRef;
1215        EGL10 mEgl;
1216        EGLDisplay mEglDisplay;
1217        EGLSurface mEglSurface;
1218        EGLConfig mEglConfig;
1219        EGLContext mEglContext;
1220
1221    }
1222
1223    /**
1224     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
1225     * to a Renderer instance to do the actual drawing. Can be configured to
1226     * render continuously or on request.
1227     *
1228     * All potentially blocking synchronization is done through the
1229     * sGLThreadManager object. This avoids multiple-lock ordering issues.
1230     *
1231     */
1232    static class GLThread extends Thread {
1233        GLThread(WeakReference<GLSurfaceView> glSurfaceViewWeakRef) {
1234            super();
1235            mWidth = 0;
1236            mHeight = 0;
1237            mRequestRender = true;
1238            mRenderMode = RENDERMODE_CONTINUOUSLY;
1239            mWantRenderNotification = false;
1240            mGLSurfaceViewWeakRef = glSurfaceViewWeakRef;
1241        }
1242
1243        @Override
1244        public void run() {
1245            setName("GLThread " + getId());
1246            if (LOG_THREADS) {
1247                Log.i("GLThread", "starting tid=" + getId());
1248            }
1249
1250            try {
1251                guardedRun();
1252            } catch (InterruptedException e) {
1253                // fall thru and exit normally
1254            } finally {
1255                sGLThreadManager.threadExiting(this);
1256            }
1257        }
1258
1259        /*
1260         * This private method should only be called inside a
1261         * synchronized(sGLThreadManager) block.
1262         */
1263        private void stopEglSurfaceLocked() {
1264            if (mHaveEglSurface) {
1265                mHaveEglSurface = false;
1266                mEglHelper.destroySurface();
1267            }
1268        }
1269
1270        /*
1271         * This private method should only be called inside a
1272         * synchronized(sGLThreadManager) block.
1273         */
1274        private void stopEglContextLocked() {
1275            if (mHaveEglContext) {
1276                mEglHelper.finish();
1277                mHaveEglContext = false;
1278                sGLThreadManager.releaseEglContextLocked(this);
1279            }
1280        }
1281        private void guardedRun() throws InterruptedException {
1282            mEglHelper = new EglHelper(mGLSurfaceViewWeakRef);
1283            mHaveEglContext = false;
1284            mHaveEglSurface = false;
1285            mWantRenderNotification = false;
1286
1287            try {
1288                GL10 gl = null;
1289                boolean createEglContext = false;
1290                boolean createEglSurface = false;
1291                boolean createGlInterface = false;
1292                boolean lostEglContext = false;
1293                boolean sizeChanged = false;
1294                boolean doRenderNotification = false;
1295                boolean askedToReleaseEglContext = false;
1296                int w = 0;
1297                int h = 0;
1298                Runnable event = null;
1299
1300                while (true) {
1301                    synchronized (sGLThreadManager) {
1302                        while (true) {
1303                            if (mShouldExit) {
1304                                return;
1305                            }
1306
1307                            if (! mEventQueue.isEmpty()) {
1308                                event = mEventQueue.remove(0);
1309                                break;
1310                            }
1311
1312                            // Update the pause state.
1313                            boolean pausing = false;
1314                            if (mPaused != mRequestPaused) {
1315                                pausing = mRequestPaused;
1316                                mPaused = mRequestPaused;
1317                                sGLThreadManager.notifyAll();
1318                                if (LOG_PAUSE_RESUME) {
1319                                    Log.i("GLThread", "mPaused is now " + mPaused + " tid=" + getId());
1320                                }
1321                            }
1322
1323                            // Do we need to give up the EGL context?
1324                            if (mShouldReleaseEglContext) {
1325                                if (LOG_SURFACE) {
1326                                    Log.i("GLThread", "releasing EGL context because asked to tid=" + getId());
1327                                }
1328                                stopEglSurfaceLocked();
1329                                stopEglContextLocked();
1330                                mShouldReleaseEglContext = false;
1331                                askedToReleaseEglContext = true;
1332                            }
1333
1334                            // Have we lost the EGL context?
1335                            if (lostEglContext) {
1336                                stopEglSurfaceLocked();
1337                                stopEglContextLocked();
1338                                lostEglContext = false;
1339                            }
1340
1341                            // When pausing, release the EGL surface:
1342                            if (pausing && mHaveEglSurface) {
1343                                if (LOG_SURFACE) {
1344                                    Log.i("GLThread", "releasing EGL surface because paused tid=" + getId());
1345                                }
1346                                stopEglSurfaceLocked();
1347                            }
1348
1349                            // When pausing, optionally release the EGL Context:
1350                            if (pausing && mHaveEglContext) {
1351                                GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1352                                boolean preserveEglContextOnPause = view == null ?
1353                                        false : view.mPreserveEGLContextOnPause;
1354                                if (!preserveEglContextOnPause || sGLThreadManager.shouldReleaseEGLContextWhenPausing()) {
1355                                    stopEglContextLocked();
1356                                    if (LOG_SURFACE) {
1357                                        Log.i("GLThread", "releasing EGL context because paused tid=" + getId());
1358                                    }
1359                                }
1360                            }
1361
1362                            // When pausing, optionally terminate EGL:
1363                            if (pausing) {
1364                                if (sGLThreadManager.shouldTerminateEGLWhenPausing()) {
1365                                    mEglHelper.finish();
1366                                    if (LOG_SURFACE) {
1367                                        Log.i("GLThread", "terminating EGL because paused tid=" + getId());
1368                                    }
1369                                }
1370                            }
1371
1372                            // Have we lost the SurfaceView surface?
1373                            if ((! mHasSurface) && (! mWaitingForSurface)) {
1374                                if (LOG_SURFACE) {
1375                                    Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId());
1376                                }
1377                                if (mHaveEglSurface) {
1378                                    stopEglSurfaceLocked();
1379                                }
1380                                mWaitingForSurface = true;
1381                                mSurfaceIsBad = false;
1382                                sGLThreadManager.notifyAll();
1383                            }
1384
1385                            // Have we acquired the surface view surface?
1386                            if (mHasSurface && mWaitingForSurface) {
1387                                if (LOG_SURFACE) {
1388                                    Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId());
1389                                }
1390                                mWaitingForSurface = false;
1391                                sGLThreadManager.notifyAll();
1392                            }
1393
1394                            if (doRenderNotification) {
1395                                if (LOG_SURFACE) {
1396                                    Log.i("GLThread", "sending render notification tid=" + getId());
1397                                }
1398                                mWantRenderNotification = false;
1399                                doRenderNotification = false;
1400                                mRenderComplete = true;
1401                                sGLThreadManager.notifyAll();
1402                            }
1403
1404                            // Ready to draw?
1405                            if (readyToDraw()) {
1406
1407                                // If we don't have an EGL context, try to acquire one.
1408                                if (! mHaveEglContext) {
1409                                    if (askedToReleaseEglContext) {
1410                                        askedToReleaseEglContext = false;
1411                                    } else if (sGLThreadManager.tryAcquireEglContextLocked(this)) {
1412                                        try {
1413                                            mEglHelper.start();
1414                                        } catch (RuntimeException t) {
1415                                            sGLThreadManager.releaseEglContextLocked(this);
1416                                            throw t;
1417                                        }
1418                                        mHaveEglContext = true;
1419                                        createEglContext = true;
1420
1421                                        sGLThreadManager.notifyAll();
1422                                    }
1423                                }
1424
1425                                if (mHaveEglContext && !mHaveEglSurface) {
1426                                    mHaveEglSurface = true;
1427                                    createEglSurface = true;
1428                                    createGlInterface = true;
1429                                    sizeChanged = true;
1430                                }
1431
1432                                if (mHaveEglSurface) {
1433                                    if (mSizeChanged) {
1434                                        sizeChanged = true;
1435                                        w = mWidth;
1436                                        h = mHeight;
1437                                        mWantRenderNotification = true;
1438                                        if (LOG_SURFACE) {
1439                                            Log.i("GLThread",
1440                                                    "noticing that we want render notification tid="
1441                                                    + getId());
1442                                        }
1443
1444                                        // Destroy and recreate the EGL surface.
1445                                        createEglSurface = true;
1446
1447                                        mSizeChanged = false;
1448                                    }
1449                                    mRequestRender = false;
1450                                    sGLThreadManager.notifyAll();
1451                                    break;
1452                                }
1453                            }
1454
1455                            // By design, this is the only place in a GLThread thread where we wait().
1456                            if (LOG_THREADS) {
1457                                Log.i("GLThread", "waiting tid=" + getId()
1458                                    + " mHaveEglContext: " + mHaveEglContext
1459                                    + " mHaveEglSurface: " + mHaveEglSurface
1460                                    + " mFinishedCreatingEglSurface: " + mFinishedCreatingEglSurface
1461                                    + " mPaused: " + mPaused
1462                                    + " mHasSurface: " + mHasSurface
1463                                    + " mSurfaceIsBad: " + mSurfaceIsBad
1464                                    + " mWaitingForSurface: " + mWaitingForSurface
1465                                    + " mWidth: " + mWidth
1466                                    + " mHeight: " + mHeight
1467                                    + " mRequestRender: " + mRequestRender
1468                                    + " mRenderMode: " + mRenderMode);
1469                            }
1470                            sGLThreadManager.wait();
1471                        }
1472                    } // end of synchronized(sGLThreadManager)
1473
1474                    if (event != null) {
1475                        event.run();
1476                        event = null;
1477                        continue;
1478                    }
1479
1480                    if (createEglSurface) {
1481                        if (LOG_SURFACE) {
1482                            Log.w("GLThread", "egl createSurface");
1483                        }
1484                        if (mEglHelper.createSurface()) {
1485                            synchronized(sGLThreadManager) {
1486                                mFinishedCreatingEglSurface = true;
1487                                sGLThreadManager.notifyAll();
1488                            }
1489                        } else {
1490                            synchronized(sGLThreadManager) {
1491                                mFinishedCreatingEglSurface = true;
1492                                mSurfaceIsBad = true;
1493                                sGLThreadManager.notifyAll();
1494                            }
1495                            continue;
1496                        }
1497                        createEglSurface = false;
1498                    }
1499
1500                    if (createGlInterface) {
1501                        gl = (GL10) mEglHelper.createGL();
1502
1503                        sGLThreadManager.checkGLDriver(gl);
1504                        createGlInterface = false;
1505                    }
1506
1507                    if (createEglContext) {
1508                        if (LOG_RENDERER) {
1509                            Log.w("GLThread", "onSurfaceCreated");
1510                        }
1511                        GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1512                        if (view != null) {
1513                            try {
1514                                Trace.traceBegin(Trace.TRACE_TAG_VIEW, "onSurfaceCreated");
1515                                view.mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1516                            } finally {
1517                                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1518                            }
1519                        }
1520                        createEglContext = false;
1521                    }
1522
1523                    if (sizeChanged) {
1524                        if (LOG_RENDERER) {
1525                            Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")");
1526                        }
1527                        GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1528                        if (view != null) {
1529                            try {
1530                                Trace.traceBegin(Trace.TRACE_TAG_VIEW, "onSurfaceChanged");
1531                                view.mRenderer.onSurfaceChanged(gl, w, h);
1532                            } finally {
1533                                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1534                            }
1535                        }
1536                        sizeChanged = false;
1537                    }
1538
1539                    if (LOG_RENDERER_DRAW_FRAME) {
1540                        Log.w("GLThread", "onDrawFrame tid=" + getId());
1541                    }
1542                    {
1543                        GLSurfaceView view = mGLSurfaceViewWeakRef.get();
1544                        if (view != null) {
1545                            try {
1546                                Trace.traceBegin(Trace.TRACE_TAG_VIEW, "onDrawFrame");
1547                                view.mRenderer.onDrawFrame(gl);
1548                            } finally {
1549                                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
1550                            }
1551                        }
1552                    }
1553                    int swapError = mEglHelper.swap();
1554                    switch (swapError) {
1555                        case EGL10.EGL_SUCCESS:
1556                            break;
1557                        case EGL11.EGL_CONTEXT_LOST:
1558                            if (LOG_SURFACE) {
1559                                Log.i("GLThread", "egl context lost tid=" + getId());
1560                            }
1561                            lostEglContext = true;
1562                            break;
1563                        default:
1564                            // Other errors typically mean that the current surface is bad,
1565                            // probably because the SurfaceView surface has been destroyed,
1566                            // but we haven't been notified yet.
1567                            // Log the error to help developers understand why rendering stopped.
1568                            EglHelper.logEglErrorAsWarning("GLThread", "eglSwapBuffers", swapError);
1569
1570                            synchronized(sGLThreadManager) {
1571                                mSurfaceIsBad = true;
1572                                sGLThreadManager.notifyAll();
1573                            }
1574                            break;
1575                    }
1576
1577                    if (mWantRenderNotification) {
1578                        doRenderNotification = true;
1579                    }
1580                }
1581
1582            } finally {
1583                /*
1584                 * clean-up everything...
1585                 */
1586                synchronized (sGLThreadManager) {
1587                    stopEglSurfaceLocked();
1588                    stopEglContextLocked();
1589                }
1590            }
1591        }
1592
1593        public boolean ableToDraw() {
1594            return mHaveEglContext && mHaveEglSurface && readyToDraw();
1595        }
1596
1597        private boolean readyToDraw() {
1598            return (!mPaused) && mHasSurface && (!mSurfaceIsBad)
1599                && (mWidth > 0) && (mHeight > 0)
1600                && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY));
1601        }
1602
1603        public void setRenderMode(int renderMode) {
1604            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1605                throw new IllegalArgumentException("renderMode");
1606            }
1607            synchronized(sGLThreadManager) {
1608                mRenderMode = renderMode;
1609                sGLThreadManager.notifyAll();
1610            }
1611        }
1612
1613        public int getRenderMode() {
1614            synchronized(sGLThreadManager) {
1615                return mRenderMode;
1616            }
1617        }
1618
1619        public void requestRender() {
1620            synchronized(sGLThreadManager) {
1621                mRequestRender = true;
1622                sGLThreadManager.notifyAll();
1623            }
1624        }
1625
1626        public void requestRenderAndWait() {
1627            synchronized(sGLThreadManager) {
1628                mWantRenderNotification = true;
1629                mRequestRender = true;
1630                mRenderComplete = false;
1631                sGLThreadManager.notifyAll();
1632                while (!mExited && !mPaused && mRenderComplete == false) {
1633                    try {
1634                        sGLThreadManager.wait();
1635                    } catch (InterruptedException ex) {
1636                        Thread.currentThread().interrupt();
1637                    }
1638                }
1639
1640            }
1641        }
1642
1643        public void surfaceCreated() {
1644            synchronized(sGLThreadManager) {
1645                if (LOG_THREADS) {
1646                    Log.i("GLThread", "surfaceCreated tid=" + getId());
1647                }
1648                mHasSurface = true;
1649                mFinishedCreatingEglSurface = false;
1650                sGLThreadManager.notifyAll();
1651                while (mWaitingForSurface
1652                       && !mFinishedCreatingEglSurface
1653                       && !mExited) {
1654                    try {
1655                        sGLThreadManager.wait();
1656                    } catch (InterruptedException e) {
1657                        Thread.currentThread().interrupt();
1658                    }
1659                }
1660            }
1661        }
1662
1663        public void surfaceDestroyed() {
1664            synchronized(sGLThreadManager) {
1665                if (LOG_THREADS) {
1666                    Log.i("GLThread", "surfaceDestroyed tid=" + getId());
1667                }
1668                mHasSurface = false;
1669                sGLThreadManager.notifyAll();
1670                while((!mWaitingForSurface) && (!mExited)) {
1671                    try {
1672                        sGLThreadManager.wait();
1673                    } catch (InterruptedException e) {
1674                        Thread.currentThread().interrupt();
1675                    }
1676                }
1677            }
1678        }
1679
1680        public void onPause() {
1681            synchronized (sGLThreadManager) {
1682                if (LOG_PAUSE_RESUME) {
1683                    Log.i("GLThread", "onPause tid=" + getId());
1684                }
1685                mRequestPaused = true;
1686                sGLThreadManager.notifyAll();
1687                while ((! mExited) && (! mPaused)) {
1688                    if (LOG_PAUSE_RESUME) {
1689                        Log.i("Main thread", "onPause waiting for mPaused.");
1690                    }
1691                    try {
1692                        sGLThreadManager.wait();
1693                    } catch (InterruptedException ex) {
1694                        Thread.currentThread().interrupt();
1695                    }
1696                }
1697            }
1698        }
1699
1700        public void onResume() {
1701            synchronized (sGLThreadManager) {
1702                if (LOG_PAUSE_RESUME) {
1703                    Log.i("GLThread", "onResume tid=" + getId());
1704                }
1705                mRequestPaused = false;
1706                mRequestRender = true;
1707                mRenderComplete = false;
1708                sGLThreadManager.notifyAll();
1709                while ((! mExited) && mPaused && (!mRenderComplete)) {
1710                    if (LOG_PAUSE_RESUME) {
1711                        Log.i("Main thread", "onResume waiting for !mPaused.");
1712                    }
1713                    try {
1714                        sGLThreadManager.wait();
1715                    } catch (InterruptedException ex) {
1716                        Thread.currentThread().interrupt();
1717                    }
1718                }
1719            }
1720        }
1721
1722        public void onWindowResize(int w, int h) {
1723            synchronized (sGLThreadManager) {
1724                mWidth = w;
1725                mHeight = h;
1726                mSizeChanged = true;
1727                mRequestRender = true;
1728                mRenderComplete = false;
1729                sGLThreadManager.notifyAll();
1730
1731                // Wait for thread to react to resize and render a frame
1732                while (! mExited && !mPaused && !mRenderComplete
1733                        && ableToDraw()) {
1734                    if (LOG_SURFACE) {
1735                        Log.i("Main thread", "onWindowResize waiting for render complete from tid=" + getId());
1736                    }
1737                    try {
1738                        sGLThreadManager.wait();
1739                    } catch (InterruptedException ex) {
1740                        Thread.currentThread().interrupt();
1741                    }
1742                }
1743            }
1744        }
1745
1746        public void requestExitAndWait() {
1747            // don't call this from GLThread thread or it is a guaranteed
1748            // deadlock!
1749            synchronized(sGLThreadManager) {
1750                mShouldExit = true;
1751                sGLThreadManager.notifyAll();
1752                while (! mExited) {
1753                    try {
1754                        sGLThreadManager.wait();
1755                    } catch (InterruptedException ex) {
1756                        Thread.currentThread().interrupt();
1757                    }
1758                }
1759            }
1760        }
1761
1762        public void requestReleaseEglContextLocked() {
1763            mShouldReleaseEglContext = true;
1764            sGLThreadManager.notifyAll();
1765        }
1766
1767        /**
1768         * Queue an "event" to be run on the GL rendering thread.
1769         * @param r the runnable to be run on the GL rendering thread.
1770         */
1771        public void queueEvent(Runnable r) {
1772            if (r == null) {
1773                throw new IllegalArgumentException("r must not be null");
1774            }
1775            synchronized(sGLThreadManager) {
1776                mEventQueue.add(r);
1777                sGLThreadManager.notifyAll();
1778            }
1779        }
1780
1781        // Once the thread is started, all accesses to the following member
1782        // variables are protected by the sGLThreadManager monitor
1783        private boolean mShouldExit;
1784        private boolean mExited;
1785        private boolean mRequestPaused;
1786        private boolean mPaused;
1787        private boolean mHasSurface;
1788        private boolean mSurfaceIsBad;
1789        private boolean mWaitingForSurface;
1790        private boolean mHaveEglContext;
1791        private boolean mHaveEglSurface;
1792        private boolean mFinishedCreatingEglSurface;
1793        private boolean mShouldReleaseEglContext;
1794        private int mWidth;
1795        private int mHeight;
1796        private int mRenderMode;
1797        private boolean mRequestRender;
1798        private boolean mWantRenderNotification;
1799        private boolean mRenderComplete;
1800        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1801        private boolean mSizeChanged = true;
1802
1803        // End of member variables protected by the sGLThreadManager monitor.
1804
1805        private EglHelper mEglHelper;
1806
1807        /**
1808         * Set once at thread construction time, nulled out when the parent view is garbage
1809         * called. This weak reference allows the GLSurfaceView to be garbage collected while
1810         * the GLThread is still alive.
1811         */
1812        private WeakReference<GLSurfaceView> mGLSurfaceViewWeakRef;
1813
1814    }
1815
1816    static class LogWriter extends Writer {
1817
1818        @Override public void close() {
1819            flushBuilder();
1820        }
1821
1822        @Override public void flush() {
1823            flushBuilder();
1824        }
1825
1826        @Override public void write(char[] buf, int offset, int count) {
1827            for(int i = 0; i < count; i++) {
1828                char c = buf[offset + i];
1829                if ( c == '\n') {
1830                    flushBuilder();
1831                }
1832                else {
1833                    mBuilder.append(c);
1834                }
1835            }
1836        }
1837
1838        private void flushBuilder() {
1839            if (mBuilder.length() > 0) {
1840                Log.v("GLSurfaceView", mBuilder.toString());
1841                mBuilder.delete(0, mBuilder.length());
1842            }
1843        }
1844
1845        private StringBuilder mBuilder = new StringBuilder();
1846    }
1847
1848
1849    private void checkRenderThreadState() {
1850        if (mGLThread != null) {
1851            throw new IllegalStateException(
1852                    "setRenderer has already been called for this instance.");
1853        }
1854    }
1855
1856    private static class GLThreadManager {
1857        private static String TAG = "GLThreadManager";
1858
1859        public synchronized void threadExiting(GLThread thread) {
1860            if (LOG_THREADS) {
1861                Log.i("GLThread", "exiting tid=" +  thread.getId());
1862            }
1863            thread.mExited = true;
1864            if (mEglOwner == thread) {
1865                mEglOwner = null;
1866            }
1867            notifyAll();
1868        }
1869
1870        /*
1871         * Tries once to acquire the right to use an EGL
1872         * context. Does not block. Requires that we are already
1873         * in the sGLThreadManager monitor when this is called.
1874         *
1875         * @return true if the right to use an EGL context was acquired.
1876         */
1877        public boolean tryAcquireEglContextLocked(GLThread thread) {
1878            if (mEglOwner == thread || mEglOwner == null) {
1879                mEglOwner = thread;
1880                notifyAll();
1881                return true;
1882            }
1883            checkGLESVersion();
1884            if (mMultipleGLESContextsAllowed) {
1885                return true;
1886            }
1887            // Notify the owning thread that it should release the context.
1888            // TODO: implement a fairness policy. Currently
1889            // if the owning thread is drawing continuously it will just
1890            // reacquire the EGL context.
1891            if (mEglOwner != null) {
1892                mEglOwner.requestReleaseEglContextLocked();
1893            }
1894            return false;
1895        }
1896
1897        /*
1898         * Releases the EGL context. Requires that we are already in the
1899         * sGLThreadManager monitor when this is called.
1900         */
1901        public void releaseEglContextLocked(GLThread thread) {
1902            if (mEglOwner == thread) {
1903                mEglOwner = null;
1904            }
1905            notifyAll();
1906        }
1907
1908        public synchronized boolean shouldReleaseEGLContextWhenPausing() {
1909            // Release the EGL context when pausing even if
1910            // the hardware supports multiple EGL contexts.
1911            // Otherwise the device could run out of EGL contexts.
1912            return mLimitedGLESContexts;
1913        }
1914
1915        public synchronized boolean shouldTerminateEGLWhenPausing() {
1916            checkGLESVersion();
1917            return !mMultipleGLESContextsAllowed;
1918        }
1919
1920        public synchronized void checkGLDriver(GL10 gl) {
1921            if (! mGLESDriverCheckComplete) {
1922                checkGLESVersion();
1923                String renderer = gl.glGetString(GL10.GL_RENDERER);
1924                if (mGLESVersion < kGLES_20) {
1925                    mMultipleGLESContextsAllowed =
1926                        ! renderer.startsWith(kMSM7K_RENDERER_PREFIX);
1927                    notifyAll();
1928                }
1929                mLimitedGLESContexts = !mMultipleGLESContextsAllowed;
1930                if (LOG_SURFACE) {
1931                    Log.w(TAG, "checkGLDriver renderer = \"" + renderer + "\" multipleContextsAllowed = "
1932                        + mMultipleGLESContextsAllowed
1933                        + " mLimitedGLESContexts = " + mLimitedGLESContexts);
1934                }
1935                mGLESDriverCheckComplete = true;
1936            }
1937        }
1938
1939        private void checkGLESVersion() {
1940            if (! mGLESVersionCheckComplete) {
1941                mGLESVersion = SystemProperties.getInt(
1942                        "ro.opengles.version",
1943                        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1944                if (mGLESVersion >= kGLES_20) {
1945                    mMultipleGLESContextsAllowed = true;
1946                }
1947                if (LOG_SURFACE) {
1948                    Log.w(TAG, "checkGLESVersion mGLESVersion =" +
1949                            " " + mGLESVersion + " mMultipleGLESContextsAllowed = " + mMultipleGLESContextsAllowed);
1950                }
1951                mGLESVersionCheckComplete = true;
1952            }
1953        }
1954
1955        /**
1956         * This check was required for some pre-Android-3.0 hardware. Android 3.0 provides
1957         * support for hardware-accelerated views, therefore multiple EGL contexts are
1958         * supported on all Android 3.0+ EGL drivers.
1959         */
1960        private boolean mGLESVersionCheckComplete;
1961        private int mGLESVersion;
1962        private boolean mGLESDriverCheckComplete;
1963        private boolean mMultipleGLESContextsAllowed;
1964        private boolean mLimitedGLESContexts;
1965        private static final int kGLES_20 = 0x20000;
1966        private static final String kMSM7K_RENDERER_PREFIX =
1967            "Q3Dimension MSM7500 ";
1968        private GLThread mEglOwner;
1969    }
1970
1971    private static final GLThreadManager sGLThreadManager = new GLThreadManager();
1972
1973    private final WeakReference<GLSurfaceView> mThisWeakRef =
1974            new WeakReference<GLSurfaceView>(this);
1975    private GLThread mGLThread;
1976    private Renderer mRenderer;
1977    private boolean mDetached;
1978    private EGLConfigChooser mEGLConfigChooser;
1979    private EGLContextFactory mEGLContextFactory;
1980    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1981    private GLWrapper mGLWrapper;
1982    private int mDebugFlags;
1983    private int mEGLContextClientVersion;
1984    private boolean mPreserveEGLContextOnPause;
1985}
1986