1page.title=Game Loops
2@jd:body
3
4<!--
5    Copyright 2014 The Android Open Source Project
6
7    Licensed under the Apache License, Version 2.0 (the "License");
8    you may not use this file except in compliance with the License.
9    You may obtain a copy of the License at
10
11        http://www.apache.org/licenses/LICENSE-2.0
12
13    Unless required by applicable law or agreed to in writing, software
14    distributed under the License is distributed on an "AS IS" BASIS,
15    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16    See the License for the specific language governing permissions and
17    limitations under the License.
18-->
19<div id="qv-wrapper">
20  <div id="qv">
21    <h2>In this document</h2>
22    <ol id="auto-toc">
23    </ol>
24  </div>
25</div>
26
27<p>A very popular way to implement a game loop looks like this:</p>
28
29<pre>
30while (playing) {
31    advance state by one frame
32    render the new frame
33    sleep until it’s time to do the next frame
34}
35</pre>
36
37<p>There are a few problems with this, the most fundamental being the idea that the
38game can define what a "frame" is.  Different displays will refresh at different
39rates, and that rate may vary over time.  If you generate frames faster than the
40display can show them, you will have to drop one occasionally.  If you generate
41them too slowly, SurfaceFlinger will periodically fail to find a new buffer to
42acquire and will re-show the previous frame.  Both of these situations can
43cause visible glitches.</p>
44
45<p>What you need to do is match the display's frame rate, and advance game state
46according to how much time has elapsed since the previous frame.  There are two
47ways to go about this: (1) stuff the BufferQueue full and rely on the "swap
48buffers" back-pressure; (2) use Choreographer (API 16+).</p>
49
50<h2 id=stuffing>Queue stuffing</h2>
51
52<p>This is very easy to implement: just swap buffers as fast as you can.  In early
53versions of Android this could actually result in a penalty where
54<code>SurfaceView#lockCanvas()</code> would put you to sleep for 100ms.  Now
55it's paced by the BufferQueue, and the BufferQueue is emptied as quickly as
56SurfaceFlinger is able.</p>
57
58<p>One example of this approach can be seen in <a
59href="https://code.google.com/p/android-breakout/">Android Breakout</a>.  It
60uses GLSurfaceView, which runs in a loop that calls the application's
61onDrawFrame() callback and then swaps the buffer.  If the BufferQueue is full,
62the <code>eglSwapBuffers()</code> call will wait until a buffer is available.
63Buffers become available when SurfaceFlinger releases them, which it does after
64acquiring a new one for display.  Because this happens on VSYNC, your draw loop
65timing will match the refresh rate.  Mostly.</p>
66
67<p>There are a couple of problems with this approach.  First, the app is tied to
68SurfaceFlinger activity, which is going to take different amounts of time
69depending on how much work there is to do and whether it's fighting for CPU time
70with other processes.  Since your game state advances according to the time
71between buffer swaps, your animation won't update at a consistent rate.  When
72running at 60fps with the inconsistencies averaged out over time, though, you
73probably won't notice the bumps.</p>
74
75<p>Second, the first couple of buffer swaps are going to happen very quickly
76because the BufferQueue isn't full yet.  The computed time between frames will
77be near zero, so the game will generate a few frames in which nothing happens.
78In a game like Breakout, which updates the screen on every refresh, the queue is
79always full except when a game is first starting (or un-paused), so the effect
80isn't noticeable.  A game that pauses animation occasionally and then returns to
81as-fast-as-possible mode might see odd hiccups.</p>
82
83<h2 id=choreographer>Choreographer</h2>
84
85<p>Choreographer allows you to set a callback that fires on the next VSYNC.  The
86actual VSYNC time is passed in as an argument.  So even if your app doesn't wake
87up right away, you still have an accurate picture of when the display refresh
88period began.  Using this value, rather than the current time, yields a
89consistent time source for your game state update logic.</p>
90
91<p>Unfortunately, the fact that you get a callback after every VSYNC does not
92guarantee that your callback will be executed in a timely fashion or that you
93will be able to act upon it sufficiently swiftly.  Your app will need to detect
94situations where it's falling behind and drop frames manually.</p>
95
96<p>The "Record GL app" activity in Grafika provides an example of this.  On some
97devices (e.g. Nexus 4 and Nexus 5), the activity will start dropping frames if
98you just sit and watch.  The GL rendering is trivial, but occasionally the View
99elements get redrawn, and the measure/layout pass can take a very long time if
100the device has dropped into a reduced-power mode.  (According to systrace, it
101takes 28ms instead of 6ms after the clocks slow on Android 4.4.  If you drag
102your finger around the screen, it thinks you're interacting with the activity,
103so the clock speeds stay high and you'll never drop a frame.)</p>
104
105<p>The simple fix was to drop a frame in the Choreographer callback if the current
106time is more than N milliseconds after the VSYNC time.  Ideally the value of N
107is determined based on previously observed VSYNC intervals.  For example, if the
108refresh period is 16.7ms (60fps), you might drop a frame if you're running more
109than 15ms late.</p>
110
111<p>If you watch "Record GL app" run, you will see the dropped-frame counter
112increase, and even see a flash of red in the border when frames drop.  Unless
113your eyes are very good, though, you won't see the animation stutter.  At 60fps,
114the app can drop the occasional frame without anyone noticing so long as the
115animation continues to advance at a constant rate.  How much you can get away
116with depends to some extent on what you're drawing, the characteristics of the
117display, and how good the person using the app is at detecting jank.</p>
118
119<h2 id=thread>Thread management</h2>
120
121<p>Generally speaking, if you're rendering onto a SurfaceView, GLSurfaceView, or
122TextureView, you want to do that rendering in a dedicated thread.  Never do any
123"heavy lifting" or anything that takes an indeterminate amount of time on the
124UI thread.</p>
125
126<p>Breakout and "Record GL app" use dedicated renderer threads, and they also
127update animation state on that thread.  This is a reasonable approach so long as
128game state can be updated quickly.</p>
129
130<p>Other games separate the game logic and rendering completely.  If you had a
131simple game that did nothing but move a block every 100ms, you could have a
132dedicated thread that just did this:</p>
133
134<pre>
135    run() {
136        Thread.sleep(100);
137        synchronized (mLock) {
138            moveBlock();
139        }
140    }
141</pre>
142
143<p>(You may want to base the sleep time off of a fixed clock to prevent drift --
144sleep() isn't perfectly consistent, and moveBlock() takes a nonzero amount of
145time -- but you get the idea.)</p>
146
147<p>When the draw code wakes up, it just grabs the lock, gets the current position
148of the block, releases the lock, and draws.  Instead of doing fractional
149movement based on inter-frame delta times, you just have one thread that moves
150things along and another thread that draws things wherever they happen to be
151when the drawing starts.</p>
152
153<p>For a scene with any complexity you'd want to create a list of upcoming events
154sorted by wake time, and sleep until the next event is due, but it's the same
155idea.</p>
156