Bachelor’s Thesis Muad Mahmud Sakah

A hybrid procedural generation applied to 2D design and terrains

Muad Mahmud Sakah

COSC-4235 Thesis

Specialization: Computer Science (Game Design) Minor: Mathematics

Director: Ratvinder Grewal

Department of Mathematics and Computer Science Faculty of Sciences, Engineering, and Architecture Laurentian University Sudbury, Ontario, Canada

©Muad Sakah, Winter 2021

1 Bachelor’s Thesis Muad Mahmud Sakah ______

Acknowledgments I would like to express my gratitude and appreciation for all the people who supported and encouraged me throughout these last four years. I would like to thank the computer science and mathematics department for the help and support they provided me. I also would like to take the time to thank Dr. Ratvinder Grewal for taking the time to be my thesis supervisor and supporter, I appreciate everything he has done for me.

Secondly, a lot of appreciation goes to Dr. Aaron Langille for introducing me to the computer science field and creating an open and exciting environment for everyone to participate in.

Finally, I would like to thank all these participants (friends) who helped me with the testing’s that were done to make this project very successful and perform efficiently:

Mouhamed Gningue Laurentian Hickey Mathieu Roy Anthony Milad Ricardo Grant Nabil Alyatem Moaad Balaban

Thank you all for your support and faith in me!

2

Bachelor’s Thesis Muad Mahmud Sakah

Abstract (English)

The main objective of this project is to create a 2D-level platformer and terrain(s) by focusing on the use of a procedural generation instead of manually designing them by hand. Procedural content generation (PCG) techniques have often been limited to very unique types of game elements in game development. PCG has mostly been used to create complete game levels, with the exception of dungeons, which are a particular category of game level found in adventure and role-playing games. Dungeon levels and terrains are particularly well-suited to demonstrating the benefits of PCG due to their unique combination of speed, gameplay, and game spaces. By focusing on procedural generation, this project took a unique approach in designing 2D-dungeons and terrains by mainly focusing on a mathematical and algorithmic approach.

This has concluded in a project that is capable of automatically re-generating itself by randomly generating different dungeon levels and terrains. Both of these procedural generations are unique with their separate techniques and aspects. The dungeon generation is designed to randomly generate a new dungeon each time the game runs, while the terrain generation is an infinite terrain that continues to generate and only focuses on the land and mountain generation.

Bear in mind, that the dungeon generation has to meet a criterion in order for it to generate properly: the feasibility of the generation, the system must be able to generate beatable dungeons; the complexity, the path challenges the levels may present to a player if this was implemented into a game.

The terrain generation had its own minor list of conditions that it needs to meet: the generation, the terrain has to be capable of infinitely re-generating itself on a single platform.

Apart from the generating procedures, the project has resulted into a procedural generation that can be used by a game developer to implement within they’re game(s).

3

Bachelor’s Thesis Muad Mahmud Sakah ______

Abstract (French) L'objectif principal de ce projet est de créer un jeu de plateforme et un (des) terrain (s) de niveau 2D en se concentrant sur l'utilisation d'une génération procédurale au lieu de les concevoir manuellement à la main. Les techniques de génération de contenu procédural (PCG) ont souvent été limitées à des types très uniques d'éléments de jeu dans le développement de jeux. PCG a principalement été utilisé pour créer des niveaux de jeu complets, à l'exception des donjons, qui sont une catégorie particulière de niveau de jeu trouvée dans les jeux d'aventure et de rôle. Les niveaux et les terrains des donjons sont particulièrement bien adaptés pour démontrer les avantages de PCG en raison de leur combinaison unique de vitesse, de gameplay et d'espaces de jeu. En se concentrant sur la génération procédurale, ce projet a adopté une approche unique dans la conception de donjons et de terrains 2D en se concentrant principalement sur une approche mathématique et algorithmique.

Cela s'est conclu dans un projet capable de se régénérer automatiquement en générant de manière aléatoire différents niveaux et terrains de donjon. Ces deux générations procédurales sont uniques avec leurs techniques et leurs aspects distincts. La génération de donjons est conçue pour générer aléatoirement un nouveau donjon à chaque exécution du jeu, tandis que la génération de terrain est un terrain infini qui continue de générer et se concentre uniquement sur la génération des terres et des montagnes.

Gardez à l'esprit que la génération de donjons doit répondre à un critère pour qu'elle se génère correctement: la faisabilité de la génération, le système doit être capable de générer des donjons battables; la complexité, le chemin défie les niveaux peuvent présenter à un joueur si cela a été implémenté dans un jeu.

La génération de terrain avait sa propre liste mineure de conditions qu'elle doit remplir: la génération, le terrain doit être capable de se régénérer à l'infini sur une seule plate-forme.

Outre les procédures de génération, le projet a abouti à une génération procédurale qui peut être utilisée par un développeur de jeu pour implémenter dans son (ses) jeu (s).

4

Bachelor’s Thesis Muad Mahmud Sakah

Contents

Acknowledgments ...... 2 Abstract (English) ...... 3 Abstract (French) ...... 4 Contents ...... 5 List of Figures...... 7 List of Tables ...... 10 Chapter 1: Introduction ...... 11 1.1 Topic (PCG) ...... 11 1.2 Problem ...... 12 1.2.1 Scope of the project ...... 13 1.2.2 Games That Use Procedural Content Generation ...... 14 1.3 Context ...... 17 1.4 Development Tools ...... 18 1.4.1 Game Engines ...... 19 1.5 Generators ...... 19 1.5.1 Level Generator (Dungeon) ...... 20 1.5.2 Tile Generator (Terrain) ...... 20 1.5.3 Game Engine ...... 20 Chapter 2: Project Organization ...... 21 2.1 The Process ...... 21 2.1.1 Research before Implementation...... 21 2.1.2 Project Planning ...... 22 2.2 Main Tasks ...... 22 2.2.1 Dungeon (map) Generator ...... 23 2.2.2 Area Generation (for dungeons) ...... 23 2.2.3 Terrain Scale Generation ...... 23 2.3 Final Tasks ...... 24 2.3.1 Action Plan ...... 24 2.3.2 Action Plan Alterations ...... 24

5

Bachelor’s Thesis Muad Mahmud Sakah ______

2.3.3 Timetable ...... 25 Chapter 3: 2D-Dungeon Procedural Generation ...... 26 3.1 Random Walker Algorithm ...... 26 3.1.1 Mathematical Implementation ...... 27 3.2 Alternative methods ...... 29 3.2.1 Teleological Algorithms ...... 29 3.2.2 Ontogenetic Algorithms ...... 30 3.3 Random Walker Algorithm with PCG ...... 31 3.4 Design ...... 32 3.4.1 Room Connections ...... 36 3.5 First Implementation ...... 36 3.5.1 Grid Initialization ...... 37 3.5.1 Update Method Implementation ...... 38 3.6 Second Implementation (Down Direction) ...... 39 3.6.1 Downwards Direction ...... 40 3.7 Third Implementation (Left and Right Direction) ...... 41 3.7.1 Right Direction Generation System ...... 42 3.7.2 Left Direction Generation System ...... 44 3.8 Early Tests/Experiments ...... 46 3.8.1 First Test/Experiment ...... 46 3.8.2 Second Test/Experiment(s) ...... 47 3.9 Final Results ...... 48 3.9.1 Final Results Examples (With Different Tiles) ...... 50 Chapter 4: Terrain, Single Scale Tile Generation ...... 52 4.1 Design Process ...... 52 4.2 Alternative Methods (Noise Algorithms) ...... 53 4.2.1 Fractal Noise ...... 53 4.2.2 Value Noise ...... 54 4.2.3 Perlin Noise ...... 55 4.3 Implementation Process ...... 56 4.3.1 Tile Creation ...... 56 4.3.2 Main Variable(s) Initialization ...... 57 4.3.3 Scale and Frequency Implementation (Height, Width, Depth) ...... 58

6

Bachelor’s Thesis Muad Mahmud Sakah

4.3.4 Height Frequency ...... 60 4.3.5 Perlin Noise Implementation ...... 61 4.4 Final Results ...... 62 Chapter 5: Conclusion ...... 65 Bibliography ...... 66

7

Bachelor’s Thesis Muad Mahmud Sakah ______List of Figures

