Masaryk University Faculty of Informatics

2D web based

Bachelor’s Thesis

Martin Petýrek

Brno, Spring 2016 Acknowledgement

I would like to thank my advisor RNDr. Barbora Kozlíková, Ph.D. for her counsel and the time we spent on this thesis.

iii Abstract

The goal of this thesis is to create a custom game engine, inspired by features of other engines that are favored by game developers. The result of this thesis should be an easy to use engine which will target simple games and will be easily portable to mobile platforms. It will also feature a with tutorials on how to start developing, short code samples for individual features of the engine and also complete games. Full API documentation will also be available on the website.

iv Keywords game engine, Javascript, Type Script, HTML5.

v Contents

1 Introduction ...... 1 2 Existing solutions ...... 3 2.1 PhaserJS ...... 3 2.2 SFML ...... 4 2.3 LibGDX ...... 5 2.4 Unity3D ...... 5 3 mini2d.js Engine ...... 7 3.1 Technologies for multi platform web games ...... 7 3.1.1 Hybrid applications ...... 8 3.2 Differences from other solutions ...... 8 3.2.1 Mobile first approach ...... 8 3.2.2 TypeScript ...... 8 3.2.3 Canvas vs. WebGL ...... 9 3.3 Performance ...... 10 3.3.1 SVG ...... 10 3.3.2 Exporting to mobile platforms ...... 11 3.3.3 Resolution ...... 12 3.3.4 Avoiding bad practices ...... 12 4 Design of mini2d.js ...... 15 4.1 Classes hierarchy ...... 15 4.1.1 Game class ...... 15 4.1.2 Game states ...... 15 4.1.3 World and UI ...... 17 4.1.4 Sound ...... 17 4.1.5 Physics ...... 17 4.1.6 Resources ...... 17 4.1.7 Other classes ...... 17 4.2 Development tools ...... 18 4.2.1 JavaScript preprocessors ...... 18 4.2.2 Task runners ...... 19 5 Implementation ...... 23 5.1 Game states ...... 23 5.2 Resource manager ...... 24 5.3 Input ...... 24 5.4 Audio ...... 25

vii 5.5 Camera ...... 25 5.6 Interfaces ...... 26 5.6.1 Destroyable ...... 26 5.6.2 Drawable ...... 26 5.6.3 Measurable ...... 26 5.7 UI ...... 27 5.7.1 Text ...... 27 5.7.2 Button ...... 27 5.8 Graphics ...... 28 5.9 Physics ...... 28 5.9.1 CollisionEngine ...... 28 5.9.2 CollisionDetector ...... 29 5.9.3 CollisionSolver ...... 29 5.9.4 Body ...... 29 5.10 Documentation ...... 30 5.11 JavaDoc ...... 30 5.12 TypeDoc ...... 30 6 mini2d.js web page ...... 31 6.1 Examples ...... 31 6.2 Tutorials ...... 31 6.3 Documentation ...... 33 7 Conclusion ...... 35 Bibliography ...... 37

viii 1 Introduction

Mobile platforms have grown to the size they are now and have already outgrown other platforms. One could argue that they have pretty much reached the point where nothing significant will ever emerge and therefore the market has become stagnant. There has also been a big shift from traditional devices such as personal computers and laptops. Nowadays more and more people have settled for a mobile device to fulfill their everyday electronic needs. Not only has the market shifted from desktop to mobile devices, it has also been steering towards the web platforms, which despite all their limitations have many advantages. These advantages allow the to write the software once and run it virtually everywhere from a smart phone to a smart TV all the way to the desktop computer. The main difference has always been the performance. However, we are now getting to the state where the performance is sufficient for simple games and therefore HTML51 has become a viable alternative to the classical approach of /C++ powered engines. And that is the kind of games we will focus on in this thesis. The types of games, that do not require the heavyweight solutions already on the market, crafted to suit the needs of every developer, which are impossible to be used by someone without a prior experi- ence. We are going to focus on simple games, that would not benefit from using an engine under normal circumstances. However, the web is well known for its different behavior on different browsers and platforms. The aim is to write an engine, that will take care of all the inconveniences tied with building mobile games on the web platform and focus on actually developing and designing the game, not dealing with problems related to portability. The goal is to create an engine everyone can use with ease. For those aspiring to more complex games, there are already very sophisticated and well documented engines with big commu- nities (Unity3D is a great example of such an engine, more on these

1. HTML5 – markup language for the web, fifth and current standard bringing key enhancements to canvas element used for 2D games.

1 1. Introduction later). However, building such a complex system is not the goal of this thesis. This engine will be called mini2d.js and is intended to be stripped of all the unnecessary features which many of these engines offer. This engine aims for portability, consistency, and simplicity. It will feature well described examples showcasing every feature of the engine both separately and combined to create a fully functional mobile first game. It will also offer tutorials for those developers who are in need ofmore in depth explanations. The first part of this work discusses the existing solutions ofHTML5 based game engines and describes the basic techniques behind these, the differences, advantages and disadvantages. The third chapter describes my own implementation and the key enhancements and differences from the existing solutions. It explains the reasoning behind the choices that were made during the process of making this engine. The fourth chapter explains the design of the mini2d.js engine and the development tools chosen for the project. The fifth chapter explains the implementation in detail and demonstrates some of the code required for creating a game in mini2d.js engine. The last part demonstrates the web presentation of the engine, which is an equally important part of this thesis.

