/lib/pods/SDLx/Controller.pod

http://github.com/PerlGameDev/SDL · Unknown · 277 lines · 190 code · 87 blank · 0 comment · 0 complexity · 3ffc3e39c85652d292984dc3d83e1d85 MD5 · raw file

  1. =head1 NAME
  2. SDLx::Controller - Handles the loops for events, movement and rendering
  3. =head1 CATEGORY
  4. Extension, Controller
  5. =head1 SYNOPSIS
  6. use SDLx::Controller;
  7. # create our controller object
  8. my $app = SDLx::Controller->new;
  9. # we could also do:
  10. my $app = SDLx::App->new;
  11. # because App is also a controller
  12. # register some callbacks
  13. $app->add_event_handler( \&on_event );
  14. $app->add_move_handler( \&on_move );
  15. $app->add_show_handler( \&on_show );
  16. # run our game loop
  17. $app->run;
  18. =head2 DESCRIPTION
  19. The core of an SDL application/game is the main loop, where you handle events
  20. and display your elements on the screen until something signals the end of
  21. the program. This usually goes in the form of:
  22. while (1) {
  23. ...
  24. }
  25. The problem most developers face, besides the repetitive work, is to ensure
  26. the screen update is independent of the frame rate. Otherwise, your game will
  27. run at different speeds on different machines and this is never good (old
  28. MS-DOS games, anyone?).
  29. One way to circumvent this is by capping the frame rate so it's the same no
  30. matter what, but this is not the right way to do it as it penalizes better
  31. hardware.
  32. This module provides an industry-proven standard for frame independent
  33. movement. It calls the movement handlers based on time (hi-res seconds) rather
  34. than frame rate. You can add/remove handlers and control your main loop with
  35. ease.
  36. =head1 METHODS
  37. =head2 new
  38. SDLx::Controller->new(
  39. dt => 0.5,
  40. min_t => 0,
  41. event => $event_object,
  42. );
  43. The C<dt> parameter specifies the length, in seconds, of a full movement step, and defaults to 0.1.
  44. The C<dt> can be anything and the game can still look the same.
  45. It is only when you change the C<dt> without changing all the things in the movement step that are being multiplied by the first move argument that it will make a difference.
  46. If you lower the C<dt>, everything will move faster than it did with it set higher, and vice-versa.
  47. This is useful to add slo-mo and fast-forward features to the game, all you would have to do is change the C<dt>.
  48. C<min_t> specifies the minimum time, in seconds, that has to accumulate before any move or show handlers are called, and defaults to 1 / 60.
  49. Having the C<min_t> at 1 / 60 ensures that the controller can update the screen at a maximum of 60 times per second.
  50. A "V-Sync" such as this is necessary to prevent video "tear", which occurs when the app is updating faster than the monitor can display.
  51. Setting it to 0, as seen above, will let the app run as fast as it possibly can.
  52. C<delay> specifies a loop delay in millisecs to place on the controller loop. B<NOTE:> Picking a good delay based on the needs can help reduce CPU load and pressure.
  53. C<event> is a SDL::Event object that events going to the event callbacks are polled in to. It defaults to C<< SDL::Event->new() >>.
  54. All parameters are optional.
  55. Returns the new object.
  56. =head2 run
  57. After creating and setting up your handlers (see below), call this method to
  58. activate the main loop. The main loop will run until C<stop> is called.
  59. All hooked functions will be called during the main loop, in this order:
  60. =over 4
  61. =item 1. Events
  62. =item 2. Movements
  63. =item 3. Displaying
  64. =back
  65. Please refer to each handler below for information on received arguments.
  66. Note that the second argument every callback receives is the C<SDLx::Controller> object.
  67. =head2 stop
  68. Returns from the C<run> loop.
  69. =head2 pause
  70. Attempts to pause the application with a call to C<SDL::Events::wait_event>. See L<SDL::Events>.
  71. Takes 1 argument which is a callback. The application waits for the next event with C<wait_event>.
  72. When one is received, it is passed to the callback as the first argument, along with the C<SDLx::Controller> object as the second argument.
  73. If the callback then returns a true value, C<pause> will return.
  74. If the callback returns a false value, C<pause> will repeat the process.
  75. This can be used to easily implement a pause when the app loses focus:
  76. sub window {
  77. my ($e, $app) = @_;
  78. if($e->type == SDL_QUIT) {
  79. $app->stop;
  80. # quit handling is here so that the app
  81. # can be stopped while paused
  82. }
  83. elsif($e->type == SDL_ACTIVEEVENT) {
  84. if($e->active_state & SDL_APPINPUTFOCUS) {
  85. if($e->active_gain) {
  86. return 1;
  87. }
  88. else {
  89. $app->pause(\&window);
  90. # recursive, but only once since the window
  91. # can't lose focus again without gaining it first
  92. }
  93. }
  94. }
  95. return 0;
  96. }
  97. Note: if you implement your own pause function, remember to update C<current_time> to the current time when the application unpauses.
  98. This should be done with C<Time::HiRes::time>.
  99. Otherwise, time will accumulate while the application is paused, and many movement steps will be called all at once when it unpauses.
  100. Note 2: a pause will be potentially dangerous to the C<run> cycle (even if you implement your own) unless called by an C<event> callback.
  101. =head2 paused
  102. Returns 1 if the app is paused, undef otherwise.
  103. This is only useful when used within code that will be run by C<pause>:
  104. sub pause {
  105. # press P to toggle pause
  106. my ($e, $app) = @_;
  107. if($e->type == SDL_QUIT) {
  108. $app->stop;
  109. # quit handling is here so that the app
  110. # can be stopped while paused
  111. }
  112. elsif($e->type == SDL_KEYDOWN) {
  113. if($e->key_sym == SDLK_p) {
  114. # We're paused, so end pause
  115. return 1 if $app->paused;
  116. # We're not paused, so pause
  117. $app->pause(\&pause);
  118. }
  119. }
  120. return 0;
  121. }
  122. =head2 add_event_handler
  123. Register a callback to handle events. You can add as many subs as you need.
  124. Whenever a SDL::Event occurs, all registered callbacks will be triggered in
  125. order. Returns the order queue number of the added callback.
  126. The first argument passed to registered callbacks is the L<< SDL::Event >> object.
  127. The second is the C<SDLx::Controller> object.
  128. sub stop {
  129. my ($event, $app) = @_;
  130. if($event->type == SDL_QUIT) {
  131. $app->stop;
  132. }
  133. }
  134. $app->add_event_handler(\&stop);
  135. =head2 add_move_handler
  136. Register a callback to update your objects. You can add as many subs as
  137. you need. Returns the order queue number of the added callback.
  138. All registered callbacks will be triggered in order for as many C<dt> as have happened between calls,
  139. and once more for any remaining time less than C<dt>.
  140. The first argument passed to the callbacks is the portion of the step, which will be 1 for a full step, and less than 1 for a partial step.
  141. Movement values should be multiplied by this value.
  142. The full steps correspond to the amount of C<dt> passed between calls, and the partial step corresponds to the call with the remaining time less than C<dt>.
  143. The argument can be 0 if no time has passed since the last cycle. If you need to protect against this, set a C<min_t>, or put a C<< return unless $_[0] >> at the start of every move handler.
  144. The second argument passed to the callbacks is the C<SDLx::Controller> object.
  145. The third is the total amount of time passed since the call of C<run>.
  146. You should use these handlers to update your in-game objects, check collisions, etc.
  147. so you can check and/or update it as necessary.
  148. sub move_ball {
  149. my ($step, $app, $t) = @_;
  150. $ball->move_x( $ball->x_vel * $step );
  151. $ball->move_y( $ball->y_vel * $step );
  152. }
  153. =head2 add_show_handler
  154. Register a callback to render objects. You can add as many subs as you need.
  155. Returns the order queue number of the added callback.
  156. All registered callbacks will be triggered in order, once per run of the C<run> loop.
  157. The first argument passed is the time, in seconds, since the previous call.
  158. The second is the C<SDLx::Controller> object.
  159. sub show_ball {
  160. my ($delta, $app) = @_;
  161. $app->draw_rect(
  162. [ $ball->x, $ball->y, $ball->size, $ball->size ],
  163. $ball->colour
  164. );
  165. }
  166. =head2 remove_move_handler( $index )
  167. =head2 remove_event_handler( $index )
  168. =head2 remove_show_handler( $index )
  169. Removes the handler with the given index from the respective calling queue.
  170. You can also pass a coderef.
  171. The first coderef in the handler list that this matches will be removed.
  172. Returns the removed handler.
  173. =head2 remove_all_move_handlers
  174. =head2 remove_all_event_handlers
  175. =head2 remove_all_show_handlers
  176. Removes all handlers from the respective calling queue.
  177. =head2 remove_all_handlers
  178. Quick access to removing all handlers at once.
  179. =head2 dt
  180. =head2 min_t
  181. =head2 current_time
  182. If an argument is passed, modifies the corresponding value to the argument.
  183. C<dt> and C<min_t> will keep their old value until the beginning of the next C<run> cycle.
  184. Returns the corresponding value.
  185. =head1 AUTHORS
  186. See L<SDL/AUTHORS>.
  187. =head2 ACKNOWLEDGEMENTS
  188. The idea and base for this module comes from Lazy Foo's L<< Frame Independent
  189. Movement|http://www.lazyfoo.net/SDL_tutorials/lesson32/index.php >> tutorial,
  190. and Glenn Fiedler's L<< Fix Your Timestep|http://gafferongames.com/game-physics/fix-your-timestep/ >> article on timing.