Figure 1: Spelunky, “Word on the wind” example of 2D platformer. [4] ...... 14 Figure 2: Rogue Legacy “GameReactor”. [5] ...... 15 Figure 3: “Terraria” – Example of a level within the game. [6] ...... 15 Figure 4: Project tools. [9] [12] [11] [10] ...... 18 Figure 5: Dungeon Generator...... 23 Figure 6: Small area part of the dungeon generator...... 23 Figure 7: Terrain generation ...... 23 Figure 8: A graph representing the Random Walk Technique. [19] ...... 26 Figure 9: First mathematical implementation [19]...... 27 Figure 10: Second step within the mathematical implementation [19]...... 27 Figure 11: Third mathematical step, unseeded set of nodes [21]...... 28 Figure 12: Fourth mathematical implementation step [21]...... 28 Figure 13: Fifth mathematical implementation step [21]...... 28 Figure 14: 4x4 Grid created on the Unity Engine [9]...... 32 Figure 15: 4x4 Grid acting as an array of size 16 (0-15)...... 33 Figure 16: Tile-set Design 1. [25] ...... 34 Figure 17: Tile-set Design 2. [25] ...... 34 Figure 18: Tile-set Design 3. [25] ...... 34 Figure 19: Tile-set Design 4. [26] ...... 35 Figure 20: Tile-set Design 5. [26] ...... 35 Figure 21: 4x4 Grid with all 16 rooms [27]...... 37 Figure 22: Dungeon-grid initialization [27]...... 37 Figure 23: Position script for all 16 positions [27]...... 38 Figure 24: Single Location Generation (First Step) [27]...... 39 Figure 25: Downward Generation Code Implementation [27]...... 40 Figure 26: Downward Direction Generation [27]...... 41 Figure 27: Right Direction Generation Implementation [27]...... 42 Figure 28: Right and Downward Generation [27]...... 43 Figure 29: Left Direction Generation Implementation [27]...... 44 Figure 30: Left and Downward Generation [27]...... 45 Figure 31: First Generation [27]...... 46 Figure 32: Test/Experiment Phases [27]...... 47 Figure 33: Test/Experiment Phases [27]...... 47 Figure 34: Completion Path 1 (From Start to Finish) [27]...... 48 Figure 35: Full Generated 2D-Dungeon [27]...... 49 Figure 36: This a 2D Dungeon using a gold brick as a Tile [27] [26]...... 50 Figure 37: This 2D Dungeon is using a regular brick wall as its Tile [27] [26]...... 50 Figure 38: This 2D Dungeon is using Soapstone bricks as its Tiles [27] [26]...... 51 Figure 39: The image on the left is a representation of our completed path. The image on the right displays the complete dungeon after the random locations have been randomly filled in with tiles [27]. .51

8

Bachelor’s Thesis Muad Mahmud Sakah

Figure 40: Fractal Noise Terrain Frequency. [31] ...... 53 Figure 41: Value Noise Terrain Frequency [33]...... 54 Figure 42: Perlin Noise Function Frequency [34]...... 55 Figure 43: Tile Creation [27] [9]...... 56 Figure 44: Tile Components [9] ...... 56 Figure 45: Variable Initialization [27]...... 57 Figure 46: Tile Skeleton [27] [9]...... 58 Figure 47: Scale Initialization within the terrain body...... 58 Figure 48: Generated Terrain Skeleton [27]...... 59 Figure 49: Terrain with Frequency signal call [27]...... 59 Figure 50: GenerateMountains() Method [27]...... 60 Figure 51: Mountains and Hills across the tile [27]...... 60 Figure 52: Up-close look at the mountains and hills [27]...... 61 Figure 53: Perlin Noise Implementation [27]...... 61 Figure 54: Terrain Generation after implementing Perlin Noise [27]...... 62 Figure 55: This is a side of view the Terrain Generation [27]...... 62 Figure 56: A full representation of a Generated Terrain...... 63 Figure 57: This Terrain’s scale was modified to a new set of dimensions [9] [27]...... 63 Figure 58: This is another example where we have modified our scale...... 64 Figure 59: This is a smaller modified dimensional scale terrain generation...... 64

9

Bachelor’s Thesis Muad Mahmud Sakah ______

List of Tables

Table 1: This table lists games that use PCG in unique and different forms [7] ...... 16 Table 2: Timetable ...... 25 Table 3: Teleological Algorithm generations ...... 30 Table 4: Ontogenetic Algorithm generations...... 31 Table 5: Estimated Generation time for 3 Tests [27]...... 49

10

Bachelor’s Thesis Muad Mahmud Sakah

Chapter 1: Introduction

The first chapter introduces the main idea of Procedural Generation (PCG) with other concepts tied in, and it will also cover the scope of the project. The main purpose of this thesis, as well as specific important tasks and objectives were also covered.

1.1 Topic (PCG)

Many users are unaware of the usability of procedural generators. These procedural generators are used all over the industry in areas such as games, software, programs, security, etc. Users need to become more aware of these generators as it has a lot of space to evolve into something greater. A procedural generator can be used with many things, but in this case, I am primarily focusing on the use of it with video games. The need for procedural generators has been growing in the last couple of years. Many gaming studios started to implement these generators within their games as it saves them a lot of time. Game developers use these generators to create characters, landscapes, buildings, random objects, etc. Procedural generators are evolving into a major component within video games and it wouldn’t be that surprising If it became a norm for most future games. Researchers such as R. Smelik and T. Tutenel describe procedural generation as “any kind of automatically generated asset based on a limited set of user-defined input parameters” [1].

Procedural Content Generation (PCG) refers to this digital content algorithmic development. In order to generate some type of material, developers establish algorithms and rules, often involving some randomness that the machine then follows. Procedural Generation has been used for a long time, in fact, it’s been used in a couple of games and films that you may have played and seen without even knowing. This thesis covers Procedural Generation in the game development field.

The main highlight of Procedural Content Generation is that a program can produce several amounts of content faster than a human designer that’s manually doing it. A lot more content can be created within a particular time frame by using computational resources when creating content. A game designer no longer has to design each level by hand, which can be a very time-consuming job. As an outcome, it is possible to produce content for any video game that can be more cheaply

11

Bachelor’s Thesis Muad Mahmud Sakah ______produced and efficient. It also helps games to have much wider variety than conventional techniques. Once the algorithm(s) have been completed, it is possible to generate a nearly infinite amount of content, which makes it theoretically possible to provide players with many different new experiences and content. Researchers Roden and Parberry [2] think that these algorithms used in PCG are amplification algorithms, meaning that we take a small piece of input parameters that are then transformed into larger sets of output data.

Procedural generation is a fascinating design/development avenue. Replay-ability is also a great draw, allowing what can be called a new experience every time you play a game.

1.2 Problem

Procedural generation is an exciting way to experiment with architecture. is a popular feature that allows players to have a new experience each time they play a game [3]. In the world of video game development, there is a well-recognized issue concerning the relentless growth in the number of assets a modern game requires. Every year, new video games usually consist of improved textures, wider/larger maps, a massive focus on graphics and design, and in general, more material for computer games assets that need artists, programmers, and designers to create them. Video game studios have taken multiple approaches in solving this manner, but there are two common methods that most studios approach: the first approach is when studios branch of their companies worldwide in order to hire more employees and obtain different skills from individuals around the world or they focus on developing a procedural generator with which consists of multiple algorithms that will execute the job that’s required.

This project is focused on developing a procedural generation for 2D dungeons and terrain platformers, which would dismiss the fact of needing a level designer to develop these procedures. Procedural generation, however, is not a method that can be used as a general solution for all situations, and a particular problem needs to be selected to completely customize the algorithm to produce something like a real designer might do.

12

Bachelor’s Thesis Muad Mahmud Sakah

1.2.1 Scope of the project

In the next few sections, I will clarify how the issue we introduced in the earlier section will be solved. Then, the project's reach and possibilities would be more clearly defined. What is more, it will clarify the methodology behind all the work, and tools or methods for monitoring and validation will also be revealed.

My idea is to design a hybrid procedural generator that will entirely focus on generating levels for a 2D game as well as auto-generating a terrain using different sets of algorithms, mathematical equations, and geometry. My research will involve me finding different techniques and ideas that can help me incorporate the three different principles I mentioned above, how I can enhance them, and how to implement them in my topic. There are many approaches I can take to creating my own procedural generator, but I’m specifically trying to develop and research a generator that can be used on 2D games as well as generating terrains that require the ability to use noise functions.

2D Dungeon: It will be a more challenging job to construct the interior of rooms where, in a similar way to the map, a graph will be generated. Each node, however, in this case will be the platforms where the dungeon path is generated from start to finish.

Terrain: The terrain is slighter easier to work with unlike the dungeon. The Terrain uses functions to generate its tall mountains without using a particular algorithm. The terrain is essentially generated on a single tile.

13

Bachelor’s Thesis Muad Mahmud Sakah ______

1.2.2 Games That Use Procedural Content Generation

It is difficult to include a full overview among all games that have used PCG, and how they have used it, given the long history of PCG in games. It is important, however, to provide a brief overview of which games have been particularly significant in the history of PCG in games, which is intended to be presented in this section.

Figure 1: Spelunky, “Word on the wind” example of 2D platformer. [4]

Spelunky is recognized as one of the best 2D side-scrolling games that implements the idea of using Procedural Generation. The levels, objects, monsters, and so on are all procedurally created each time you play. The dungeon is a destructible environment, and the different game elements will communicate with each other in quite a few ways.