2 2 Existing solutions

In this chapter we introduce the existing game engines. We then ex- plain their strengths and weaknesses. Some aspects of these solutions have been an inspiration for my work. It was my goal to capture the best concepts of these solutions and combine them into a simple en- gine. The other solutions often possess a feature set that far exceeds what it is required by a developer to do. This could potentially mean using ten megabytes big engine for the game like tic tac toe. Using no engine at all would help to minimize the size of the game, however, it significantly reduces the speed of the development. The existing solu- tions also come with inconveniences specific to those engines when used for the development, so it was also my goal to avoid these and only use the best practice of these solutions. Now we are going to focus on the best solutions that exist as of today on the market.

2.1 PhaserJS

PhaserJS[1] is one of the most used HTML5 game frameworks pub- lished on GitHub1. It is an open solution using Pixi.js2 for rendering. It is actively developed and maintained by Photon Storm Limited[2]. It has a great user base and provides many live examples on its website. I believe the examples are a great way to demonstrate what the engine is capable of and because of this, I have decided to create similar examples for my engine as well. The development team behind PhaserJS has released the last stable version 2.4.6 and is work- ing on rebranding. The new name of the library is going to be Lazer, but it is now in an experimental phase and is not recommended to be used for the development. PhaserJS, although not written in Type- Script, contains TypeScript definitions for TypeScript development and provides the programmer with the ability to take full advantage of TypeScript’s type system.

1. GitHub – the most popular open source repository hosting service. See https://github.com/. 2. Pixi.js – is a 2D webGL renderer with canvas fallback

3 2. Existing solutions

However, it does not come without any shortcomings. PhaserJS is by no means bug free and has many great features that may not be required, making the engine heavyweight. It comes with four different physics engines and many of these features, although useful, have not been authored with the mobile first attitude we strive for. It is still, however, a solid choice for any new game to come.

2.2 SFML

SFML[3], created by Laurent Gomila, is very different from PhaserJS and has been the second biggest inspiration for my engine. It takes fundamentally different approach as a game engine. It is written in C++ and the rendering is based on OpenGL3 and Direct3D4. PhaserJS is an engine, that tries to do everything for the programmer and does many things behind the scenes. On the other hand, SFML provides the very basic functionality and the programmer is left to implement the game logic by himself. This is the reason for SFML being lightweight, making it potentially very good, but it does have its big drawbacks which will be mentioned. It is not a complete game engine, but merely a multimedia library, used primarily for simple desktop games. As its homepage says: "It provides a simple interface to the various components of your PC..." It takes care of OpenGL/Direct3D API calls and the creation of a window on any supported . All of this can be either confusing or too complicated for the programmer. SFML makes it easier to use, and provides an API that works across all supported platforms with a single code base. It is by no means easily portable to mobile platforms and that is a big problem for an engine such as this one. Although planned for a long time now, it only works on desktop operating systems and that is not enough for simple games, that most developers want to publish on mobile devices. The simplicity of SFML would make it a great candidate for the type of games mini2d.js is aimed for, however, SFML cannot be ported to mobile platforms and therefore is not usable for the purpose.

3. OpenGL is a cross platform GPU API for rendering 2D and 3D graphics. 4. Direct3D – is an API for rendering 2D and 3D graphics on platforms

4 2. Existing solutions 2.3 LibGDX

LibGDX[4], developed by BadLogicGames, is a cross-platform game engine based on the language and solves the problems with the portability of SFML. It is a full featured engine which does not leave as much room for the programmer to solve problems as SFML does. It has a big community and has been the engine of choice for many years. However, in the last years, other frameworks have started to take its place and LibGDX is slowly starting to be less and less used by the developers. LibGDX lays somewhere in between engines like PhaserJS and Unity3D. It is too complex and brings too much overhead for simple games. Therefore many developers choose solutions like PhaserJS instead for this type of games. And it does not provide as good tools for developing large games as Unity3D. Because of this, it is starting to lose the user community.

2.4 Unity3D

Unity3D[5], developed and maintained by Technologies, is an- other cross-platform game engine. It has exploded in popularity over the last couple of years and has become the engine of choice for the vast majority of developers. It supports basically every platform and has all the features required for making an AAA game5. It has a huge community and great learning resources. Besides all these strengths it also features an asset store, where other artists and can publish their plugins or assets, such as 3D models or custom functionality (e.g., inventory system for an RPG game). Its web export is experimental for now and the engine is by no means lightweight, it is meant to be a full featured, full scale game engine and does that very well and size is the necessary cost for that. It is capable of creating simple 2D games and some developers choose to do so. The reason behind this is the same reason JavaScript has had a success on the server side lately. The developers are already familiar with the technology and want to take full advantage of their

5. AAA game – a large scale game created by big studios with large budget.

5 2. Existing solutions experience instead of using something else. Otherwise, there are not enough reasons to justify using Unity3D for a small scale 2D game.

6 3 mini2d.js Engine

