Full text
End-of-Degree Project Bachelor’s Degree in Informatics Engineering 2014/2015 X-GSD: Cross-Platform Game Skeleton (Data-Driven) A basic data-driven C++ game engine built upon SFML Official name (Spanish): Motor de videojuegos en C++ sobre SFML Author: Andr´es Ruiz Bernabeu Supervisor: Jordi Joan Linares Pellicer June, 2015
Abstract The purpose of this end-of-degree project report is to explain some general concepts about video game programming, game engines and their utility, and how X-GSD is built around some of these ideas, including: types of game loop and simulation, resource management, scene graph, entity-component system, events and basic physics. Nowadays, game engines have become very popular and a fundamental part for many game developers. Despite their benefits, this tendency comes with costs: As the most popular engines are proprietary, game developers become reliant on closed third-party software, which could lead —among others— to a deadlock of their projects in the worst case. This and more against-reasons regarding popularity of proprietary and big game engines are discussed along this work. X-GSD stands for Cross-platform Game Skeleton (Data- Driven), a basic data-driven C++ game engine built upon SFML1. It is a totally free and open basic game engine which aims to solve some of the problems of proprietary game engines, or being a starting point for custom solutions. It can also serve as an academic example of how to start building the core of a game, or a game engine. - Keywords: Video games, game engine, programming, SFML, X-GSD. 1Simple and Fast Media Library
Contents 0 Abbreviations and Symbols 1 1 Introduction 3 1.1 Previousresearch............................ 4 1.1.1 Bibliographic review . . . . . . . . . . . . . . . . . . . . . . 5 1.1.2 Stateoftheart ......................... 6 1.2 Objectives................................ 9 2 Methodology 11 2.1 Cross-platform targeting . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Data-drivenengine ........................... 13 2.3 Free software and open-source . . . . . . . . . . . . . . . . . . . . . 15 2.4 Examplegame.............................. 15 3 Development 17 3.1 Gameclass ............................... 17 3.1.1 Interface review . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.1.2 TheGameLoop......................... 22 3.1.3 Basic fixed delta time . . . . . . . . . . . . . . . . . . . . . . 24 3.1.4 Variable delta time . . . . . . . . . . . . . . . . . . . . . . . 26 3.1.5 Semi fixed delta time . . . . . . . . . . . . . . . . . . . . . . 29 3.1.6 Fixed delta time with variable rendering frame rate . . . . . 30 3.1.7 The game’s entry point . . . . . . . . . . . . . . . . . . . . . 32 3.2 Scenes, the scene graph and its nodes . . . . . . . . . . . . . . . . . 32 3.2.1 Sceneclass............................ 33 3.2.2 SceneGraphNode class . . . . . . . . . . . . . . . . . . . . . 41 3.3 Entity-Component system . . . . . . . . . . . . . . . . . . . . . . . 46 3.3.1 Entityclass ........................... 47 3.3.2 Componentclass ........................ 50 3.3.3 ComponentSprite . . . . . . . . . . . . . . . . . . . . . . . . 51 3.3.4 ComponentRigidBody . . . . . . . . . . . . . . . . . . . . . 53 3.3.5 ComponentCollider . . . . . . . . . . . . . . . . . . . . . . . 55 3.3.6 Controllers: User-defined Components . . . . . . . . . . . . 57 3.4 Examplegame.............................. 60 4 Conclusion 67 5 Improvement proposals 68
6 Appendix 70 6.1 Debugutils ............................... 70 6.2 Timeutils................................ 71 6.3 Event wrapper class and CustomEvent . . . . . . . . . . . . . . . . 71 6.4 ResourceManager class . . . . . . . . . . . . . . . . . . . . . . . . . 72 6.5 PhysicStateclass ............................ 74 6.6 PhysicsEngine class . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 4
X-GSD Section 0 ABBREVIATIONS AND SYMBOLS 0 Abbreviations and Symbols 1. X-GSD: Cross-Platform Game Skeleton (Data-Driven), the name of the game engine developed along this work. 2. OOP: Object Oriented Programming. A programming paradigm based in the encapsulation of data and behaviour on logic structures called objects. 3. C++: Programming language invented by Bjarne Stroustrup on 1983. It is one of the most popular[1] programming languages, including games development. 4. RAII : Resource Acquisition Is Initialization, an idiom which encourages to manage all memory on constructors and destructors. 5. SFML: Simple and Fast Media Library. A multi-purpose modular crossplatform framework. It is the abstraction layer used by X-GSD to achieve cross-platform targeting. 6. SDL: Simple DirectMedia Layer. A very popular abstraction layer similar to SFML, but older and less object-oriented. 7. API : Application Programming Interface. This are the public operations and data which can be used to program a software application without knowing about the underlying implementation. 8. SDK: Software Development Kit. Software suite with a range of tools for developing on a particular platform or system. 9. IDE: Integrated Development Environment. Software that integrates different development tools (even a whole SDK) into a single application. 10. FPS: Frames Per Seconds, which refers to the rendering frequency of the portion of the screen where the game is shown. 11. JSON : JavaScript Object Notation. A widely-supported lightweight datainterchange format. [19] 12. YAGNI : You Ain’t Gonna Need It. An idiom which warns to avoid anticipating the future by implementing features that might be needed, keeping the focus on the features that are actually needed at the present. [1] LangPop. Programming language popularity. http://langpop.com/. 1
Section 0 ABBREVIATIONS AND SYMBOLS X-GSD 13. WYSIWYG:What You See Is What You Get, which means that the resulting product will look the same as it looked in the editor. 14. AAA: Common term to refer to video games mega-productions. 2
X-GSD Section 1 INTRODUCTION 1 Introduction Game development can be still considered as a very new area of knowledge and an emerging industry. Moreover, university studies related to video games and game development are still too young —when the author of this work began its bachelor’s degree, university studies related to video games did not even exist in Spain— and there are no clear standards. The video games industry has been utterly hermetic for many years, especially the most technical parts as programming. Therefore, only those who were into it —working for some big company— had proven knowledge on which programming decisions are better for which scenarios, and companies would not allow their workers to reveal any information, making almost impossible to generate a collective and public knowledge base with regards to game development. This can be seen as one of the causes of game developers deciding to buy a proprietary game engine license, as these game engines handle big part of the game core programming itself and frees the programmer of this task to focus on developing games. These proprietary game engines are very robust and helpful in general, plenty of tools and editors which make game development easier and faster. But most of these developers forget the price they pay for it —appart from the license, which generally does not fit everyone’s budget—, which is becoming dependant on a closed and proprietary third-party technology. This may lead to face some problems such as: •Targeting to a platform which is not compatible with this particular game engine. •The need of low-level details control (for optimization or any other matters), which this particular game engine does not allow. •A new version of the game engine is needed to target to a new platform, but this new version introduce drastic changes and deprecations. The project might stay on older platforms and engine’s version, or need to invest time in deep refactoring. •A distribution platform the team is using requires some mandatory updates (e.g. Apple required 64 bit compatible binaries for iOS apps[2]), but the game engine has not been updated yet and therefore the game or its updates cannot be published. May cause temporal deadlock of the project (or total if that update never happens). •The proprietary company closes and/or the game engine gets discontinued. May cause total deadlock of the project. •The programmer could become too much dependant to that particular engine workflow and may stop learning other technologies —a special word of caution on this: a job change can occur to a company where that particular engine is not used—. [2] Apple Inc. 64-bit and ios 8 requirements for app updates. https://developer.apple. com/news/?id=12172014b. 3
Section 1 INTRODUCTION X-GSD In contrast, if using an open game engine and some of these problems would appear, the whole community of that game engine could take action to solve the issues as anyone can see, modify and compile the engine’s code. This is also true if the programmer is using its own technology —although there may not be any community and the problem has to be solved by the programmer itself—. The point is the project does not totally depend on a closed proprietary third-party software which could —in the worst case— deadlock it. This report of end-of-degree project shows how one could build its own technology or game engine, either by serving as an academic example or by being a possible basic solution to the problems stated before. 1.1 Previous research Fortunately, with the arrival and growth of the Internet —as many other aspects of people’s lives— this hermetic tendency of the games industry has been changing: free and open-source game engines and tools appeared on the web for anyone to look inside or freely download and use; on-line collaborative systems —see GitHub[3]— have revolutionised the way free software and open source is understood as anyone can very easily look how a particular part of a specific application or project has been made, and even try to enhance it and collaborate with the author of that project; There are also personal websites, blogs, social networks and wikis which are filled with information from people who want to share their knowledge about this topic all around the world. The combination of all these phenomenons with digital distribution have resulted in the appearance of the socalled “Indie developers” —small teams of developers that can now afford to get into the industry and create very innovative and/or artistic game experiences as opposed to big companies’ AAA2games—. Maybe because of the origin and nature of these Indie developers, or because they do not have the pressure of a big company that forbids sharing information, they are generally very transparent and give very valuable information to the community —sales data, programming advices, reports detailing all the development process... Gamasutra[4] is a mine of them—. It is truly encouraging to see how much the games development scenario has changed, becoming more accessible. However, despite the rise of this knowledge-for-everyone epoch the Internet has brought, the fact is that there are no clear standards for game programming yet. As it was stated above, the games development scenario has been changing and information sharing is more common. There are free and open game engines and tools to look into their code and some valuable documentation sources available for anyone. Therefore, it is a good starting point to look at what others have done in this field. 2Common term to refer to millionaire mega-productions. [3] GitHub Inc. Github ·build software better, together. https://github.com/, February 2008. [4] UBM TechWeb. Gamasutra - the art & business of making games. http://www. gamasutra.com/, 1997. 4
X-GSD Section 1 INTRODUCTION 1.1.1 Bibliographic review The most valuable information sources for the development of this work are referenced in this section with brief descriptions and the reasons why they have been taken into account. •SFML Game Development book [18] This introductory book to SFML is from where most initial key ideas have been taken and the main source of inspiration of this project. It is an almost perfect starting point for building a game from scratch —provided the reader has enough C++ knowledge—. The book covers the concepts of game loop, basic vector algebra, resource management, error handling, entities, scenes, input handling and many other topics which are out of the scope of this work, such as on-line multiplayer. It also recommends some best practises using C++11 new features, such as smart pointers in combination of RAII3. •A Tour of C++ (C++ in Depth Series) book [36] As the title suggests, the book does a review of C++ with special attention to the new features of the C++11 standard. Recommended to programmers who need to refresh their knowledge of C++ or are new to it, but have knowledge of OOP4. •Gaffer on Games website [11] This website features many technical interesting articles regarding game programming. The first two of them, Integration basics[12] and Fix your timestep![10] have been specially useful to implement the core of X-GSD: The game loop and how objects advance in the simulation through integration. •OpTank development blog [33] A blog with good game development design articles which were useful to implement the Entity-Component system of X-GSD. It also encourages good habits and principles like YAGNI5 •Game Programming Patterns book/website [25] This book has been a recent discovery and therefore most of the brilliant ideas and concepts of this book were not included on the project. It is a gem of game programming that any game developer should take a look at. The web version[26] is free. But please, if you find it really helpful, consider buying the book or eBook. 3Resource Acquisition Is Initialization, an idiom which encourages to manage all memory on constructors and destructors. 4Object Oriented Programming. A programming paradigm based in the encapsulation of data and behaviour on logic structures called objects. 5You Ain’t Gonna Need It. An idiom which warns to avoid anticipating the future by implementing features that might be needed, keeping the focus on the features that are actually needed at the present. 5
Section 2 METHODOLOGY X-GSD Figure 2: Comparison between compiled and interpreted code phases. approach is to build the core and the most critical parts of the game —that usually is the engine— in a compiled programming language as C++, and let the user of the engine to “script” the game in a (partially or totally) interpreted language as C#, Java, JavaScript or LUA because —among other qualities such as automated memory management— these type of programming languages usually permit code hot-swapping9which translates in more flexibility, faster development iterations and better integration with IDEs or editor tools. However, building such systems can be complex and therefore —for simplicity— X-GSD is entirely built with C++. The problem is that each target platform has its own API on some particular programming language. This translates in different ways of handling input devices, rendering, application and window behaviour, threading facilities, file systems, etc. And there is where SFML comes in: SFML provides a generic API which hides the platform-specific part to the programmer. Therefore, loading a texture, for example, becomes as easy as invoking a SFML procedure which does all the platform-specific work: look for the texture file on a particular file system, communicate with the graphics card and load the texture in its memory. And that line of code would produce the same result on Windows, Mac OS X, GNU/Linux, iOS or Android —the main platforms that SFML can target to—. The main reason to choose SFML instead of other well known libraries with the same purpose, such as the industry proven SDL10, is that SFML has a very clear, organised and modular API with C++ OOP in mind, as opposed to SDL which exposes a C in- 9In software, hot-swapping refers to the ability to modify the code while running, where code changes materialize without the need of re-compiling and relaunching the program. 10Simple DirectMedia Layer 12
X-GSD Section 2 METHODOLOGY terface. Moreover, SFML has a very active development and community, whereas SDL looks stalled. Figure 3: Comparison between programming with native APIs and with an abstraction layer API. 2.2 Data-driven engine The “Data-Driven” part of X-GSD referrs to the ability of the code to produce different results depending on some input data. In an extreme case, the entire program flow would depend on data. For instance, a music player software produces different sounds as output —the music— depending on a particular input data —that song’s file and its meta-data—, while the code of the music player remains unaltered. A more data-driven music player would accept, for example, a play list file that the music player would follow song per song. Figure 4: Comparison between non data-driven and data-driven programs. In the game engines field, data-driven behaviour is an increasing demand by developers as it provides faster iterations for tuning particular parts of a game in 13
Section 2 METHODOLOGY X-GSD development —generally, there is no need to recompile after some changes—. This can be achieved by storing and loading the needed values from configuration files, which in turn provides and encourages decoupling —the game may be organised in some logic units the engine provides—. This is totally opposed to hardcoding values in code. Of course, this more dynamic behaviour involve an overhead, although this trade-off is reasonable in most cases. With regard to X-GSD, this feature is achieved by a structure of Scenes,Entities and Components which are stored in and loaded from a JSON11 file per scene and a general configuration file of the game. Scenes are a set of a name, a scene graph node, some managers (resources, physics and controllers) and other properties. They can be considered as a container of entities and their resources. When a scene is loaded from a JSON file, every entity described on it is created and attached to the scene, and every specified resource is loaded into memory; after a basic fade-out/fade-in transition (if enabled), the previous scene is deleted from memory and the new scene begins. Figure 5: Representation of a scene and the scene graph. Entities can be seen as the fundamental units of the scene. They are a combination of a name, a scene graph node —which in turn stores a collection of zero or more scene graph nodes or Entities as children and spatial information such as position, scale and rotation— and a collection of zero or more components. Components give particular properties and behaviour to entities, so they can have visual representation —a sprite12— by attaching a ComponentSprite to it; or physics-related components —ComponentCollider and ComponentRigidBody— and even custom components that the user of X-GSD can write to add custom behaviour to the entity, known as controllers —the “scripting” part of the engine—. 11JavaScript Object Notation. It is a lightweight data-interchange format.[19] 12Graphical object of the scene (the character, a bullet, etc.) 14
X-GSD Section 2 METHODOLOGY Figure 6: Representation of an Entity and its Components. 2.3 Free software and open-source Free software and open-source have an important role nowadays: They encourage transparency, free and accessible learning, collaboration and altruism. Thanks to these philosophies, countless projects and technologies have seen the light of day for the benefit of the whole Internet community, which at the same time has an influence on people’s lives. X-GSD would not have been possible without SFML or a similar free and open-source project, which in turn is made with C++ —also free of use—. Because of that, and as stated before, X-GSD is released in a permisive zlib/png license —the same used by SFML— with full access to source code. Therefore, anyone can look into X-GSD classes and files to investigate how it is built and/or modify it freely, be it to enhance or completely change a particular part of the engine, be it because of simple curiosity. At its current state, this game engine is functional with basic features. The project is available on a GitHub repository[2] so that anyone can collaborate and improve the engine by adding functionality, enhance some parts, optimise algorithms, etc. 2.4 Example game Once all the X-GSD development is explained, a little example game will be developed so that one can see how to use X-GSD easily, covering all the needed parts: •How to create the configuration file and its options. •The game’s entry point in the main.cpp file and how to start its execution with the invocation of a game run method. •The creation and loading of scene files (with some resources and entities) 15
Section 2 METHODOLOGY X-GSD •How to write custom components (the controllers previously mentioned) to add logic and behaviour to the game. 16
X-GSD Section 3 DEVELOPMENT 3 Development This section will present each part of X-GSD, class by class, explaining their interface and functionality of each and some annotations about the corresponding code if it takes place. Some fragments of code (include guards, header includes, namespaces, etc.) will be omitted for better readability and focus on the interesting parts. Code fragments will start with a single-line comment that indicate the source file from which code has been extracted, if any (the .hpp extension hints a header file, which generally corresponds to the interface or API; The .cpp extension is for implementation files) and can contain a “...” code ellipsis indicators. For more details, full source code is available as attached files of this work or on the GitHub repository[2]. It is plenty of comments and comes with some examples of use in order to make it easier to dive into it and understand each little part. Note that the presented fragments of code have a line numbering as visual aid, but it may not coincide with the source code’s as these code fragments may be adapted and some parts omitted. 3.1 Game class This class is the responsible to load the game’s initial configuration, keep the game running in a specific game loop, handle resources and subsystems such as physics engine or events, and serve as a global point of access to these resources and subsystems. In order to achieve this functionality, the Game class is implemented similarly to the infamous singleton pattern[27] —but for a good reason: it offers accessibility while avoiding similar global state in other classes13—. 1// Game.hpp 2 3class Game 4{ 5// Methods 6public: 7static Game& instance() { return globalInstance; } 8 9... 10 11 private: 12 // Private constructor to ensure the static globalInstance is the only one 13 Game(); 14 ... 15 16 // Variables (member / properties) 17 private: 18 static Game globalInstance; 19 20 ... 21 }; 22 23 24 // Game.cpp 25 26 Game Game::globalInstance; // Static initialization of the Game globalInstance 13“The goal of removing all global state is admirable, but rarely practical. Most codebases will still have a couple of globally available objects, such as a single Game or World object representing the entire game state.”[27] 17
Section 3 DEVELOPMENT X-GSD The static method instance() returns a reference to the Game globalInstance. Game() constructor is set as private in order to ensure that the class cannot be instantiated besides the global instance. Any other class including Game’s header file can get the game’s instance simply by calling Game::instance(). 1// Some class .cpp or .hpp 2 3#include <X-GSD/Game.hpp> 4 5// Retrieve the global instance, store its reference and do something with it 6Game *myGame = Game::instance(); 7myGame->someMethod(); 8 9// Or simply use it directly 10 Game::instance()->someMethod(); 3.1.1 Interface review The state of the Game class is given by the following member variables: 1// Game.hpp 2 3class Game 4{ 5// Typedefs and enumerations 6private: 7typedef std::unordered_map<std::string, std::string> StringDataStore; 8 9... 10 11 // Variables (member / properties) 12 private: 13 static Game globalInstance; 14 15 xgsd::HiResDuration mTimeSinceStart; 16 sf::RenderWindow* mWindow; 17 bool mVSync; 18 xgsd::Scene* mScene; 19 sf::Event mEvent; 20 xgsd::PhysicsEngine mPhysicsEngine; 21 22 // Resources managers 23 xgsd::FontManager mFontManager; 24 xgsd::TextureManager mTextureManager; 25 xgsd::SoundManager mSoundManager; 26 27 #ifdef DEBUG 28 // Statistics 29 bool mDebugRendering; 30 bool mEnableStatistics; 31 sf::RectangleShape mStatisticsBackground; 32 sf::Text mStatisticsText; 33 xgsd::HiResDuration mStatisticsUpdateTime; 34 std::size_t mStatisticsNumFrames; 35 std::size_t mStatisticsNumSimulationSteps; 36 #endif 37 38 public: 39 StringDataStore DataStore; 40 }; From top to bottom: •mTimeSinceStart holds the amount of time the game has been running. 18
X-GSD Section 3 DEVELOPMENT •mWindow points to a sf::RenderWindow, an SFML class which represents the portion of the screen where the game will render and which have information about resolution/size of the window, video mode, etc. •mVSync is a boolean which stores the vertical synchronization option. •The mScene member variable is one of the most important of Game class. This xgsd::Scene* points to the current scene of the game. The Scene class contains all the scene-related behaviour and state which make possible to modularize the game in scenes, switch between them, load specific resources, etc. It will be explained in detail in its own section. •mEvent is an sf::Event, another SFML class which represents a system event —generally, input-related such as mouse, keyboard or joystick input, or window-related such as closing or resizing the window—. •The mPhysicsEngine member, of type xgsd::PhysicsEngine, is an object which handles basic collision detection. •Resource managers of the Game class are useful to store global resources. For example, if the same font is used in all or a fair amount of the game’s scenes, it is better to place it in xgsd::FontManager of this class to avoid loading, unloading and reloading the same font scene after scene. For more information, see (Appendix 6.4) or source code. •All the variables between #ifdef DEBUG and #endif preprocessor directives will only be available if DEBUG symbol has been defined. They have statistic purposes such as displaying the frames per second in debug mode. •Finally, DataStore is a StringDataStore which is a type definition of std::unordered map<std::string, std::string>. This unordered map can be used to pass basic information in form of std::strings between objects of the game. For example, in a game with two levels and a class for each, level1 scene could store points and remaining lives before loading level2 scene so that the latter can know that information: 1// level_1_scene.cpp 2// Store player’s lives in a "lives" record of the DataStore (from level1 scene) 3Game::instance().DataStore["lives"] = std::to_string(mLives); 4 5// level_2_scene.cpp 6// Load player’s lives from "lives" of DataStore (in level2 scene) 7mLives = std::stod(Game::instance().DataStore["lives"]); The behaviour of the Game class is defined with these methods: 1// Game.hpp 2 3class Game 4{ 5... 6 7// Methods 8public: 9static Game& instance() { return globalInstance; } 19
Section 3 DEVELOPMENT X-GSD 10 11 void runFixedDeltaTime(int stepsPerSecond = 60); 12 void runVariableDeltaTime(); 13 void runSemiFixedDeltaTime(int simulationFrequency = 60, int stepLimit = 3); 14 void runFixedSimulationVariableFramerate(int simulationFrequency = 60); 15 16 Scene& getSceneManager() { return *mScene; } 17 ControllersManager& getControllersManager() { return mScene->getControllersManager(); } 18 PhysicsEngine& getPhysicsEngine() { return mPhysicsEngine; } 19 FontManager& getGlobalFontManager() { return mFontManager; } 20 TextureManager& getGlobalTextureManager() { return mTextureManager; } 21 SoundManager& getGlobalSoundManager() { return mSoundManager; } 22 FontManager& getLocalFontManager() { return mScene->getLocalFontManager(); } 23 TextureManager& getLocalTextureManager() { return mScene->getLocalTextureManager(); } 24 SoundManager& getLocalSoundManager() { return mScene->getLocalSoundManager(); } 25 sf::RenderWindow& getWindow() { return *mWindow; } 26 HiResDuration getRunningTime() { return mTimeSinceStart; } 27 28 void broadcastEvent(const Event& event); 29 30 #ifdef DEBUG 31 bool isDebugRenderingEnabled() { return mDebugRendering; } 32 void updateStatistics(const HiResDuration& elapsedTime); 33 #endif 34 35 private: 36 // Private constructor to ensure the static globalInstance is the only one 37 Game(); 38 void loadConfigurationFromFile(); 39 void update(const HiResDuration& dt); 40 void render(); 41 void handleEvents(); 42 43 ... 44 }; All methods starting with ‘get’ —known as getters— return a reference to a subsystem such as Scene,ControllersManager,PhysicsEngine, resource managers (global, which belong to the Game; and local, which belong to the current scene) or the game’s sf::RenderWindow. The method getRunningTime returns the amount of time the game has been running. There is also a isDebugRenderingEnabled method in debug mode to know whether debug rendering is active (for example, print on screen rendering information such as FPS, or visualize colliders of entities which have one). broadcastEvent can be invoked from any class in order to inform to Entities belonging to the scene graph (and their Components/Controllers, if any) that a certain event occurred. It can be an xgsd::Event (a wrapper class of sf::Event. See Appendix 6.3) of type xgsd::Event::EventType::System —the system events explained before— or a custom event of type xgsd::Event::EventType::Custom, which are user-defined events such as PlayerDied or GameWon. The rest of the methods (starting with ‘run’, updateStatistics and those defined as private) need a more detailed explanation, which will be developed below. Starting with loadConfigurationFromFile, this is the first method called by Game when it is instantiated. That is, it is called in its constructor: 1// Game.cpp 2 3// Constructor 20
X-GSD Section 3 DEVELOPMENT 4Game::Game() 5: mVSync(false) 6, mTimeSinceStart(0) 7{ 8// Load configuration (window properties, first scene to load...) 9loadConfigurationFromFile(); 10 11 ... 12 } In this method, a JSON file named gameconfig.json will be read in order to get the initial configuration of the game. These are the JSON elements to load: •windowName (as string). Default value: empty string. •windowSize (as object, containing width and height as integers). Default value: 800, 600. •fullscreen (as bool). Default value: false. •vsync (as bool). Default value: true. •keyRepetition (as bool). Default value: false. •mouseCursorVisible (as bool). Default value: true. •debugFont (as string). Default value: empty string. Only in Debug mode. •icon (as string). Default value: empty string. •initialScene (as string). No default value: Valid initialScene is required. Here is a valid example of the gameconfig.json file: 1{ 2"windowName" : "Example Game", 3"windowSize" : { 4"width" : 720, 5"height" : 480 6}, 7"fullscreen" : true, 8"vsync" : true, 9"keyRepetition" : false, 10 "mouseCursorVisible" : false, 11 "debugFont": "fonts/PressStart2P.ttf", 12 "icon" : "textures/ballSpriteRed.png", 13 "initialScene" : "scenes/TitleMenuScene.json" 14 } The following gameconfig.json file is also valid. Note that initialScene is the only configuration parameter that is compulsory as it cannot have a default value. 1{ 2"initialScene" : "InitialScene.json" 3} 21
Section 3 DEVELOPMENT X-GSD would be considered as a hit because the enemy has a radius of 5m. Figure 8: Movement of a bullet with variable delta time loop. Part 1 However, some random circumstance of the operating system (e.g. a software update notification) made that third frame to last longer than expected, and it takes 0.08sto complete. Then, update gets called with that time passed as its argument, and the simulation advances in 0.08s. Therefore, the bullet travels more distance than before: 0.08s·400m/s = 32m Then, the bullet’s new position is at 12.8m+32m= 44.8m, which is far beyond the distance of 20m±5mof radius that separated the player from the enemy, and the bullet did not hit him. Figure 9: Movement of a bullet with variable delta time loop. Part 2 The consequence of that random performance drop is a collision not happening, which results in undesired behaviour of the game. Now suppose what would happen if another random event cause a performance drop and the delta time accumulates one second. That is just a simple example, but in a real game, a high delta time for the physics update could break the entire game, making the player and objects to fall through the floor or pass through walls, among other undesired effects. Therefore, this game loop variation can be considered even more unreliable than the previous, and other solutions become necessary. Note that in this case Vertical Synchronization would only lower FPS and simulation frequency to the display’s rate, but as the delta time is variable, the 28
X-GSD Section 3 DEVELOPMENT game would still run at normal speed without needing to synchronize frequencies as it was the case with fixed delta time loop. 3.1.5 Semi fixed delta time With the fixed delta time the problem was to simulate at normal speed in different machines and conditions, but physics behaved correctly —at least if a good enough simulation frequency was specified—. The variable delta time solved the problem of the speed, but lacked a consistent enough simulation. Taking the best of both worlds is the aim of the semi fixed delta time, which will be explained after the code: 1// Game.cpp 2 3void Game::runSemiFixedDeltaTime(int minSimulationFrequency, int stepLimit) 4{ 5// stepLimit must be at least 1, or it would not update the simulation 6assert(stepLimit > 0); 7 8HiResDuration simulationFixedDuration(ONE_SECOND/minSimulationFrequency); // Simulation delta time 9 10 const short multipleStepLimit = stepLimit; // Limit of steps to consume the frame time. Needed to avoid the spiral of death effect. Tuning is recommended 11 short multipleStepCounter = 0; 12 13 HiResDuration lastRenderDuration; 14 HiResDuration simulationDuration; 15 16 HiResTime lastTimeMeasure = HiResClock::now(); 17 HiResTime newTimeMeasure; 18 19 while (mWindow->isOpen()) 20 { 21 newTimeMeasure = HiResClock::now(); 22 lastRenderDuration = newTimeMeasure - lastTimeMeasure; 23 lastTimeMeasure = newTimeMeasure; 24 25 ... 26 27 while (lastRenderDuration > HiResDuration::zero() && multipleStepCounter < multipleStepLimit) 28 { 29 simulationDuration = std::min(lastRenderDuration, simulationFixedDuration); 30 31 handleEvents(); 32 update(simulationDuration); 33 34 lastRenderDuration -= simulationDuration; 35 ... 36 ++multipleStepCounter; 37 } 38 multipleStepCounter = 0; 39 40 render(); 41 } 42 } The idea is that one can provide a simulation frequency —as it was possible with the fixed delta time—, while the frame time is also measured. Then, before updating, the minimum of the two times is selected to be passed as the argument of update. This way, if the FPS are high, the simulation frequency will be high as well; but on the contrary, if the FPS are low or a load spike or random event occurs and affect the game’s FPS, the simulation is guaranteed to update at least 29
Section 3 DEVELOPMENT X-GSD at a specific frequency. This can prevent the physics from breaking and leaving the game in an undesired state. However, if the iteration —especially the simulation update— takes too many time to complete, having a guaranteed minimum simulation frequency could lead to a worse slow down, which would result in longer iterations, and the cycle repeats making performance to drop heavily. To avoid this, a multiple simulation step limit can be added. With it, in the worse scenario the game would still run slower, but at least it would not fall into that undesired cycle. To achieve this, another loop is needed (see line 27) in order to handle the process. Each iteration of the outer loop measures the time of the last iteration and enters the inner loop. This inner loop is responsible for: •Check the remaining frame time and the multiple step counter against the limit. •Selecting the minimum time between the last frame time and the provided fixed delta time. •Handle events and update with the previously selected delta time. •Subtract the simulated time from the frame time. •Raise the multiple step counter. Therefore, when the minimum simulation time that is selected coincides with the frame time, this inner loop will perform a single iteration and it will behave as the variable delta time in favorable conditions. On the contrary, if the frame time is higher than the provided simulation fixed time, the simulation will advance in that fixed time, subtract it from the frame time, raise the multiple step counter and repeat the loop until the frame time is zero or the counter reach the specified limit. Although this game loop variation still has some drawbacks, it is arguably better than the fixed or variable delta time loops, and it will work well in most cases. It may also be appropriate for particular targets as mobile platforms for the same reasons given on the fixed delta time: Any condition that can affect performance may slow down the game instead of performing big simulation or physics steps, and therefore the player can react to these events. 3.1.6 Fixed delta time with variable rendering frame rate The previously discussed game loop variation is one of the best and is suitable and good enough for a wide range of games. However, it does not feature a deterministic simulation —that is, each execution is guaranteed output the same exact results for the same exact input values, independently of the FPS—, which may be a needed or desirable behaviour. This is because the simulation duration passed as argument of the update call is not always a fixed time. The fixed delta time game loop provided this feature, but at the cost of strongly coupling FPS and simulation frequency which derived in other problems. 30
X-GSD Section 3 DEVELOPMENT The last game loop variation that will be presented on this work is the fixed delta time with variable frame rate. This game loop achieves deterministic simulation while running at normal speed by decoupling simulation and rendering. In order to understand it better, one can think of render as a producer of time and of update as the consumer of that time. The loop will measure the time the renderer took to generate a frame and accumulate it, and then an inner loop will advance the simulation in fixed delta time steps until that time is consumed: 1// Game.cpp 2 3void Game::runFixedSimulationVariableFramerate(int simulationFrequency) 4{ 5HiResDuration accumulatedRenderTime(0); // Accumulator of render time to be consumed by simulations 6HiResDuration simulationFixedDuration(ONE_SECOND/simulationFrequency); // Fixed simulation delta time 7 8HiResDuration lastRenderDuration; // Frame Time 9 10 HiResTime lastTimeMeasure = HiResClock::now(); 11 HiResTime newTimeMeasure; 12 13 while (mWindow->isOpen()) 14 { 15 newTimeMeasure = HiResClock::now(); 16 lastRenderDuration = newTimeMeasure - lastTimeMeasure; 17 lastTimeMeasure = newTimeMeasure; 18 19 accumulatedRenderTime += lastRenderDuration; 20 21 while (accumulatedRenderTime >= simulationFixedDuration) 22 { 23 accumulatedRenderTime -= simulationFixedDuration; 24 25 handleEvents(); 26 update(simulationFixedDuration); 27 } 28 ... 29 30 render(); 31 } 32 } For example, if the simulation frequency has been set to 120Hz and the game outputs 60 FPS, the inner loop will iterate and update the simulation twice each frame. On the opposite, with 60Hz for the simulation and 120 FPS, the inner loop would perform one iteration each 2 frames because time must be consumed in fixed delta time durations, and therefore the first attempt will not enter the inner loop but the time will be accumulated and consumed at the second attempt. In the case of non exact divisions between simulation frequency and FPS, as for example 100Hz and 60 FPS, some temporal aliasing16 can appear because of an alternation between the inner loop executing and consuming the accumulated time and not executing and accumulating time. Following with the same example, 60 FPS ∼0.0166s, and 100Hz = 0.01s. Therefore, each frame will add 0.0166s to the accumulator and the inner loop will run once and subtract 0.01sfrom the accumulator, leaving 0.0066sthat cannot be consumed yet. Then, the renderer will produce another 0.0166s, making a total of 0.0232s, and the inner loop will 16An undesired visual effect of stuttering. 31
Section 3 DEVELOPMENT X-GSD iterate twice, subtracting 0.01seach iteration and leaving 0.0032sas remainder, which will accumulate with subsequent remainders until it reaches 0.01sand gets consumed by the inner simulation loop. In order to avoid the temporal aliasing problem, one can set Vertical Synchronization on and configure a simulation frequency which results in an exact division (60 FPS and 30Hz or 120Hz, for example). The problem with this is the dependency on Vertical Synchronization. There is a better approach to correct that temporal aliasing, which consists in performing a linear interpolation between the previous and new state with the remainder time left in the accumulator. However, this is not implemented in X-GSD as it goes out of the academic scope of the project, and the previous solutions work fairly well for almost all scenarios. 3.1.7 The game’s entry point All C++ programs require at least one function called main from which the program will start. Therefore, the simplest manner to start the game is to include the Game class in the file which will contain the main function, and then invoke a run method of the four previously explained: 1// main.cpp 2 3#include <X-GSD/Game.hpp> 4 5int main() 6{ 7/* Invoke one of these 8xgsd::Game::instance().runFixedDeltaTime(); 9xgsd::Game::instance().runVariableDeltaTime(); 10 xgsd::Game::instance().runSemiFixedDeltaTime(); 11 xgsd::Game::instance().runFixedSimulationVariableFramerate(); 12 */ 13 14 xgsd::Game::instance().runFixedSimulationVariableFramerate(30); 15 } Excepting the runVariableDeltaTime method, an argument can be passed to these methods for tuning purposes. In the example above, a value of 30 has been passed as an argument indicating the desired simulation frequency. If no argument is provided, a default value is set (that value would be 60Hz in the example). See the previous sections for more details. This instruction is the entry point of the game, and it will remain running in the specified loop until the end of execution. 3.2 Scenes, the scene graph and its nodes Almost every game can be separated in scenes. A scene can be considered as an organization unit in which one can place objects —or Entities, which will be explained on the next section— with some relation that end up conforming a part of a game: The main menu, a battle, a mini game or a level are some examples of typical parts of a game which conform a scene. 32
X-GSD Section 3 DEVELOPMENT Figure 10: Example of a game organized in scenes. 3.2.1 Scene class In X-GSD, a Scene is the owner of the root SceneGraphNode of the scene graph17 and some properties (name, paused, camera, a reference to the game’s window and others related to transitions) and managers for elements that are specific to that scene such as resources and physics. These resource managers are the same as the Game class, but the difference relies on their life cycle: The scene’s resource managers will load/unload specific resources for that scene at its loading/unloading, while Game’s resource managers will remain until the game ends. For more information about resource managers, see Appendix 6.4 or source code. 1// Scene.hpp 2 3... 4 5// Typedefs and enumerations 6public: 7typedef std::unique_ptr<Scene> Ptr; 8 9... 10 11 // Variables (member / properties) 12 private: 13 std::string mName; 14 SceneGraphNode::Ptr mSceneGraph; 15 sf::RenderWindow& mWindow; 16 sf::View mSceneView; // Camera 17 std::string mNextScenePath; 18 bool mSceneChangeRequest; 19 bool mPaused; 20 21 // Resources managers 22 FontManager::Ptr mFontManager; 23 TextureManager::Ptr mTextureManager; 24 SoundManager::Ptr mSoundManager; 25 26 ControllersManager mControllersManager; 27 28 PhysicsEngine& mPhysicsEngine; 29 30 bool mTransitionEnabled; 31 TransitionState mTransitionState; 32 HiResDuration mTransitionTime; 17A scene graph, despite its name, is commonly implemented with a tree structure in which all the elements of a scene are stored or referenced in a specific order. It generally determines the simulation and rendering order of the objects belonging to the scene. 33
Section 3 DEVELOPMENT X-GSD 33 HiResDuration mTransitionDuration; 34 sf::RectangleShape mTransitionFadingRectangle; 35 }; The behaviour of the Scene class can be separated in the following methods: 1// Scene.hpp 2 3... 4 5// Methods 6public: 7Scene(sf::RenderWindow& window); 8~Scene(); 9 10 void update(const HiResDuration &dt); 11 void render(); 12 void handleEvent(const Event &event); 13 14 std::string getName(); 15 FontManager& getLocalFontManager() { return *mFontManager; } 16 TextureManager& getLocalTextureManager() { return *mTextureManager; } 17 SoundManager& getLocalSoundManager() { return *mSoundManager; } 18 ControllersManager& getControllersManager() { return mControllersManager; } 19 20 void addNode(SceneGraphNode::Ptr node); 21 22 void loadSceneFromFile(std::string jsonPath); 23 24 bool isTransitionEnabled(); 25 void setTransitionEnabled(bool option); 26 void pauseGame(); 27 void resumeGame(); 28 29 private: 30 void readJsonSceneFile(std::string jsonPath); 31 void performSceneChange(); 32 void unloadScene(); 33 34 void updateTransition(const HiResDuration &dt); 35 void renderTransition(); 36 37 ... The constructor only requires a sf::RenderWindow, which is a reference of the game’s window. As it was mentioned earlier (section 3.1.2), update,render and handleEvent methods of Scene are invoked from the Game class with a specific order in the game loop. Then, the Scene invoke the same methods of its root SceneGraphNode —that is, they are propagated to the next level—. See the implementation: 1// Scene.cpp 2 3void Scene::update(const HiResDuration &dt) 4{ 5if (mPaused) 6mSceneGraph->onPause(dt); 7 8// If a scene change is requested, do not update 9else if (!mSceneChangeRequest) { 10 mPhysicsEngine.checkCollisions(); 11 mSceneGraph->update(dt); 12 mSceneGraph->performPendingSceneGraphOperations(); 13 } 14 15 // Perform the scene change transition when requested 34
X-GSD Section 3 DEVELOPMENT 16 else if (mTransitionEnabled) 17 updateTransition(dt); 18 } 19 20 void Scene::render() 21 { 22 // If a scene change is requested, do not render the transition instead of the scene graph 23 if (!mSceneChangeRequest) 24 mWindow.draw(*mSceneGraph); 25 else if (mTransitionEnabled) 26 renderTransition(); 27 } 28 29 void Scene::handleEvent(const Event &event) 30 { 31 mSceneGraph->handleEvent(event); 32 } The update method checks if the game is paused, in which case it will invoke onPause on the SceneGraphNode instead of update so that nodes can perform tasks when the game is paused such as a pause menu. Because of a Scene could receive a request for changing to another scene, the update method also checks that condition. If neither paused nor requested to change the scene, the Scene will ask the physics engine to check for collisions, invoke update on the scene graph and perform some scene graph operations (both checkCollisions and performPendingSceneGraphOperations methods are explained later on Appendix 6.6 and Section 3.2.2). The last part will only be executed if a scene change occurs and the transition effect is enabled. In fact, this part is responsible to update the forementioned transition. The render method also checks if the scene has been requested to change in order to render the transition effect. The rest of the time it will invoke the draw method of the window passing a pointer to the root scene graph node as an argument. This will result in SFML invoking draw on the root scene graph node, which is possible because the SceneGraphNode class inherits from sf::Drawable —any class that is intended to render something on the game’s window must inherit from it—. Finally, the handleEvent method just propagates the call to the scene graph. Returning to the Scene’s behaviour interface, the next methods are simple getters of the aforementioned managers. The addNode method simply attaches a SceneGraphNode (or derived classes, such as Entity) as a child of the root scene graph node (this will be explained in the next section). The loadSceneFromFile method, along with the auxiliary private methods performSceneChange,unloadScene and readJsonSceneFile, is responsible of loading and switching to a new scene. If the transition is disabled, it immediately calls performSceneChange. Otherwise it will be called at transition end —but it will not be shown for simplicity. For more details on transition implementation, see source code—. In any case, performSceneChange will call unloadScene in order to release resources and unload the entire scene graph, and finally invoke readJsonSceneFile which will parse the new scene’s json file and generate the new scene graph and load the needed resources. See the implementation: 35
Section 3 DEVELOPMENT X-GSD 1// Scene.cpp 2 3void Scene::loadSceneFromFile(std::string jsonPath) 4{ 5mSceneChangeRequest = true; 6mNextScenePath = jsonPath; 7 8if (!mTransitionEnabled) 9performSceneChange(); 10 else 11 mTransitionState = out; 12 } 13 14 void Scene::performSceneChange() 15 { 16 // Unload current scene’s resources, nodes, values, etc. 17 unloadScene(); 18 19 // Load the new scene’s resources, entities, etc. 20 readJsonSceneFile(mNextScenePath); 21 22 mNextScenePath = ""; 23 } 24 25 void Scene::unloadScene() 26 { 27 mName = ""; 28 29 // Reset the scene graph 30 mSceneGraph.reset(new SceneGraphNode); 31 32 // Reset resources managers 33 mFontManager.reset(new FontManager); 34 mTextureManager.reset(new TextureManager); 35 mSoundManager.reset(new SoundManager); 36 } The readJsonSceneFile method reads a JSON file as the loadConfigurationFromFile from the Game class did: It uses the JsonCpp[21] parser in order to collect all the needed information. In X-GSD, a scene is described with the following JSON structure: name (as string). No default value: a valid name for the scene is required. entities (as list of objects). Default value: empty list. •name (as string). No default value: a valid name for the entity is required. •parentEntityName (as string). Default value: ”root”. Name of the entity to which this one will be added as child. •transform (as object). Default value: a default-initialized transform. –origin (as object). Default value: default-initialized components. •x(as float). Default value: 0. •y(as float). Default value: 0. –position (as object). Default value: default-initialized components. •relative (as bool). Default value: false. If true, values are interpreted as a ratio of the view’s width and height. For example, x:0.5 is equivalent to view.width*0.5. •x(as float). Default value: 0. •y(as float). Default value: 0. 36
X-GSD Section 3 DEVELOPMENT –scale (as object). Default value: default-initialized components. •x(as float). Default value: 1. •y(as float). Default value: 1. –rotation (as float). Default value: 0. •components (as object). Default value: null. –ComponentSprite (as object). Default value: null. •globalTexture (as bool). Default value: false. Determines whether the texture will be fetched from the local texture manager or the Game’s global one. •texture (as string). No default value: a texture identifier (from ’textures’ of ’resources’) is needed. •textureRect (as object). Default value: a rectangle containing the complete texture. This can be used to select part of a texture such as a spritesheet. ·top (as int). Default value: 0. ·left (as int). Default value: 0. ·width (as int). Default value: 0. ·height (as int). Default value: 0. –ComponentCollider (as object). Default value: null. •boundsRect (as object). Default value: default-initialized components. It represents the bounding box of an entity which detect collisions. ·top (as int). Default value: 0. ·left (as int). Default value: 0. ·width (as int). Default value: 0. ·height (as int). Default value: 0. –ComponentRigidBody (as object). Default value: null. •kinematic (as bool). Default value: false. If true, forces do not affect this rigid body. –controllers (as list of objects). Default value: empty list. •type (as string). No default value: A valid user-controller identifier is needed. resources (as object). Default value: null. •textures (as list of objects). Default value: empty list. –name (as string). No default value: An identifier is needed. –path (as string). No default value: The path of the resource file is needed (relative to the resources folder). •fonts (as list of objects). Default value: empty list. –name (as string). No default value: An identifier is needed. –path (as string). No default value: The path of the resource file is needed (relative to the resources folder). •sounds (as list of objects). Default value: empty list. 37
Section 3 DEVELOPMENT X-GSD The second part of the behaviour of the SceneGraphNode class manages the relationships between nodes. It divides into public methods (those starting with request-), and private methods: 1// SceneGraphNode.cpp 2 3// public methods 4void SceneGraphNode::requestAttach(Ptr child) 5{ 6mPendingAttachments.push_back(std::move(child)); 7} 8 9void SceneGraphNode::requestDetach(SceneGraphNode* child) 10 { 11 mPendingDetachments.push_back(child); 12 } 13 14 void SceneGraphNode::requestDestroy() 15 { 16 mPendingDestruction = true; 17 } 18 19 void SceneGraphNode::performPendingSceneGraphOperations() 20 { 21 // Perform delayed node attachment/detachment/destruction, when it is safe 22 23 // Invoke the same method on children first 24 for (auto childIter = mChildren.begin(); childIter != mChildren.end(); ++childIter) { 25 (*childIter)->performPendingSceneGraphOperations(); 26 } 27 28 // Perform delayed node attachments 29 for (auto nodeIter = mPendingAttachments.begin(); nodeIter != mPendingAttachments.end(); ++nodeIter) { 30 attachChild(std::move(*nodeIter)); 31 } 32 mPendingAttachments.clear(); 33 34 // Perform delayed node detachments 35 for (auto nodeIter = mPendingDetachments.begin(); nodeIter != mPendingDetachments.end(); ++nodeIter) { 36 detachChild(**nodeIter); 37 } 38 mPendingDetachments.clear(); 39 40 // Perform delayed destruction of this node 41 if (mPendingDestruction) { 42 destroy(); 43 } 44 } 45 46 // private methods 47 void SceneGraphNode::attachChild(Ptr child) 48 { 49 // Set this node as the parent reference for the new child and add it to the children collection 50 child->mParent = this; 51 child->onAttach(); 52 mChildren.push_back(std::move(child)); 53 } 54 55 SceneGraphNode::Ptr SceneGraphNode::detachChild(SceneGraphNode& child) 56 { 57 // Look for the child node to detach 58 auto found = std::find_if(mChildren.begin(), mChildren.end(), [&] (Ptr& p) { return p.get() == &node; }); 59 assert(found != mChildren.end()); 60 61 child.onDetach(); 62 63 // Delete the parent reference, the node from the children collection and return it 44
X-GSD Section 3 DEVELOPMENT 64 Ptr result = std::move(*found); 65 result->mParent = nullptr; 66 mChildren.erase(found); % TODO: Update if changed in source code 67 return result; 68 } 69 70 void SceneGraphNode::destroy() 71 { 72 assert(mParent && "Attempted to destroy the root scene graph node, or a node which has not been attached as a child of another yet!"); % TODO: Cambiar por warning? Detectar si es el root de otro modo? 73 // Clear the collection of children and request the parent of this node to detach it 74 this->mChildren.clear(); 75 mParent->requestDetach(this); 76 this->mParent = nullptr; 77 } These public requestmethods store the nodes to attach, references of nodes to detach or set the flag of pending destruction. But the real operations —calling the private methods— are delayed to be done all at once, when the node get its performPendingSceneGraphOperations method invoked (the Scene class is the responsible to do it. See the update and loadSceneFromFile methods implementation of Scene for more details). Delaying such actions provides consistency to the scene graph, so that it does not change in middle of an update. Finally, this class offers some getters, of which these two require an explanation: 1// SceneGraphNode.cpp 2 3sf::Transform SceneGraphNode::getWorldTransform() const 4{ 5sf::Transform worldTransform = sf::Transform::Identity; 6 7// Navigate through the scene graph in reverse order (from this node to the root) and multiply their transforms 8for (const SceneGraphNode* node = this; node != nullptr; node = node->mParent) 9worldTransform = node->mTransformable.getTransform() * worldTransform; 10 11 // The transform is now in coordinates of the ’world’ (the scene root node) 12 return worldTransform; 13 } 14 15 sf::Vector2f SceneGraphNode::getWorldPosition() const 16 { 17 return getWorldTransform() * sf::Vector2f(); 18 } Every node has its own transform, and the information that it contains is considered as local (for example, being at position x=2, y=3). However, if a node is child of another node, its final ‘state’ does not depend only on its own transform, but its parent’s too, and the parent of its parent, and so forth. Continuing with the example, suppose that the previous node is attached to another with a local position of x=1, y=1. Then, although the previous node is locally at x=2, y=3, it would be at x=3, y=4 in world coordinates. Then, if a comparison of positions would be necessary for any reason (for example, collision detection), it is non-sense to compare local values. This problem is even worse if the nodes to be compared do not even pertain to the same parent-children hierarchy. This may look tedious to solve. However, the fact is that using matrices for 45
Section 3 DEVELOPMENT X-GSD Figure 11: Local and global positions of nodes. describing transformations has the purpose to facilitate these operations, as it can be seen in the getWorldTransform and getWorldPosition methods: By multiplying the transfoms until reaching the scene root node, the resulting transform is in coordinates of the world, and therefore comparisons become possible now. 3.3 Entity-Component system In the previous section it was introduced that Entity is a derived class of Scene- GraphNode, and therefore, it has the same functionality with some additions. Essentially, those are: having a name as an identifier and serving as a container of Components, which are the final links of the chain of invocations used all along X- GSD. Components are intended to implement the behaviour of different elements, such as rendering a visual representation (a Sprite) or the logic of a character (moving, jumping, shooting, etc.). Entities and Components are two fundamental high-abstraction-level elements for the user of X-GSD in the sense that a user of X-GSD is unlikely to use bare Scene or SceneGraphNode objects, but instead use high-level options as creating JSON files describing scenes and the entities-components inside them. A user would also create Entity and Component-derived objects programmatically or implement a new type of Component (or Controller). For example: •Describe a simple Scene in a JSON file: –Load needed resources –An Entity for the player’s character with these Components: •A Sprite so that the character has a visual representation (using a texture specified at resources loading) •A Collider in order to detect collisions between the character and other elements (floor, enemies...) 46
X-GSD Section 3 DEVELOPMENT •A custom PlayerController where to implement the logic related to the character (controls, actions, movement, life...) –Some more Entities for several elements of the world (floor, walls, enemies...) with the needed Components for each. •Create the PlayerController class, inheriting from ComponentController. Implement the character-related logic within this class. For example, a Shoot action: –Implement the action of shooting in a Shoot method, in which a new Entity (and the needed Components) representing a bullet is created programmatically. –Override the handleEvent method. In its implementation, check if some specific button or key has been pressed in order to invoke the Shoot method. This example shows how a user of X-GSD can create a simple game without the need of (directly) using other X-GSD classes apart from Entity and Componentderived. 3.3.1 Entity class As usual, here is the class inteface: 1// Entity.hpp 2 3class Entity : public SceneGraphNode 4{ 5// Typedefs and enumerations 6public: 7typedef std::unique_ptr<Entity> Ptr; 8 9// Methods 10 public: 11 Entity(std::string name); 12 ~Entity(); 13 14 void onAttachThis() override; 15 void onDetachThis() override; 16 void onPauseThis(const HiResDuration &dt) override; 17 18 void updateThis(const HiResDuration& dt) override; 19 void drawThis(sf::RenderTarget& target, sf::RenderStates states) const override; 20 void handleEventThis(const Event& event) override; 21 22 void addComponent(Component::Ptr component); 23 template <typename T> 24 std::unique_ptr<T> removeComponent(); 25 template <typename T> 26 T* getComponent(); 27 28 void collisionHandler(Entity* theOtherEntity, sf::FloatRect collision); 29 30 std::string getName(); 31 static Entity* getEntityNamed(std::string name); 32 33 // Variables (member / properties) 34 private: 35 std::map<std::type_index, Component::Ptr> mComponents; 36 std::string mName; 37 38 static std::unordered_map<std::string, Entity*> entities; 47
Section 3 DEVELOPMENT X-GSD 39 }; In order to provide the aforementioned functionality of an Entity, this class has to inherit from SceneGraphNode and hold a mName string and mComponents, a collection of Component::Ptr —an alias typedef for Component wrapped into std::unique ptr—. This collection is a std::map in which the key is a particular std::type index, and therefore an Entity can only hold one instance per type. The behaviour of the Entity class divides in methods which override those marked as virtual in SceneGraphNode, methods for Component handling, the collisionHandler callback method and a pair of getters. All overridden methods limit to propagate the invocation to all components of the Entity, if any. For example, this is the onPauseThis implementation: 1// Entity.cpp 2 3void Entity::onPauseThis(const HiResDuration& dt) 4{ 5// Perform update call of components/controllers 6for (auto iter = mComponents.begin(); iter != mComponents.end(); ++iter) 7{ 8iter->second->onPause(dt); 9} 10 } The collisionHandler method’s implementation follows the same structure, although it does not override any method. This method is used as a callback by the PhysicsEngine if a collision occurs. More details will be given later in its section. The addComponent,removeComponent and getComponent methods are responsible of handling the mComponents collection accordingly and notifying the Component of attachment/detachment events. For an in-depth explanation, read the comments of the implementation: 1// Entity.cpp 2 3void Entity::addComponent(Component::Ptr component) 4{ 5// Add this entity’s reference to the component’s pointer 6component->entity = this; 7 8// Notify the component that it has been added to an entity 9component->attachedToEntity(); 10 11 // Store the component according to its type 12 mComponents[std::type_index(typeid(*component))] = std::move(component); 13 } 14 15 16 // Entity.hpp 17 18 template <typename T> 19 std::unique_ptr<T> Entity::removeComponent() 20 { 21 // Retrieve the type_index of T 22 std::type_index index(typeid(T)); 23 24 // Ensure that a component with type T exists in the collection 48
X-GSD Section 3 DEVELOPMENT 25 assert(mComponents.count(std::type_index(typeid(T))) != 0); 26 27 // Retrieve it from the collection and cast it back to the T polymorphic type 28 T *tmp = static_cast<T*>(mComponents[index].get()); 29 30 // Remove it from the collection and return it 31 std::unique_ptr<T> removedComponent(tmp); 32 mComponents[index].release(); 33 mComponents.erase(index); 34 35 // Notify the component that it has been removed from an entity 36 removedComponent->detachedFromEntity(); 37 38 // Finally, return the component. If no ownership is claimed, it will be destroyed. 39 return removedComponent; 40 } 41 42 template <typename T> 43 T* Entity::getComponent() 44 { 45 // Retrieve the type_index of T 46 std::type_index index(typeid(T)); 47 48 // If it exists in the collection, retrieve it, cast it back to the T polymorphic type and return it 49 if (mComponents.count(std::type_index(typeid(T))) != 0) { 50 return static_cast<T*>(mComponents[index].get()); 51 } 52 // Otherwise, a nullptr is returned 53 else { 54 return nullptr; 55 } 56 } Finally, the Entity class offer a simple mechanism of retrieving any Entity anywhere in code only by specifying its name. A static collection of entities (a map of string as keys and Entity pointers as values) is filled/emptied as instances of Entity are constructed/destructed. 1// Entity.cpp 2 3// Static initialization 4std::unordered_map<std::string, Entity*> Entity::entities; 5 6// Static method 7Entity* Entity::getEntityNamed(std::string name) 8{ 9// Look for an specific entity by its name in the entities collection 10 auto found = entities.find(name); 11 if (found != entities.end()) 12 return found->second; 13 else 14 return nullptr; 15 } 16 17 // Constructor 18 Entity::Entity(std::string name) 19 : mName(name) 20 { 21 // Insert a reference of the new Entity in a collection of pairs name-entityPointer 22 auto inserted = entities.insert(std::make_pair(name, this)); 23 24 if (inserted.second == false) 25 throw std::runtime_error("Insertion of entity with name [" + name + "] failed."); 26 } 27 28 // Destructor 29 Entity::~Entity() 30 { 31 // Delete this entity’s pointer from the entities collection 49
Section 3 DEVELOPMENT X-GSD 32 auto found = Entity::entities.find(mName); 33 assert(found != Entity::entities.end()); 34 Entity::entities.erase(mName); 35 } Then, from any place one can retrieve a pointer to a specific Entity using the getEntityNamed static method: 1// Some class .cpp or .hpp 2 3Entity *playerEntity = Entity::getEntityNamed("player"); 3.3.2 Component class This class mainly serves as the base class from which to inherit when implementing a specific Component, such as ComponentSprite. The derived class must override the desired methods and implement their behaviour. If a method is not overridden, the Component’s implementation of that method will be used instead, which is an empty method. The Component class, similarly to the SceneGraphNode class, inherits from sf::NonCopyable and therefore its copy constructor is disabled, making it less error-prone. 1// Component.hpp 2 3class Component : sf::NonCopyable 4{ 5// Typedefs and enumerations 6public: 7typedef std::unique_ptr<Component> Ptr; 8 9// Methods 10 public: 11 Component(); 12 virtual ~Component(); 13 14 virtual void attachedToEntity(); 15 virtual void detachedFromEntity(); 16 17 virtual void onEntityAttach(); 18 virtual void onEntityDetach(); 19 virtual void onPause(const HiResDuration& dt); 20 21 virtual void update(const HiResDuration& dt); 22 virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; 23 virtual void handleEvent(const Event& event); 24 25 // Callbacks for other common components 26 virtual void collisionHandler(Entity* theOtherEntity, sf::FloatRect collision); 27 28 // Variables (member / properties) 29 public: 30 Entity* entity; 31 32 }; Regarding the data of the class, it only stores a pointer to the Entity holding this Component. The available methods are mostly the already known update, draw,handleEvent,onPause and collisionHandler; two renamed methods from Entity: onEntityAttach and onEntityDetach (called onAttach and onDetach 50
X-GSD Section 3 DEVELOPMENT in the Entity class) and a new pair of methods with names attachedToEntity and detachedFromEntity. These last two get invoked when the Component is attached to or detached from an Entity, which should not be confused with onEntityAttach and onEntityDetach because these are invoked when a Scene- GraphNode or Entity is attached to or detached from another SceneGraphNode or Entity —but it is interesting to have them in Component so that actions can be taken in response to these events—. X-GSD already provides three Component-derived classes integrated with the engine: ComponentSprite, ComponentRigidBody and ComponentCollider. They offer very basic functionality with much room for improvement, but sufficient for the scope of this project and for building some example games. There exists also the option for the user to create their own custom components —the Controllers—, so that custom behaviour can be implemented and then added to entities. Figure 12: UML diagram of Component-derived classes. 3.3.3 ComponentSprite The term sprite has already been explained along this work, but as a remainder: it is a graphical representation (in 2D) of some object of the game, such as the character. There is almost no game without graphics, and therefore a Component to implement such behaviour is compulsory. SFML already provides this functionality with the sf::Sprite class, so the ComponentSprite class is a simple wrapper of it. Its interface is fairly simple: A private sf::Sprite of which some properties can be accessed through some getters and setters, two different constructors which vary in the number of arguments, and an override of the draw method. 1// ComponentSprite.hpp 51
Section 3 DEVELOPMENT X-GSD 2 3class ComponentSprite : public Component 4{ 5// Methods 6public: 7ComponentSprite(const sf::Texture& texture); 8ComponentSprite(const sf::Texture& texture, sf::IntRect textureRect); 9~ComponentSprite(); 10 11 void draw(sf::RenderTarget& target, sf::RenderStates states) const override; 12 13 sf::FloatRect getGlobalBounds(); 14 sf::Color getColor(); 15 const sf::Texture& getTexture(); 16 sf::IntRect getTextureRect(); 17 18 void setColor(sf::Color color); 19 void setTexture(sf::Texture& texture); 20 void setTextureRect(sf::IntRect textureRect); 21 22 23 // Variables (member / properties) 24 private: 25 sf::Sprite mSprite; 26 }; The sf::Texture argument of both constructors and the setter represents the texture —the picture from which the sprite will draw pixels—. One of the constructors and a setter expect a sf::IntRect, which is an SFML data structure to hold a rectangle (a point and a size), and in this case represents the portion of the texture19 which will be used to render the sprite. If no texture rect is given, the entire texture is used for rendering the sprite. More advanced implementations could configure the texture of the sprite from a configuration file generated by a texture-packing software. Figure 13: Texture atlas and single texture files. Finally, getGlobalBounds return a rectangle in which the sprite is contained, 19In games development is very common to optimize the GPU operations by putting many textures together in the same file —called texture atlas,sprite sheet or tile set depending on their contents— so that the texture is uploaded to the GPU memory only once. Then, each object hold the coordinates and the size of the desired texture in the texture atlas. 52
X-GSD Section 3 DEVELOPMENT and the -Color getter and setter let the user to access and modify the tint colour of the sprite —a colour which will be added to the texels20 The implementation will not be shown here as it simply consists on calling the same setters and getters of sf::Sprite on the mSprite private variable, excepting the draw method that finally uses the sf::RenderTarget& reference that has been passed around all these classes to render the sprite: 1// ComponentSprite.cpp 2 3void ComponentSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const 4{ 5// Draw the sprite on the render target 6target.draw(mSprite, states); 7} 3.3.4 ComponentRigidBody This component can be added to an Entity with needs for physics simulation. That is, the Entity will get its position updated according to several physics properties such as mass, velocity and force. Such physics properties are represented by the PhysicState class (see Appendix 6.5). Besides, if the Entity also holds a ComponentCollider —the class is explained on the next section—, the PhysicsEngine (see Appendix 6.6) will track it and call its collisionHandler method if a collision occurs. 1// ComponentRigidBody.hpp 2 3class ComponentRigidBody : public Component 4{ 5// Methods 6public: 7ComponentRigidBody(bool isKinematic); 8~ComponentRigidBody(); 9 10 void onEntityAttach() override; 11 void update(const HiResDuration& dt) override; 12 13 void returnToLastPhysicsState(); 14 15 PhysicState& getPhysicsState(); 16 17 void pausePhysics(); 18 void resumePhysics(); 19 20 // Variables (member / properties) 21 private: 22 bool mKinematic; // If true, the Entity’s position does not get affected by physics, but still triggers collisions 23 bool mPausedPhysics; 24 25 PhysicState mPhysics; 26 27 PhysicState mLastPhysicsState; 28 sf::Transformable mLastTransformable; 29 }; 20Texture elements, similarly to the concept of pixel or picture elements, are the individual coloured square-dots that conform the texture. 53
Section 3 DEVELOPMENT X-GSD 7#include <X-GSD/ComponentRigidBody.hpp> 8#include <X-GSD/ComponentCollider.hpp> 9#include <X-GSD/Entity.hpp> 10 #include <X-GSD/Event.hpp> 11 #include <X-GSD/Game.hpp> 12 #include <X-GSD/Debug.hpp> 13 #include <X-GSD/Time.hpp> 14 15 #include <SFML/Graphics.hpp> 16 #include <SFML/Audio.hpp> 17 #include <SFML/System/Vector2.hpp> This solution is far from ideal and lacks some features such as being able to configure some values of the controllers in scene JSON files or make modifications to scripts without recompiling. Dynamic libraries were considered, but their compatibility through different platforms and operating systems depend on their native APIs, and therefore the decision was not to use dynamic libraries for simplicity. However, one could implement that feature, or rely in a library like Poco.sharedLibrary[28] With this, all aspects and elements of X-GSD have been finally covered. 3.4 Example game The next section will explain step by step how to create an example game with X-GSD. Here is a list of the steps to be done: 1. Install dependencies and tools (SFML, IDE, compiler, etc.) 2. Create a new project (directory structure, X-GSD files, etc.) 3. Modify the contents of gameconfig.json 4. Create a TitleScene.json file and add the necessary resources 5. Create and implement a TitleSceneController 6. Modify the ControllersRegistration.hpp after each Controller creation 7. Create a GameScene.json file and add the necessary resources 8. Create and implement a GameSceneController 9. Create and implement a PlayerController 10. Create and implement an AsteroidController 11. Build and run! First of all, SFML must be installed as it is the main dependency of X-GSD. There is a learn[7] section in the SFML website with instructions for installing the library and configure a IDE/compiler. X-GSD is developed with SFML 2.1, but there should not be a problem to use newer versions. However, if that is the case, it can be solved installing SFML 2.1, or looking into the error messages and trying [7] Laurent Gomila. SFML. http://www.sfml-dev.org/learn.php. 60
X-GSD Section 3 DEVELOPMENT to fix them. The project creation depends on the platform, IDE and personal preferences. The tutorials in the SFML website also offer project templates for some IDEs in order to create new SFML projects easily. Once the project is created, the X-GSD files must be referenced or copied into the project. The recommended directory structure is the following: If the decision was to reference X-GSD, it is still recommended to copy the ControllersRegistration.hpp file into GameProject/include/Game/ and the Main.cpp file into GameProject/src/Game and use these. If not, modifying these would result in side effects for other projects using X-GSD also in referenced mode. The next step is to create the gameconfig.json file in GameProject/resources/configuration/. For the example, this configuration will be used: { "windowName" : "X-GSD Example Game", "windowSize" : { "width" : 720, "height" : 480 }, 61
Section 3 DEVELOPMENT X-GSD "fullscreen" : false, "vsync" : false, "keyRepetition" : false, "mouseCursorVisible" : false, "debugFont": "PressStart2P.ttf", "icon" : "playerShip.gif", "initialScene" : "TitleScene.json" } This configuration file will make the game to run in windowed mode of resolution 720x480, without vsync (if the OS allows that), no key repetition, invisible mouse cursor, a custom icon, a font for debug information on screen and an initial scene called TitleScene.json. The needed resources (the icon, font and scene) must be placed correctly in their directories as explained before. The initial scene TitleScene.json must be created and added to the scenes directory: { "name": "TitleScene", "entities": [ { "name": "levelControllersContainer", "components": { "controllers": [ { "type": "TitleController" } ] } }, { "name": "logo", "parentEntityName": "root", "transform": { "origin": { "x": 128, "y": 128 }, "position": { "relative": true, "x": 0.5, "y": 0.35 }, "scale": { "x": 2, "y": 2 } }, "components": { "ComponentSprite": { "globalTexture": false, "texture": "titleLogoTexture" }, "controllers": [] } } ], "resources": { "textures": [ { "name": "titleLogoTexture", "path": "logoSprite.png" } ], "fonts": [ { "name": "mainFont", 62
X-GSD Section 3 DEVELOPMENT "path": "PressStart2P.ttf" } ], "sounds": [ { "name": "selectionSound", "path": "selection.ogg" } ] } } This file declares some dependencies: A texture, a font, a sound and a Controller of type TitleController. All these must be added to the appropriate directories. The the header and implementation files of the TitleController are the following: // TitleScene.hpp #pragma once #include <X-GSD/ControllerHeaders.hpp> using namespace xgsd; /* Controller for the logic of the TitleScene. */ class TitleMenuController : public Component { // Typedefs and enumerations private: // Methods public: TitleMenuController(); ~TitleMenuController(); void onEntityAttach() override; void update(const HiResDuration& dt) override; void draw(sf::RenderTarget& target, sf::RenderStates states) const override; void handleEvent(const Event& event) override; // Variables (member / properties) private: sf::Text mTextPressAnyKey; sf::RectangleShape mBackground; sf::Sound mMenuSound; HiResDuration mPressAnyKeyTime; }; #include "TitleController.hpp" TitleMenuController::TitleMenuController() : mBackground() { // Load resources here (RAII) } void TitleMenuController::onEntityAttach() { // Sound mMenuSound.setBuffer(Game::instance().getLocalSoundManager().get("selectionSound")); 63
Section 3 DEVELOPMENT X-GSD // Font sf::Font& mainFont = Game::instance().getLocalFontManager().get("mainFont"); mTextPressAnyKey.setFont(mainFont); // String mTextPressAnyKey.setString("Press any key to start"); // Size mTextPressAnyKey.setCharacterSize(14); // Positioning sf::Vector2f viewSize = Game::instance().getWindow().getView().getSize(); sf::FloatRect textRect = mTextPressAnyKey.getLocalBounds(); mTextPressAnyKey.setOrigin(textRect.left + textRect.width/2.0f, textRect.top + textRect.height/2.0f); mTextPressAnyKey.setPosition(viewSize.x / 2.0f, viewSize.y / 1.2f); // Color mTextPressAnyKey.setColor(sf::Color::Transparent); // Background mBackground.setSize(viewSize); mBackground.setFillColor(sf::Color(50, 100, 200)); } void TitleMenuController::update(const HiResDuration& dt) { // Update "Press any key" blinking animation mPressAnyKeyTime += dt; if (mPressAnyKeyTime > ONE_SECOND / 2) { if (mTextPressAnyKey.getColor() == sf::Color::White) mTextPressAnyKey.setColor(sf::Color::Transparent); else mTextPressAnyKey.setColor(sf::Color::White); mPressAnyKeyTime = xgsd::HiResDuration(0); } } void TitleMenuController::draw(sf::RenderTarget &target, sf::RenderStates states) const { // Draw background target.draw(mBackground, states); // Draw text on top of everything target.draw(mTextPressAnyKey, states); } void TitleMenuController::handleEvent(const Event& event) { if (event.type == Event::System) { auto systemEvent = event.systemEvent; // Perform appropiate actions if (systemEvent.type == sf::Event::KeyPressed || systemEvent.type == sf::Event::JoystickButtonPressed) { // Pressing Esc will close the game if (systemEvent.key.code == sf::Keyboard::Escape) { Game::instance().getWindow().close(); return; } // Any other key or button: mMenuSound.play(); // Load Game scene Game::instance().getSceneManager().loadSceneFromFile("GameScene.json"); } } } 64
X-GSD Section 3 DEVELOPMENT TitleMenuController::~TitleMenuController() { // Cleanup } This Controller must be added to ControllersRegistration.hpp #pragma once #include <X-GSD/ControllersManager.hpp> // Include all of your controllers #include "TitleController.hpp" // <- Added line class ControllersRegistration { public: void registerControllers(xgsd::ControllersManager& controllersManager) { // Register controllers this way controllersManager.registerController<TitleMenuController>("TitleController"); // <- Added line } }; This is the result: The following steps would be creating a JSON scene file for the game scene, implement a Controller for the logic of that scene, create and implement other two Controllers for the player and the enemies, modify the ControllersRegistration.hpp file to include these and finally build and run the game. 65
Section 3 DEVELOPMENT X-GSD Figure 15: Example game running with debug rendering activated. The code for the remaining steps will be omitted for simplicity. It can be found in the attached files of this work and the GitHub repository[2]. 66
X-GSD Section 4 CONCLUSION 4 Conclusion The game development field is relatively new and continuously evolving. With each new game and with every new technology or platform, many new programming challenges emerge. Game engines can help developers to worry less about technologies and platforms and focus more on the development of the game, working on a higher level of abstraction. However, being bound to a closed third-party game engine can be a problem —the reasons were explained at the beginning of this work—. Besides, the fact that game engines handle the low level details does not mean the programmer should not know about them: After all, a programmer who has understandings of the game engine internals will probably do better than a programmer who does not. In one hand, the exercise of creating a game engine can help a programmer to understand how game engines work, to think of the vast amount of possibilities behind every single feature and to reason about each decision-making. In that sense it is clear that facing such challenge has a beneficial learning value for the programmer. On the other hand, to create a game engine with plans for using it in real-world projects in mind can also be dangerous if the magnitude of the project and required features are not measured properly, or the team is too small or inexpert in this field, because it could lead to undesired results or be too much time-consuming. One could consider creating its own game engine to meet the requirements of some project for several reasons. But if the game to be developed needs cuttingedge features and the team is not capable of developing them or it is not worthwhile, it may be wiser to use an industry-proven game engine. If that is the decision, one should then preferably look for an open-source engine so that one could modify it, be it for features addition, error fixing or even being able to react at some unfortunate event such as those listed at the introduction of this work without having to rely on external factors. All along this work, a simple game engine has been successfully developed with the goals of cross-platform targeting, data-oriented programming, free software and simplicity, although it does offer few features with much room for improvement. Because of these and other reasons explained in the methodology section, C++, SFML and JSON were selected to develop the engine, X-GSD. The structure of the engine consist of a continuous simulation loop combined with a simple scene graph implemented by a tree structure and a scene-entity- component organization hierarchy. Such structure can be seen as a mix of the one proposed at the SFML Game Development Book[14] and a organization hierarchy similar to some popular engines as Unity, which would be easy to understand and result familiar to some of the users of those engines. Due to the dangers of creating a game engine stated above, some of the initial plans were cancelled: more components such as GUI-related ones and more features for the existing components as automatic reaction to collisions for ComponentRigidBody. The game engine is working and available for free on a GitHub repository[2] with the hope of being useful for those interested in learning about games programming, or even grow with the contributions of different people. 67
Section 5 IMPROVEMENT PROPOSALS X-GSD 5 Improvement proposals Aiming to build a full-featured game engine by oneself is both hard and unrealistic. Even with this taken into account, several features were implemented in a very basic manner and others were cancelled due to lack of time. Besides, even the most complete engines continue evolving, adding features, enhancing several parts and fixing many errors. With this in mind, a list of improvement proposals —with no specific order— has been elaborated: •Graphical editor: Because positioning elements with a scene editor is always clearer and easier. The editor would read and write scene JSON files with the format presented in this work or an enhanced one. •Provide more built-in Components: At least basic components such as GUI- related (texts, buttons, etc.), light sources and particle emitters. •Enhance the ComponentSprite, ComponentCollider and ComponentRigid- Body: There are details on what parts could be enhanced in their sections. •Actions and callbacks for Entities, with easing options. •Input bindings instead of hard-coded values for the controls of the game. •Add a Z-index property to SceneGraphNodes. The renderer should get a collection of drawable references in the desired order of rendering. In order for this to work, drawables should be decoupled from the scene graph (may be in a separate binary tree, with references between them). •Enhance the physics engine or integrate an open-source solution. •Enhance the resources managing system (see [8]). •Let the user to specify options and values of their controllers in scene JSON files (see [9]). •Introduce a runtime-compiled C++ system (see [10] and [11] or a scripting language compatibility such as LUA or JavaScript for faster development iterations. •Introduce threading/multi-core features (SFML does provide a Thread class). [8] Sean Middleditch. Dangers of std::shared ptr. http://seanmiddleditch.com/ dangers-of-stdshared_ptr/. [9] Stefan Reinalter. Schema-based entity-component data for fast iteration times. https://molecularmusings.wordpress.com/2014/02/21/ schema-based-entity-component-data-for-fast-iteration-times/#more-484. [10] Doug Binks, Adam Rutkowski, Matthew Jack, and Juliette Foucaut. Runtime-compiled c++. http://runtimecompiledcplusplus.blogspot.co.uk/. [11] Stefan Reinalter. Using runtime-compiled c++ code as a scripting language: under the hood. https://molecularmusings.wordpress.com/2014/05/10/ using-runtime-compiled-c-code-as-a-scripting-language-under-the-hood/ #more-487. 68
X-GSD Section 5 IMPROVEMENT PROPOSALS •Network-related features (SFML also provides networking classes and utilities). 69
Section 6 APPENDIX X-GSD 39 40 void PhysicState::setMass(float mass) 41 { 42 assert(mass > 0); 43 mMass = mass; 44 } 45 46 float PhysicState::getMass() const 47 { 48 return mMass; 49 } 6.6 PhysicsEngine class This class provide a simple collision detection mechanism based on axis-aligned bounding boxes intersection, taking advantage of the intersects method of SFML’s sf::Rect<typename T> class. For more advanced collision detection techniques, see these two articles: N Tutorial A - Collision Detection and Response[22], N Tutorial B - Broad-Phase Collision[23]. The integration methods of this class have been implemented with the help of this Integration Basics article[12]. 1// PhysicsEngine.hpp 2 3#pragma once 4 5#include <X-GSD/Time.hpp> 6#include <X-GSD/PhysicState.hpp> 7#include <X-GSD/ComponentCollider.hpp> 8 9#include <SFML/System/Vector2.hpp> 10 #include <SFML/Graphics/Transformable.hpp> 11 12 #include <set> 13 14 namespace xgsd { 15 16 // Needed struct for RK4 method. 17 struct Derivative 18 { 19 sf::Vector2f dp; // dp/dt = velocity 20 sf::Vector2f dv; // dv/dt = acceleration 21 }; 22 23 class PhysicsEngine 24 { 25 // Typedefs and enumerations 26 public: 27 typedef std::unique_ptr<PhysicsEngine> Ptr; 28 29 // Methods 30 public: 31 void checkCollisions(); 32 33 void addStaticCollider(ComponentCollider* collider); 34 void addDynamicCollider(ComponentCollider* collider); 35 void deleteStaticCollider(ComponentCollider* collider); 36 void deleteDynamicCollider(ComponentCollider* collider); 37 38 private: 39 Derivative static evaluateRK4(const PhysicState& initialPhysics, 40 const sf::Transformable& initialTransf, 41 const HiResDuration& dt, 76
X-GSD Section 6 APPENDIX 42 const Derivative& d); 43 44 sf::Vector2f static accelerationRK4(const PhysicState& 45 physics); 46 47 // Class methods 48 public: 49 void static integrateEuler(PhysicState& physics, 50 PhysicState& lastPhysics, 51 sf::Transformable& transf, 52 sf::Transformable& lastTransf, 53 const HiResDuration& dt); 54 55 void static integrateRK4(PhysicState& physics, 56 PhysicState& lastPhysics, 57 sf::Transformable& transf, 58 sf::Transformable& lastTransf, 59 const HiResDuration& dt); 60 61 // Variables (member / properties) 62 private: 63 std::set<ComponentCollider*> staticColliders; // Colliders whose Entity does not have a RigidBody 64 std::set<ComponentCollider*> dynamicColliders; // Colliders whose Entity has a RigidBody 65 }; 66 67 }// namespace xgsd The implementation of the collision detection mechanism is plenty of comments explaining each step. For better understanding of the integration methods, see the aforementioned Integration Basics article. 1// PhysicsEngine.cpp 2 3#include <X-GSD/PhysicsEngine.hpp> 4 5#include <SFML/Graphics/Rect.hpp> 6 7using namespace xgsd; 8 9// Very basic collision detection algorithm based on axis-aligned bounding boxes intersection 10 void PhysicsEngine::checkCollisions() { 11 12 // Check between dynamic colliders first (entities which have a collider and a rigidBody) 13 for (auto iterD = dynamicColliders.begin(); iterD != dynamicColliders.end(); ++iterD) { 14 15 // If the entity containing this collider is pending of destruction, skip it 16 if ((*iterD)->entity->isDestroyPending()) 17 continue; 18 19 sf::FloatRect intersection; 20 21 // Get the global bounds rect of one entity 22 sf::FloatRect rectD = (*iterD)->entity->getWorldTransform().transformRect((*iterD)->getRectBounds()); 23 24 // Check between dynamic colliders (entities which have a collider and a rigidBody) 25 for (auto iterD2 = std::next(iterD); iterD2 != dynamicColliders.end(); ++iterD2) { 26 27 /* The starting point of the iterator is the next item of iterD because dynamic colliders 28 must check collision between them avoiding repetition (1-2 is the same as 2-1). Also, 29 it avoids self-collision detecton (1-1, 2-2, etc). 30 */ 31 32 // If the entity containing this collider is pending of destruction, skip it 33 if ((*iterD2)->entity->isDestroyPending() || (*iterD)->entity->isDestroyPending()) 34 continue; 35 77
Section 6 APPENDIX X-GSD 36 // Get the global bounds rect of the other entity 37 sf::FloatRect rectD2 = (*iterD2)->entity->getWorldTransform().transformRect((*iterD2)->getRectBounds()); 38 39 // Check collision with SFML and call collisionHandler of both entities 40 if(rectD.intersects(rectD2, intersection)){ 41 (*iterD)->entity->collisionHandler((*iterD2)->entity, intersection); 42 (*iterD2)->entity->collisionHandler((*iterD)->entity, intersection); 43 } 44 } 45 46 // Check between dynamic (entities which have a collider and a rigidBody) and static colliders (entities which have a collider but no rigidBody) 47 for (auto iterS = staticColliders.begin(); iterS != staticColliders.end(); ++iterS) { 48 49 // If the entity containing this collider is pending of destruction, skip it 50 if ((*iterS)->entity->isDestroyPending() || (*iterD)->entity->isDestroyPending()) 51 continue; 52 53 // Get the global bounds rect of the other entity 54 sf::FloatRect rectS = (*iterS)->entity->getWorldTransform().transformRect((*iterS)->getRectBounds()); 55 56 // Check collision with SFML and call collisionHandler of both entities 57 if(rectD.intersects(rectS, intersection)){ 58 (*iterD)->entity->collisionHandler((*iterS)->entity, intersection); 59 (*iterS)->entity->collisionHandler((*iterD)->entity, intersection); 60 } 61 } 62 } 63 } 64 65 void PhysicsEngine::addStaticCollider(xgsd::ComponentCollider *collider) 66 { 67 auto inserted = staticColliders.insert(collider); 68 assert(inserted.second); 69 } 70 71 void PhysicsEngine::addDynamicCollider(xgsd::ComponentCollider *collider) 72 { 73 auto inserted = dynamicColliders.insert(collider); 74 assert(inserted.second); 75 } 76 77 void PhysicsEngine::deleteStaticCollider(xgsd::ComponentCollider *collider) 78 { 79 auto found = staticColliders.find(collider); 80 assert(found != staticColliders.end()); 81 staticColliders.erase(collider); 82 } 83 84 void PhysicsEngine::deleteDynamicCollider(xgsd::ComponentCollider *collider) 85 { 86 auto found = dynamicColliders.find(collider); 87 assert(found != dynamicColliders.end()); 88 dynamicColliders.erase(collider); 89 } 90 91 // Simple integrator. Cheap, but accumulates a lot of error as time advances. 92 void PhysicsEngine::integrateEuler(PhysicState& physics, 93 PhysicState& lastPhysics, 94 sf::Transformable& transf, 95 sf::Transformable& lastTransf, 96 const HiResDuration& dt) 97 { 98 float dtValue = ((float)dt.count()/ONE_SECOND.count()); 99 100 // Save last physics state and transformable 101 lastPhysics = physics; 102 lastTransf = transf; 103 transf.setPosition(transf.getPosition() + physics.getVelocity() * dtValue); 104 physics.setVelocity(physics.getVelocity() + (physics.getForce() / physics.getMass()) * dtValue); 105 } 106 78
X-GSD Section 6 APPENDIX 107 // More accurate than Euler, but a bit more resource-consuming. 108 void PhysicsEngine::integrateRK4(PhysicState& physics, 109 PhysicState& lastPhysics, 110 sf::Transformable& transf, 111 sf::Transformable& lastTransf, 112 const HiResDuration& dt) 113 { 114 float dtValue = ((float)dt.count()/ONE_SECOND.count()); 115 116 // Save last physics state and transformable 117 lastPhysics = physics; 118 lastTransf = transf; 119 120 Derivative a,b,c,d; 121 Derivative initial; 122 123 a = evaluateRK4(physics, transf, HiResDuration::zero(), initial); 124 b = evaluateRK4(physics, transf, dt / 2, a); 125 c = evaluateRK4(physics, transf, dt / 2, b); 126 d = evaluateRK4(physics, transf, dt, c); 127 128 sf::Vector2f dpdt = 1.0f / 6.0f * 129 ( a.dp + 2.0f * (b.dp + c.dp) + d.dp ); 130 131 sf::Vector2f dvdt = 1.0f / 6.0f * 132 ( a.dv + 2.0f * (b.dv + c.dv) + d.dv ); 133 134 transf.setPosition(transf.getPosition() + dpdt * dtValue); 135 physics.setVelocity(physics.getVelocity() + dvdt * dtValue); 136 } 137 138 // Auxiliar function for RK4 integrator 139 Derivative PhysicsEngine::evaluateRK4(const PhysicState& initialPhysics, 140 const sf::Transformable& initialTransf, 141 const HiResDuration& dt, 142 const Derivative& d) 143 { 144 float dtValue = ((float)dt.count()/ONE_SECOND.count()); 145 146 PhysicState physics; 147 sf::Transformable transf; 148 transf.setPosition(initialTransf.getPosition() + d.dp * dtValue); // Add the velocity to position 149 physics.setVelocity(initialPhysics.getVelocity() + d.dv * dtValue); // Add the acceleration to velocity 150 physics.setForce(initialPhysics.getForce()); 151 physics.setMass(initialPhysics.getMass()); 152 153 Derivative output; 154 output.dp = physics.getVelocity(); 155 output.dv = accelerationRK4(physics); 156 return output; 157 } 158 159 // Auxiliar function for RK4 integrator 160 sf::Vector2f PhysicsEngine::accelerationRK4(const PhysicState& physics) 161 { 162 return physics.getForce() / physics.getMass(); 163 } 79
Section REFERENCES X-GSD References [1] Apple Inc. 64-bit and ios 8 requirements for app updates. https:// developer.apple.com/news/?id=12172014b. [2] Andr´es Ruiz Bernabeu. X-gsd github repository. https://github.com/ AndresRuizBernabeu/X-GSD. [3] Doug Binks, Adam Rutkowski, Matthew Jack, and Juliette Foucaut. Runtime-compiled c++. http://runtimecompiledcplusplus.blogspot. co.uk/. [4] Blender Foundation. Blender. http://www.blender.org. [5] Neil Butterworth. C++ debug macros. https://latedev.wordpress.com/ 2012/08/09/c-debug-macros/. [6] Cocos2d-x.org. Cocos2d-x. http://www.cocos2d-x.org/products# cocos2dx. [7] Crytek GmbH. Cryengine. http://cryengine.com/features. [8] Beman Dawes and Rene Rivera. Boost filesystem library. http://www.boost. org/doc/libs/1_36_0/libs/filesystem/doc/index.htm. [9] Epic Games Inc. Unreal engine. https://www.unrealengine.com/ what-is-unreal-engine-4. [10] Glenn Fiedler. Fix your timestep! http://gafferongames.com/ game-physics/fix-your-timestep/. [11] Glenn Fiedler. Gaffer on games. http://gafferongames.com/. [12] Glenn Fiedler. Integration basics. http://gafferongames.com/ game-physics/integration-basics/. [13] GitHub Inc. Github ·build software better, together. https://github.com/, February 2008. [14] Laurent Gomila. Github of the SFML game development book, resourceholder class. https://github.com/LaurentGomila/ SFML-Game-Development-Book/blob/master/02_Resources/Include/ Book/ResourceHolder.hpp. [15] Laurent Gomila. Github of the SFML game development book, scenenode class. https://github.com/SFML/SFML-Game-Development-Book/ blob/master/03_World/Include/Book/SceneNode.hpp. [16] Laurent Gomila. SFML. http://www.sfml-dev.org/learn.php. [17] Laurent Gomila. SFML github wiki. https://github.com/LaurentGomila/ SFML/wiki. [18] Jan Haller, Henrik Vogelius Hansson, and Artur Moreira. SFML Game Development. Packt Publishing, June 2013. 80
X-GSD Section REFERENCES [19] json.org. Introducing json. http://www.json.org. [20] LangPop. Programming language popularity. http://langpop.com/. [21] Baptiste Lepilleur. Jsoncpp. https://github.com/open-source-parsers/ jsoncpp. [22] Metanet Software. N tutorial a - collision detection and response. http: //www.metanetsoftware.com/technique/tutorialA.html. [23] Metanet Software. N tutorial b - broad-phase collision. http://www. metanetsoftware.com/technique/tutorialB.html. [24] Sean Middleditch. Dangers of std::shared ptr. http://seanmiddleditch. com/dangers-of-stdshared_ptr/. [25] Robert Nystrom. Game Programming Patterns. Genever Benning; 1 edition, November 2014. [26] Robert Nystrom. Game programming patterns. http:// gameprogrammingpatterns.com/, 2014. [27] Robert Nystrom. Game programming patterns. singleton. http:// gameprogrammingpatterns.com/singleton.html, 2014. [28] G¨unter Obiltschnig. Poco class sharedlibrary. http://pocoproject.org/ docs/Poco.SharedLibrary.html. [29] Okam Studio. Godot game engine. http://www.godotengine.org/. [30] Photon Storm Ltd. Phaser. http://phaser.io. [31] Stefan Reinalter. Schema-based entity-component data for fast iteration times. https://molecularmusings.wordpress.com/2014/02/21/ schema-based-entity-component-data-for-fast-iteration-times/ #more-484. [32] Stefan Reinalter. Using runtime-compiled c++ code as a scripting language: under the hood. https://molecularmusings.wordpress.com/2014/05/10/ using-runtime-compiled-c-code-as-a-scripting-language-under-the-hood/ #more-487. [33] Stefan Schindler. Optank development. http://www.optank.org/ game-development-design/. [34] Scirra Ltd. Construct 2. https://www.scirra.com/construct2. [35] ShiVa Technologies SAS. Shiva. http://www.shivaengine.com/. [36] Bjarne Stroustrup. A Tour of C++ (C++ in Depth Series). Addison Wesley, September 2013. [37] UBM TechWeb. Gamasutra - the art & business of making games. http: //www.gamasutra.com/, 1997. [38] Unity Technologies. Unity. http://unity3d.com/unity. 81
Section REFERENCES X-GSD [39] Wikipedia. List of unreal engine games. http://en.wikipedia.org/wiki/ List_of_Unreal_Engine_games. [40] YoYo Games Ltd. Gamemaker: Studio. https://www.yoyogames.com/ studio. 82