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