Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 15
Текст из файла (страница 15)
This makes the threads thatdo need actually need to run more responsive, because they don’t haveto compete for a time slice. And when no threads need to run, SymbianOS can enter a power-saving state where all threads are suspended, thusoptimizing the battery life.Games, and other applications with constantly changing graphics,have different requirements to the event-driven applications describedabove, because they must continue to execute regularly in order toupdate their graphics and perform other calculations (such as detectingcollisions or displaying countdown timers on their screens).
For a gameto execute regularly, regardless of the user input received, it is driven bywhat is known as a game loop, which is a loop that runs regularly for theduration of the game.Typically, each time the game loop runs:• The time elapsed since the last time the game loop executed iscalculated, and any user input that has occurred since then is retrieved.• The game engine updates the game internals, taking into accountfactors such as the time elapsed and the user input received.For example, in a game like Asteroids,1 the user’s key presses are usedto calculate the new position of the player’s ship, based on the actualinput received and the time that has passed since the last graphicsupdate. Besides making calculations to correspond to the player’sinput, the game engine also computes the new positions of all othermoving graphics elements relative to the time of the last redraw.
The1See developer.symbian.com/roidsgame for a paper which describes writing an Asteroids clone for Symbian OS v9.THE GAME LOOP45game engine must determine if there have been any collisions betweenthe graphics elements and calculate their resulting status, such as theirvisibility (Have they moved off screen? Is one asteroid overlapping theothers? Has a collision broken an asteroid into fragments?), and theirchanges in shape or color. The game engine also calculates statusvalues, such as the player’s score or the ammunition available.• The screen is updated according to the new state calculated by thegame engine.Having calculated the internal game state to reflect the new positionsand status of each game object, the game engine prepares the nextimage to display on the screen to reflect those changes.
Once the newframe is prepared, it is drawn to the screen. Each time the screen isupdated, the new image displayed is known as a frame. The numberof frames written to the screen per second is known as the frame rate.The higher the number of frames per second (fps), the smoother thegraphics transitions appear, so a desirable frame rate is a high onein games with rapidly changing graphics. However, the exact figuredepends on the game in question, affected by factors such as theamount of processing required to generate the next frame and thegenre of game, since some games, such as turn-based games, do notrequire a high frame rate.• The game’s audio (background music and sound effects) are synchronized with the game state.For example, the sound of an explosion is played if the latest gameupdate calculated that a collision occurred.Figure 2.1 shows this graphically, while in pseudocode, a basic gameloop can be expressed as follows:while ( game is running ){calculate time elapsed and retrieve user inputupdate game internalsupdate graphics (prepare frame, draw frame)synchronize sound}Note that a constantly running game loop is not necessary in everygame.
While it is needed for a game with frequently changing graphicsin order to update the display, some games are more like typical eventdriven applications. A turn-based game, like chess, may not need a gameloop to run all the time, but can be driven by user input. The loop startsrunning when a turn is taken, to update the graphics to reflect the move,and calculate the AI’s response, then returns to waiting on an event toindicate the user’s next move or other input, such as deciding to quit thegame.46SYMBIAN OS GAME BASICSCalculate time elapsedRetrieve user inputUpdate game internalsLOOPUpdate graphicsSynchronize audioFigure 2.1A graphical representation of a game loop2.3 The Heartbeat TimerOn Symbian OS, it is important not to hog the CPU so you should notrun a tight synchronous loop like the one shown in pseudocode above.The game loop must return control to the thread’s active scheduler toallow other system events to run as necessary, allowing other threads inthe system the opportunity to run.
If the game loop prevents the activescheduler from running a particular active object associated with the viewserver regularly, between 10 and 20 seconds, the infamous EVwsViewEventTimeOut panic occurs. This terminates the game thread withpanic category ViewSrv and error code 11.So instead of trying to work around this, on Symbian OS, a game loopshould be run using a timer active object, such as CTimer or CPeriodic,to trigger the game loop to run regularly.
It is better to use a single timer torun one iteration of the game loop than to use multiple timers to controldifferent time-based events in the game. The latter approach can lead tovery complex code, since there may be many elements in a game thatrespond after different timeouts have expired, which would be difficultto synchronize and to debug. Active objects cannot be pre-empted, sothe accuracy of a timer active object is also dependent on other activeobjects in the system. If multiple timers are used for different events, thecombination could lead to significant timer drift for some lower-priorityactive objects. Additionally, each timer consumes kernel resources – if alarge number are required, this could add up to an undesirable systemoverhead.THE HEARTBEAT TIMER47The solution is to use a single timer object to provide a game ‘heartbeat.’All elements of the game that require a particular time-based activity usethe heartbeat to synchronize themselves.
The timer fires as many timesper second as necessary to achieve the desired frame rate. Each time thetimer fires, it runs the game loop once, and increments a stored valueknown as the tick count. The tick count is used to provide the timeelapsed to the rest of the game.The resulting pseudocode for the game loop looks as follows, whereTimerEventHandler() is the method called once every heartbeat tohandle the timer event:TimerEventHandler(){calculate the time elapsed and retrieve user inputupdate game internalsupdate graphics (prepare frame, draw frame)synchronize sound}One of the benefits of using a single heartbeat timer is that the beatrate can easily be slowed down for debugging purposes, stopped entirelywhen the game needs to pause, or tweaked to modify the frame rate whenthe graphics performance differs across a range of devices with differentcapabilities.The CPeriodic timer is used most commonly to drive a game loop.It uses a callback function to execute the game loop on each heartbeat.CPeriodic is the simplest class to use to provide a timer without cominginto direct contact with active objects because it hides the details of theactive object framework (it derives from CTimer – an active objectbased timer class – and implements the active object methods RunL()and DoCancel() for its callers).
The Skeleton example uses this class,as shown below. However, if you already use a number of active objectsin your game, you may simply prefer to use the CTimer class directly.void CSkeletonAppView::ConstructL( const TRect& aRect ){...// Create the heartbeat timer for the game loop.iPeriodicTimer = CPeriodic::NewL(CActive::EPriorityStandard);// Activate the window (calls StartHeartbeat())ActivateL();}void CSkeletonAppView::StartHeartbeat(){// Start the CPeriodic timer, passing the Tick() method for callbackif (!iPeriodicTimer->IsActive())iPeriodicTimer->Start(KFramesPerSecond, KFramesPerSecond,TCallBack(CSkeletonAppView::Tick, this));}48SYMBIAN OS GAME BASICS// Tick() callback methodTInt CSkeletonAppView::Tick(TAny* aCallback){ASSERT(aCallback);static_cast<CSkeletonAppView*>(aCallback)->GameLoop();// Return a value of ETrue to continue loopingreturn ETrue;}void CSkeletonAppView::GameLoop(){// Update the game internals - details omitted here}As I mentioned above, because Symbian OS active objects cannotbe pre-empted, if another active object event is being handled whenthe timer expires, the timer callback is blocked until the other eventhandler completes.
The timer’s event processing is delayed, and the timerrequest is not rescheduled until it runs. This means that periodic timersare susceptible to drift, and will give a frame rate slightly lower thanexpected. Additionally on Symbian OS v9, the standard timer resolutionis 1/64 seconds (15.625 milliseconds) on both hardware and the emulator.So, for example, if you request a period of 20 milliseconds, you actuallyreceive an event approximately once every 30 milliseconds (that is,2 × 15.625 milliseconds).
What’s more, if you’ve just missed a 1/64th‘tick’ when you submitted the timer, then it’ll only be submitted on thenext tick, which means that the first period will be almost 3 × 15.625(=48.875) milliseconds. This can add up to a significant jitter.As an example, in the Skeleton example, I set the timer period to be1/30 second (33.3 milliseconds), which at first sight could be expected todeliver 30 fps The frame rate actually observed was relatively constant at22 fps occasionally dropping to 21 fps. To deliver 30 fps, I would needto increase the period and add in logic to see how much time has passedbetween each tick, and then compensate for it when rescheduling thetimer.Symbian OS does actually provide a heartbeat timer class, calledCHeartBeat to do this.