Mini2d.js is the name of the engine created within this thesis. Each of the previously mentioned engines came with some shortcomings. When developing, it is important to choose the best tool for reaching the goal, in order to be effective. I believe that there is still a gap for simple enough games. This is because libraries like PhaserJS are too complex for these types of games and as features were added to them, they became too big for simple games. Writing a game from scratch without the assistance of a framework can too be difficult because our goal is to create multi platform games. That can be challenging due to inconsistency of the web platform. Every platform and even every browser has a little different behavior and API and therefore can make even the easy tasks a little harder. Although other solutions on the market can be useful when creat- ing an HTML5 based game, they usually come with many unneces- sary features which bring a lot of overhead with them. My goal was to highly minimize the overhead, deliver only the core functionality which then can be extended by the programmer if required. This ap- proach allows for less code to be present in the engine, which should ultimately translate to less bugs overall. Furthermore, it tries to make the process of creating a game as easy as possible for the programmer. For this purpose this engine is accompanied with a web page, where the programmer can find the API documentation, code examples and text tutorials.

3.1 Technologies for multi platform web games

Mini2d.js is meant to be a multi-platform game engine. It is not possible to write a native application which would then run on every platform. That is the reason for mini2d.js to be based on the web technologies. HTML5 and JavaScript are supported on every desktop and mobile platform, but are supposed to be running as a web page in a browser.

7 3. mini2d.js Engine

3.1.1 Hybrid applications Because we do not want to run our game in a browser, and want to publish a native application on mobile stores, it is necessary to do a compromise between a web page and a native application. Such applications are called Hybrid. Hybrid applications are web appli- cations displayed on a WebView1 element. This means it is a native application with a single WebView element used for rendering of the web page. There are tools specifically made for the export of to a native one.

3.2 Differences from other solutions

In the following text we will explain how this engine differs from its competitors and describe the reasoning behind certain design deci- sions when creating the mini2d.js engine.

3.2.1 Mobile first approach This engine is intended for the creation of mobile first games. This means that it only contains the functionality that is available on mobile platforms. This ensures its consistency across platforms and reduces the overhead of the engine itself, which results in better performance which is so critical in HTML5 games. Although this means that the options for controls are limited, it is opened to extensions and the user is free to define these with the help of the engine.

3.2.2 TypeScript TypeScript[6], developed and maintained by Microsoft, is a typed superset of Javascript. This means that every valid Javascript file is also a valid TypeScript. The engine has been written in TypeScript to ensure better structure which vanilla JavaScript2 struggles to deliver. It is one of the greatest

1. WebView – is an element in native mobile applications used to display the content of a web page. 2. Vanilla JavaScript – is a name refering to plain JavaScript without any extensions, tooling or libraries.

8 3. mini2d.js Engine

strengths of TypeScript to offer better scaling and compilation-time type safety. I also believe that every library highly profits from being written in a statically typed language. It makes the process of creating the documentation easier because some information can be automatically inferred from the type annotations. Furthermore, if the author of the library does not want the potential user to be prevented from benefits of TypeScript such as code auto-completion, the library has to provide TypeScript definitions (this is what PhaserJS does and in my opinion it is better to use TypeScript right from the start, but this is probably caused by the fact, that PhaserJS was created before TypeScript was popular). The compilation time type check can also prevent bugs, that would otherwise go unnoticed and be discovered later during the compilation. Using TypeScript does have a disadvantage. As the new specifica- tions for the EcmaScript language bring new features to the language, the ability to use those in a TypeScript project depends on third party authoring TypeScript, in this case Microsoft.

3.2.3 Canvas vs. WebGL HTML canvas[7] is an HTML element used to draw graphics. The API of canvas is accessible via JavaScript and is a great way of displaying 2D graphics. Canvas is often used as an alternative to DOM manipu- lation for complex animations, because manipulating the DOM tree is without respect to performance when working with a lot of elements. On the other hand, WebGL[8] is a JavaScript API for rendering graphics within a supported browser. It is based on OpenGL ES 2.0 and in theory should provide a far superior performance to Canvas making it a great candidate for web based games. In reality the implementation is not well supported on mobile platforms and this results in Canvas being the better choice for the majority of platforms. In my experiments I have concluded that mobile performance of Canvas is better than WebGL and therefore WebGL is entirely absent from the engine, removing another unnecessary feature, which other solutions include in their implementations. Many of the existing so- lutions utilize the Pixi.js library, which handles the rendering using both these technologies. Because mini2d.js takes the mobile first ap-

9 3. mini2d.js Engine proach, it automatically supposes that a desktop (which does have a better WebGL) with superior performance to mobile devices will have enough power, to run the game smoothly using canvas. This is because the games created with this engine should be intended for mobile devices. For mobile devices Canvas is the better choice and so if the game is running smoothly on a mobile device, the performance gain of WebGL is unnecessary for desktop platforms.

3.3 Performance

Here I will explain the important factors of game performance on mobile devices. Based on my experience regarding HTML5 games development, there are numerous factors to consider. Because there are many dif- ferent devices with different power, it is important to consider these, when creating the game, in order to support as many devices as possi- ble.

