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