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