3.3.1 SVG SVG[svg] (short for scalable vector graphics) is a vector based graphics format. Unlike PNG for example, it does not contain the information about the pixels in the image. It is a collection of geometrical shapes, which are defined by vectors. The image is therefore scalable toany size without the loss of quality. SVG is, however, not very popular among game creators. Although being able to display an image at any size with perfect quality is great benefit, it is often a worse choice. The creation of such graphic assets is more complicated than creating sim- ple raster sprites. For some games, with little logic this approach may be better, for example for the game of chess. But it is more complicated than that as we will explain below. It is limiting for a programmer requiring full control over what is happening on the scene as SVG is often controlled via DOM3 manipulations which are expensive in re- gards to performance and so it is barely used for mobile games at this

3. DOM – is a virtual element tree representing an HTML document.

10 3. mini2d.js Engine

time. Redrawing a lot of objects in SVG can take a bigger performance toll than in the case of canvas. Furthermore and most importantly, when speaking about mobile games, SVG is not well supported across web browsers. Therefore, it is not currently used for games and this why we did not include the SVG format into our mini2D.js engine as well.

3.3.2 Exporting to mobile platforms

Because implementations of Canvas and WebView element differ on different platforms, exporting the HTML5 game using a tool that pro- vides custom, performance focused implementation is a guaranteed way to improve the performance significantly. The main reason for HTML5 games to be so popular is their porta- bility – write once and run anywhere, using a . But devel- opers often want to release the game as a native application and that requires some extra steps. The industry standard for this is Apache Cordova. Exporting tools are often built on top of the Apache Cordova framework which takes the content of your web based game, wraps it into a native application and renders the content using the WebView element.

Apache Cordova

Apache Cordova[9] is the industry standard for wrapping HTML5 applications into native. It has a big community and rich documen- tation. The learning materials for these suffer from mobile platforms changing significantly over the last years and so the materials you find are often inaccurate or outdated.

Adobe PhoneGap

PhoneGap[10] is directly built upon Apache Cordova and it offers similar features in all regards. It is basically a branded version of Apache Cordova by Adobe.

11 3. mini2d.js Engine

CocoonJS

CocoonJS[11] is a custom solution build on Cordova and offers mul- tiple WebView engines, such as Canvas+, offers a significant boost in performance and is regarded the best performing solution at the moment. It comes with a cloud compiler and can sign the application package for you, making it effortless to publish on the store. CocoonsJS does have some drawbacks as well. It is a commercial product and therefore has its limitations unless you pay the full price of the license.

3.3.3 Resolution

Resolution is one of the major factors on performance. Even if your game is supposed to be run on devices that can have the resolution up to 1440p. It is wise to use a lower resolution and stretch the assets, because manipulating with high resolution textures on a low end phone can have a great effect on performance and may render your game unplayable. The solution to preserve high quality assets on high-end phones and keeping the game performant for lower-end phones would be to use assets with multiple resolutions and decide which assets to use when loading the game. When using WebGL for graphics rendering there are currently scaling problems when exporting the game for mobile platforms us- ing CocoonJS, which is another reason for not including WebGL into mini2s.js but could potentially cause problems when using other solu- tions like PhaserJS.

3.3.4 Avoiding bad practices

Many developers believe that they can develop in JavaScript without any knowledge of the language. For historical reasons, the language itself has its bad parts as explained by some of the best developers in the JavaScript community[12]. And because many inexperienced developers write JavaScript code, it can result in a badly performing source code.

12 3. mini2d.js Engine

Caching variables An example of this performance factor can be caching the array size in loops, size of which is not going to change when looping through it. This way we can speed up the process by simply storing the ar- ray length instead of looking it up in the loop condition every time. Another, more significant example, can be caching jQuery4 selectors especially in loops. This can have a great effect on both performance and battery life of the device.

Garbage collection Because JavaScript is a garbage collected language and the behavior of the garbage collector is not deterministic, the developer of the game has to be aware of the fact. The recommended approach is to try to make use of a renewable pool of objects, instead of creating new ones all the time, which then ultimately translates to more unused objects required to be garbage collected.

Limiting the number of objects Although rendering more objects may be visually appealing and can help create visual effects, it can also affect the performance signif- icantly. The performance for web based games is not sufficient for complex games as of today. For such games it is advised to use more sophisticated engine, such as Unity3D.

4. jQuery – the most used JavaScript library, primarily used for DOM manipula- tions.

13 4 Design of mini2d.js

Many of the HTML5 game engines follow a similar pattern. The design of mini2d.js was inspired by the PhaserJS game engine. We will now explain the basics of how mini2d.js works and will outline the class diagram of the engine. More details about the individual classes will follow in the implementation chapter.

4.1 Classes hierarchy

The design intended for the mini2d.js was to automatically do most of the work. This approach results in less code required for the game and allows quick prototyping. For this approach it is required to design the engine around a central class which binds other classes together and executes the maximum amount of logic automatically without the user interference. In our case the Game class represents this central class. The whole hierarchy of classes of the engine can bee seen in Figure 4.1.

4.1.1 Game class

The Game class is standing on the top of the hierarchy in the class hierarchy of the mini2d.js engine. It initializes the game instance and initializes the other classes that exist as members of the game class. Because we want the engine to preserve performance and we only want to update things relevant to the current state of the game, the assets added to the game are bound to the game state, not to the game instance.

