GLSurfaceView.java revision 83835359e51ddb8be37cea9bf4bb32f9390d82b7
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 boolean LOG_THREADS = false;
159    private final static boolean LOG_SURFACE = false;
160    private final static boolean LOG_RENDERER = false;
161    private final static boolean LOG_RENDERER_DRAW_FRAME = false;
162    // Work-around for bug 2263168
163    private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true;
164    /**
165     * The renderer only renders
166     * when the surface is created, or when {@link #requestRender} is called.
167     *
168     * @see #getRenderMode()
169     * @see #setRenderMode(int)
170     * @see #requestRender()
171     */
172    public final static int RENDERMODE_WHEN_DIRTY = 0;
173    /**
174     * The renderer is called
175     * continuously to re-render the scene.
176     *
177     * @see #getRenderMode()
178     * @see #setRenderMode(int)
179     */
180    public final static int RENDERMODE_CONTINUOUSLY = 1;
181
182    /**
183     * Check glError() after every GL call and throw an exception if glError indicates
184     * that an error has occurred. This can be used to help track down which OpenGL ES call
185     * is causing an error.
186     *
187     * @see #getDebugFlags
188     * @see #setDebugFlags
189     */
190    public final static int DEBUG_CHECK_GL_ERROR = 1;
191
192    /**
193     * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView".
194     *
195     * @see #getDebugFlags
196     * @see #setDebugFlags
197     */
198    public final static int DEBUG_LOG_GL_CALLS = 2;
199
200    /**
201     * Standard View constructor. In order to render something, you
202     * must call {@link #setRenderer} to register a renderer.
203     */
204    public GLSurfaceView(Context context) {
205        super(context);
206        init();
207    }
208
209    /**
210     * Standard View constructor. In order to render something, you
211     * must call {@link #setRenderer} to register a renderer.
212     */
213    public GLSurfaceView(Context context, AttributeSet attrs) {
214        super(context, attrs);
215        init();
216    }
217
218    private void init() {
219        // Install a SurfaceHolder.Callback so we get notified when the
220        // underlying surface is created and destroyed
221        SurfaceHolder holder = getHolder();
222        holder.addCallback(this);
223        holder.setFormat(PixelFormat.RGB_565);
224        // setType is not needed for SDK 2.0 or newer. Uncomment this
225        // statement if back-porting this code to older SDKs.
226        // holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
227    }
228
229    /**
230     * Set the glWrapper. If the glWrapper is not null, its
231     * {@link GLWrapper#wrap(GL)} method is called
232     * whenever a surface is created. A GLWrapper can be used to wrap
233     * the GL object that's passed to the renderer. Wrapping a GL
234     * object enables examining and modifying the behavior of the
235     * GL calls made by the renderer.
236     * <p>
237     * Wrapping is typically used for debugging purposes.
238     * <p>
239     * The default value is null.
240     * @param glWrapper the new GLWrapper
241     */
242    public void setGLWrapper(GLWrapper glWrapper) {
243        mGLWrapper = glWrapper;
244    }
245
246    /**
247     * Set the debug flags to a new value. The value is
248     * constructed by OR-together zero or more
249     * of the DEBUG_CHECK_* constants. The debug flags take effect
250     * whenever a surface is created. The default value is zero.
251     * @param debugFlags the new debug flags
252     * @see #DEBUG_CHECK_GL_ERROR
253     * @see #DEBUG_LOG_GL_CALLS
254     */
255    public void setDebugFlags(int debugFlags) {
256        mDebugFlags = debugFlags;
257    }
258
259    /**
260     * Get the current value of the debug flags.
261     * @return the current value of the debug flags.
262     */
263    public int getDebugFlags() {
264        return mDebugFlags;
265    }
266
267    /**
268     * Set the renderer associated with this view. Also starts the thread that
269     * will call the renderer, which in turn causes the rendering to start.
270     * <p>This method should be called once and only once in the life-cycle of
271     * a GLSurfaceView.
272     * <p>The following GLSurfaceView methods can only be called <em>before</em>
273     * setRenderer is called:
274     * <ul>
275     * <li>{@link #setEGLConfigChooser(boolean)}
276     * <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
277     * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
278     * </ul>
279     * <p>
280     * The following GLSurfaceView methods can only be called <em>after</em>
281     * setRenderer is called:
282     * <ul>
283     * <li>{@link #getRenderMode()}
284     * <li>{@link #onPause()}
285     * <li>{@link #onResume()}
286     * <li>{@link #queueEvent(Runnable)}
287     * <li>{@link #requestRender()}
288     * <li>{@link #setRenderMode(int)}
289     * </ul>
290     *
291     * @param renderer the renderer to use to perform OpenGL drawing.
292     */
293    public void setRenderer(Renderer renderer) {
294        checkRenderThreadState();
295        if (mEGLConfigChooser == null) {
296            mEGLConfigChooser = new SimpleEGLConfigChooser(true);
297        }
298        if (mEGLContextFactory == null) {
299            mEGLContextFactory = new DefaultContextFactory();
300        }
301        if (mEGLWindowSurfaceFactory == null) {
302            mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
303        }
304        mGLThread = new GLThread(renderer);
305        mGLThread.start();
306    }
307
308    /**
309     * Install a custom EGLContextFactory.
310     * <p>If this method is
311     * called, it must be called before {@link #setRenderer(Renderer)}
312     * is called.
313     * <p>
314     * If this method is not called, then by default
315     * a context will be created with no shared context and
316     * with a null attribute list.
317     */
318    public void setEGLContextFactory(EGLContextFactory factory) {
319        checkRenderThreadState();
320        mEGLContextFactory = factory;
321    }
322
323    /**
324     * Install a custom EGLWindowSurfaceFactory.
325     * <p>If this method is
326     * called, it must be called before {@link #setRenderer(Renderer)}
327     * is called.
328     * <p>
329     * If this method is not called, then by default
330     * a window surface will be created with a null attribute list.
331     */
332    public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
333        checkRenderThreadState();
334        mEGLWindowSurfaceFactory = factory;
335    }
336
337    /**
338     * Install a custom EGLConfigChooser.
339     * <p>If this method is
340     * called, it must be called before {@link #setRenderer(Renderer)}
341     * is called.
342     * <p>
343     * If no setEGLConfigChooser method is called, then by default the
344     * view will choose an EGLConfig that is compatible with the current
345     * android.view.Surface, with a depth buffer depth of
346     * at least 16 bits.
347     * @param configChooser
348     */
349    public void setEGLConfigChooser(EGLConfigChooser configChooser) {
350        checkRenderThreadState();
351        mEGLConfigChooser = configChooser;
352    }
353
354    /**
355     * Install a config chooser which will choose a config
356     * as close to 16-bit RGB as possible, with or without an optional depth
357     * buffer as close to 16-bits as possible.
358     * <p>If this method is
359     * called, it must be called before {@link #setRenderer(Renderer)}
360     * is called.
361     * <p>
362     * If no setEGLConfigChooser method is called, then by default the
363     * view will choose an RGB_565 surface with a depth buffer depth of
364     * at least 16 bits.
365     *
366     * @param needDepth
367     */
368    public void setEGLConfigChooser(boolean needDepth) {
369        setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
370    }
371
372    /**
373     * Install a config chooser which will choose a config
374     * with at least the specified depthSize and stencilSize,
375     * and exactly the specified redSize, greenSize, blueSize and alphaSize.
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 RGB_565 surface with a depth buffer depth of
382     * at least 16 bits.
383     *
384     */
385    public void setEGLConfigChooser(int redSize, int greenSize, int blueSize,
386            int alphaSize, int depthSize, int stencilSize) {
387        setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
388                blueSize, alphaSize, depthSize, stencilSize));
389    }
390
391    /**
392     * Inform the default EGLContextFactory and default EGLConfigChooser
393     * which EGLContext client version to pick.
394     * <p>Use this method to create an OpenGL ES 2.0-compatible context.
395     * Example:
396     * <pre class="prettyprint">
397     *     public MyView(Context context) {
398     *         super(context);
399     *         setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
400     *         setRenderer(new MyRenderer());
401     *     }
402     * </pre>
403     * <p>Note: Activities which require OpenGL ES 2.0 should indicate this by
404     * setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the activity's
405     * AndroidManifest.xml file.
406     * <p>If this method is called, it must be called before {@link #setRenderer(Renderer)}
407     * is called.
408     * <p>This method only affects the behavior of the default EGLContexFactory and the
409     * default EGLConfigChooser. If
410     * {@link #setEGLContextFactory(EGLContextFactory)} has been called, then the supplied
411     * EGLContextFactory is responsible for creating an OpenGL ES 2.0-compatible context.
412     * If
413     * {@link #setEGLConfigChooser(EGLConfigChooser)} has been called, then the supplied
414     * EGLConfigChooser is responsible for choosing an OpenGL ES 2.0-compatible config.
415     * @param version The EGLContext client version to choose. Use 2 for OpenGL ES 2.0
416     */
417    public void setEGLContextClientVersion(int version) {
418        checkRenderThreadState();
419        mEGLContextClientVersion = version;
420    }
421
422    /**
423     * Set the rendering mode. When renderMode is
424     * RENDERMODE_CONTINUOUSLY, the renderer is called
425     * repeatedly to re-render the scene. When renderMode
426     * is RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface
427     * is created, or when {@link #requestRender} is called. Defaults to RENDERMODE_CONTINUOUSLY.
428     * <p>
429     * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system performance
430     * by allowing the GPU and CPU to idle when the view does not need to be updated.
431     * <p>
432     * This method can only be called after {@link #setRenderer(Renderer)}
433     *
434     * @param renderMode one of the RENDERMODE_X constants
435     * @see #RENDERMODE_CONTINUOUSLY
436     * @see #RENDERMODE_WHEN_DIRTY
437     */
438    public void setRenderMode(int renderMode) {
439        mGLThread.setRenderMode(renderMode);
440    }
441
442    /**
443     * Get the current rendering mode. May be called
444     * from any thread. Must not be called before a renderer has been set.
445     * @return the current rendering mode.
446     * @see #RENDERMODE_CONTINUOUSLY
447     * @see #RENDERMODE_WHEN_DIRTY
448     */
449    public int getRenderMode() {
450        return mGLThread.getRenderMode();
451    }
452
453    /**
454     * Request that the renderer render a frame.
455     * This method is typically used when the render mode has been set to
456     * {@link #RENDERMODE_WHEN_DIRTY}, so that frames are only rendered on demand.
457     * May be called
458     * from any thread. Must not be called before a renderer has been set.
459     */
460    public void requestRender() {
461        mGLThread.requestRender();
462    }
463
464    /**
465     * This method is part of the SurfaceHolder.Callback interface, and is
466     * not normally called or subclassed by clients of GLSurfaceView.
467     */
468    public void surfaceCreated(SurfaceHolder holder) {
469        mGLThread.surfaceCreated();
470    }
471
472    /**
473     * This method is part of the SurfaceHolder.Callback interface, and is
474     * not normally called or subclassed by clients of GLSurfaceView.
475     */
476    public void surfaceDestroyed(SurfaceHolder holder) {
477        // Surface will be destroyed when we return
478        mGLThread.surfaceDestroyed();
479    }
480
481    /**
482     * This method is part of the SurfaceHolder.Callback interface, and is
483     * not normally called or subclassed by clients of GLSurfaceView.
484     */
485    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
486        mGLThread.onWindowResize(w, h);
487    }
488
489    /**
490     * Inform the view that the activity is paused. The owner of this view must
491     * call this method when the activity is paused. Calling this method will
492     * pause the rendering thread.
493     * Must not be called before a renderer has been set.
494     */
495    public void onPause() {
496        mGLThread.onPause();
497    }
498
499    /**
500     * Inform the view that the activity is resumed. The owner of this view must
501     * call this method when the activity is resumed. Calling this method will
502     * recreate the OpenGL display and resume the rendering
503     * thread.
504     * Must not be called before a renderer has been set.
505     */
506    public void onResume() {
507        mGLThread.onResume();
508    }
509
510    /**
511     * Queue a runnable to be run on the GL rendering thread. This can be used
512     * to communicate with the Renderer on the rendering thread.
513     * Must not be called before a renderer has been set.
514     * @param r the runnable to be run on the GL rendering thread.
515     */
516    public void queueEvent(Runnable r) {
517        mGLThread.queueEvent(r);
518    }
519
520    /**
521     * This method is used as part of the View class and is not normally
522     * called or subclassed by clients of GLSurfaceView.
523     * Must not be called before a renderer has been set.
524     */
525    @Override
526    protected void onDetachedFromWindow() {
527        super.onDetachedFromWindow();
528        mGLThread.requestExitAndWait();
529    }
530
531    // ----------------------------------------------------------------------
532
533    /**
534     * An interface used to wrap a GL interface.
535     * <p>Typically
536     * used for implementing debugging and tracing on top of the default
537     * GL interface. You would typically use this by creating your own class
538     * that implemented all the GL methods by delegating to another GL instance.
539     * Then you could add your own behavior before or after calling the
540     * delegate. All the GLWrapper would do was instantiate and return the
541     * wrapper GL instance:
542     * <pre class="prettyprint">
543     * class MyGLWrapper implements GLWrapper {
544     *     GL wrap(GL gl) {
545     *         return new MyGLImplementation(gl);
546     *     }
547     *     static class MyGLImplementation implements GL,GL10,GL11,... {
548     *         ...
549     *     }
550     * }
551     * </pre>
552     * @see #setGLWrapper(GLWrapper)
553     */
554    public interface GLWrapper {
555        /**
556         * Wraps a gl interface in another gl interface.
557         * @param gl a GL interface that is to be wrapped.
558         * @return either the input argument or another GL object that wraps the input argument.
559         */
560        GL wrap(GL gl);
561    }
562
563    /**
564     * A generic renderer interface.
565     * <p>
566     * The renderer is responsible for making OpenGL calls to render a frame.
567     * <p>
568     * GLSurfaceView clients typically create their own classes that implement
569     * this interface, and then call {@link GLSurfaceView#setRenderer} to
570     * register the renderer with the GLSurfaceView.
571     * <p>
572     * <h3>Threading</h3>
573     * The renderer will be called on a separate thread, so that rendering
574     * performance is decoupled from the UI thread. Clients typically need to
575     * communicate with the renderer from the UI thread, because that's where
576     * input events are received. Clients can communicate using any of the
577     * standard Java techniques for cross-thread communication, or they can
578     * use the {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
579     * <p>
580     * <h3>EGL Context Lost</h3>
581     * There are situations where the EGL rendering context will be lost. This
582     * typically happens when device wakes up after going to sleep. When
583     * the EGL context is lost, all OpenGL resources (such as textures) that are
584     * associated with that context will be automatically deleted. In order to
585     * keep rendering correctly, a renderer must recreate any lost resources
586     * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} method
587     * is a convenient place to do this.
588     *
589     *
590     * @see #setRenderer(Renderer)
591     */
592    public interface Renderer {
593        /**
594         * Called when the surface is created or recreated.
595         * <p>
596         * Called when the rendering thread
597         * starts and whenever the EGL context is lost. The EGL context will typically
598         * be lost when the Android device awakes after going to sleep.
599         * <p>
600         * Since this method is called at the beginning of rendering, as well as
601         * every time the EGL context is lost, this method is a convenient place to put
602         * code to create resources that need to be created when the rendering
603         * starts, and that need to be recreated when the EGL context is lost.
604         * Textures are an example of a resource that you might want to create
605         * here.
606         * <p>
607         * Note that when the EGL context is lost, all OpenGL resources associated
608         * with that context will be automatically deleted. You do not need to call
609         * the corresponding "glDelete" methods such as glDeleteTextures to
610         * manually delete these lost resources.
611         * <p>
612         * @param gl the GL interface. Use <code>instanceof</code> to
613         * test if the interface supports GL11 or higher interfaces.
614         * @param config the EGLConfig of the created surface. Can be used
615         * to create matching pbuffers.
616         */
617        void onSurfaceCreated(GL10 gl, EGLConfig config);
618
619        /**
620         * Called when the surface changed size.
621         * <p>
622         * Called after the surface is created and whenever
623         * the OpenGL ES surface size changes.
624         * <p>
625         * Typically you will set your viewport here. If your camera
626         * is fixed then you could also set your projection matrix here:
627         * <pre class="prettyprint">
628         * void onSurfaceChanged(GL10 gl, int width, int height) {
629         *     gl.glViewport(0, 0, width, height);
630         *     // for a fixed camera, set the projection too
631         *     float ratio = (float) width / height;
632         *     gl.glMatrixMode(GL10.GL_PROJECTION);
633         *     gl.glLoadIdentity();
634         *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
635         * }
636         * </pre>
637         * @param gl the GL interface. Use <code>instanceof</code> to
638         * test if the interface supports GL11 or higher interfaces.
639         * @param width
640         * @param height
641         */
642        void onSurfaceChanged(GL10 gl, int width, int height);
643
644        /**
645         * Called to draw the current frame.
646         * <p>
647         * This method is responsible for drawing the current frame.
648         * <p>
649         * The implementation of this method typically looks like this:
650         * <pre class="prettyprint">
651         * void onDrawFrame(GL10 gl) {
652         *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
653         *     //... other gl calls to render the scene ...
654         * }
655         * </pre>
656         * @param gl the GL interface. Use <code>instanceof</code> to
657         * test if the interface supports GL11 or higher interfaces.
658         */
659        void onDrawFrame(GL10 gl);
660    }
661
662    /**
663     * An interface for customizing the eglCreateContext and eglDestroyContext calls.
664     * <p>
665     * This interface must be implemented by clients wishing to call
666     * {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
667     */
668    public interface EGLContextFactory {
669        EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig);
670        void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
671    }
672
673    private class DefaultContextFactory implements EGLContextFactory {
674        private int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
675
676        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) {
677            int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion,
678                    EGL10.EGL_NONE };
679
680            return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
681                    mEGLContextClientVersion != 0 ? attrib_list : null);
682        }
683
684        public void destroyContext(EGL10 egl, EGLDisplay display,
685                EGLContext context) {
686            egl.eglDestroyContext(display, context);
687        }
688    }
689
690    /**
691     * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
692     * <p>
693     * This interface must be implemented by clients wishing to call
694     * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
695     */
696    public interface EGLWindowSurfaceFactory {
697        EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
698                Object nativeWindow);
699        void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
700    }
701
702    private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory {
703
704        public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
705                EGLConfig config, Object nativeWindow) {
706            return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
707        }
708
709        public void destroySurface(EGL10 egl, EGLDisplay display,
710                EGLSurface surface) {
711            egl.eglDestroySurface(display, surface);
712        }
713    }
714
715    /**
716     * An interface for choosing an EGLConfig configuration from a list of
717     * potential configurations.
718     * <p>
719     * This interface must be implemented by clients wishing to call
720     * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
721     */
722    public interface EGLConfigChooser {
723        /**
724         * Choose a configuration from the list. Implementors typically
725         * implement this method by calling
726         * {@link EGL10#eglChooseConfig} and iterating through the results. Please consult the
727         * EGL specification available from The Khronos Group to learn how to call eglChooseConfig.
728         * @param egl the EGL10 for the current display.
729         * @param display the current display.
730         * @return the chosen configuration.
731         */
732        EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
733    }
734
735    private abstract class BaseConfigChooser
736            implements EGLConfigChooser {
737        public BaseConfigChooser(int[] configSpec) {
738            mConfigSpec = filterConfigSpec(configSpec);
739        }
740
741        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
742            int[] num_config = new int[1];
743            if (!egl.eglChooseConfig(display, mConfigSpec, null, 0,
744                    num_config)) {
745                throw new IllegalArgumentException("eglChooseConfig failed");
746            }
747
748            int numConfigs = num_config[0];
749
750            if (numConfigs <= 0) {
751                throw new IllegalArgumentException(
752                        "No configs match configSpec");
753            }
754
755            EGLConfig[] configs = new EGLConfig[numConfigs];
756            if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
757                    num_config)) {
758                throw new IllegalArgumentException("eglChooseConfig#2 failed");
759            }
760            EGLConfig config = chooseConfig(egl, display, configs);
761            if (config == null) {
762                throw new IllegalArgumentException("No config chosen");
763            }
764            return config;
765        }
766
767        abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
768                EGLConfig[] configs);
769
770        protected int[] mConfigSpec;
771
772        private int[] filterConfigSpec(int[] configSpec) {
773            if (mEGLContextClientVersion != 2) {
774                return configSpec;
775            }
776            /* We know none of the subclasses define EGL_RENDERABLE_TYPE.
777             * And we know the configSpec is well formed.
778             */
779            int len = configSpec.length;
780            int[] newConfigSpec = new int[len + 2];
781            System.arraycopy(configSpec, 0, newConfigSpec, 0, len-1);
782            newConfigSpec[len-1] = EGL10.EGL_RENDERABLE_TYPE;
783            newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */
784            newConfigSpec[len+1] = EGL10.EGL_NONE;
785            return newConfigSpec;
786        }
787    }
788
789    /**
790     * Choose a configuration with exactly the specified r,g,b,a sizes,
791     * and at least the specified depth and stencil sizes.
792     */
793    private class ComponentSizeChooser extends BaseConfigChooser {
794        public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
795                int alphaSize, int depthSize, int stencilSize) {
796            super(new int[] {
797                    EGL10.EGL_RED_SIZE, redSize,
798                    EGL10.EGL_GREEN_SIZE, greenSize,
799                    EGL10.EGL_BLUE_SIZE, blueSize,
800                    EGL10.EGL_ALPHA_SIZE, alphaSize,
801                    EGL10.EGL_DEPTH_SIZE, depthSize,
802                    EGL10.EGL_STENCIL_SIZE, stencilSize,
803                    EGL10.EGL_NONE});
804            mValue = new int[1];
805            mRedSize = redSize;
806            mGreenSize = greenSize;
807            mBlueSize = blueSize;
808            mAlphaSize = alphaSize;
809            mDepthSize = depthSize;
810            mStencilSize = stencilSize;
811       }
812
813        @Override
814        public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
815                EGLConfig[] configs) {
816            for (EGLConfig config : configs) {
817                int d = findConfigAttrib(egl, display, config,
818                        EGL10.EGL_DEPTH_SIZE, 0);
819                int s = findConfigAttrib(egl, display, config,
820                        EGL10.EGL_STENCIL_SIZE, 0);
821                if ((d >= mDepthSize) && (s >= mStencilSize)) {
822                    int r = findConfigAttrib(egl, display, config,
823                            EGL10.EGL_RED_SIZE, 0);
824                    int g = findConfigAttrib(egl, display, config,
825                             EGL10.EGL_GREEN_SIZE, 0);
826                    int b = findConfigAttrib(egl, display, config,
827                              EGL10.EGL_BLUE_SIZE, 0);
828                    int a = findConfigAttrib(egl, display, config,
829                            EGL10.EGL_ALPHA_SIZE, 0);
830                    if ((r == mRedSize) && (g == mGreenSize)
831                            && (b == mBlueSize) && (a == mAlphaSize)) {
832                        return config;
833                    }
834                }
835            }
836            return null;
837        }
838
839        private int findConfigAttrib(EGL10 egl, EGLDisplay display,
840                EGLConfig config, int attribute, int defaultValue) {
841
842            if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
843                return mValue[0];
844            }
845            return defaultValue;
846        }
847
848        private int[] mValue;
849        // Subclasses can adjust these values:
850        protected int mRedSize;
851        protected int mGreenSize;
852        protected int mBlueSize;
853        protected int mAlphaSize;
854        protected int mDepthSize;
855        protected int mStencilSize;
856        }
857
858    /**
859     * This class will choose a RGB_565 surface with
860     * or without a depth buffer.
861     *
862     */
863    private class SimpleEGLConfigChooser extends ComponentSizeChooser {
864        public SimpleEGLConfigChooser(boolean withDepthBuffer) {
865            super(5, 6, 5, 0, withDepthBuffer ? 16 : 0, 0);
866        }
867    }
868
869    /**
870     * An EGL helper class.
871     */
872
873    private class EglHelper {
874        public EglHelper() {
875
876        }
877
878        /**
879         * Initialize EGL for a given configuration spec.
880         * @param configSpec
881         */
882        public void start() {
883            /*
884             * Get an EGL instance
885             */
886            mEgl = (EGL10) EGLContext.getEGL();
887
888            /*
889             * Get to the default display.
890             */
891            mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
892
893            if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
894                throw new RuntimeException("eglGetDisplay failed");
895            }
896
897            /*
898             * We can now initialize EGL for that display
899             */
900            int[] version = new int[2];
901            if(!mEgl.eglInitialize(mEglDisplay, version)) {
902                throw new RuntimeException("eglInitialize failed");
903            }
904            mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
905
906            /*
907            * Create an EGL context. We want to do this as rarely as we can, because an
908            * EGL context is a somewhat heavy object.
909            */
910            mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
911            if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
912                throwEglException("createContext");
913            }
914
915            mEglSurface = null;
916        }
917
918        /*
919         * React to the creation of a new surface by creating and returning an
920         * OpenGL interface that renders to that surface.
921         */
922        public GL createSurface(SurfaceHolder holder) {
923            /*
924             *  The window size has changed, so we need to create a new
925             *  surface.
926             */
927            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
928
929                /*
930                 * Unbind and destroy the old EGL surface, if
931                 * there is one.
932                 */
933                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
934                        EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
935                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
936            }
937
938            /*
939             * Create an EGL surface we can render into.
940             */
941            mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
942                    mEglDisplay, mEglConfig, holder);
943
944            if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
945                throwEglException("createWindowSurface");
946            }
947
948            /*
949             * Before we can issue GL commands, we need to make sure
950             * the context is current and bound to a surface.
951             */
952            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
953                throwEglException("eglMakeCurrent");
954            }
955
956            GL gl = mEglContext.getGL();
957            if (mGLWrapper != null) {
958                gl = mGLWrapper.wrap(gl);
959            }
960
961            if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
962                int configFlags = 0;
963                Writer log = null;
964                if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
965                    configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
966                }
967                if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
968                    log = new LogWriter();
969                }
970                gl = GLDebugHelper.wrap(gl, configFlags, log);
971            }
972            return gl;
973        }
974
975        /**
976         * Display the current render surface.
977         * @return false if the context has been lost.
978         */
979        public boolean swap() {
980            mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
981
982            /*
983             * Always check for EGL_CONTEXT_LOST, which means the context
984             * and all associated data were lost (For instance because
985             * the device went to sleep). We need to sleep until we
986             * get a new surface.
987             */
988            return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
989        }
990
991        public void destroySurface() {
992            if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
993                mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
994                        EGL10.EGL_NO_SURFACE,
995                        EGL10.EGL_NO_CONTEXT);
996                mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface);
997                mEglSurface = null;
998            }
999        }
1000
1001        public void finish() {
1002            if (mEglContext != null) {
1003                mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext);
1004                mEglContext = null;
1005            }
1006            if (mEglDisplay != null) {
1007                mEgl.eglTerminate(mEglDisplay);
1008                mEglDisplay = null;
1009            }
1010        }
1011
1012        private void throwEglException(String function) {
1013            throw new RuntimeException(function + " failed: " + mEgl.eglGetError());
1014        }
1015
1016        EGL10 mEgl;
1017        EGLDisplay mEglDisplay;
1018        EGLSurface mEglSurface;
1019        EGLConfig mEglConfig;
1020        EGLContext mEglContext;
1021
1022    }
1023
1024    /**
1025     * A generic GL Thread. Takes care of initializing EGL and GL. Delegates
1026     * to a Renderer instance to do the actual drawing. Can be configured to
1027     * render continuously or on request.
1028     *
1029     * All potentially blocking synchronization is done through the
1030     * sGLThreadManager object. This avoids multiple-lock ordering issues.
1031     *
1032     */
1033    class GLThread extends Thread {
1034        GLThread(Renderer renderer) {
1035            super();
1036            mWidth = 0;
1037            mHeight = 0;
1038            mRequestRender = true;
1039            mRenderMode = RENDERMODE_CONTINUOUSLY;
1040            mRenderer = renderer;
1041        }
1042
1043
1044        @Override
1045        public void run() {
1046            setName("GLThread " + getId());
1047            if (LOG_THREADS) {
1048                Log.i("GLThread", "starting tid=" + getId());
1049            }
1050
1051            try {
1052                guardedRun();
1053            } catch (InterruptedException e) {
1054                // fall thru and exit normally
1055            } finally {
1056                sGLThreadManager.threadExiting(this);
1057            }
1058        }
1059
1060        /*
1061         * This private method should only be called inside a
1062         * synchronized(sGLThreadManager) block.
1063         */
1064        private void stopEglSurfaceLocked() {
1065            if (mHaveEglSurface) {
1066                mHaveEglSurface = false;
1067                mEglHelper.destroySurface();
1068            }
1069        }
1070
1071        /*
1072         * This private method should only be called inside a
1073         * synchronized(sGLThreadManager) block.
1074         */
1075        private void stopEglContextLocked() {
1076            if (mHaveEglContext) {
1077                mEglHelper.finish();
1078                mHaveEglContext = false;
1079                sGLThreadManager.releaseEglContextLocked(this);
1080            }
1081        }
1082        private void guardedRun() throws InterruptedException {
1083            mEglHelper = new EglHelper();
1084            mHaveEglContext = false;
1085            mHaveEglSurface = false;
1086            try {
1087                GL10 gl = null;
1088                boolean createEglContext = false;
1089                boolean createEglSurface = false;
1090                boolean lostEglContext = false;
1091                boolean sizeChanged = false;
1092                boolean wantRenderNotification = false;
1093                boolean doRenderNotification = false;
1094                int w = 0;
1095                int h = 0;
1096                Runnable event = null;
1097
1098                while (true) {
1099                    synchronized (sGLThreadManager) {
1100                        while (true) {
1101                            if (mShouldExit) {
1102                                return;
1103                            }
1104
1105                            if (! mEventQueue.isEmpty()) {
1106                                event = mEventQueue.remove(0);
1107                                break;
1108                            }
1109
1110                            // Have we lost the EGL context?
1111                            if (lostEglContext) {
1112                                stopEglSurfaceLocked();
1113                                stopEglContextLocked();
1114                                lostEglContext = false;
1115                            }
1116
1117                            // Do we need to release the EGL surface?
1118                            if (mHaveEglSurface && mPaused) {
1119                                if (LOG_SURFACE) {
1120                                    Log.i("GLThread", "releasing EGL surface because paused tid=" + getId());
1121                                }
1122                                stopEglSurfaceLocked();
1123                                if (sGLThreadManager.shouldReleaseEGLContextWhenPausing()) {
1124                                    stopEglContextLocked();
1125                                    if (LOG_SURFACE) {
1126                                        Log.i("GLThread", "releasing EGL context because paused tid=" + getId());
1127                                    }
1128                                }
1129                            }
1130
1131                            // Have we lost the surface view surface?
1132                            if ((! mHasSurface) && (! mWaitingForSurface)) {
1133                                if (LOG_SURFACE) {
1134                                    Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId());
1135                                }
1136                                if (mHaveEglSurface) {
1137                                    stopEglSurfaceLocked();
1138                                }
1139                                mWaitingForSurface = true;
1140                                sGLThreadManager.notifyAll();
1141                            }
1142
1143                            // Have we acquired the surface view surface?
1144                            if (mHasSurface && mWaitingForSurface) {
1145                                if (LOG_SURFACE) {
1146                                    Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId());
1147                                }
1148                                mWaitingForSurface = false;
1149                                sGLThreadManager.notifyAll();
1150                            }
1151
1152                            if (doRenderNotification) {
1153                                wantRenderNotification = false;
1154                                doRenderNotification = false;
1155                                mRenderComplete = true;
1156                                sGLThreadManager.notifyAll();
1157                            }
1158
1159                            // Ready to draw?
1160                            if ((!mPaused) && mHasSurface
1161                                && (mWidth > 0) && (mHeight > 0)
1162                                && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) {
1163
1164                                // If we don't have an EGL context, try to acquire one.
1165                                if ((! mHaveEglContext) && sGLThreadManager.tryAcquireEglContextLocked(this)) {
1166                                    mHaveEglContext = true;
1167                                    createEglContext = true;
1168                                    mEglHelper.start();
1169
1170                                    sGLThreadManager.notifyAll();
1171                                }
1172
1173                                if (mHaveEglContext && !mHaveEglSurface) {
1174                                    mHaveEglSurface = true;
1175                                    createEglSurface = true;
1176                                    sizeChanged = true;
1177                                }
1178
1179                                if (mHaveEglSurface) {
1180                                    if (mSizeChanged) {
1181                                        sizeChanged = true;
1182                                        w = mWidth;
1183                                        h = mHeight;
1184                                        wantRenderNotification = true;
1185
1186                                        if (DRAW_TWICE_AFTER_SIZE_CHANGED) {
1187                                            // We keep mRequestRender true so that we draw twice after the size changes.
1188                                            // (Once because of mSizeChanged, the second time because of mRequestRender.)
1189                                            // This forces the updated graphics onto the screen.
1190                                        } else {
1191                                            mRequestRender = false;
1192                                        }
1193                                        mSizeChanged = false;
1194                                    } else {
1195                                        mRequestRender = false;
1196                                    }
1197                                    sGLThreadManager.notifyAll();
1198                                    break;
1199                                }
1200                            }
1201
1202                            // By design, this is the only place in a GLThread thread where we wait().
1203                            if (LOG_THREADS) {
1204                                Log.i("GLThread", "waiting tid=" + getId());
1205                            }
1206                            sGLThreadManager.wait();
1207                        }
1208                    } // end of synchronized(sGLThreadManager)
1209
1210                    if (event != null) {
1211                        event.run();
1212                        event = null;
1213                        continue;
1214                    }
1215
1216                    if (createEglSurface) {
1217                        if (LOG_SURFACE) {
1218                            Log.w("GLThread", "egl createSurface");
1219                        }
1220                        gl = (GL10) mEglHelper.createSurface(getHolder());
1221                        sGLThreadManager.checkGLDriver(gl);
1222                        createEglSurface = false;
1223                    }
1224
1225                    if (createEglContext) {
1226                        if (LOG_RENDERER) {
1227                            Log.w("GLThread", "onSurfaceCreated");
1228                        }
1229                        mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig);
1230                        createEglContext = false;
1231                    }
1232
1233                    if (sizeChanged) {
1234                        if (LOG_RENDERER) {
1235                            Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")");
1236                        }
1237                        mRenderer.onSurfaceChanged(gl, w, h);
1238                        sizeChanged = false;
1239                    }
1240
1241                    if (LOG_RENDERER_DRAW_FRAME) {
1242                        Log.w("GLThread", "onDrawFrame");
1243                    }
1244                    mRenderer.onDrawFrame(gl);
1245                    if (!mEglHelper.swap()) {
1246                        if (LOG_SURFACE) {
1247                            Log.i("GLThread", "egl context lost tid=" + getId());
1248                        }
1249                        lostEglContext = true;
1250                    }
1251
1252                    if (wantRenderNotification) {
1253                        doRenderNotification = true;
1254                    }
1255                }
1256
1257            } finally {
1258                /*
1259                 * clean-up everything...
1260                 */
1261                synchronized (sGLThreadManager) {
1262                    stopEglSurfaceLocked();
1263                    stopEglContextLocked();
1264                }
1265            }
1266        }
1267
1268        public void setRenderMode(int renderMode) {
1269            if ( !((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY)) ) {
1270                throw new IllegalArgumentException("renderMode");
1271            }
1272            synchronized(sGLThreadManager) {
1273                mRenderMode = renderMode;
1274                sGLThreadManager.notifyAll();
1275            }
1276        }
1277
1278        public int getRenderMode() {
1279            synchronized(sGLThreadManager) {
1280                return mRenderMode;
1281            }
1282        }
1283
1284        public void requestRender() {
1285            synchronized(sGLThreadManager) {
1286                mRequestRender = true;
1287                sGLThreadManager.notifyAll();
1288            }
1289        }
1290
1291        public void surfaceCreated() {
1292            synchronized(sGLThreadManager) {
1293                if (LOG_THREADS) {
1294                    Log.i("GLThread", "surfaceCreated tid=" + getId());
1295                }
1296                mHasSurface = true;
1297                sGLThreadManager.notifyAll();
1298            }
1299        }
1300
1301        public void surfaceDestroyed() {
1302            synchronized(sGLThreadManager) {
1303                if (LOG_THREADS) {
1304                    Log.i("GLThread", "surfaceDestroyed tid=" + getId());
1305                }
1306                mHasSurface = false;
1307                sGLThreadManager.notifyAll();
1308                while((!mWaitingForSurface) && (!mExited)) {
1309                    try {
1310                        sGLThreadManager.wait();
1311                    } catch (InterruptedException e) {
1312                        Thread.currentThread().interrupt();
1313                    }
1314                }
1315            }
1316        }
1317
1318        public void onPause() {
1319            synchronized (sGLThreadManager) {
1320                mPaused = true;
1321                sGLThreadManager.notifyAll();
1322            }
1323        }
1324
1325        public void onResume() {
1326            synchronized (sGLThreadManager) {
1327                mPaused = false;
1328                mRequestRender = true;
1329                sGLThreadManager.notifyAll();
1330            }
1331        }
1332
1333        public void onWindowResize(int w, int h) {
1334            synchronized (sGLThreadManager) {
1335                mWidth = w;
1336                mHeight = h;
1337                mSizeChanged = true;
1338                mRequestRender = true;
1339                mRenderComplete = false;
1340                sGLThreadManager.notifyAll();
1341
1342                // Wait for thread to react to resize and render a frame
1343                while (! mExited && !mPaused && !mRenderComplete ) {
1344                    if (LOG_SURFACE) {
1345                        Log.i("Main thread", "onWindowResize waiting for render complete.");
1346                    }
1347                    try {
1348                        sGLThreadManager.wait();
1349                    } catch (InterruptedException ex) {
1350                        Thread.currentThread().interrupt();
1351                    }
1352                }
1353            }
1354        }
1355
1356        public void requestExitAndWait() {
1357            // don't call this from GLThread thread or it is a guaranteed
1358            // deadlock!
1359            synchronized(sGLThreadManager) {
1360                mShouldExit = true;
1361                sGLThreadManager.notifyAll();
1362                while (! mExited) {
1363                    try {
1364                        sGLThreadManager.wait();
1365                    } catch (InterruptedException ex) {
1366                        Thread.currentThread().interrupt();
1367                    }
1368                }
1369            }
1370        }
1371
1372        /**
1373         * Queue an "event" to be run on the GL rendering thread.
1374         * @param r the runnable to be run on the GL rendering thread.
1375         */
1376        public void queueEvent(Runnable r) {
1377            if (r == null) {
1378                throw new IllegalArgumentException("r must not be null");
1379            }
1380            synchronized(sGLThreadManager) {
1381                mEventQueue.add(r);
1382                sGLThreadManager.notifyAll();
1383            }
1384        }
1385
1386        // Once the thread is started, all accesses to the following member
1387        // variables are protected by the sGLThreadManager monitor
1388        private boolean mShouldExit;
1389        private boolean mExited;
1390        private boolean mPaused;
1391        private boolean mHasSurface;
1392        private boolean mWaitingForSurface;
1393        private boolean mHaveEglContext;
1394        private boolean mHaveEglSurface;
1395        private int mWidth;
1396        private int mHeight;
1397        private int mRenderMode;
1398        private boolean mRequestRender;
1399        private boolean mRenderComplete;
1400        private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
1401
1402        // End of member variables protected by the sGLThreadManager monitor.
1403
1404        private Renderer mRenderer;
1405        private EglHelper mEglHelper;
1406    }
1407
1408    static class LogWriter extends Writer {
1409
1410        @Override public void close() {
1411            flushBuilder();
1412        }
1413
1414        @Override public void flush() {
1415            flushBuilder();
1416        }
1417
1418        @Override public void write(char[] buf, int offset, int count) {
1419            for(int i = 0; i < count; i++) {
1420                char c = buf[offset + i];
1421                if ( c == '\n') {
1422                    flushBuilder();
1423                }
1424                else {
1425                    mBuilder.append(c);
1426                }
1427            }
1428        }
1429
1430        private void flushBuilder() {
1431            if (mBuilder.length() > 0) {
1432                Log.v("GLSurfaceView", mBuilder.toString());
1433                mBuilder.delete(0, mBuilder.length());
1434            }
1435        }
1436
1437        private StringBuilder mBuilder = new StringBuilder();
1438    }
1439
1440
1441    private void checkRenderThreadState() {
1442        if (mGLThread != null) {
1443            throw new IllegalStateException(
1444                    "setRenderer has already been called for this instance.");
1445        }
1446    }
1447
1448    private static class GLThreadManager {
1449        private static String TAG = "GLThreadManager";
1450
1451        public synchronized void threadExiting(GLThread thread) {
1452            if (LOG_THREADS) {
1453                Log.i("GLThread", "exiting tid=" +  thread.getId());
1454            }
1455            thread.mExited = true;
1456            if (mEglOwner == thread) {
1457                mEglOwner = null;
1458            }
1459            notifyAll();
1460        }
1461
1462        /*
1463         * Tries once to acquire the right to use an EGL
1464         * context. Does not block. Requires that we are already
1465         * in the sGLThreadManager monitor when this is called.
1466         *
1467         * @return true if the right to use an EGL context was acquired.
1468         */
1469        public boolean tryAcquireEglContextLocked(GLThread thread) {
1470            if (mEglOwner == thread || mEglOwner == null) {
1471                mEglOwner = thread;
1472                notifyAll();
1473                return true;
1474            }
1475            checkGLESVersion();
1476            if (mMultipleGLESContextsAllowed) {
1477                return true;
1478            }
1479            return false;
1480        }
1481
1482        /*
1483         * Releases the EGL context. Requires that we are already in the
1484         * sGLThreadManager monitor when this is called.
1485         */
1486        public void releaseEglContextLocked(GLThread thread) {
1487            if (mEglOwner == thread) {
1488                mEglOwner = null;
1489            }
1490            notifyAll();
1491        }
1492
1493        public synchronized boolean shouldReleaseEGLContextWhenPausing() {
1494            checkGLESVersion();
1495            return !mMultipleGLESContextsAllowed;
1496        }
1497
1498        public synchronized void checkGLDriver(GL10 gl) {
1499            if (! mGLESDriverCheckComplete) {
1500                checkGLESVersion();
1501                if (mGLESVersion < kGLES_20) {
1502                    String renderer = gl.glGetString(GL10.GL_RENDERER);
1503                    mMultipleGLESContextsAllowed =
1504                        ! renderer.startsWith(kMSM7K_RENDERER_PREFIX);
1505                    if (LOG_SURFACE) {
1506                        Log.w(TAG, "checkGLDriver renderer = \"" + renderer + "\" multipleContextsAllowed = "
1507                            + mMultipleGLESContextsAllowed);
1508                    }
1509                    notifyAll();
1510                }
1511                mGLESDriverCheckComplete = true;
1512            }
1513        }
1514
1515        private void checkGLESVersion() {
1516            if (! mGLESVersionCheckComplete) {
1517                mGLESVersion = SystemProperties.getInt(
1518                        "ro.opengles.version",
1519                        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1520                if (mGLESVersion >= kGLES_20) {
1521                    mMultipleGLESContextsAllowed = true;
1522                }
1523                if (LOG_SURFACE) {
1524                    Log.w(TAG, "checkGLESVersion mGLESVersion =" +
1525                            " " + mGLESVersion + " mMultipleGLESContextsAllowed = " + mMultipleGLESContextsAllowed);
1526                }
1527                mGLESVersionCheckComplete = true;
1528            }
1529        }
1530
1531        private boolean mGLESVersionCheckComplete;
1532        private int mGLESVersion;
1533        private boolean mGLESDriverCheckComplete;
1534        private boolean mMultipleGLESContextsAllowed;
1535        private static final int kGLES_20 = 0x20000;
1536        private static final String kMSM7K_RENDERER_PREFIX =
1537            "Q3Dimension MSM7500 ";
1538        private GLThread mEglOwner;
1539    }
1540
1541    private static final GLThreadManager sGLThreadManager = new GLThreadManager();
1542    private boolean mSizeChanged = true;
1543
1544    private GLThread mGLThread;
1545    private EGLConfigChooser mEGLConfigChooser;
1546    private EGLContextFactory mEGLContextFactory;
1547    private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
1548    private GLWrapper mGLWrapper;
1549    private int mDebugFlags;
1550    private int mEGLContextClientVersion;
1551}
1552