GLSurfaceView.java revision 75f2bc04df11c67d7074186432278f182381b9f2
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_656 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        /**
1077         * Display the current render surface.
1078         * @return false if the context has been lost.
1079         */
1080        public boolean swap() {
1081            if (! mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) {
1082
1083                /*
1084                 * Check for EGL_CONTEXT_LOST, which means the context
1085                 * and all associated data were lost (For instance because
1086                 * the device went to sleep). We need to sleep until we
1087                 * get a new surface.
1088                 */
1089                int error = mEgl.eglGetError();
1090                switch(error) {
1091                case EGL11.EGL_CONTEXT_LOST:
1092                    return false;
1093                case EGL10.EGL_BAD_NATIVE_WINDOW:
1094                    // The native window is bad, probably because the
1095                    // window manager has closed it. Ignore this error,
1096                    // on the expectation that the application will be closed soon.
1097                    Log.e("EglHelper", "eglSwapBuffers returned EGL_BAD_NATIVE_WINDOW. tid=" + Thread.currentThread().getId());
1098                    break;
1099                default:
1100                    throwEglException("eglSwapBuffers", error);
1101                }
1102            }
1103            return true;
1104        }
1105
1106        public void destroySurface() {
1107            if (LOG_EGL) {
1108                Log.w("EglHelper", "destroySurface()  tid=" + Thread.currentThread().getId());
1109            }
1110            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
1111                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
1112                        EGL10.EGL_NO_SURFACE,
1113                        EGL10.EGL_NO_CONTEXT);
1114                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
1115                mEglSurface = null;
1116            }
1117        }
1118
1119        public void finish() {
1120            if (LOG_EGL) {
1121                Log.w("EglHelper", "finish() tid=" + Thread.currentThread().getId());
1122            }
1123            if (mEglContext != null) {
1124                mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
1125                mEglContext = null;
1126            }
1127            if (mEglDisplay != null) {
1128                mEgl.eglTerminate(mEglDisplay);
1129                mEglDisplay = null;
1130            }
1131        }
1132
1133        private void throwEglException(String function) {
1134            throwEglException(function, mEgl.eglGetError());
1135        }
1136
1137        private void throwEglException(String function, int error) {
1138            String message = function + " failed: " + EGLLogWrapper.getErrorString(error);
1139            if (LOG_THREADS) {
1140                Log.e("EglHelper", "throwEglException tid=" + Thread.currentThread().getId() + " " + message);
1141            }
1142            throw new RuntimeException(message);
1143        }
1144
1145        EGL10 mEgl;
1146        EGLDisplay mEglDisplay;
1147        EGLSurface mEglSurface;
1148        EGLConfig mEglConfig;
1149        EGLContext mEglContext;
1150
1151    }
1152
1153    /**
1154     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
1155     * to a Renderer instance to do the actual drawing. Can be configured to
1156     * render continuously or on request.
1157     *
1158     * All potentially blocking synchronization is done through the
1159     * sGLThreadManager object. This avoids multiple-lock ordering issues.
1160     *
1161     */
1162    class GLThread extends Thread {
1163        GLThread(Renderer renderer) {
1164            super();
1165            mWidth = 0;
1166            mHeight = 0;
1167            mRequestRender = true;
1168            mRenderMode = RENDERMODE_CONTINUOUSLY;
1169            mRenderer = renderer;
1170        }
1171
1172        @Override
1173        public void run() {
1174            setName("GLThread " + getId());
1175            if (LOG_THREADS) {
1176                Log.i("GLThread", "starting tid=" + getId());
1177            }
1178
1179            try {
1180                guardedRun();
1181            } catch (InterruptedException e) {
1182                // fall thru and exit normally
1183            } finally {
1184                sGLThreadManager.threadExiting(this);
1185            }
1186        }
1187
1188        /*
1189         * This private method should only be called inside a
1190         * synchronized(sGLThreadManager) block.
1191         */
1192        private void stopEglSurfaceLocked() {
1193            if (mHaveEglSurface) {
1194                mHaveEglSurface = false;
1195                mEglHelper.destroySurface();
1196            }
1197        }
1198
1199        /*
1200         * This private method should only be called inside a
1201         * synchronized(sGLThreadManager) block.
1202         */
1203        private void stopEglContextLocked() {
1204            if (mHaveEglContext) {
1205                mEglHelper.finish();
1206                mHaveEglContext = false;
1207                sGLThreadManager.releaseEglContextLocked(this);
1208            }
1209        }
1210        private void guardedRun() throws InterruptedException {
1211            mEglHelper = new EglHelper();
1212            mHaveEglContext = false;
1213            mHaveEglSurface = false;
1214            try {
1215                GL10 gl = null;
1216                boolean createEglContext = false;
1217                boolean createEglSurface = false;
1218                boolean lostEglContext = false;
1219                boolean sizeChanged = false;
1220                boolean wantRenderNotification = false;
1221                boolean doRenderNotification = false;
1222                boolean askedToReleaseEglContext = false;
1223                int w = 0;
1224                int h = 0;
1225                Runnable event = null;
1226
1227                while (true) {
1228                    synchronized (sGLThreadManager) {
1229                        while (true) {
1230                            if (mShouldExit) {
1231                                return;
1232                            }
1233
1234                            if (! mEventQueue.isEmpty()) {
1235                                event = mEventQueue.remove(0);
1236                                break;
1237                            }
1238
1239                            // Update the pause state.
1240                            if (mPaused != mRequestPaused) {
1241                                mPaused = mRequestPaused;
1242                                sGLThreadManager.notifyAll();
1243                                if (LOG_PAUSE_RESUME) {
1244                                    Log.i("GLThread", "mPaused is now " + mPaused + " tid=" + getId());
1245                                }
1246                            }
1247
1248                            // Do we need to give up the EGL context?
1249                            if (mShouldReleaseEglContext) {
1250                                if (LOG_SURFACE) {
1251                                    Log.i("GLThread", "releasing EGL context because asked to tid=" + getId());
1252                                }
1253                                stopEglSurfaceLocked();
1254                                stopEglContextLocked();
1255                                mShouldReleaseEglContext = false;
1256                                askedToReleaseEglContext = true;
1257                            }
1258
1259                            // Have we lost the EGL context?
1260                            if (lostEglContext) {
1261                                stopEglSurfaceLocked();
1262                                stopEglContextLocked();
1263                                lostEglContext = false;
1264                            }
1265
1266                            // Do we need to release the EGL surface?
1267                            if (mHaveEglSurface && mPaused) {
1268                                if (LOG_SURFACE) {
1269                                    Log.i("GLThread", "releasing EGL surface because paused tid=" + getId());
1270                                }
1271                                stopEglSurfaceLocked();
1272                                if (!mPreserveEGLContextOnPause || sGLThreadManager.shouldReleaseEGLContextWhenPausing()) {
1273                                    stopEglContextLocked();
1274                                    if (LOG_SURFACE) {
1275                                        Log.i("GLThread", "releasing EGL context because paused tid=" + getId());
1276                                    }
1277                                }
1278                                if (sGLThreadManager.shouldTerminateEGLWhenPausing()) {
1279                                    mEglHelper.finish();
1280                                    if (LOG_SURFACE) {
1281                                        Log.i("GLThread", "terminating EGL because paused tid=" + getId());
1282                                    }
1283                                }
1284                            }
1285
1286                            // Have we lost the surface view surface?
1287                            if ((! mHasSurface) && (! mWaitingForSurface)) {
1288                                if (LOG_SURFACE) {
1289                                    Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId());
1290                                }
1291                                if (mHaveEglSurface) {
1292                                    stopEglSurfaceLocked();
1293                                }
1294                                mWaitingForSurface = true;
1295                                sGLThreadManager.notifyAll();
1296                            }
1297
1298                            // Have we acquired the surface view surface?
1299                            if (mHasSurface && mWaitingForSurface) {
1300                                if (LOG_SURFACE) {
1301                                    Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId());
1302                                }
1303                                mWaitingForSurface = false;
1304                                sGLThreadManager.notifyAll();
1305                            }
1306
1307                            if (doRenderNotification) {
1308                                if (LOG_SURFACE) {
1309                                    Log.i("GLThread", "sending render notification tid=" + getId());
1310                                }
1311                                wantRenderNotification = false;
1312                                doRenderNotification = false;
1313                                mRenderComplete = true;
1314                                sGLThreadManager.notifyAll();
1315                            }
1316
1317                            // Ready to draw?
1318                            if (readyToDraw()) {
1319
1320                                // If we don't have an EGL context, try to acquire one.
1321                                if (! mHaveEglContext) {
1322                                    if (askedToReleaseEglContext) {
1323                                        askedToReleaseEglContext = false;
1324                                    } else if (sGLThreadManager.tryAcquireEglContextLocked(this)) {
1325                                        try {
1326                                            mEglHelper.start();
1327                                        } catch (RuntimeException t) {
1328                                            sGLThreadManager.releaseEglContextLocked(this);
1329                                            throw t;
1330                                        }
1331                                        mHaveEglContext = true;
1332                                        createEglContext = true;
1333
1334                                        sGLThreadManager.notifyAll();
1335                                    }
1336                                }
1337
1338                                if (mHaveEglContext && !mHaveEglSurface) {
1339                                    mHaveEglSurface = true;
1340                                    createEglSurface = true;
1341                                    sizeChanged = true;
1342                                }
1343
1344                                if (mHaveEglSurface) {
1345                                    if (mSizeChanged) {
1346                                        sizeChanged = true;
1347                                        w = mWidth;
1348                                        h = mHeight;
1349                                        wantRenderNotification = true;
1350                                        if (LOG_SURFACE) {
1351                                            Log.i("GLThread", "noticing that we want render notification tid=" + getId());
1352                                        }
1353
1354                                        if (DRAW_TWICE_AFTER_SIZE_CHANGED) {
1355                                            // We keep mRequestRender true so that we draw twice after the size changes.
1356                                            // (Once because of mSizeChanged, the second time because of mRequestRender.)
1357                                            // This forces the updated graphics onto the screen.
1358                                        } else {
1359                                            mRequestRender = false;
1360                                        }
1361                                        mSizeChanged = false;
1362                                    } else {
1363                                        mRequestRender = false;
1364                                    }
1365                                    sGLThreadManager.notifyAll();
1366                                    break;
1367                                }
1368                            }
1369
1370                            // By design, this is the only place in a GLThread thread where we wait().
1371                            if (LOG_THREADS) {
1372                                Log.i("GLThread", "waiting tid=" + getId()
1373                                    + " mHaveEglContext: " + mHaveEglContext
1374                                    + " mHaveEglSurface: " + mHaveEglSurface
1375                                    + " mPaused: " + mPaused
1376                                    + " mHasSurface: " + mHasSurface
1377                                    + " mWaitingForSurface: " + mWaitingForSurface
1378                                    + " mWidth: " + mWidth
1379                                    + " mHeight: " + mHeight
1380                                    + " mRequestRender: " + mRequestRender
1381                                    + " mRenderMode: " + mRenderMode);
1382                            }
1383                            sGLThreadManager.wait();
1384                        }
1385                    } // end of synchronized(sGLThreadManager)
1386
1387                    if (event != null) {
1388                        event.run();
1389                        event = null;
1390                        continue;
1391                    }
1392
1393                    if (createEglSurface) {
1394                        if (LOG_SURFACE) {
1395                            Log.w("GLThread", "egl createSurface");
1396                        }
1397                        gl = (GL10) mEglHelper.createSurface(getHolder());
1398                        if (gl == null) {
1399                            // Couldn't create a surface. Quit quietly.
1400                            break;
1401                        }
1402                        sGLThreadManager.checkGLDriver(gl);
1403                        createEglSurface = false;
1404                    }
1405
1406                    if (createEglContext) {
1407                        if (LOG_RENDERER) {
1408                            Log.w("GLThread", "onSurfaceCreated");
1409                        }
1410                        mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1411                        createEglContext = false;
1412                    }
1413
1414                    if (sizeChanged) {
1415                        if (LOG_RENDERER) {
1416                            Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")");
1417                        }
1418                        mRenderer.onSurfaceChanged(gl, w, h);
1419                        sizeChanged = false;
1420                    }
1421
1422                    if (LOG_RENDERER_DRAW_FRAME) {
1423                        Log.w("GLThread", "onDrawFrame tid=" + getId());
1424                    }
1425                    mRenderer.onDrawFrame(gl);
1426                    if (!mEglHelper.swap()) {
1427                        if (LOG_SURFACE) {
1428                            Log.i("GLThread", "egl context lost tid=" + getId());
1429                        }
1430                        lostEglContext = true;
1431                    }
1432
1433                    if (wantRenderNotification) {
1434                        doRenderNotification = true;
1435                    }
1436                }
1437
1438            } finally {
1439                /*
1440                 * clean-up everything...
1441                 */
1442                synchronized (sGLThreadManager) {
1443                    stopEglSurfaceLocked();
1444                    stopEglContextLocked();
1445                }
1446            }
1447        }
1448
1449        public boolean ableToDraw() {
1450            return mHaveEglContext && mHaveEglSurface && readyToDraw();
1451        }
1452
1453        private boolean readyToDraw() {
1454            return (!mPaused) && mHasSurface
1455                && (mWidth > 0) && (mHeight > 0)
1456                && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY));
1457        }
1458
1459        public void setRenderMode(int renderMode) {
1460            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1461                throw new IllegalArgumentException("renderMode");
1462            }
1463            synchronized(sGLThreadManager) {
1464                mRenderMode = renderMode;
1465                sGLThreadManager.notifyAll();
1466            }
1467        }
1468
1469        public int getRenderMode() {
1470            synchronized(sGLThreadManager) {
1471                return mRenderMode;
1472            }
1473        }
1474
1475        public void requestRender() {
1476            synchronized(sGLThreadManager) {
1477                mRequestRender = true;
1478                sGLThreadManager.notifyAll();
1479            }
1480        }
1481
1482        public void surfaceCreated() {
1483            synchronized(sGLThreadManager) {
1484                if (LOG_THREADS) {
1485                    Log.i("GLThread", "surfaceCreated tid=" + getId());
1486                }
1487                mHasSurface = true;
1488                sGLThreadManager.notifyAll();
1489                while((mWaitingForSurface) && (!mExited)) {
1490                    try {
1491                        sGLThreadManager.wait();
1492                    } catch (InterruptedException e) {
1493                        Thread.currentThread().interrupt();
1494                    }
1495                }
1496            }
1497        }
1498
1499        public void surfaceDestroyed() {
1500            synchronized(sGLThreadManager) {
1501                if (LOG_THREADS) {
1502                    Log.i("GLThread", "surfaceDestroyed tid=" + getId());
1503                }
1504                mHasSurface = false;
1505                sGLThreadManager.notifyAll();
1506                while((!mWaitingForSurface) && (!mExited)) {
1507                    try {
1508                        sGLThreadManager.wait();
1509                    } catch (InterruptedException e) {
1510                        Thread.currentThread().interrupt();
1511                    }
1512                }
1513            }
1514        }
1515
1516        public void onPause() {
1517            synchronized (sGLThreadManager) {
1518                if (LOG_PAUSE_RESUME) {
1519                    Log.i("GLThread", "onPause tid=" + getId());
1520                }
1521                mRequestPaused = true;
1522                sGLThreadManager.notifyAll();
1523                while ((! mExited) && (! mPaused)) {
1524                    if (LOG_PAUSE_RESUME) {
1525                        Log.i("Main thread", "onPause waiting for mPaused.");
1526                    }
1527                    try {
1528                        sGLThreadManager.wait();
1529                    } catch (InterruptedException ex) {
1530                        Thread.currentThread().interrupt();
1531                    }
1532                }
1533            }
1534        }
1535
1536        public void onResume() {
1537            synchronized (sGLThreadManager) {
1538                if (LOG_PAUSE_RESUME) {
1539                    Log.i("GLThread", "onResume tid=" + getId());
1540                }
1541                mRequestPaused = false;
1542                mRequestRender = true;
1543                mRenderComplete = false;
1544                sGLThreadManager.notifyAll();
1545                while ((! mExited) && mPaused && (!mRenderComplete)) {
1546                    if (LOG_PAUSE_RESUME) {
1547                        Log.i("Main thread", "onResume waiting for !mPaused.");
1548                    }
1549                    try {
1550                        sGLThreadManager.wait();
1551                    } catch (InterruptedException ex) {
1552                        Thread.currentThread().interrupt();
1553                    }
1554                }
1555            }
1556        }
1557
1558        public void onWindowResize(int w, int h) {
1559            synchronized (sGLThreadManager) {
1560                mWidth = w;
1561                mHeight = h;
1562                mSizeChanged = true;
1563                mRequestRender = true;
1564                mRenderComplete = false;
1565                sGLThreadManager.notifyAll();
1566
1567                // Wait for thread to react to resize and render a frame
1568                while (! mExited && !mPaused && !mRenderComplete
1569                        && (mGLThread != null && mGLThread.ableToDraw())) {
1570                    if (LOG_SURFACE) {
1571                        Log.i("Main thread", "onWindowResize waiting for render complete from tid=" + mGLThread.getId());
1572                    }
1573                    try {
1574                        sGLThreadManager.wait();
1575                    } catch (InterruptedException ex) {
1576                        Thread.currentThread().interrupt();
1577                    }
1578                }
1579            }
1580        }
1581
1582        public void requestExitAndWait() {
1583            // don't call this from GLThread thread or it is a guaranteed
1584            // deadlock!
1585            synchronized(sGLThreadManager) {
1586                mShouldExit = true;
1587                sGLThreadManager.notifyAll();
1588                while (! mExited) {
1589                    try {
1590                        sGLThreadManager.wait();
1591                    } catch (InterruptedException ex) {
1592                        Thread.currentThread().interrupt();
1593                    }
1594                }
1595            }
1596        }
1597
1598        public void requestReleaseEglContextLocked() {
1599            mShouldReleaseEglContext = true;
1600            sGLThreadManager.notifyAll();
1601        }
1602
1603        /**
1604         * Queue an "event" to be run on the GL rendering thread.
1605         * @param r the runnable to be run on the GL rendering thread.
1606         */
1607        public void queueEvent(Runnable r) {
1608            if (r == null) {
1609                throw new IllegalArgumentException("r must not be null");
1610            }
1611            synchronized(sGLThreadManager) {
1612                mEventQueue.add(r);
1613                sGLThreadManager.notifyAll();
1614            }
1615        }
1616
1617        // Once the thread is started, all accesses to the following member
1618        // variables are protected by the sGLThreadManager monitor
1619        private boolean mShouldExit;
1620        private boolean mExited;
1621        private boolean mRequestPaused;
1622        private boolean mPaused;
1623        private boolean mHasSurface;
1624        private boolean mWaitingForSurface;
1625        private boolean mHaveEglContext;
1626        private boolean mHaveEglSurface;
1627        private boolean mShouldReleaseEglContext;
1628        private int mWidth;
1629        private int mHeight;
1630        private int mRenderMode;
1631        private boolean mRequestRender;
1632        private boolean mRenderComplete;
1633        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1634
1635        // End of member variables protected by the sGLThreadManager monitor.
1636
1637        private Renderer mRenderer;
1638        private EglHelper mEglHelper;
1639    }
1640
1641    static class LogWriter extends Writer {
1642
1643        @Override public void close() {
1644            flushBuilder();
1645        }
1646
1647        @Override public void flush() {
1648            flushBuilder();
1649        }
1650
1651        @Override public void write(char[] buf, int offset, int count) {
1652            for(int i = 0; i < count; i++) {
1653                char c = buf[offset + i];
1654                if ( c == '\n') {
1655                    flushBuilder();
1656                }
1657                else {
1658                    mBuilder.append(c);
1659                }
1660            }
1661        }
1662
1663        private void flushBuilder() {
1664            if (mBuilder.length() > 0) {
1665                Log.v("GLSurfaceView", mBuilder.toString());
1666                mBuilder.delete(0, mBuilder.length());
1667            }
1668        }
1669
1670        private StringBuilder mBuilder = new StringBuilder();
1671    }
1672
1673
1674    private void checkRenderThreadState() {
1675        if (mGLThread != null) {
1676            throw new IllegalStateException(
1677                    "setRenderer has already been called for this instance.");
1678        }
1679    }
1680
1681    private static class GLThreadManager {
1682        private static String TAG = "GLThreadManager";
1683
1684        public synchronized void threadExiting(GLThread thread) {
1685            if (LOG_THREADS) {
1686                Log.i("GLThread", "exiting tid=" +  thread.getId());
1687            }
1688            thread.mExited = true;
1689            if (mEglOwner == thread) {
1690                mEglOwner = null;
1691            }
1692            notifyAll();
1693        }
1694
1695        /*
1696         * Tries once to acquire the right to use an EGL
1697         * context. Does not block. Requires that we are already
1698         * in the sGLThreadManager monitor when this is called.
1699         *
1700         * @return true if the right to use an EGL context was acquired.
1701         */
1702        public boolean tryAcquireEglContextLocked(GLThread thread) {
1703            if (mEglOwner == thread || mEglOwner == null) {
1704                mEglOwner = thread;
1705                notifyAll();
1706                return true;
1707            }
1708            checkGLESVersion();
1709            if (mMultipleGLESContextsAllowed) {
1710                return true;
1711            }
1712            // Notify the owning thread that it should release the context.
1713            // TODO: implement a fairness policy. Currently
1714            // if the owning thread is drawing continuously it will just
1715            // reacquire the EGL context.
1716            if (mEglOwner != null) {
1717                mEglOwner.requestReleaseEglContextLocked();
1718            }
1719            return false;
1720        }
1721
1722        /*
1723         * Releases the EGL context. Requires that we are already in the
1724         * sGLThreadManager monitor when this is called.
1725         */
1726        public void releaseEglContextLocked(GLThread thread) {
1727            if (mEglOwner == thread) {
1728                mEglOwner = null;
1729            }
1730            notifyAll();
1731        }
1732
1733        public synchronized boolean shouldReleaseEGLContextWhenPausing() {
1734            // Release the EGL context when pausing even if
1735            // the hardware supports multiple EGL contexts.
1736            // Otherwise the device could run out of EGL contexts.
1737            return mLimitedGLESContexts;
1738        }
1739
1740        public synchronized boolean shouldTerminateEGLWhenPausing() {
1741            checkGLESVersion();
1742            return !mMultipleGLESContextsAllowed;
1743        }
1744
1745        public synchronized void checkGLDriver(GL10 gl) {
1746            if (! mGLESDriverCheckComplete) {
1747                checkGLESVersion();
1748                String renderer = gl.glGetString(GL10.GL_RENDERER);
1749                if (mGLESVersion < kGLES_20) {
1750                    mMultipleGLESContextsAllowed =
1751                        ! renderer.startsWith(kMSM7K_RENDERER_PREFIX);
1752                    notifyAll();
1753                }
1754                mLimitedGLESContexts = !mMultipleGLESContextsAllowed || renderer.startsWith(kADRENO);
1755                if (LOG_SURFACE) {
1756                    Log.w(TAG, "checkGLDriver renderer = \"" + renderer + "\" multipleContextsAllowed = "
1757                        + mMultipleGLESContextsAllowed
1758                        + " mLimitedGLESContexts = " + mLimitedGLESContexts);
1759                }
1760                mGLESDriverCheckComplete = true;
1761            }
1762        }
1763
1764        private void checkGLESVersion() {
1765            if (! mGLESVersionCheckComplete) {
1766                mGLESVersion = SystemProperties.getInt(
1767                        "ro.opengles.version",
1768                        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1769                if (mGLESVersion >= kGLES_20) {
1770                    mMultipleGLESContextsAllowed = true;
1771                }
1772                if (LOG_SURFACE) {
1773                    Log.w(TAG, "checkGLESVersion mGLESVersion =" +
1774                            " " + mGLESVersion + " mMultipleGLESContextsAllowed = " + mMultipleGLESContextsAllowed);
1775                }
1776                mGLESVersionCheckComplete = true;
1777            }
1778        }
1779
1780        private boolean mGLESVersionCheckComplete;
1781        private int mGLESVersion;
1782        private boolean mGLESDriverCheckComplete;
1783        private boolean mMultipleGLESContextsAllowed;
1784        private boolean mLimitedGLESContexts;
1785        private static final int kGLES_20 = 0x20000;
1786        private static final String kMSM7K_RENDERER_PREFIX =
1787            "Q3Dimension MSM7500 ";
1788        private static final String kADRENO = "Adreno";
1789        private GLThread mEglOwner;
1790    }
1791
1792    private static final GLThreadManager sGLThreadManager = new GLThreadManager();
1793    private boolean mSizeChanged = true;
1794
1795    private GLThread mGLThread;
1796    private Renderer mRenderer;
1797    private boolean mDetached;
1798    private EGLConfigChooser mEGLConfigChooser;
1799    private EGLContextFactory mEGLContextFactory;
1800    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1801    private GLWrapper mGLWrapper;
1802    private int mDebugFlags;
1803    private int mEGLContextClientVersion;
1804    private boolean mPreserveEGLContextOnPause;
1805}
1806