Spelunky creates random levels, but also has a level builder that enables the sharing of levels. The game consists of various levels throughout five different regions, which are created to contrast the standard level layout between each area using various procedural generation algorithms: this also helps to lead to a slightly distinct style of dungeon crawling for each area.

14

Bachelor’s Thesis Muad Mahmud Sakah

Figure 2: Rogue Legacy “GameReactor”. [5]

Rogue Legacy is a 2D platformer that’s centered around a castle discovery. The map is made of rooms, as in The Binding of Isaac, but the rooms may be of various sizes in this case and are combinations of pre-made components. This game gave us the concept of allowing the map to take more liberty in its creation while not breaking the rules we make, and it is the most similar to the planned outcome of the project.

A game such as Terraria is a great example since it implements the use of both dungeon and terrain generation.

Figure 3: “Terraria” – Example of a level within the game. [6]

15

Bachelor’s Thesis Muad Mahmud Sakah ______

Terraria [6] is great example of procedural content generation with the mixture of both terrain and dungeon generation. It uses a large scale of procedural content generation in generating a large range of 2D worlds that players can interact with at their own will. We will discuss games such as Terraria [6] and the process behind their design/development more in depth as we proceed throughout this paper.

These two video game examples mentioned above are but a glimpse of the enormous number of games using PCG and the varying quantities of content that can be produced, but hopefully it will provide some insight into PCG's various possibilities and how it has been used.

Title Developer Year PCG Content Rogue Legacy Cell Door Games 2011 Interconnected rooms in a 2D Side-Scroller. Spelunky Mossmouth 2008 Tile-based 2D side-scrolling underground rectangular levels No Man’s Sky Hello Games 2016 Planets and their flora and fauna in 3D galaxies Factorio Wube Software 2016 Terrain generation in 2D Starbound Chucklefish 2016 Generated planets with content such as dungeons and bosses on them. 2D Pixel Piracy Quadro Delta 2015 2D world with islands, cities, and stores, as well as the crew of a ship Minecraft Mojang 2011 3D worlds generated with monsters and dungeons Terraria Re-Logic 2011 2D-World with generated terrain content

Table 1: This table lists games that use PCG in unique and different forms [7]

The table above lists eight different games that implement some sort of procedural generation content within them. These are some of the games that I proceeded with learning their development process so that it gives me and understanding of how these developers were able to implement different types of content into their games.

16

Bachelor’s Thesis Muad Mahmud Sakah

1.3 Context Virtual worlds are gaining growing prominence in the sense of games and simulations. If we look at a game such as The Elder Scrolls V: Skyrim [8]. The complexity and commitment to create a believable and functional 3D or 2D world can be seen as a task for a wide team of experienced designers over a period of several months.

This project has three main areas of focus that are not entirely apart from each other. First, we must make sure that both of our generations are organized and structured properly so that the implemented methods can execute accordingly. Second, we have to focus on the design and generation of the 2D dungeon by implementing our used methods/algorithms and running a couple of tests to make sure that we receive the output that we expected. Third, is to focus on the generation of our Terrain by implementing suitable methods and functions to make sure that our Terrain generates itself properly.

When speaking about automatically generating levels, game developers have developed many methods to generate many levels using random or pseudo-random generators and sets of rules to control this generation as a workaround or alternative to hiring a level designer. There are several techniques that adjust to the numerous options we may been researching for. We intended to analyze the automatic level generators that operate with phases of maps and 2D platformers, and to create a combination that adds something different to this field of interest.

I needed to dig deep into many other projects that have tried this for this reason, and we need to take the concepts that might be beneficial and simplify them for the mix.

The idea of using PCG has been around for a quite long time period. Many researchers and companies have come up with their own PCG’s for specific uses on whatever projects they intended on using them for.

17

Bachelor’s Thesis Muad Mahmud Sakah ______

1.4 Development Tools

The main tool for the creation of this entire project was the Unity Game Engine [9], which is a great engine for most game development that I am familiar with. At first, the go to engine was Godot [10], but I had no experience with it so I stuck with Unity which turned out for the better at the end. The programming language used in this project was C# since that's the default IDE in Unity [9].

All the code for this project was written in the latest version of Visual Studio [11]. There was a little focus on using Aseprite [12] to make sprites and tiles for the artistic design of the generation.

Figure 4: Project tools. [9] [12] [11] [10]

There are many alternative assets and methods that can be used to complete this project, but these programs that were used completed the task very well.

working on. The idea here was to research those methods and to simply apply the one(s) that were suitable for these specific tasks: 2D Dungeon and Terrain.

18

Bachelor’s Thesis Muad Mahmud Sakah

1.4.1 Game Engines A game engine is the key tool for making a video game and there are two ways: to create your own engine for the video game you want to build or to use a game engine already made for a general purpose. A general-purpose game engine will be used to create the video game and save time, as the main aim of the project is to concentrate on the procedural generation in the level (dungeon) design and terrain generation.

Unity Game Engine [9]. It’s one of the most well-known gaming engines out there and it still maintains a great number of features and tools that can be used for game development. One of the best features available on Unity is that its accessible to many assets and they are very easy to import and use.

1.5 Generators One of the most used components of procedural generation in video games is map generation and particularly dungeon generation (a dungeon made of different connected rooms), which is also a frequent topic for discussion [13] [14] [15]. There are several methods for generating maps that have already been made, but we will not focus on any prior implementation besides the Random Walker Algorithm. We will build a map generator specifically built for a 2D side-view dungeon platformer and generate a random terrain using all the ideas gathered from the methods investigated. The decision to build my own generator is partly due to the fact that much of the previous research was not conducted with a side-view platformer as the goal in mind and because of the feeling of having to create my own creative procedures by focusing on that one specific algorithm.

19

Bachelor’s Thesis Muad Mahmud Sakah ______

1.5.1 Level Generator (Dungeon) The process of generating small challenges in spaces procedurally instead of utilizing pre-made patterns seems not to have been explored very much, so we can introduce our own approach (which is intended to have a result that is much less repeated than other simplified approaches we have seen). Keep in mind that this is a procedural generation meaning that each time the level Is executed, it randomly generates an entirely new level.

1.5.2 Tile Generator (Terrain)

The procedure of infinitely generating a terrain on a single tile sounds more complex than I originally anticipated. During this procedure, I was introduced to a function known as Perlin Noise which was available to use on the Unity Game Engine. I essentially used this function and applied my knowledge and research to make it unique compared to many others that exist.

1.5.3 Game Engine

Unity will be my main tool for the development of this project since its versatile enough to allow us without any complexities to use procedural generation, and it is easy enough not to spend time studying how it works. In addition, I am more familiar with the Unity engine compared to the rest that exist today which save me a good chunk of time.

20

Bachelor’s Thesis Muad Mahmud Sakah

Chapter 2: Project Organization This chapter is going to breakdown the planning and organization of the time and resources spent on this project. The project officially started around mid-September 2020 after this topic was accepted by my supervisor Dr. Ratvinder Grewal. The planning described in the next few pages is the optimal commitment allocation for the 6-7month period between the start and finish of the project, but we must keep in mind that the work time would almost certainly have to conform to the progress.

2.1 The Process Although the project will be run using the Unity Engine for development, which means tasks will be described at each phase, a prior classification of all, or at least groups of, tasks is required to schedule the project's timeline. In certain ways, agile implementation would enable the development to evolve and look for alternatives, but the following are the classes of tasks that must be completed for the project to be finished.

2.1.1 Research before Implementation. This minor section covers the information and research that was conducted before officially starting to work on this project:

➢ Examining the backgrounds and current state of the art of interesting subjects. ➢ Examining the feasibility and time investment of multiple solutions. ➢ Deciding on an optimal and efficient solution ➢ Classifying the problem's initial name and definition. ➢ Testing out small prototypes ➢ Watching other programs attempting to create Procedural Generators.

A couple of these tasks were performed with the assistance of the some of the acknowledged students, and although they are not part of the project, they were decisions that led to its growth. They will also assist in future activities such as defining the latest state of the project preparation.

21

Bachelor’s Thesis Muad Mahmud Sakah ______

2.1.2 Project Planning This small subsection quickly covers the project phases in brief bullet points. All these tasks had their own small phases that needed to be completed for that entire task to be accomplished:

➢ Planning ahead of time ➢ Time management is essential. ➢ Presentation of the preliminary data. ➢ Bibliography and context ➢ Justification for specialization ➢ Presentation and final text are in the preparation stages.

The plan was to accomplish a criteria every 3-4 weeks, this is the part of the project with the most flexibility over the time for each task so that the project works according to plan.

2.2 Main Tasks The tasks in this part would take the most commitment and resources out of the whole project. They are often the most vulnerable activities to modify and be influenced by alternatives as the project is being developed. They can be classified into three major categories.

These three major components are all discussed in the scope portion of the planning, although it's worth noting that the two generators are largely independent of one another, despite the fact that the goal is for them to function according to plan. As a result, the generators' development, like the rest of the project, will be iterative, and other minor portions of the project will begin development as soon as the generators are functional.