4.1.2 Game states

There can be an unlimited number of game states, every one of which should serve for a different purpose and represent a different stateof the game. The programmer can then switch between these in order to quickly change what is happening on the screen.

15 4. Design of mini2d.js

Figure 4.1: Simplified class hierarchy

16 4. Design of mini2d.js

4.1.3 World and UI Every game state has its own World and UI class. These classes are used only internally and the user does not have to be aware of them. When a sprite is added to a game state, it is internally added to the World instance of the state, which then handles the functionality of all sprites such as drawing them on the canvas and updating them based on the physical properties. The same thing is happening for the UI elements such as Buttons and Texts, which are saved in the UI class after adding to the game state. This class then handles the behavior of these UI elements.

4.1.4 Sound Because sound can persist throughout states, it is implemented dif- ferently from the graphical and UI assets. It is added directly to the game instance because it is not required to differentiate between game states and every sound is at the programmer’s disposal at every time.

4.1.5 Physics The mini2d.js engine includes a basic rectangle-based engine which can be enabled for individual sprites. The user is free not to use the physics engine and implement a custom physics engine.

4.1.6 Resources Resources are handled internally by the resources manager. Every asset, such as an image or a sound file, has to be loaded before it is used. This approach enables to load everything before the game is initialized and then run smoothly without the need of loading at runtime. This approach was required for the engine to preserve its simplicity because the process of loading assets is asynchronous and that can be difficult for beginner programmers.

4.1.7 Other classes Other classes used in the mini2d.js engine have no specific design and will be mentioned in the implementation chapter.

17 4. Design of mini2d.js 4.2 Development tools

In order to make the development efficient, it was required to choose from the tools currently available in the JavaScript world. As JavaScript has become more popular recently, more tools have emerged. We will now look at what was used for mini2d.js development and why it was selected.

4.2.1 JavaScript preprocessors Despite JavaScript’s popularity, the language itself has its limitations. This is the reason for the creation of JavaScript preprocessors. JavaScript preprocessor is a tool, that compiles different languages into JavaScript. These languages tend to be similar to JavaScript, but bring enhance- ments that are not possible to reach using JavaScript. ReactJS1 is one of the most used front-end frameworks in web application libraries and a lot of its learning resources are popularizing the usage of the newest EcmaScript6 language features. This requires the developers to use EcmaScript6 preprocessor in order to support the older versions of browsers.

EcmaScript6 ES6[13] or ES2015 is the last standard of EcmaScript2 language. It brings many great features that were missing in the JavaScript lan- guage such as object destructuring, classes, promises3, and many more. The reason we cannot use the language features directly is that not all the features of the language are implemented in current browser’s JavaScript engines. It is also important to note, that older versions of browsers which are still in use today (e.g., older versions of Internet Explorer) do not support these features at all. Because of this, ES6 is used in a of preprocessor language and is then transpiled to the older EcmaScript standard, which is supported. This way it is

1. ReactJS – created by Facebook, it is the View component in the MVC (model, view, controller) architecture. 2. EcmaScript – is the official name of the JavaScript standard and is often used interchangeably. 3. Promise – is an object for asynchronous operations.

18 4. Design of mini2d.js possible to write up-to-date modern code even though we support older browsers.

CoffeeScript CofeeScript[14] is a small white-space indented language similar to Python and its goal is to expose the best parts of JavaScript. It automat- ically fixes the problems of JavaScript such as the usage of undeclared variables. CoffeeScript is very expressive language and can signifi- cantly reduce the number of lines required for a given task. Everything is an expression in CoffeeScript and that can help the programmer to write source code in a functional paradigm style.

TypeScript TypeScript is a typed superset of JavaScript. This means that every valid JavaScript file is also a valid TypeScript file. However, inorder to benefit from using TypeScript it is, however, neccessary to provide type annotations in the TypeScript source code. It comes with its own module system and other features such as classes, that were later introduced in ES6. Mini2d.js was at first written in JavaScript, but then rewritten to TypeScript, because TypeScript scales better, prevents some of the bugs from ever occurring because it is statically typed. Furthermore, it is convenient for the programmer who decides to write the game in TypeScript to take full advantage of the code hints. This is possible because of the static code analysis of TypeScript and would not be possible otherwise. Therefore, TypeScript was chosen for mini2d.js development.

Other preprocessors There are many more options for JavaScript preprocessors such as ClojureScript or PureScript, but these variants are very different from JavaScript and therefore have not been considered for mini2d.js engine.

4.2.2 Task runners Because a JavaScript preprocessor was used for the development of mini2d.js, it is necessary to use an automated build system for a sus-

19 4. Design of mini2d.js tainable long-term development. Most of the tools that are used in the JavaScript ecosystem are based on the Node.js4 JavaScript runtime platform. One could argue that Node.js supports so called tasks, which is an alias for terminal commands. This could be used for smaller tasks, but it does not scale well in terms of readability and is not as compati- ble across platforms as other task runners which will be mentioned as well in the following text.

