GameHandler.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /************************************************************************
  2. * GameHandler.js
  3. ************************************************************************
  4. * Copyright (c) 2021 Pedro Tonini Rosenberg Schneider.
  5. *
  6. * This file is part of Pandora.
  7. *
  8. * Pandora is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * Pandora is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with Pandora. If not, see <https://www.gnu.org/licenses/>.
  20. *************************************************************************/
  21. /**
  22. * This {@code GameHandler} singleton provides an interface for the user
  23. * to manipulate various parameters of the game, instance objects, and more.
  24. *
  25. * @author Pedro Schneider
  26. *
  27. * @namespace
  28. */
  29. const GameHandler = {
  30. nextId: 0, // ID to be given to the next object added to the tree.
  31. rootObjects: [], // List of objects on the root of the tree.
  32. renderMode: RENDER_MODES.P2D, // Can be RENDER_MODES.P2D or RENDER_MODES.WEBGL.
  33. bDrawDebugFPS: false, // Should fps be drawn (for debug only).
  34. debugFpsLabel: null, // Object that drwas fps.
  35. prevMillis: 0, // Milliseconds ellapsed since the begining of the application.
  36. delta: 0, // Milliseconds ellapsed since the last frame.
  37. db: null, // Object to hold the secondary buffer.
  38. dbWidth: 1920, // Width of the secondary buffer.
  39. dbHeight: 1080, // Height of the secondary buffer.
  40. isMobile: null, // True if the device is a mobile device (tablet of phone).
  41. pixelDen: 1, // Pixel density for the canvas on destop devices.
  42. pixelDenMobile: 2, // Pixel denisty for the canvas on mobile devices.
  43. /**
  44. * Sets the initial game render mode.
  45. *
  46. * @param {RENDER_MODES} mode RENDER_MODES.P2D for default P5Js render or
  47. * RENDER_MODES.WEBGL for webgl (not recomended for mobile).
  48. */
  49. setRenderMode: function(mode)
  50. {
  51. this.renderMode = mode;
  52. },
  53. /**
  54. * Sets the width and height in pixels to initialize the secondary buffer.
  55. *
  56. * @param {number} w width in pixels to initialize the secondary buffer.
  57. * @param {number} h height in pixels to initialize the secondary buffer.
  58. */
  59. setDoubleBufferSize: function(w, h)
  60. {
  61. this.dbWidth = w;
  62. this.dbHeight = h;
  63. },
  64. /**
  65. * Sets the pixel density for the canvas to be initialized with on desktop
  66. * devices.
  67. *
  68. * @param {number} val pixel density for the canvas on desktop devices.
  69. */
  70. setPixelDensity: function(val)
  71. {
  72. this.pixelDen = val;
  73. },
  74. /**
  75. * Sets the pixel density for the canvas to be initialized with on desktop
  76. * devices.
  77. *
  78. * @param {number} val pixel density for the canvas on desktop devices.
  79. */
  80. setPixelDensityMobile: function(val)
  81. {
  82. this.pixelDenMobile = val;
  83. },
  84. /**
  85. * Sets the flag to draw the debug fps.
  86. *
  87. * @param {boolean} val true if debug fps should be drawn, false if not.
  88. */
  89. drawDebugFPS(val)
  90. {
  91. this.bDrawDebugFPS = val;
  92. },
  93. /**
  94. * Initializes the game, creating the canvas, secondary buffer, and creates the
  95. * debug fps label if necessary.
  96. *
  97. * @param {number} fps target fps for the game (default if 60).
  98. */
  99. init: function(fps = 60)
  100. {
  101. // Sets the mobile flag.
  102. this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  103. // Creates the main canvas and the secondary buffer with the specified size and render mode.
  104. switch (this.renderMode)
  105. {
  106. case RENDER_MODES.P2D:
  107. createCanvas(windowWidth, windowHeight);
  108. this.db = createGraphics(this.dbWidth, this.dbHeight);
  109. break;
  110. case RENDER_MODES.WEBGL:
  111. createCanvas(windowWidth, windowHeight, WEBGL);
  112. this.db = createGraphics(this.dbWidth, this.dbHeight, WEBGL);
  113. this.db.smooth();
  114. break;
  115. }
  116. // Sets framerate and pixel density accordingly.
  117. frameRate(fps);
  118. if (this.isMobile)
  119. pixelDensity(this.pixelDenMobile);
  120. else
  121. pixelDensity(this.pixelDen);
  122. smooth();
  123. // Translates the canvas to the middle if render mode is webgl to maintain
  124. // consistency on the coordinate system.
  125. if (this.renderMode == RENDER_MODES.WEBGL)
  126. {
  127. translate(-windowWidth / 2, -windowHeight / 2);
  128. db.translate(-this.dbWidth / 2, -this.dbHeight / 2);
  129. }
  130. // Creates the debug fps label.
  131. if (this.bDrawDebugFPS)
  132. {
  133. this.debugFpsLabel = new Label("debugFps", `FPS: ${frameRate()}`);
  134. this.addRootObject(this.debugFpsLabel);
  135. }
  136. },
  137. /**
  138. * Instances a GameObject, meaning to give it an ID. This function is only called on the
  139. * constructor of GameObject, and probably shouldn't be used for anything else.
  140. *
  141. * @param {GameObject} obj GameObject to be instanced.
  142. */
  143. instanceGameObject: function(obj)
  144. {
  145. obj.id = this.nextId;
  146. this.nextId++;
  147. },
  148. /**
  149. * Adds a GameObject to the root of the tree. There should be as little root objects as possible.
  150. *
  151. * @param {GameObject} obj GameObject to be added as a root of the tree.
  152. */
  153. addRootObject: function(obj)
  154. {
  155. this.rootObjects.push(obj);
  156. obj.isRoot = true;
  157. obj.setup();
  158. },
  159. /**
  160. * Removes a GameObject from the root of the tree. This function is called automatically when a root object
  161. * is freed from memory, and probably shoudn't be used for anything else. DOES NOT DELETE THE OBJECT, ONLY
  162. * REMOVES IT FROM THE TREE.
  163. *
  164. * @param {number} id object id of the GameObject that should be removed from the tree.
  165. */
  166. removeRootObjectById: function(id)
  167. {
  168. for (let i = 0; i < this.rootObjects.length; i++)
  169. {
  170. if (this.rootObjects[i].id == id)
  171. this.rootObjects.splice(i, 1);
  172. }
  173. },
  174. upframecount: 0, // Frame count to be displayed.
  175. upframenum: 20, // Delay in frames to update the frame count.
  176. /**
  177. * Updates all of the GameObjects on the tree.
  178. */
  179. update: function()
  180. {
  181. // Updates the debug fps label if it existis.
  182. if (this.bDrawDebugFPS)
  183. {
  184. if (frameCount % this.upframenum == 0)
  185. {
  186. this.debugFpsLabel.setText(`FPS: ${
  187. Math.round(this.upframecount * 1000) / 1000
  188. }`);
  189. this.upframecount = 0;
  190. }
  191. else
  192. this.upframecount = max(this.upframecount, frameRate());
  193. }
  194. // Updates the delta.
  195. this.delta = (millis() - this.prevMillis) / 1000;
  196. // Updates all game objects on the tree.
  197. for (let i = 0; i < this.rootObjects.length; i++)
  198. this.rootObjects[i].update(this.delta);
  199. },
  200. /**
  201. * Draws all of the GameObjects on the tree.
  202. */
  203. draw: function()
  204. {
  205. // Clear the secondary buffer.
  206. this.db.clear();
  207. // Draw all game objects.
  208. for (let i = 0; i < this.rootObjects.length; i++)
  209. this.rootObjects[i].draw(this.delta, this.db);
  210. // Draw a rectangle to visualize the secondary buffer.
  211. // TODO: remove this
  212. this.db.push();
  213. this.db.strokeWeight(5);
  214. this.db.noFill();
  215. this.db.rect(0, 0, this.dbWidth, this.dbHeight);
  216. this.db.pop();
  217. // Centers the image and calculates the dimensions of the secondary
  218. // buffer to best fit the size of the window.
  219. imageMode(CENTER);
  220. if (windowWidth / windowHeight < this.dbWidth / this.dbHeight)
  221. {
  222. this.db.screenWidth = windowWidth;
  223. this.db.screenHeight = windowWidth * (this.dbHeight / this.dbWidth);
  224. }
  225. else
  226. {
  227. this.db.screenHeight = windowHeight;
  228. this.db.screenWidth = windowHeight * (this.dbWidth / this.dbHeight);
  229. }
  230. // Draws the secondary buffer to the main canvas.
  231. image(this.db, windowWidth / 2, windowHeight / 2, this.db.screenWidth, this.db.screenHeight);
  232. // Updates the delta
  233. this.prevMillis = millis();
  234. }
  235. }
  236. /**
  237. * @callback
  238. * This function is called once every time the browser window is resized. Here, its used to make the game
  239. * always ocupy the entire browser window.
  240. */
  241. function windowResized()
  242. {
  243. resizeCanvas(windowWidth, windowHeight);
  244. }