Due to this iterative approach, it's a smart idea to set aside some time after production to refactor the code. Refactoring the code can result in some optimization, but it is more necessary to improve readability and reduce flexibility for future maintainability and reuse in case anybody wanted to build upon it.

22

Bachelor’s Thesis Muad Mahmud Sakah

2.2.1 Dungeon (map) Generator During this process of the project, we must investigate and analyze various known algorithms, as well as the application and modification of these algorithms to the correct outcome for the dungeon generation we are trying to make, are all part of the creation of this generator.

Figure 5: Dungeon Generator.

2.2.2 Area Generation (for dungeons) The area generator, like the map generator, can be divided into two parts: research and implementation of an algorithm. Specific areas of our dungeon must generate properly and accordingly.

Figure 6: Small area part of the dungeon generator.

2.2.3 Terrain Scale Generation During this process of the project, we are required to implement our researched functions and algorithms that are specifically made for a specific task such as terrain generation. We must be able to work with large scales and use them to our advantage to implement different methods and algorithms for a hybrid generation.

Figure 7: Terrain generation

23

Bachelor’s Thesis Muad Mahmud Sakah ______

2.3 Final Tasks This category of tasks includes all of the tasks necessary to complete the documentation. It gives me time to complete any incomplete work and plan the project's final presentation. It's also the time to fix some last-minute issues when double-checking that everything is in order.

2.3.1 Action Plan Finally, a clarification of how the project will be executed.

The plan is to work off based on the research and methods conducted for this project such as the different sets of ontogenetic [16] and teleological [17] algorithms and the use of noise functions, but tasks are vulnerable to challenges and unforeseen delays, so we must be prepared to prioritize our main goal. First and foremost, if the implementation time is reduced, portions of the timeline such as code refactoring will be cut because they boost the project's consistency but are not completely necessary for it to function. In the worst-case situation, the analytics implementation will be the last thing to go, leaving the testers' assessment as completely arbitrary. If the time was already insufficient, the preparation would have been completely incorrect, and instead of just lowering the project standard, a new schedule based on the next semester would be implemented.

2.3.2 Action Plan Alterations This portion will explain how the time and resource planning has been implemented, as well as how it has altered. The task categories do not need to be repeated because they are the same as in the initial plan; however, we will show a timetable for each task, the first scheduled hours for these tasks, the approximate number of hours completed before the final presentation and an average of how finished the task was, and an approximate number of hours completed at the end.

24

Bachelor’s Thesis Muad Mahmud Sakah

2.3.3 Timetable Since this is a one-person project (me), we just need the table that indicates the time required for each task that we have identified in the text so far.

Tasks Estimated Hours Spent Hours Spent Hours Spent Hours (Fall Semester) (Winter (Final) Semester) Research 60 19 37 56 Project Planning 25 11 16 27 Dungeon 35 15 23 38 Generator Terrain 25 12 17 29 Generation Coding 30 10 15 25 Tests & 15 5 15 20 Prototypes Final Tasks 25 0 21 21 Total 215 72 144 216

Table 2: Timetable

The table above represents a rough estimate of the number of hours that was put in for each task. The four tasks that were the most time consuming was the conducted research, dungeon generator, terrain generation, and project planning.

25

Bachelor’s Thesis Muad Mahmud Sakah ______

Chapter 3: 2D-Dungeon Procedural Generation

This chapter explores the 2D-Dungeon procedural generation and the theory that relates to the project's method and effect. The different research methods that were used and discovered for this portion of the project are covered in detail. To have a basic understanding of some of the problems that must be tackled in Procedural Content Generation, some basic definitions and terminology widely used in procedural content generation are added.

3.1 Random Walker Algorithm

The random-walking is a sampling process whereby the number of paces between sample points is calculated by random numbers, typically taken from random-number tables, and the position of the next point is determined by a right-angle turn from each sample point, with a coin toss used to decide whether to turn left or right [18]. The random walker technique is categorized under the list of “path-finding” algorithms due to the reasons that it provides you with which ever type of path you need depending on the ground rules and criteria the developer has set in place.

Figure 8: A graph representing the Random Walk Technique. [19]

Figure 8 is a great visualization of how the random walker algorithm is executed. The random walker algorithm is a segmentation algorithm. The picture is represented as a line, with each pixel corresponding to a node that is connected to neighboring pixels by edges, which are weighted to indicate the degree of similarity between the pixels [20]. As we can see, there are 4 separate nodes placed on the grid, each node is referencing a specific location and the goal is that the nodes need

26

Bachelor’s Thesis Muad Mahmud Sakah

to connect by finding the most reliable and efficient path. In most cases, the start position is random and so is the end point, unless the developer had a specific idea in mind, he or she can modify the algorithm with their own liking so that the execution can meet the targeted requirements.

3.1.1 Mathematical Implementation

The likelihood that each node sends a random walker to the seeds can be determined analytically by solving a sparse, positive-definite set of linear equations with the Laplacian matrix, which can be represented with the variable L [19].

The algorithm was demonstrated to work for any number of labels (entities), but the example here uses only two labels (for simplicity of exposition).

Figure 9: First mathematical implementation [19].

Assume the image is represented by a line, with each node representing a pixel and each edge linking pixels in the same direction [20]. Node similarity is encoded using edge weights, which can be obtained from variations in image strength, color, texture, or some other significant function. It is normal to use the edge weighting function when using image strength at node, for example [19].

The map Laplacian matrix can then be built using the nodes, edges, and weights.

The random walker algorithm reduces the amount of energy used.

Figure 10: Second step within the mathematical implementation [19].

27

Bachelor’s Thesis Muad Mahmud Sakah ______

The optimization is constrained by Xi = 1 for Vi ∈f and Xi = 0 for Vi ∈b, where F and B denote the sets of foreground and background seeds, respectively. If we consider S to be the seeded set of nodes (i.e., S = F U B) and S' to be the unseeded set of nodes (i.e., S U S' = V, where V is the subset of all nodes), then the approach to the energy minimization problem is S U S' = V

Figure 11: Third mathematical step, unseeded set of nodes [21].

The subscripts denote the portion of the graph Laplacian matrix L indexed by each set.

It was shown in that one can maximize the energy by using probability (unary) terms in the algorithm.

Figure 12: Fourth mathematical implementation step [21]. F and B are positive, diagonal matrices. The system of linear equations is created by optimizing this capacity.

Figure 13: Fifth mathematical implementation step [21].