GruntJS GruntJS[15] is the most commonly used task runner and has been used to build a majority of the big JavaScript projects. It can be obtained as a Node.js package and most of the JavaScript based tools such as CSS5 minification tools do exist in the form of Node.js plugin for GruntJS. This made GruntJS very popular among developers.

Webpack [16] is gaining a lot of popularity among developers using Re- actJS. Many developers prefer Webpack to other solutions like GruntJS or Gulp. Webpack, however, is not a task runner. It is a module bundler which is capable of most of the tasks required from the task runners. It can therefore replace those entirely. However, because mini2d.js engine has more complicated requirements for the build process, it was necessary to use more complete solution such as Gulp or GruntJS.

Gulp Gulp[17] is a newer alternative to GruntJS and offers the same Node.JS plugins but is superior in terms of readability of the configuration file. It is faster than GruntJS, because it takes use of Node.js streams instead of temporary files that GruntJS uses. It has slightly lesser user base because it arrived long after GruntJS had been established as the task runner of choice. Because it has many advantages over

4. Node.js is a JavaScript runtime environment which makes possible to run JavaScript virtually everywhere. 5. CSS – Cascading Style Sheets is a language used for altering the visuals of a web page.

20 4. Design of mini2d.js

GruntJS, however, it is rising in popularity while GruntJS’s popularity is declining. Because of these benefits, Gulp had been chosen asthe task runner for mini2d.js engine.

21 5 Implementation

In the center of the implementation is the Game class which initializes the game when an instance is created. The following code shows how the instance of a game is created. Lets suppose for the future code examples, that our game variable is available as defined in the line below:

var game= new mini2d.Game(width, height);

This command creates a canvas element and initializes it according to given dimensions. During the canvas initialization it runs a regular expression check on the user agent string in the browser and deter- mines if the game is running on a desktop computer or on a mobile or tablet. If the device is determined as mobile or tablet, the canvas is stretched to fill the entire screen of the device.

5.1 Game states

Another core part of the implementation is formed by the game states. Game states in mini2d.js are handled by the StateManager class. Game states consist of two major functions, init and update. The role of the init function is to run the logic once, when the game state is initialized and this is where graphic, interface and other objects are created and set up. The update function is defining the functionality which is meant to be run in every frame. The game class contains a function to add a game state.

