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