In this case, the set of seeded nodes, S, may be empty (i.e., S' = V), but the positive diagonal matrices allow for a special solution to this linear system.

28

Bachelor’s Thesis Muad Mahmud Sakah

3.2 Alternative methods

There were two alternative methods that could have been used to proceed with this particular part of the project. These two algorithms can be implemented in many different factors for procedural generation. Each algorithm has its unique features for different cases of generation including this 2D dungeon, but the random walker algorithm has proven to be the most efficient for dungeon generation, due to the fact that it focuses on one particular goal.

3.2.1 Teleological Algorithms

The teleological method builds an accurate physical model of the world and the mechanism that generates the thing created, then runs the simulation, with the effects appearing as they do in fact [22]. Teleological algorithms try to model the physical processes that lead to the desired procedural performance. Teleological algorithms are mostly approximations, but they may yield unexpected or unexpected effects.

Type(s) of Generation Teleological Algorithm

Artificial ☑️

City Generation

Dungeon Generation

Fluid Dynamics ☑️

Genetic Algorithm ☑️

Mazes

29

Bachelor’s Thesis Muad Mahmud Sakah ______

Reaction-Diffusion System ☑️

L-System

Table 3: Teleological Algorithm generations

The table above displays the generation possibilities by using the Teleological algorithm. The use of this algorithm would not have been efficient for a dungeon generation unless we working on developing a video game. In that case, there would be another algorithm used for the dungeon generation and the teleological algorithm(s) can be used to generate content and weather dynamics around or within the dungeon. In conclusion, proceeding with the random walker algorithm in this case is more suitable for this type of work.

3.2.2 Ontogenetic Algorithms

Ontogenetic algorithms try to replicate the final product of a physical process by ignoring the intermediate stages. They are, in this sense, an ad hoc algorithm rather than a simulation. The ontogenetic method looks at the end effects of the process and only uses ad hoc algorithms to try to replicate them directly. In real-time implementations such as games, ontogenetic methods are more widely used [23].

Type(s) of Generation Ontogenetic Algorithm

Artificial Life

City Generation ☑️

30

Bachelor’s Thesis Muad Mahmud Sakah

Dungeon Generation ☑️

Fluid Dynamics

Genetic Algorithm

Mazes ☑️

Reaction-Diffusion System

L-System ☑️

Table 4: Ontogenetic Algorithm generations.

The table above displays the key concepts for using the ontogenetic algorithm. The algorithm is capable of executing many different tasks, but its more efficient when it’s used for the specific tasks that are checked off above [16]. In conclusion, if I didn’t proceed with using the Random Walker Algorithm, I would of most likely have focused on different methods of performing the ontogenetic algorithm since it’s the closest to performance with the random walker algorithm.

3.3 Random Walker Algorithm with PCG When applying the random walker algorithm, we must ensure that it’s implemented in a procedurally generated technique. Meaning that our dungeon generation will have a couple of boundaries and advantages that will allow our generator to have more freedom. The main advantage is our dungeon will be capable of generating itself from any of the 16 locations on the grid as well as ending in any random location.

31

Bachelor’s Thesis Muad Mahmud Sakah ______

With this approach, we are capable of generating a dungeon that has the ability to completely generate a full path from start to finish. Afterwards, we can randomly generate more tiles so that we can completely cover our generated level, meaning that all of our empty locations will be filled in with randomly generated tiles so that we can have a complete dungeon on every area of our grid.

3.4 Design The map we want to create, as mentioned in the scope section of this paper, is a simple 4x4 grid with each box-grid representing a room and arcs between them representing adjacency. Furthermore, each box-grid contains all of the data required to construct its random generated path (which will be the responsibility of the room generator).

The first design choices were that the dungeon would have a path that is complete from start-to- finish so that if it was implemented into a video game, the level would be playable. A parameter was inserted in one of the functions that indicates whether or not the room has been generated correctly, and that the grid would not have loops and anything that’s copy-paste from one grid to another.

Figure 14: 4x4 Grid created on the Unity Engine [9].

32

Bachelor’s Thesis Muad Mahmud Sakah

This initial design was somewhat changed for implementation, as we wanted to make the box-grid of each space act as an array tile (no overlapping), which would make finding a room much simpler and the algorithm can work as planned. This has a number of other benefits, such as preventing two rooms from colliding in space and obtaining the closest rooms to connect with each other to form a full completable path.

Figure 15: 4x4 Grid acting as an array of size 16 (0-15).

As we seen in Figure 15, the 4x4 gird created in Unity has now been split-up and each room (area) has been numbered to indicate the number of rooms we have and the size of this dungeon.

When prototyping and researching, I soon discovered that making every room be the same size would significantly reduce the variety of the rooms (which is critical for the project) and make it impossible to build more than one exit on any of the rectangular room's walls, meaning that we can generate a dungeon that starts and ends from any room. So, the most optimal solution in this case was to implement an array of size 16 so that each area within the dungeon will act as its individual separate room and generate on its own and form one single path that is beatable. The initial idea to work with a grid was presented by a game developer who recommended it for anyone trying to create 2D dungeons [24].

This prompted me to revisit the concept, this time using the tiles and the tile collection (as in a grid of tiles) in a completely different way. Instead of spaces, each tile would be an indivisible portion

33

Bachelor’s Thesis Muad Mahmud Sakah ______of the space with partitions, exits, or none on each of its four sides, and each tile would have a connection to its room such that it can be easily determined if it is being used or not, and from which room whether it is not vacant.

Figure 16: Tile-set Design 1. [25]

Figure 17: Tile-set Design 2. [25]

Figure 18: Tile-set Design 3. [25]

34

Bachelor’s Thesis Muad Mahmud Sakah

Figure 19: Tile-set Design 4. [26]

Figure 20: Tile-set Design 5. [26]

These are five different style sets of tiles used within the dungeon generation. These different styles create the aesthetic appeal and ultimately the design of the procedural generated dungeon. In the end, any tile design can be used within the generation as long as it meets the right dimensions so that it fits within the grid. These different style options come into play depending on the style of a developer’s game. As I mentioned above, any tile design can be used within this generation, but it’s all dependent on how the developer what’s they’re game to appear.

My personal favorites are tile-set 1 and 5 due to the reasons that they create the most unique procedurally generated dungeons and they will be showcased later in this paper. However, I wanted to impose my restriction on approaching this design: all rooms and tiles must be in a square form. This limit was set to make map execution simpler, but also to avoid making the job of the room generators too complex before they started.

35

Bachelor’s Thesis Muad Mahmud Sakah ______

3.4.1 Room Connections With the aim of procedurally generating small task such as connecting our 16 locations rather than using pre-made patterns, we devised a graph strategy to aid in the creation of connecting our different rooms to ensure that they are compatible with each other. The graph's nodes are the various platforms that can be found in one of the locations, and the graph's edges are the moving relations between these platforms.

The 16 different locations on the grid only have details about their type and space, while relations have information about the platform from which location it begins and the location where it ends, the original position for the movement, the final position, and the type of movement this connection is.

This type of grid allows us to quickly determine if the path is feasible by determining whether a clear route exists between any of the room's exits. However, we can also verify whether the whole grid is linked to ensure there are no dead ends or pointless platforms with no way to access them. We will discuss the implementation in our next section where we go over the overall implementation of these different locations.

3.5 First Implementation

I began the actual development of the map generator after I had a clear understanding of what the map generator could produce and I was confident that I could do so thanks to the investigation and prototyping. As I said in the introduction, we would use an efficient algorithm that would create a 2D dungeon by using our grid that uses all 16 locations. This design, as discussed in the previous section, will be the most efficient method to use, with each room connected to its previous and subsequent rooms to form a complete dungeon.

36

Bachelor’s Thesis Muad Mahmud Sakah

Figure 21: 4x4 Grid with all 16 rooms [27].

The figure above is representing the implemented grid within Unity that will be used for this procedural generation. As we can see, each location on the grid has a blue dot that indicates which areas on the grid are the rooms where the procedural generation will occur. The first part of our generation is to complete generate our main path from start to finish. Afterwards, every available location will fill itself randomly with whichever tile we used. Each location has a room position script implemented within it that determines if the room if available or not.

3.5.1 Grid Initialization The information above discussed how the grid functions and briefly explains the implementation behind it. In this section, we are looking at how the grid has been formatted from its skeleton.

Figure 22: Dungeon-grid initialization [27].

37

Bachelor’s Thesis Muad Mahmud Sakah ______

From what we see in figure 22, the grid is structured around a 2d-array that helps us distinguish the different locations and areas within our map. Ultimately, each of the 16 locations will need to work together to form a generated path, this 2D array helps us achieve this specific generation and makes it much more understandable and efficient to work with.

3.5.1 Update Method Implementation

Figure 23: Position script for all 16 positions [27].

As we see in figure 23, this is the official script method that is implemented in every location on the grid. The method helps us determine if we should continue to procedurally generate the next location, depending on if the room is available or not. We used a couple of Unity’s commands such as deltaTime, Instantiate( ), Quaternion, and Physics2D.OverlapCircle [9] which can help us determine our conditions as well as the support use of the math functions implemented within Quaternion which can be used to limit the length of the generation in each room. In this case, we can place our GameObject which is the key RoomIsFull in Instantiate( ) to return a reference to the specific room we are trying to generate. Instantiate( ) is a RigidBody source where Unity can replicate the whole GameObject, including all elements, but the RigidBody portion of the cloned GameObject will be referenced by instantiate [9]. As a result, casting to GameObject will fail. Due to this method, we can efficiently implement our algorithm (that we will discuss in the next section) in another script and add to our grid so we can form an appropriate 2D dungeon generation.

38

Bachelor’s Thesis Muad Mahmud Sakah

As a result, we have a map that we can explore by following the links or easily reach a particular location by using the tile set’s tiles. The gird’s locations also show where it is and include a trail on how to get there that can be used in a variety of ways.

3.6 Second Implementation (Down Direction)

In this particular implementation, we have to focus and make sure that our dungeon is capable of generating at least one location. If we refer back to figure 23, this “Update” method will help us execute just a single location as we see below.

Figure 24: Single Location Generation (First Step) [27].

As we can see from figure 24, we have successfully generated one location at the top of our grid. The main objective in this case is to have the program generate in any of four locations that are located at the top of the grid. We want our generation to start at the top and work its way down by generating in different directions such as left, right and down. In this particular section, we will focus on the down generation.

39

Bachelor’s Thesis Muad Mahmud Sakah ______

3.6.1 Downwards Direction

Figure 25: Downward Generation Code Implementation [27].

The most critical feature within the dungeon is granting it the ability to generate downwards. We want our dungeon to have the freedom to generate in whichever location it wishes, however, we must adjust a couple of barriers so that it doesn’t infinitely continue to generate outside of our grid. We want to ensure that the program is capable of reading every location on the grid so that our path will be visible and there will be no overlapping within the tiles (generation that occurs over another generation).

Figure 25 displays the implementation method and techniques that were used to execute the downward direction generation. This implementation has two main features; First, it discovers the location of our opening room (between 1-4) so that it can use that as a starting point to generate downwards; The second main feature is the boundaries that exist within this implementation, it sets a couple of conditions on the generation so that it doesn’t oppose the circumstances which can cause it to overload the generation.

40

Bachelor’s Thesis Muad Mahmud Sakah

Figure 26: Downward Direction Generation [27].

Figure 26 is a representation of the downward direction generation on the grid. As we can see, the generation begins in the first position on the top left corner, the dungeon then generated downwards which leaves it with only two options available, it can either continue to generate downwards or generate in the right direction in order to complete a full dungeon generation.

3.7 Third Implementation (Left and Right Direction)

This is an important implementation after considering the downward direction first. We could of easily not have considered implementing a left and right direction system since we are already capable of generating a dungeon by just using the downward direction implementation, but we proceeded with idea of implementing the left and right movements so that it adds more creativity and realistic movements to our dungeon.

The implementation for both the left and right directions are part of the same method as the downward direction. All three movements were done within the same method so that we can efficiently use the random walker algorithm.

41

Bachelor’s Thesis Muad Mahmud Sakah ______

3.7.1 Right Direction Generation System

Figure 27: Right Direction Generation Implementation [27].

The “LocationMovement” method which consists of all three direction (left, right, down) generations is the most critical implementation for the complete generation of this dungeon. We first start off with the right direction movement. The function checks for the nearest location that is available on the right-hand side only, but there are also boundaries and conditions that are set in order for this generation to occur properly. We must ensure that the right-hand side generation does not proceed outside of our grid or occur unnecessarily when it’s not required.

After the conditions and boundaries have been set, the dungeon will continue to generate as long as the movement range does not exceed the grid. All three functions within this one method must communicate with each other in order to complete this generation. If it’s impossible for the dungeon to continue generating in the right-hand side, we must have a second and third alternative which are the left and downward generations.

42

Bachelor’s Thesis Muad Mahmud Sakah

Figure 28: Right and Downward Generation [27].

Figure 28 displays a representation of both the right and downward generation system in action. As we can see, this generation begins at the same location as figure 26, but the interior style of the dungeon location is different. When the dungeon reached the third location down the grid, it was left with two options; first, it could have completed its generation by making its way downwards once more, but instead it decided to generate in the right-hand side to form a more unique dungeon. This is not controllable by the programmer nor the designer, due to the format of its implementation, the dungeon has its own mind and it will randomly generate in which over location it wishes to with the boundaries and conditions we have set.

43

Bachelor’s Thesis Muad Mahmud Sakah ______

3.7.2 Left Direction Generation System

Figure 29: Left Direction Generation Implementation [27].

The left direction function is connected with right direction giving them the ability to communicate and work together. Similar to the right direction function, the left section ensures that the dungeon is generating within the correct parameters of our dungeon. The function must first recognize its current location so it could proceed its movement in either of the three directions.

We are working with a 2D scale, but we must initialize a 3D-vector with a z value of 0 so that the random walker algorithm can execute properly. After doing so, we can set the vector tile position as our main position so that the generated tile will be visible and different each and every time.

44

Bachelor’s Thesis Muad Mahmud Sakah

Figure 30: Left and Downward Generation [27].

Figure 30 is a great representation of both the left and downward direction generation. The main obvious difference here is the use of a different set of tile design compared to the previous images. Regardless of the different sets of tiles used, it does not have an impact on the generation aspect.

We can see that our generation begins at the top right corner. It eventually starts to procedurally generate downwards to the third level on the grid, then it decided to create a left direction generation all the way until the end which completes our full path from start to finish.

45

Bachelor’s Thesis Muad Mahmud Sakah ______

3.8 Early Tests/Experiments This minor section of chapter three explores a couple of early tests and experiments that were conducted throughout this phase of the project. These tests and experiments were conducted until we finally achieved our desired output which I we will discover in the next section.

We didn't think our own opinion would be enough to confirm the project's findings, so I devised a review for a couple of friends who were unaware of this project. These experiments were very brief and did not take much of these individuals times. What I essentially did was show them how the program would run and generate itself, then I would ask for any feedback such as if something should be changed or not. From a total of five individuals, everyone was surprised and thought the generation was unique and interesting. One individual on the other hand suggested I use different sets of tiles to generate new dungeons that have a different theme/style. This is the main reason why some of the figures above had separate styles and designs, it was due to the different sets of tiles used within those generations. Aside from this feedback, this simple test/experiment was set up so that I could draw my own conclusions on their reaction and feedback.

3.8.1 First Test/Experiment

Figure 31: First Generation [27].

46

Bachelor’s Thesis Muad Mahmud Sakah

This is the same image as figure 24. This is the first step in proceeding with this dungeon generation. Our first goal was to be able to at least generate one random location within our grid, this will give us the green light to advance with other generations so that they can procedurally generate together as a link.

3.8.2 Second Test/Experiment(s)

Figure 32: Test/Experiment Phases [27].

Figure 33: Test/Experiment Phases [27].

Figure 32 and 33 are a representation of a couple early tests I completed while the research method was still in progress. In Figure 32 for example, we can see that the right direction generation completely ignores our boundaries and conditions and continues to generate outside the grid. This why I had to emphasize on these conditions earlier since the proper format of this generation solely depended on them. Figure 33 is representation of all three directional generations down, right, and

47

Bachelor’s Thesis Muad Mahmud Sakah ______left. We can also notice that our generation continues to ignore the boundaries and conditions as if the borders around the grid don’t even exist. This is why it’s crucial to implement the random walker algorithm with a couple of conditions in place. Otherwise, we run into situations such as these two images above which will contradict the purpose behind the generation of these dungeons.

3.9 Final Results After we have completed implementing the random walker algorithm efficiently as show above in figures [29, 27, 25, 23]. The dungeon should be capable of generating a complete path from start to finish allowing us to perceive the completion route of that specific level, in case if this was implemented within a video game.

Figure 34: Completion Path 1 (From Start to Finish) [27].

In figure 34, the program executes the random walker algorithm we implemented and generates an entire path within our dungeon. The next step is to fill-in the empty locations (rooms) with randomly generated tiles so that our generated system would be visualized as a proper dungeon.

48

Bachelor’s Thesis Muad Mahmud Sakah

Figure 35: Full Generated 2D-Dungeon [27].

Figure 35 is the same example as figure 34, but this time the entire dungeon has been generated in every location of our grid. The original generated path we see in figure 34 still exists, the program only needed to randomly generate random tiles that can be placed within the empty rooms. This portion of the generation was not done using the random walker algorithm, it was a different function that only reacted as soon as it notices that the dungeon path is complete.

Generation # Path Time (Seconds) Full Generation Generation Time (Seconds) Movements 1 0.7 1 Down, Right, Down 2 1 2 Right, Down 3 0.9 1.4 Left, Down, Right

Table 5: Estimated Generation time for 3 Tests [27].

The table above displays the exact time for three conducted tests on this dungeon generation. The purpose behind this is to recognize the small amount of time that the random walker algorithm took to generate the complete dungeon.

Therefore, we can conclude that our methodology for the 2D Dungeon generation has efficiently accomplished our main objectives for this particular portion of this research project.

49

Bachelor’s Thesis Muad Mahmud Sakah ______3.9.1 Final Results Examples (With Different Tiles) Here are a couple more examples of a fully generated dungeon with different sets of tiles.

Figure 36: This a 2D Dungeon using a gold brick as a Tile [27] [26].

Figure 37: This 2D Dungeon is using a regular brick wall as its Tile [27] [26].

50

Bachelor’s Thesis Muad Mahmud Sakah

Figure 38: This 2D Dungeon is using Soapstone bricks as its Tiles [27] [26].

Figure 39: The image on the left is a representation of our completed path. The image on the right displays the complete dungeon after the random locations have been randomly filled in with tiles [27].

51

Bachelor’s Thesis Muad Mahmud Sakah ______

Chapter 4: Terrain, Single Scale Tile Generation This chapter will explore the final portion of this research project which is to procedurally generate an infinite terrain on a single tile. We will explore the research method that was implemented and discuss alternative methods and algorithms that could have been used. After introducing the topic and explaining the designing process, we will proceed with the implementation and discuss the unique features that these terrains are capable of performing.

This section will also cover many methods for creating and rendering spherical landscapes in real time. While the former task isn't difficult and can be accomplished using a number of techniques, the latter task necessitates the introduction of a suitable degree of information algorithm. The vast scale of the terrain that needs to be made in real time is the main reason for this.

4.1 Design Process In many games, terrain and landscapes are important since they can provide both scenery and gameplay opportunities. For a long time, procedurally generated terrains have been common in recent video games, with “Minecraft” acting as the successful role-model, where geometric algorithms were used to dynamically generate terrains during runtime [28].

The use of heightmaps (or heightfields), which are basically a collection of data containing height values for the surface, is a basic and very general way of representing a landscape [29]. Incorporating noise into a height map is one way to create a procedural terrain. Although merely randomizing each height value would not provide something that can be used as terrain in most situations, there are many different methods for creating more suitable conditions that use noise. Two noise algorithms are described below, as well as how to use fractals to make the terrain appear more normal [29].

52

Bachelor’s Thesis Muad Mahmud Sakah

4.2 Alternative Methods (Noise Algorithms) Let’s first briefly discuss our alternative methods that could have been implemented before we be examine our researched method in full detail. All three of these alternative methods are “Noise” frequency algorithms, which are the best tools for procedurally generating any sort of terrain. Due to the general lattice spacing, one consequence of using noise functions is that the outputted terrain is very smooth and fluctuates at very visible frequencies. Real geography, on the other hand, has many degrees of variety, which means that it has massive mountains and valleys, but when one looks closely, the same trend can be seen at a much smaller scale, creating surface roughness.

4.2.1 Fractal Noise Our first considered method was Fractal noise. Fractal algorithms are a popular approach for creating realistic looking terrain, particularly in game development, due to their simplicity and computational efficiency [30].

Figure 40: Fractal Noise Terrain Frequency. [31]

The concept is to build several heightmaps at various scales and then combine them together. The large-scale properties are first formed with a high intensity or amplitude of the noise function, and then the intensity is reduced while the frequency is increased with each subsequent phase, as seen in figure 40. As a result, when used in several passes, any noise function can be called a fractal noise algorithm, but there are other ways to create fractal terrain. The midpoint displacement method is one of the most basic and commonly used [32].

53

Bachelor’s Thesis Muad Mahmud Sakah ______

The concept of midpoint displacement is based on the positioning of two points and the consideration of a line segment extending between them. After that, the line is cut in two, and the center point is arbitrarily displaced with a maximum force [32]. This process is then repeated recursively for each newly generated line segment with a smaller displacement factor.

4.2.2 Value Noise Value noise is a basic method of creating a height map that involves randomly computing the heights of a variety of starting points and then interpolating between them. The starting points are set at a constant distance from one another, which can be adjusted depending on the situation. The height randomization range can also be adjusted to an appropriate value [28].

A slope function s is used for interpolation. The closest starting points are assigned weights according to a chosen function s(d), where d is the range from p to the starting point, for any point p between the starting points. The height at p would be if a point p is 1/10th of the way between lattice point a and lattice point b: (1 − s(1/10)) ∗ height(a) + s(1/10) ∗ height(b) [28].

Since the form of the function s influences the structure of the landscape, the function chosen has a major impact on the outcome. Linear, cosine, and cubic functions are common functions to use. A linear function produces straight lines with sharp ends, a cosine produces rounded results, and cubic functions generate slopes with different S-shapes based on the coefficients used.

Figure 41: Value Noise Terrain Frequency [33].

54

Bachelor’s Thesis Muad Mahmud Sakah

Cubic functions provide the best outcomes, but they are still the slowest. In comparison to the jagged lines of the linear function, the cubic function provides a smoother curvature, as seen in the figure 41.

4.2.3 Perlin Noise The function I decided to proceed with for the terrain generation is the Perlin Noise frequency algorithm. The main reasons for doing so are first, the Unity game engine has the algorithm already embedded within the engine making it easy to access and use compared to others, second, its due to the reason that many individuals are aware of Perlin Noise, but are not sure how it functions and that’s something I aim to show.

Perlin noise is similar to value noise in that it acts in the same manner. The distinction is that instead of creating random heights [32], the starting points are given random slopes and their heights are all equal. The heights of the points in between are then calculated based on the slopes of the surrounding starting points. The height at point p is determined by measuring what the height of p would be if it were only influenced by the particular starting point for each surrounding starting point. This is accomplished by multiplying the slope's value by the distance from that point. This involves using the dot product of the slope vector and the distance vector if the slopes are two- or more-dimensional. The various measured heights of p are then interpolated into a single value in the same manner as the heights of value noise are interpolated [30].

Perlin noise is a more complicated algorithm than value noise and fractal noise, but since the computations can be modified in a variety of ways, it isn't inherently more computationally intensive [28].

Figure 42: Perlin Noise Function Frequency [34].

55

Bachelor’s Thesis Muad Mahmud Sakah ______4.3 Implementation Process In this section, we will go over every step that was taken during the implementation process of this terrain generation. As mentioned back chapter 1, this project was completed using the Unity game engine and C# as the tool for coding.

4.3.1 Tile Creation The first step within this implementation, is we must create a tile using the “create object” option we are giving by Unity. We must keep in mind that the purpose of this generation is to design an infinite generating terrain on a single tile, meaning that we will only create one tile and keep its dimensions set as default.

Figure 43: Tile Creation [27] [9].

Figure 43 displays our created tile with its default dimension settings in the unity scene. Afterwards, we must add two important components to our tile, these components will be able to manage our terrain generation.

Figure 44: Tile Components [9]

56

Bachelor’s Thesis Muad Mahmud Sakah

As we can see from figure 44, we have two components; Terrain and Terrain Collider. Both of these components make unity recognize our tile object as a terrain, so that the implementation of our function would also recognize it as terrain triggering unity to place its terrain properties onto the tile.

4.3.2 Main Variable(s) Initialization During this implementation, we must set up our both of our Y and X coordinates. These two axes will support the generation from beginning to end, as well as determining the range of the generation.

Figure 45: Variable Initialization [27].

We first Initialized both force values and set them up as float variables that are equal to a 100. The variables don’t specifically need to be 100, but in this case, it helped us extend our generation range. Afterwards, we must set the floating range for both values by using Unity’s special command “Random.Range” which will set a range on both the X and Y axis. In this circumstance, we kept the X axis set as default which is 0 and set our Y axis to 9999 so our mountains and hills can generate efficiently.

57

Bachelor’s Thesis Muad Mahmud Sakah ______

Figure 46: Tile Skeleton [27] [9]. Figure 46 is a skeleton representation of our tile after both the component and force implementations. The skeleton is a great representation of the terrain components since it gives us a visualization of how the generation should occur.

4.3.3 Scale and Frequency Implementation (Height, Width, Depth) The scale portion of the implementation is essentially the main gut of the entire terrain. The scale will help us determine a combination of structures within the terrain such as the height, width, depth, and the scale value itself. These dimensional variables are adjustable and if their value is changed, it will affect the entire frequency of the terrain.

Figure 47: Scale Initialization within the terrain body [27].

This is the body of our terrain generation. We will first start off our generation by adjusting its speed to an appropriate value. Afterwards, we will create a 3D vector that will takes in the width,

58

Bachelor’s Thesis Muad Mahmud Sakah

depth, and height, allowing us to adjust the size for each of the three values. The adjustment to all three of these variables will ultimately affect the outcome of the terrain generation. Near the end of this chapter, we will look at some examples of how these modifications affect the generation of the terrain.

Figure 48: Generated Terrain Skeleton [27]. Figure 48 represents a completely generated dungeon skeleton. The reason being it’s a skeleton is due to the fact that we have not called in our Perlin Noise function. In this image, we have a frozen skeleton terrain, which is only missing a frequency signal that can only be done by calling the Perlin Noise function.

Figure 49: Terrain with Frequency signal call [27].

59

Bachelor’s Thesis Muad Mahmud Sakah ______

Figure 49 is the next step after figure 48. In figure 48, there was no frequency call which caused it to generate an empty dark terrain. Figure 49 is the same idea, but in this case, we have implemented a noise function frequency call which causes the terrain to display itself including some of the terrain components we placed on our tile earlier.

4.3.4 Height Frequency This section will present the implementation process for the different scales of mountains and hills that are founded on the terrain. This implementation step is what ultimately makes this project generate a full terrain that is not yet infinite, until we implement the Perlin Noise function.

Figure 50: GenerateMountains() Method [27].

This implementation consisted of a 2D array that repeatedly kept looping itself to generate different shapes and sizes of mountains across a single tile.

Figure 51: Mountains and Hills across the tile [27].

60

Bachelor’s Thesis Muad Mahmud Sakah

Figure 52: Up-close look at the mountains and hills [27]. Figure 51 and 52 are the outcome of the implementation from figure 50. If we pay close attention to both figures 51 and 52, we can notice the different shapes and sizes of mountains across the terrain. With this single approach, we have managed to procedurally generate a terrain without using the Perlin Noise function. Our original goal was to design a terrain that will continuously generate for infinity, this is where the Perlin Noise function comes into play.

4.3.5 Perlin Noise Implementation After initializing the proper variables and building the appropriate body structure for our terrain, we can finally call in the Perlin Noise function to finish off the job.

Figure 53: Perlin Noise Implementation [27]. This implementation will essentially continue to execute the entire program and change the terrains frequency waves. The “Mathf.PerlinNoise” [9] command is a built in Unity function that will only execute accordingly, as long as there is a body built that the function can work off of.

61

Bachelor’s Thesis Muad Mahmud Sakah ______

Figure 54: Terrain Generation after implementing Perlin Noise [27]. This complete terrain generation occurred on a single tile after we implemented the Perlin Noise function. This terrain consists a series of frequency waves that were execute by Perlin Noise and the body section we implemented. In that case, if we kept the program running, we would have seen an infinite terrain that will continuously generate on a single tile.

4.4 Final Results Here we will look at the final results of our terrain and show off a couple of different sets of generations.

Figure 55: This is a side of view the Terrain Generation [27].

62

Bachelor’s Thesis Muad Mahmud Sakah

Figure 56: A full representation of a Generated Terrain [27].

Figure 57: This Terrain’s scale was modified to a new set of dimensions [9] [27].

63

Bachelor’s Thesis Muad Mahmud Sakah ______

Figure 58: This is another example where we have modified our scale [27] [9].

Figure 59: This is a smaller modified dimensional scale terrain generation [27].

We can officially conclude that our infinite terrain generation has concluded in the format that I initially intended for.

64

Bachelor’s Thesis Muad Mahmud Sakah

Chapter 5: Conclusion

First and foremost, I'd like to discuss the challenges and dangers I was concerned about during the planning period, as well as how genuine they were. The tight timetable and delays were an apparent risk and barrier that I was able to conquer thanks to the approach I selected, which we discussed in the previous two chapters. The last significant risks considered were potential code bugs, which could still pose a challenge even with all of the fixes made thanks to the validation, and the probability that the approach I discovered was skewed to my own preferences in games, which I couldn't deny before the validation phase with testers.

The next point I'd like to talk about is how looking at other works has been much more interesting than I first imagined. The Unity game engine and state-of-the-art allowed me to better understand what I was trying to tackle, to see what other teams have tried, and to get great ideas for developing my own process. I believe that this methodology is special, and that while other approaches might have performed well in the past, I have investigated something different and will be able to demonstrate what I have learned from it.

As a result of these findings and the positive outcome of the evaluation process, I believe that this project was a success in terms of achieving my main objectives. We essentially have a project that takes on some less-explored subjects, finds new ways to tackle the chosen problem nicely (if we consider the conclusions of our small validation process as valid), and lays the groundwork for some very exciting possibilities. I also want to acknowledge that the project is constrained by the context chosen and the production time available, but I am very pleased with the outcome I accomplished under these circumstances.

65

Bachelor’s Thesis Muad Mahmud Sakah

Bibliography

[1] R. M. Smelik, T. Tutenel, K. J. de Kraker and R. Bidarra , "A declarative approach to procedural modeling of," pp. 352-363, 2011. [2] T. Roden and I. Parberry, "A structured methodology for procedural content creation.," pp. 301-304, 2004.

[3] R. v. d. Linden, R. Lopes and R. Bidarra, "Procedural Generation of Dungeons," IEEE Xplore, vol. VI, pp. 78- 89, 2014. [4] Word on the Wind, "Spelunky," 26 February 2018. [Online]. Available: http://www.hardcoregaming101.net/spelunky/. [5] S. Bishop, "Rogue Legacy," GAMEREACTOR, 20 Novemeber 2018. [Online]. Available: https://www.gamereactor.eu/rogue-legacy-review/. [Accessed 2 October 2020]. [6] "Terraria," Wikipedia, [Online]. Available: https://en.wikipedia.org/wiki/Terraria. [Accessed 11 January 2021]. [7] Wikipedia, "List of games using procedural generation," Wikipedia, 9 January 2021. [Online]. Available: https://en.wikipedia.org/wiki/List_of_games_using_procedural_generation. [Accessed 16 January 2021].

[8] Bethesda Games Studio, "The Elder Scrolls V: Skyrim," Bethesda Games Studio, 2011. [Online]. Available: https://elderscrolls.bethesda.net/en/skyrim. [Accessed 13 October 2020]. [9] "Unity," [Online]. Available: https://unity.com/. [Accessed 15 September 2020]. [10] "GODOT," [Online]. Available: https://godotengine.org/. [Accessed 29 September 2020]. [11] "Visual Studio," Microsoft, 21 February 2021. [Online]. Available: https://visualstudio.microsoft.com/. [Accessed 15 September 2020]. [12] "Aseprite," [Online]. Available: https://www.aseprite.org/. [Accessed 19 September 2020]. [13] N. Williams, "An investigation into dungeon generation.," 2014. [14] A. David, " Automatic generation of dungeons for computer games.," 2002. [Online]. Available: http://www.dcs.shef.ac.uk/intranet/teaching/public/projects/. [Accessed 2 November 2020]. [15] R. Van der Linden, " Designing procedurally generated levels.," 2013. [Online]. Available: http://repository.tudelft.nl/view/ir/uuid%. [Accessed 1 November 2020]. [16] J. Dąbroś, M. Iwaniec, M. Patyk and J. Wesół, "Machine learning gait analysis algorithm for ontogenetic features compensation," IEEE, Lviv, Ukraine, 2018.

66

Bachelor’s Thesis Muad Mahmud Sakah

[17] G. Tomaino, H. Abdulhalim, P. Kireyev and K. Wertenbroch, "Denied by an (Unexplainable) Algorithm: Teleological Explanations for Algorithmic Decisions Enhance Customer Satisfaction," SSRN, 2020. [18] A. K. Sinop and L. Grady, "A Seeded Image Segmentation Framework Unifying Graph Cuts And Random Walker Which Yields A New Algorithm," IEEE, Rio de Janeiro, 2007.

[19] "Random Walk," Wikipedia, [Online]. Available: https://en.wikipedia.org/wiki/Random_walk. [20] F. Wang and D. P. Landau, "Efficient, Multiple-Range Random Walk Algorithm to Calculate the Density of States," Physical Review Letters, 2001. [21] L. Grady, "Multilabel Random Walker Image Segmentation Using Prior Models," CVPR, vol. Vol 1, pp. 763-770, 2005. [22] C. D. Hafner and D. H. Berman, "The role of context in case-based legal reasoning: teleological, temporal, and procedural," SpringerLink, pp. 19-64, 2002. [23] L. Bond, "Procedural Generation: An Algorithmic Analysis of Video Game Design and Level Creation," Scholarly Commons, Honors Theses, no. 249, pp. 1-69, 2017.

[24] Blackthornprod, "ROGUE LIKE RANDOM LEVEL GENERATION," Youtube, 2018. [25] IGL Space, "Unity Asset Store," Unity, 13 October 2018. [Online]. Available: https://assetstore.unity.com/packages/2d/environments/free-wall-tile-set-130514. [Accessed 11 Novemeber 2020]. [26] Unity, "Unity Asset Store," Unity, [Online]. Available: https://assetstore.unity.com/?gclid=Cj0KCQjwmIuDBhDXARIsAFITC_6KtrF2SFvrMsPur7MfKuG_AGAGBTU- _UZfnAwaysPgbU4sykZAIysaAgV-EALw_wcB. [Accessed 11 Novemeber 2020]. [27] M. Sakah, A hybrid procedural generation applied to 2D video game level design and terrains, Sudbury, 2021.

[28] N. Shaker, J. Togelius and M. J. Nelson, Procedural Content Generation in Games: A Textbook and an Overview of Current Research, Springer, 2016. [29] B. T., Procedural Content Generation" in Handbook of Digital Games, Wiley, 2014. [30] M. Frade and C. C, "Evolution of artificial terrains for video," vol. 6024, 2010. [31] "Fractal Noise," Ignite Pro, 2018. [Online]. Available: https://www.manula.com/manuals/fxhome/ignite- pro/5/en/topic/fractal-noise. [Accessed 28 January 2021]. [32] A. T, "Procedurally Generating Terrains," 2011. [33] "Value Noise," Wikipedia, 19 September 2018. [Online]. Available: https://en.wikipedia.org/wiki/Value_noise. [Accessed 3 February 2021].

67

Bachelor’s Thesis Muad Mahmud Sakah ______

[34] "Procedural generation: Perlin noise," Dens, 14 May 2020. [Online]. Available: https://dens.website/articles/procedural-generation/perlin-noise. [Accessed 2 January 2021]. [35] D. Wood, "Controlling 2D player animations with C# code in Unity," CODEMAHAL, 30 September 2016. [Online]. Available: https://www.codemahal.com/video/controlling-2d-player-animations-with-c-code-in-unity/. [Accessed 1 January 2021]. [36] ChonkyPixel, "Unity Asset Store," Unity, 15 Novemeber 2019. [Online]. Available: https://assetstore.unity.com/packages/2d/textures-materials/tiles/2d-tile-gap-fixing-tool-157060#releases. [Accessed 2 December 2020]. [37] J. Oslen, "Realtime Procedural Terrain Generation," no. 1-20, 2004.

[38] T. J. Ong, R. Saunders, J. Keyser and J. J. Leggett, "Terrain generation using genetic algorithms," ACM Digital Library, pp. 1463-1470, 2005. [39] G. Cordonnier, J. Braun, M. Cani, B. Benes, É. Galin, A. Peytavie and É. Guérin, "Large Scale Terrain Generation from Tectonic Uplift and Fluvial Erosion," Wiley Online Library, 2016. [40] J. v. L. v. Pabst and H. Jense, "Dynamic Terrain Generation Based on Multifractal Techniques," pp. 183-203, 1996.

68