var state= game.addState({ init: function(){ // code to be run upon the // initialization of the game state }, update: function(){ // the function called in every frame } });

23 5. Implementation

This returns a game state prefab (short for prefabricate) which is a template from which a new game states with the same init and update functions are created. This is required because multiple instances of the same game state might be required. For example, every time we restart the game, we have to create a new game state with the same properties, that is in its proper initial state. The game state prefab has one method called start which after calling creates a new game state. The newly created game state is based on the init and update functions provided in the addState method and sets the state as the current one in the StateManager. It runs the init function upon initialization and then keeps calling the update function in every frame.

5.2 Resource manager

The resource manager is used mostly for internal purposes of the engine. There is only one method that is essential for the usage of mini2d.js by the user. This function can be accessed from the game instance. game.load([paths], state);

Before any asset is used in the engine, it is required to be loaded before. The loading is achieved by the load method on the game in- stance. It accepts two parameters, an array of paths to the assets to be loaded and an optional reference to a game state which is to be started when the loading is finished. For internal purposes the resource manager stores the assets in the array using the path as a key. The resource manager stores both graphic assets in PNG and JPEG formats and sound files in OGG and MP3 formats.

5.3 Input

Input is handled by the input class. It can be accessed from the game instance. game.input;

24 5. Implementation

The input class subscribes to the cursor events of the browser and sets its members accordingly. It then retrieves the cursor’s position and recalculates these with the help of updateCoordinates member function. This function recalculates the values it gets from the DOM event, be- cause the canvas is influenced by properties such as offset, stretching for mobile browsers and the document scroll offset. The updateCo- ordinates method calculates the correct values based on the factors. Another responsibility of the input class is to handle button clicks and respond to those by triggering the onclick functions and changing the button active flag. The last function of the input class is to unlock iOS audio upon the first click that occurs within the game. Thisis because in iOS web applications, Apple is blocking every audio unless it is triggered in response to a user action. Because of this, mini2d.js plays an empty sound in response to the first touch event that happens within the application and this action unlocks the audio.

5.4 Audio

For audio there are two classes. AudioManager class, which creates a single instance of audioContext, which is required to play an audio file. It also has a member method to add a sound. The following command shows how to add a sound to mini2d.js.

var sound= game.addSound(path);

This returns an instance of the second audio class in the engine, the Sound class. It internally retrieves the sound from the resource manager, which has to be previously loaded by the load function. The sound class offers a basic API for manipulation with the sound file. The following methods are available: play, pause, resume, stop, setVolume. It is using the web audio API and using the audioContext from the AudioManager class to create a buffer source from the audio file.

5.5 Camera

The Camera class is there to provide an easy and convenient way to move sprites on the screen and not requiring to move every individual

25 5. Implementation sprite separately. It contains a single method used for moving the camera, as shown in the following code: game.camera.move(x, y);

5.6 Interfaces

Before proceeding to other classes that are also important parts of the mini2d.js engine, it is necessary to first focus on the interfaces they implement.

5.6.1 Destroyable

The Destroyable interface requires from the classes implementing it to define the destroy method, which removes every reference to objects so they can be garbage-collected. Although, garbage collection is best to avoid entirely, as mentioned in Section 3.3.4 (Avoiding bad practices) section.

5.6.2 Drawable

The Drawable interface requires from the classes that implement this interface to define the draw method, which purpose is to render the element on the canvas, using the CanvasRenderingContext2D1 reference stored in the game class.

5.6.3 Measurable

The measurable interface requires from classes implementing it to have a position member, which keeps track of the current position of the object within the scene. It also requires to have a width and height members defining its dimensions.

1. CanvasRenderingContext2D is a rendering context for drawing graphics onto a canvas element.

26 5. Implementation 5.7 UI

The UI elements of the engine consist of two elements and that are the Text and Button classes.

5.7.1 Text The text class implements the Measurable, Drawable and Destroyable interfaces and is an easy way to display a static text within the engine. The text can be altered during runtime. An instance of the text class can be added in the following way: this.addText(x, y, text, font, color); The this keyword references the current state, therefore it needs to be called inside the game state method. The font family and size can be customized by supplying the optional font parameter in the form of string "15px sans-serif" and the color of the string can be altered by the optional color parameter in the form of string containing the HEX value of the color "#000".

5.7.2 Button The button class is similar to the Text class in terms of API. It also implements the Measurable, Drawable and Destroyable interfaces and can be added similarly. var button= this.addButton(x, y, callback, normalPath, activePath); The callback parameter is executed when the button is clicked. The fourth and fifth arguments are paths to textures to be applied tothe button element being in normal and active state respectively. The button has the option to effectively become a TextButton, upon calling the setText member. button.addText(text, font, color); This adds the text element inside the button and automatically centers it. The parameters are similar to those used when adding a text element. The only exception is that positional parameters x and y are omitted because the text is centered within the button.

27 5. Implementation 5.8 Graphics

The main and currently the only class for displaying graphics is the Sprite class. It implements Measurable, Drawable and Destroyable interfaces. It can be added in one of the two state functions init or update in the following way: var sprite= this.addSprite(x, y, path);

Sprite is the main way to display graphic assets in the game. Sprites are also the only elements within the engine that are affected by the position of the Camera class. Other elements which are meant to be used in the user interface are not affected by the position of the camera. Mini2d.js also features a basic physics engine that can be used for sprites. It is not enabled by default and must be enabled with a member method as shown on the following code. sprite.enableBody();

This creates an instance of the Body class for this sprite instance and involves it in physics calculations.

5.9 Physics

Mini2d.js includes a basic Physics engine based on AABB (axis-aligned bounding box). More complex physics engines, such as , are too demanding on performance and therefore more simple approach is required. The engine itself contains four classes that handle physics. The implementation of the physics was heavily influenced by the article on 2D physics [18].

5.9.1 CollisionEngine The CollisionEngine updates the entities on which the enableBody method was called and therefore possess the body class instance at- tached to them. The bodies are updated based on the values of its physical variables such as velocity, acceleration and gravity. These entities can also collide with world bounds if set using the collide- WorldBounds method. It is possible to only set the body to collide with

28 5. Implementation

specified game boundaries (e.g., only the top game boundary). The role of the CollisionEngine is to perform the check whether the entity is colliding with world bounds and update it accordingly.

5.9.2 CollisionDetector

The CollisionDetector class has a collideRect member method, which determines whether two bodies are colliding. This is used by the Body class, when checking for a collision with another object with the collide method.

5.9.3 CollisionSolver

The CollisionSolver class is called if two entities are colliding and updates them accordingly. It updates the physical forces on these bodies and translates the bodies so that they no longer collide.

5.9.4 Body

The Body class is instantiated on the sprite class using the enableBody method. This includes the sprite into physical calculations in each frame based on the body’s velocity and other physical properties. In order for the mini2d.js engine to handle the collisions between two objects, a collide method must be called on the body. The collide method is then passed another body which is to be checked for a collision. Lets suppose we have two sprites, sprite1 and sprite2, created and method enableBody called on these sprites. Then in order for the physics to work correctly, the collide method must be called in the following way:

sprite1.body.collide(sprite2.body, callback, resolve);

The collide method also has a second optional callback argument to be called upon collision and a third optional argument which specifies whether to resolve the collision or not. Its default value is true.

29 5. Implementation 5.10 Documentation

For TypeScript there is no official documentation generation tool. There are, however, several solutions available. Most of these solutions are incomplete and do not benefit from type annotations present inthe TypeScript source code. They are usually based on JavaDoc.

5.11 JavaDoc

Javadoc[19] is a documentation generator originally created for the Java programming language, and it is an industry standard for docu- menting a Java code. The popularity of this tool has exceeded the Java language and adaptations of JavaDoc are used in other languages as well.

5.12 TypeDoc

The mini2d.js documentation was generated using the TypeDoc[20] tool, which is a documentation generator based on JavaDoc. The differ- ence from other documentation generators is that it benefits from type annotations present in TypeScript source code. This allows for some of the type information to be inferred from the type signatures and therefore does not need to be present in the JavaDoc type comments. It then generates the documentation to a HTML, CSS and JavaScript formats, so it can be effortlessly included in the mini2d.js web page.

30 6 mini2d.js web page

Every library requires some form of information for the user so that he or she understands what the library does and how it is used. For this purpose mini2d.js has a dedicated website with general information about the engine itself, what the goals of the engine are, what are the benefits of using it and what are the limitations. It also features live code examples using the engine which can be edited and run on the website. It also features a TypeDoc generated documentation where the user can learn about everything the library is capable of. The last part of the web page consists of tutorials that offer guidance for starting developers.

6.1 Examples

The web page features code examples which demonstrate the capa- bilities of the engine as displayed in Figure 6.1. Each of the features is demonstrated both separately and combined to create a fully func- tional game. The example page contains an embedded code editor, where you can edit the samples and test the results directly on the web page. It is the fastest way to learn how to use the engine, but it assumes the knowledge of JavaScript, HTML and working with a local web server if you want to start developing using this engine. For developers not familiar with these technologies there is a dedicated page with tutorials, which guide the inexperienced programmer through the process of setting up the development environment and reproducing the example game step by step.

6.2 Tutorials

Those unfamiliar with game development may require better resources for learning than just code samples. Therefore, the web page provides the user with a set of tutorials as displayed in Figure 6.2, which explain how to start to use the engine. It demonstrates how to setup your HTML file and install and start your local web server, which is required for developing the game locally.

31 6. mini2d.js web page

Figure 6.1: Editable source code examples on mini2d.js web page

Figure 6.2: Tutorials available for the users on the mini2d.js web page

32 6. mini2d.js web page

Figure 6.3: Complete documentation of the mini2d.js API available on the mini2d.js web page

After following these guidelines the user will be able to setup a local development environment and start with the development. It explains step by step each line of the example pong game source code and the reasoning behind.

6.3 Documentation

The mini2d.js web page also includes a link to the documentation generated by the TypeDoc documentation generation tool. The doc- umentation is fully generated by the tool and is reachable from the navigation of the mini2d.js website. The documentation is displayed in Figure 6.3.

33 7 Conclusion

The aim of this thesis was to create an engine which provides the core functionality required for HTML5 game and unifies the inconsistent web API. With the help of the engine the user will be able to create simple games more easily and more quickly. Furthermore, the engine is intentionally missing some of the features which the existing so- lutions possess, in order to minimize the overhead. It is impossible to predict every feature that might be required in the games this en- gine is targeting. The engine could be extended in the future to cover more features that are necessary for the targeted games. As previously stated, for more complex games there are already very good solutions on the market. It was not my goal to provide a complete solution to every possible HTML5 game, but rather offer a lightweight alternative, better suited for the game the user wants to create. The engine is also a great way to start with game development due to the simplistic API of the mini2d.js engine and several examples and explanations in the form of tutorials on its website. Because HTML5 game development requirements are very different for every game, it is usual that a developer creates his or her own engine. This engine, however, can serve the purpose of educating the developer on the subject of game development, before creating own solution. The engine could potentially be enhanced in the future with some of the features that are currently missing, such as animations. Another part that could benefit from being expanded and would hurt the min- imalistic size of mini2d.js would be adding more in-depth examples with better graphics.

35 Bibliography

[1] . url: http://phaser.io (visited on 04/2016). [2] Photon Storm. url: http://www.photonstorm.com/ (visited on 04/2016). [3] SFML. url: http://www.sfml-dev.org/ (visited on 04/2016). [4] LibGDX. url: https://libgdx.badlogicgames.com/ (visited on 04/2016). [5] Unity3D. url: https://unity3d.com/ (visited on 04/2016). [6] TypeScript. url: https://www.typescriptlang.org/ (visited on 04/2016). [7] Canvas. url: https://developer.mozilla.org/en-US/docs/ Web/API/Canvas_API (visited on 04/2016). [8] WebGL. url: https://developer.mozilla.org/en-US/docs/ Web/API/WebGL_API (visited on 04/2016). [9] Apache Cordova. url: https://cordova.apache.org/ (visited on 04/2016). [10] PhoneGap. url: http://phonegap.com/ (visited on 04/2016). [11] Cocoon. url: https://cocoon.io/ (visited on 04/2016). [12] . JavaScript: The Good Parts. O’Reilly Media / Yahoo Press, 2008. [13] EcmaScript6. url: http://es6-features.org/ (visited on 04/2016). [14] Coffeescript. url: http://coffeescript.org/ (visited on 04/2016). [15] Grunt. url: http://gruntjs.com/ (visited on 04/2016). [16] Webpack. url: https://webpack.github.io/ (visited on 04/2016). [17] Gulp. url: http://gulpjs.com/ (visited on 04/2016). [18] Build a simple 2D physics engine for JavaScript games. url: http:// www.ibm.com/developerworks/library/wa-build2dphysicsengine/ (visited on 04/2016). [19] JavaDoc. url: http : / / docs . oracle . com / javase / 8 / docs / technotes/tools/windows/javadoc. (visited on 04/2016). [20] TypeDoc. url: http://typedoc.io/ (visited on 04/2016).

37