GameHandler.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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: 1, // 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. bDrawDebugBufferBounds: false, // Should the secondary buffer's bounds be drawn?
  36. prevMillis: 0, // Milliseconds ellapsed since the begining of the application.
  37. delta: 0, // Milliseconds ellapsed since the last frame.
  38. db: null, // Object to hold the secondary buffer.
  39. dbWidth: 1920, // Width of the secondary buffer.
  40. dbHeight: 1080, // Height of the secondary buffer.
  41. isMobile: null, // True if the device is a mobile device (tablet of phone).
  42. pixelDen: 1, // Pixel density for the canvas on destop devices.
  43. pixelDenMobile: 2, // Pixel denisty for the canvas on mobile devices.
  44. mouseX: 0, // X position of the mouse relative to the secondary buffer.
  45. mouseY: 0, // Y position of the mouse relative to the secondary buffer.
  46. backgroundColor: null, // Default color to be drawn to the background.
  47. /**
  48. * Sets the initial game render mode.
  49. *
  50. * @param {RENDER_MODES} mode RENDER_MODES.P2D for default P5Js render or
  51. * RENDER_MODES.WEBGL for webgl (not recomended for mobile).
  52. */
  53. setRenderMode(mode)
  54. {
  55. this.renderMode = mode;
  56. },
  57. /**
  58. * Sets the width and height in pixels to initialize the secondary buffer.
  59. *
  60. * @param {number} w width in pixels to initialize the secondary buffer.
  61. * @param {number} h height in pixels to initialize the secondary buffer.
  62. */
  63. setDoubleBufferSize(w, h)
  64. {
  65. this.dbWidth = w;
  66. this.dbHeight = h;
  67. },
  68. /**
  69. * Sets the pixel density for the canvas to be initialized with on desktop
  70. * devices.
  71. *
  72. * @param {number} val pixel density for the canvas on desktop devices.
  73. */
  74. setPixelDensity(val)
  75. {
  76. this.pixelDen = val;
  77. },
  78. /**
  79. * Sets the pixel density for the canvas to be initialized with on desktop
  80. * devices.
  81. *
  82. * @param {number} val pixel density for the canvas on desktop devices.
  83. */
  84. setPixelDensityMobile(val)
  85. {
  86. this.pixelDenMobile = val;
  87. },
  88. /**
  89. * Sets the default color to be drawn to the main buffer's background.
  90. *
  91. * @param {Color} col new background color;
  92. */
  93. setBackgroundColor(col)
  94. {
  95. this.backgroundColor = col;
  96. },
  97. /**
  98. * Sets the flag to draw the debug fps.
  99. *
  100. * @param {boolean} val true if debug fps should be drawn, false if not.
  101. */
  102. drawDebugFPS(val)
  103. {
  104. this.bDrawDebugFPS = val;
  105. },
  106. /**
  107. * Sets the flag to draw secondary buffer bounds.
  108. *
  109. * @param {boolean} val true if debug secondary buffer bounds should be drawn, false if not.
  110. */
  111. drawDebugBufferBounds(val)
  112. {
  113. this.bDrawDebugBufferBounds = val;
  114. },
  115. /**
  116. * Initializes the game, creating the canvas, secondary buffer, and creates the
  117. * debug fps label if necessary.
  118. *
  119. * @param {number} fps target fps for the game (default if 60).
  120. */
  121. init(fps = 60)
  122. {
  123. // Sets the mobile flag.
  124. this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  125. // Creates the main canvas and the secondary buffer with the specified size and render mode.
  126. switch (this.renderMode)
  127. {
  128. case RENDER_MODES.P2D:
  129. createCanvas(windowWidth, windowHeight);
  130. this.db = createGraphics(this.dbWidth, this.dbHeight);
  131. break;
  132. case RENDER_MODES.WEBGL:
  133. createCanvas(windowWidth, windowHeight, WEBGL);
  134. this.db = createGraphics(this.dbWidth, this.dbHeight, WEBGL);
  135. this.db.smooth();
  136. break;
  137. }
  138. // Sets framerate and pixel density accordingly.
  139. frameRate(fps);
  140. if (this.isMobile)
  141. pixelDensity(this.pixelDenMobile);
  142. else
  143. pixelDensity(this.pixelDen);
  144. smooth();
  145. // Translates the canvas to the middle if render mode is webgl to maintain
  146. // consistency on the coordinate system.
  147. if (this.renderMode == RENDER_MODES.WEBGL)
  148. {
  149. translate(-windowWidth / 2, -windowHeight / 2);
  150. db.translate(-this.dbWidth / 2, -this.dbHeight / 2);
  151. }
  152. // Creates the debug fps label.
  153. if (this.bDrawDebugFPS)
  154. {
  155. this.debugFpsLabel = new Label("debugFps", `FPS: ${frameRate()}`);
  156. this.addRootObject(this.debugFpsLabel);
  157. }
  158. },
  159. /**
  160. * Instances a GameObject, meaning to give it an ID. This function is only called on the
  161. * constructor of GameObject, and probably shouldn't be used for anything else.
  162. *
  163. * @param {GameObject} obj GameObject to be instanced.
  164. */
  165. instanceGameObject(obj)
  166. {
  167. obj.id = this.nextId;
  168. this.nextId++;
  169. },
  170. /**
  171. * Adds a GameObject to the root of the tree. There should be as little root objects as possible.
  172. *
  173. * @param {GameObject} obj GameObject to be added as a root of the tree.
  174. */
  175. addRootObject(obj)
  176. {
  177. this.rootObjects.push(obj);
  178. obj.isRoot = true;
  179. obj.setup();
  180. },
  181. /**
  182. * Removes a GameObject from the root of the tree. This function is called automatically when a root object
  183. * is freed from memory, and probably shoudn't be used for anything else. DOES NOT DELETE THE OBJECT, ONLY
  184. * REMOVES IT FROM THE TREE.
  185. *
  186. * @param {number} id object id of the GameObject that should be removed from the tree.
  187. */
  188. removeRootObjectById(id)
  189. {
  190. for (let i = 0; i < this.rootObjects.length; i++)
  191. {
  192. if (this.rootObjects[i].id == id)
  193. this.rootObjects.splice(i, 1);
  194. }
  195. },
  196. upframecount: 0, // Frame count to be displayed.
  197. upframenum: 20, // Delay in frames to update the frame count.
  198. /**
  199. * Updates all of the GameObjects on the tree.
  200. */
  201. update()
  202. {
  203. // Updates the debug fps label if it existis.
  204. if (this.bDrawDebugFPS)
  205. {
  206. if (frameCount % this.upframenum == 0)
  207. {
  208. this.debugFpsLabel.setText(`FPS: ${
  209. Math.round(this.upframecount * 1000) / 1000
  210. }`);
  211. this.upframecount = 0;
  212. }
  213. else
  214. this.upframecount = max(this.upframecount, frameRate());
  215. }
  216. // Updates the delta.
  217. this.delta = (millis() - this.prevMillis) / 1000;
  218. let ar = this.db.screenWidth / this.db.width;
  219. let offsetx = (windowWidth - this.db.screenWidth) / 2;
  220. let offsety = (windowHeight - this.db.screenHeight) / 2;
  221. this.mouseX = (mouseX - offsetx) / ar;
  222. this.mouseY = (mouseY - offsety) / ar;
  223. // Updates all game objects on the tree.
  224. for (let i = 0; i < this.rootObjects.length; i++)
  225. this.rootObjects[i].update(this.delta);
  226. },
  227. /**
  228. * Draws all of the GameObjects on the tree.
  229. */
  230. draw()
  231. {
  232. // Clear the secondary buffer.
  233. this.db.clear();
  234. if (this.bDrawDebugBufferBounds)
  235. {
  236. // Draw a rectangle to visualize the secondary buffer.
  237. this.db.push();
  238. this.db.strokeWeight(5);
  239. this.db.noFill();
  240. this.db.rect(0, 0, this.dbWidth, this.dbHeight);
  241. this.db.pop();
  242. }
  243. // Centers the image and calculates the dimensions of the secondary
  244. // buffer to best fit the size of the window.
  245. imageMode(CENTER);
  246. if (windowWidth / windowHeight < this.dbWidth / this.dbHeight)
  247. {
  248. this.db.screenWidth = windowWidth;
  249. this.db.screenHeight = windowWidth * (this.dbHeight / this.dbWidth);
  250. }
  251. else
  252. {
  253. this.db.screenHeight = windowHeight;
  254. this.db.screenWidth = windowHeight * (this.dbWidth / this.dbHeight);
  255. }
  256. // Draw all game objects.
  257. for (let i = 0; i < this.rootObjects.length; i++)
  258. this.rootObjects[i].draw(this.delta, this.db);
  259. // Draws the secondary buffer to the main canvas.
  260. image(this.db, windowWidth / 2, windowHeight / 2, this.db.screenWidth, this.db.screenHeight);
  261. // Updates the delta
  262. this.prevMillis = millis();
  263. },
  264. /**
  265. * ! This function should be overriden, it provides no default functionality.
  266. * This function is called once when the page loads, and should be used by the user to load
  267. * assets and other forms of data that need to be already loaded when the prorgam starts.
  268. *
  269. * @callback
  270. */
  271. _preload()
  272. {
  273. },
  274. /**
  275. * ! This function should be overriden, it provides no default functionality.
  276. * This function is called once when the program starts, and should be used by the user to
  277. * initialize any necessary aspects of the game.
  278. *
  279. * @callback
  280. */
  281. _setup()
  282. {
  283. },
  284. }
  285. /**
  286. * This function is called once when the page loads. Serves to load assets and other
  287. * data that needs to be loaded when the program starts.
  288. *
  289. * @callback
  290. */
  291. function preload()
  292. {
  293. GameHandler._preload();
  294. }
  295. /**
  296. * This function is called once at the start of the program. Serves to initialize several
  297. * aspects of the game.
  298. *
  299. * @callback
  300. */
  301. function setup()
  302. {
  303. GameHandler._setup();
  304. GameHandler.init();
  305. }
  306. /**
  307. * This function is called once every frame. Serves to update and draw all GameObjects.
  308. *
  309. * @callback
  310. */
  311. function draw()
  312. {
  313. if (GameHandler.backgroundColor)
  314. background(GameHandler.backgroundColor.getP5Color());
  315. else
  316. background(200);
  317. GameHandler.update();
  318. GameHandler.draw();
  319. }
  320. /**
  321. * This function is called once every time the browser window is resized. Here, its used to make the game
  322. * always ocupy the entire browser window.
  323. *
  324. * @callback
  325. */
  326. function windowResized()
  327. {
  328. resizeCanvas(windowWidth, windowHeight);
  329. }