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