Return Of The Glitch

In an earlier post i described an old program I wrote in C++ using Openframeworks. I tried remaking that program in Unity but the process of updating textures in unity simply took too much time and bottlenecked the entire program. I ultimately shelved it for this reason.

I decided to try once more to port this program over to the Godot game engine. Initial tests were promising. Texture updating was quicker compared to unity, but still not quite as quick as it was in C++.

Taking it to the next level

There were several improvements I had planned:

  • Allow the chaining of filters, so it would be possible to process several filters per iteration. Furthermore, i wanted to be able to visually connect and disconnect the filters. Something interactive like this would make it easy to combine filters for even cooler results, while also making the program intuitive and user-friendly.
  • Add a nice user interface that allows the user to toggle automatic image processing and save images on the fly.
  • Allow for any size of image, as opposed to hardcoding the dimensions.
  • Make it easy for the user to code new filters and register them.
  • Have a parameter system where data can be assigned to individual pixels by the filter, and give filters parameters that the user could modify through the UI. Exposing the parameters via the user interface turned out to be a bit more work than i had hoped, so i didn’t finish that functionality.

One idea I had was to make this a program that any person could download and use. There are two problems with this approach: This program is more fun to use if you know how to code your own filters, and I’m selfish and prefer to keep my algorithms secret.

Why is this so slow?

There was one critical oversight I made when I started porting the C++ program to Unity.

I presumed that images being manipulated in the old C++ program were 1080p. if i had looked closer at my old source code, i would have seen that the images were only 720p. with more pixels to iterate over, any new program I wrote would certainly take longer to process an image. This isn’t necessarily bad (higher resolution images are a good thing) but it contributed to the confusion as to why the old C++ program was so much faster than any new code I wrote.

I didn’t notice this key distinction until I started writing the program over in Godot. It made it a bit easier to live with the realization that my new program wouldn’t be as fast as it was in C++. I traded the speed of C++ for a better user interface, a more modular object oriented system and a nice interactive filter pipeline.

The pipeline

After handling the boilerplate code for the user interface and interactive filter system, all that was left to do was actually write some filters to test it.

Unfortunately, I didn’t keep track of all of my old C++ code, so I lost a lot of interesting filters that gave me fantastic results in the past. Still, using some of the code I still had access to, I could come up with some interesting new stuff.

It turns out that allowing the chaining of multiple filters was a game changer. If a filter gives underwhelming results on its own, then I’d simply combine it with a different filter. It’s damn near impossible to predict how filters are going to interact when chained together.

With the old C++ program there were a lot of “dud” algorithms that I would test and discard if they simply didn’t give interesting results. There was a lot of wasted code and dead ends. With the new filter pipeline, I can take duds and combine their logic. There’s a greater chance I might be able to salvage a filter by combining its effects with another.

Some of my most interesting recent results are the product of chaining filters together. What makes this even more interesting is that I can run the program on autopilot and let it iterate several times and if I don’t see favorable results, I can just pause execution and re-wire the filter chain. This wasn’t possible with the old program.

Enough chatter, show me the goods

The images you see below started out as photos taken on Lake of the Woods.

Anatomy Of A Space Station

Foreword

Space Station 13 is a brilliant game concept. It was originally created in 2003 using the BYOND engine. A more detailed (and in my opinion, very interesting) accounting of the history of Space Station 13 can be found here. The jist of it is that the source code for Space Station 13 was released to the general public. Not long after that, several communities were created, each with their own branch of the code with their own features and ideas for how the game should play.

The concept is simple:

  1. Take 80 players, give each of them a job, and stick them on a space station.
  2. Pick a random game concept from a hat and activate it. Maybe one player becomes an alien that has to stealthily absorb the DNA of several crew members and escape the station safely. Maybe several players are designated as rogue operatives who have to set off a nuke in the station engine room. Maybe several players are given a specific task or target to assassinate.
  3. Watch as the space station slowly descends into utter chaos until it becomes so bad that an evac shuttle has to be called. Generally this happens within a half hour, depending on how chaotic things get. Once the station becomes too unsafe and too many staff members are dead or at risk of death, the station commander will call the shuttle.
  4. Once the station is evacuated, reveal what the game was and who won.

What makes this formula work is that Space Station 13 has a lot of depth. It is first and foremost an atmospheric simulator. If a room is breached and exposed to outer space, it quickly becomes freezing cold and players without a breathing apparatus will suffocate.

In addition to simulating the atmosphere everywhere in the station, the game allows players to interact with damn near every entity on the station in nearly every conceivable way. You can inject light bulbs with highly flammable liquids and watch as the hallway bursts into flame when someone turns the light on. You can spike someone’s water with LSD. You can open the maintenance hatch on an APC and snip some wires to disable the power for an entire section of the station. You can open the maintenance panel on an airlock, engage its locks, disable its power, then weld it shut for good measure. You can tear up the floor tiles and reroute the garbage chute so it empties trash into the captain’s quarters. Any nefarious thing you can think of is probably possible in this game.

Since Space Station 13 grants players such a large degree of freedom, there’s a lot of potential for abuse. There are a lot of rules that players have to abide by or face discipline from an administrator for a particular server. For example, players who have not been designated as a rogue operative get in trouble for murdering people freely. The idea is that you’re supposed to act in good faith. If you sign up as a janitor, then you’re expected to at least spend a bit of time keeping the station tidy. As long as you don’t ruin the game for other players or break certain rules you are free to do whatever you please. It is for this reason that every game of Space Station 13 ends up being something different and interesting. Every game has its own story and every player plays a part in determining the outcome of the round.

Players are also expected to roleplay a bit, since everything is described through text. You are allowed to create your character as you see fit and choose which jobs you would prefer to do.

All players are equipped with a radio headset and can choose to talk into the headset or chat with the person next to them. There is an incredible amount of depth to the communications system, communication is a critical element of the gameplay. If you lose your radio headset, you have to rely on wall-mounted intercoms to communicate over the station radio channels. If someone steals your headset then welds you into a locker, all you can do is scream for help and hope some player nearby can hear you.

The station

I enjoy playing SS13 a lot, but what really caught my eye is the level of detail that goes into the space station itself. Every aspect of the station has to be carefully considered for both aesthetics and gameplay purposes.

Here is an overview of what people consider the gold standard for space stations currently. Players vote for this map the most often because it plays exceptionally well and is aesthetically pleasing. But what makes a map good? There are a lot of design considerations a map needs to tackle while still looking good.

  • The medbay needs to be somewhat central and accessible. Players will inevitably get injured and if medical facilities are too inaccessible, injuries will turn into deaths. Often a map will also have small medical hubs in the areas that are too far from the medbay.
  • The security sector needs to be somewhat central as well, because players will misbehave and if security officers can’t deal with them easily, the station will fall into anarchy.
  • The bridge and station AI room need to be well protected. If they get destroyed, the station becomes a much more dangerous place.
  • There are lots of non-essential rooms that should still be fairly exposed to major traffic arteries, since otherwise players will never visit them. A good station has many social hubs where players will naturally end up visiting since you want to force interactions between players for the station to stay interesting.

These are just a fraction of the considerations that have to be made.

The plan

Before starting any work I had to figure out how I wanted to approach the design. Every person that makes a space station has their own ideas of what it needs to look like. Making a space station is a lot of work so planning ahead is a no brainer. Having to redo vast portions of the station is not a good problem to have.

I started by drawing my layout roughly on graph paper.

I wanted the station to have more looping hallways than other existing stations. Instead of being one main root hallway with a bunch of branches, the station would instead have a web of interconnected hallways. The dark blue tiles represent these hallways in the image.

I had several principles in mind when i started creating the layout:

  • No room will be larger than the player screen size. If a department has more space than that, then it needs to be properly partitioned.
  • Main hallways should be 4 tiles wide, secondary hallways should be 3 tiles wide, maintenance tunnels should be 1-2 tiles wide.
  • The research sector and engine should be kept on the external fringes of the station since they’re the most likely to cause catastrophic damage. The engine that powers the station is powered by a small black hole and nefarious players can unleash this mini singularity and watch as it moves around and randomly destroys sections of the station.
  • Social hubs such as the bar and cafeteria should be near the center of the station. Medbay and security should also get prime real estate.
  • The map needs to be aesthetically pleasing but also designed in a way that uses the least amount of space possible and promotes good gameplay. This can be harder than it sounds, sometimes the best looking solution isn’t always the one that players will enjoy.

From start to finish

With the rough draft finished, i started working on the actual map. The first step was to create the rough footprint for the walls and floors. There’s a few changes i made right off the bat that contradicted my original drawn plan. I moved the evacuation shuttle to the southeast corner and rearranged a few other departments.

My approach to designing the map was to start at the top and work downwards. If i needed to resize a department for any reason, i could simply add or subtract space from its southern neighbor. The arrivals shuttle, botany, animal storage, kitchen, bar, jazz lounge, rec room, crew quarters, tool storage, head of personnel and captain’s quarters were the first departments i worked on.

My first attempt at making the security department was an overwhelming failure. The layout of the department was too clunky. The brig was exposed to the main hallway which meant jailbreaks would be common. The layout of the rooms was clunky and maze-like.

I continued to revise rooms. Crew quarters was really poorly set up so i gutted it and started over. Security underwent 3 revisions before i was satisfied with it.

A lot of rooms took up way too much space, so I did a lot of downsizing early on. It’s easy to overestimate how much space a room will require.

I spent a lot of time planning out the medbay initially before committing to working on it since it’s one of the most important parts of the station. From the medbay lobby, the northern route brings you to the surgery rooms and the southern route brings you to the corpse processing areas: the cloning lab (where dead players are brought back to life with the cloning machine), the morgue, the robotics lab (where dead players can be turned into cyborgs), and the genetics lab (where corpses can have their genes modified before being cloned). In the middle there’s a reception desk and a cryostasis chamber where patients can be put in cryochambers. The west side of the medbay contains the less important rooms, such as the storage room, a quarantine room for infected patients and the medical director’s office.

The medbay and security department were built, but far from perfect. These are the most important departments on the station so i spent a lot of time sharing screenshots with SS13 community developers and getting opinions from people who have made maps before.

I redid security again after getting plenty of feedback, tweaked the medbay layout a bit, added the station bridge and worked on finishing the first pass for the research sector. The station bridge is kept airgapped from the rest of the station in the middle, which makes it very hard for villains to break into it without a space suit.

The security department and research department were mostly complete at this point. I did my first pass for the chapel, quartermaster’s office, pool, owlery, arcade and mechanics’ office.

I decided to have a bit of fun with the engine design. Normally, a space station has a single engine that provides power to the station. The engine can be a thermo-electric generator (which is relatively safe to operate) or a singularity engine (which is easy to operate but also fairly dangerous since it’s pretty easy to turn off the containment field that stops the mini singularity from moving around and destroying the station). I opted to make a dual singularity engine.

With the engine finished, all i had to do was finish the engineering sector, the mining sector, the escape shuttle bay, and a few other miscellaneous departments. Even with the rough layouts for the departments completed, there was still a lot of work to do.

Solar panels are needed for backup energy if the station engine dies, so i placed 3 different arrays at different locations. I also added a wreckage to the northeast which serves as a separate spawn area used in certain gametypes (for example, the red ship is where rogue operatives will spawn).

A good space station will also have a network of mail chutes that allow players to mail items from one department to another, so i worked on that. Space stations also need a disposal chute network so players can send trash to the disposals room for processing. Light fixtures (with lightswitches), electrical wiring, area power control panels (also called APCs), security cameras and emergency air injectors are also something that every room needs.

It’s a good idea to really nail down your room layout before placing all of the auxiliary stuff like mail chutes. If you mess something up and it isn’t caught until you’ve placed all these things, you’ll have to do a lot of tedious surgery on your station to fix your mistake. After finishing everything and taking a step back to examine the station as a whole, I do have some regrets about certain aspects of the layout. The map has not been playtested yet so I can’t say for certain which areas really need to be reworked.

Since i used version control to keep track of my changes i wanted to make a timelapse animation showing my gradual progress. It was too much of a hassle to do, sadly.

The vital organs

I took some screenshots of the various networks of underlying systems that all fit together to make the station.

The disposal and mail pipes:

The electrical wiring (with the contrast turned up to make the wires easier to see):

The walls and floors with all other stuff hidden:

The wiring and pipe networks all follow the main hallways of the station since it makes them easier to access and generally just makes sense.

Is it good?

The map has gone through a lot of changes since I started work on it, but the question still remains: Is this map good at all?

This is a difficult question to answer. This map was designed using the goonstation codebase (recall that there are several communities, each with their own custom SS13 build). Since this map was made for goonstation, it needs to be tested on their servers (ideally with a good handful of volunteers). Getting a map accepted into production is an arduous process since it needs to pass inspection. This means that the administrators and coders need to sign off on it being admitted into the map pool, and any major design flaws need to be ironed out.

What constitutes a design flaw is kind of difficult to determine. Obvious mistakes like putting the medbay way too far from the center of the station will probably negatively impact a map’s impression on the community. There are many other aspects of the map that can be nitpicked, and it’s not always black and white. I fully expect that this map will be dissected and roasted many times over once it’s released as 1.0. Whether it will actually be accepted into production depends on how many aspects of its design are considered acceptable by the community.

There’s also a minor issue: I can’t get it to compile. It was designed using a third party map editor tool, and while i can open it with that tool, i can’t open it with the BYOND dev tools. Some aspect of the map file is causing the compiler to freak out and the error message it gives is too cryptic to be helpful.

For now this space station is stuck in limbo until I can coordinate with the developer of the other mapping tool to try and debug this map and figure out what is causing the crash.

 

 

To Make A Map

Foreword

I play a game called Dominions. Dominions is an incredibly deep 4x turn based strategy game that takes place in a fantasy setting with a very large variety of magic spells, rituals and units.

 

In Dominions you take are a powerful being that rules a nation and aspires to godhood. The player creates an avatar, known as a Pretender God, to represent them in the world. The type of Pretender God you can create varies from magically powerful arch mages to dragons, huge titans or large immobile monuments. When you start the game you decide what kind of god you are and how your Dominion affects your lands, followers and sacred soldiers. In order to win a game of Dominions, you must either eliminate all players, or capture a certain amount of thrones which are scattered around the map. Thrones are defended by powerful AI armies so you must be careful when seizing them.

 

There are currently 3 ways to play Dominions.

  1. You can play on a map which was hand-designed by somebody. These maps have the start positions for players and thrones placed manually by hand and typically have some sort of artwork made by hand. Maps like these can be uploaded to the Steam workshop. Since these maps are not randomly generated, you can memorize their layout. Some players might not have fair starting positions. There are a lot of variables that can make or break a handcrafted map.
  2. You can use the game’s built-in random map generator. Many people detest this tool because it has a tendency to not place the thrones fairly on the map. Ideally, all players should start off equidistant from each-other. Thrones should also be fairly distributed in a truly balanced game of Dominions.
  3. You can use Cartographic Revision, a closed-source third party map generator. This tool is much better than the default map generator. It places thrones fairly and it produces good looking maps. The logic it uses when determining province distribution and player start locations seems more robust.

 

Why make your own map generator?

Though I really like Cartographic Revision (it’s what inspired me to make this tool), it does have some downsides:

  • The user has no control over the generated map. You can’t edit manually alter anything once you’ve generated a map, what you see is what you get. This is a problem with the built-in Dominions map generator as well.
  • Certain player counts are unsupported. Do you have 11 players? You’re going to have to make a 12 player map and leave one of the player starts empty. This means a few players are going to have a vacant lot as a neighbor, which means they get some free real estate.
  • Cap rings are too random. A cap ring is the provinces adjacent to a player’s main starting castle. Castles draw resources from adjacent provinces. If you start with only 3 connected provinces, your income and available resources will be worse than that of another player who has 5 provinces in their cap ring. In Dominions the game balance is already dubious at best. Some nations are considered much stronger than others. Some nations are outright banned from games for being too powerful. My goal was to make every nation have 5 provinces in their cap ring so that no player ends up stuck with a bad starting position.
  • No roads. A road is a connection between provinces which reduces the movement cost between them, allowing armies to move further in a single turn. For reasons unknown to me, Cartographic Revision does not have these.
  • Certain combined province types, such as cave forests or reefs, don’t exist in Cartographic Revision. I planned to expose all available province modifiers in my map generator and allow the random generation to use them.
  • A memory leak causes Cartographic Revision to crash after you regenerate the map 3 or 4 times. Not the end of the world but slightly annoying at times.

Of all these reasons, the first is the highest value. Being able to manually tweak a generated map is extremely useful.

I had other goals in mind once I started planning my own map generator:

  • Make the map generator open ended so other people could add their own art styles to it. The ideal situation would be that the user chooses the art style from a dropdown menu. In the end I only partially accomplished this goal. There were enough bugs to fix and features to tweak in the original map generator art style that I never had time to focus on non-essential features.
  • Make provinces have distinct visual cues. One thing i dislike is not being able to tell what attributes a province has at first glance. If a wasteland province has the warmer province attribute, then logically there should be cacti growing on it. If a plains province has the large province attribute, then it should have buildings scattered around which let the player know that it has a higher population than the average province.
  • Expose more options to the user. If the user wants to cluster water nations together to create one gigantic ocean, they should have the choice. Ideally i also wanted to expose everything to the user – what percentage of the provinces on the map will be forest, how often rivers and mountain passes are placed, and so-on.

 

From start to finish

Though Cartographic Revision is closed source, you could de-compile it to read the logic behind it. I personally don’t like doing this because it’s disrespecting the wishes of the creator and both of our map generators take a different approach to creating maps anyhow. Thus I made the conscious decision to not peek under the hood.

 

I documented everything from start to finish, partly for motivation and partly because I have a habit of keeping tabs on how things progress and what my thought process is at the time.

 

The very first functional map generator version was incredibly basic. Just a collection of nodes with player starts pseudo-randomly inserted. This obviously would not do. It was evident from first glance that player starts need to be static in order to be fair.

Next, I generated connections between nodes. Since the map has to wrap horizontally and vertically, there needs to be edge connections that wrap the far ends of the map together. I did not show these visually (yet) but they were programmed.

Next, nation data and world generation needed to be fleshed out. I hard-coded the types of provinces in the cap rings of each nation and added some logic for the sprinkling of different province types across all the nodes. Connection generation was also worked on. Rivers and cliffs are sprinkled between nodes to create interesting bottlenecks.

Next, support for some other player counts was added to test the speed of the map generation. For a 20 player map it only took about 0.3 seconds to finish.

At this point i was pretty confident that implementing manual province and connection editing was doable. All that was needed was a simple UI that allows the player to tweak the province flags and connection flags. The user clicks a node and the UI pops up.

With simple province and connection editing finished, it was time to start introducing some randomness into the location of each province. The pink border represents the final dimensions of the map.

Next, I focused on making sure that the map would wrap properly along the seams. With 4 copies of the map tiled you can see there was one issue at the corner connection, but otherwise everything looked good.

With wrapping complete, it was time to start producing the actual provinces. My goal was to use simple meshes for all 2d polygon shapes.

The simple polygons don’t look very appealing, so next I worked on adding some randomness to the polygons, and improving the edge cases.

This looked better, but it still wasn’t good enough. Introducing random noise to a line between point A and point B will just give you a squiggly line. I wanted something more organic, so I started using bezier curves.

These shapes were definitely more interesting, though still too simple. The bezier curves needed more knots to make them more interesting.

These shapes were better, but not perfect. I finished the province wrap logic and started work on river and road polygons. It became immediately clear that complex bezier curves with a lot of knots from point A to point B resulted in the best organic looking shapes.

Roads did not need to be as complex, as long as they connected province A to province B.

One thing that was really important to me was visually obvious borders between provinces. I used line renderers to highlight polygon edges.

Next, I worked on making some shaders for the province polygons to make them look more like terrain. Using a perlin noise shader, it was easy to make my provinces look similar to the ones generated by Cartographic Revision.

With province shaders finished, i started work on sprite placement. This was the most costly process in terms of processing power required. In order to properly find all valid sprite positions inside of a province polygon, i do hundreds of ray-traces downward onto the polygon. If the ray hits, it’s added to a list of valid sprite positions. Doing this across the entire map takes time but I was pleased with the end result. I took a mental note that this process could likely be optimized in the future.

With my approach, I am placing meshes and sprites in front of a static camera which then renders what it sees to a RenderTexture. This texture can then be read and output as the final product. I also display this texture off to the side next to the meshes and sprites, so the user can see the interactive nodes, and also look at the map as it would appear without them.

In order to organize sprites properly and make it easy to tweak, I exposed everything to the Unity editor UI. There are plenty of options for each sprite which help determine its color, chances of being placed, space taken, and terrain which it can be considered valid for.

Connections between provinces also need to place sprites in some cases. A mountain pass has specific rules to create a dip in the middle to show the players that it can be traversed. I also introduced more jitter to the province polygons to give them a more organic shape.

At this point my main concern was creating sprites for all different terrain types.

Each sprite requires a summer and winter version, since the seasons do change in Dominions. Provinces also require a different colored shader for winter.

Once all the basic artwork was complete, the next step was writing the output logic. All map information such as province connections and terrain information is stored as plaintext in a .MAP file. The coordinates of pixels that belong to a given province are also stored in this file. Testing this output meant you had to output the map, then open it in the built-in Dominions map editor to visually inspect it.

Finally, I had to figure out fair layouts for the oddball playercounts. For 16 players it is trivial to organize the player starts into a 4×4 grid. Each player gets 4×4 provinces to themselves, which means 15 normal provinces and 1 throne.

How do you do this with 17 players? I had to start playing around with grids in MSPaint to solve this. Green squares are player starts, blue squares are potential provinces that would be in their cap ring, and purple squares are thrones. Some liberties had to be taken, for example, the center player may possibly have a slight advantage in terms of available real estate and nearby thrones. I tried to balance this by giving other players thrones that are closer to their cap ring.

Once I was happy with the grid layout, I could use the grid as a reference to figure out the coordinates of player starts and throne positions.

And that was it! With support for all player counts, I could output maps of any size.

 

The gritty details

I kind of glossed over some of the more technical stuff, so I’ll try and explain some of the more complex aspects of this tool in detail.

 

Province polygons

In order to create a group of provinces that connect without gaps, I had to figure out the shared borders between provinces.

In this example, let’s focus on the 2 large colored province nodes. A province border can’t just use each connection center (the second smallest dots) as a corner. The borders are determined by taking all the connections that form triangles and computing the triangle center. The pink lines show this in action. The pink connection dot and its neighboring green connection dots form a triangle, so I compute their center point. This point belongs to all 3 of those connections. If this logic is repeated across the entire set of connections, each connection will have 2 neighboring triangle center points that are relevant to it. If you traverse through the connections belonging to a province node and connect their triangle center points, you form a polygon. Repeat this logic for all province nodes and you have a collection of province polygons perfectly connected without gaps.

Since in this case the grid of nodes are equidistant, the resulting polygon will be a predictable shape. I make several tweaks to get a more interesting result:

  1. Deform the grid a little bit by applying random jitter to the province positions (being careful not to overdo it).
  2. Make the polygon borders more interesting by using bezier curves.
  3. Adjust the connections based on the traits of their nodes. For example, if the green province had a small province flag assigned, then it would pull the center of its associated connections towards it slightly, resulting in a smaller polygon.

 

Sprite placement

There is a specific order in which things are generated when a new map is created.

  1. Generate the conceptual information (a simple grid of conceptual nodes and connections) and assign terrain data.
  2. Place the actual unity objects in the scene and assign the conceptual data to these objects, taking care to keep the conceptual and unity object logic separate.
  3. Compute the meshes to be used by each province and connection.
  4. Compute valid sprite placement positions for each mesh.
  5. Place all sprites.
  6. Assign sorting order to sprites (so sprites render in the proper order).

This farmland province is on the bottom left of the map, so parts of its mesh fall outside of the map border. I ignore the outer portions of the mesh since they won’t appear on the final outputted image.

In order to determine positions where sprites can be placed, I compute the bounding box of the mesh and trace hundreds of rays within that bounding box. I resize the bounding box if it falls outside of the red border to avoid unneeded raycasts. If the ray collides with the mesh, it’s a valid position. If the ray collides with a different mesh, it’s an invalid position.

I apply a small amount of jitter to the start position of the ray so that the sprites don’t appear to be placed uniformly. Green dots are valid points and red dots are invalid.

Once the set of green points is determined, I start placing sprites. When a sprite is placed, it deletes all other potential sprite placement points within a certain radius of itself. In the diagram, a farm house would clear out all the nearby positions so that the wheat doesn’t get placed too close to it. Each province type has different settings. Farmland places wheat sprites very densely, so it uses almost all of the computed sprite positions. Other provinces such as wastelands don’t need to place a lot of sprites, so they require less positions.

 

Province textures

I use a very simple set of perlin noise shaders to give the provinces their texture.

There are a few parameters i have control over in each material:

  • X/Y randomization seed (this is mostly unused since most of the shaders use different scaling anyhow)
  • X/Y scale. This determines how squashed the blobs are. With an X scale of 1.0 and a Y scale of 0.3, the blobs become vertically squashed to give the feeling of perspective. With an X and Y scale of 0.01, the blobs become very small and the texture looks grainy, almost like the white noise you’d see on a tv screen.
  • Colors. There can be anywhere from 2 to 5 different colors used.
  • Thresholds. Each pixel computed by the shader has a perlin noise value that ranges from 0 to 1. The thresholds determine what range of values will belong to a certain color. In the plains province shader, values from 0 to 0.35 result in off-white, values from 0.35 to 0.75 result in pale yellow, and values from 0.75 to 1 result in green. These thresholds can be tweaked to increase or decrease the size of the off-white and green blobs.

That’s all there is to it. Each province type has a texture for summer and winter, and typically the only thing that differs between these textures is the color palette used.

 

Shorelines

My water shaders alone didn’t look very convincing so i used line renderers to add shorelines to the rivers and seas. In order to make it look good without overlapping onto land with the line renderers, i used modified versions of the perlin noise shader that makes use of stencil buffers. The logic is simple, any edge line that borders a body of water will create one line renderer for the black edge line, and one line renderer for the shoreline. Unity line renderers use 2d meshes to draw the line, so materials and shaders can be assigned to them.

Once i had the stencil buffers working, i could put the shorelines on every connection that touches a water province.

And with shorelines working properly, the water shaders could be tweaked to look a bit more realistic. I also used these shorelines on the river meshes since they looked so good.

And there you have it, low-effort shorelines.

 

What’s next?

I’m keeping track of my to-do list on the github page for this project. It’s mostly been whittled down to the non-essential features at this point.

I made the choice to make this open-source because I believe that the sprite art could be revised by someone more artistically inclined. There’s certainly a lot of ways that the world generation could be optimized as well. In the long run this tool can only benefit from more pairs of eyes looking through the code and finding ways to improve it.

You can download this tool for free on itch.io.

 

Arena Simulator

I created a Unity game that simulates a Hunger Games sort of scenario. The idea was to make it as modular as possible so that users could control virtually everything about the characters, weapons, and arena via XML.

For example, the user can create different types of bodies and define each body part. The body is organized as a tree, so in a human body if a pawn’s leg were destroyed then it would follow that their shin and foot would become unusable. Here’s an excerpt from a human body definition:

<BodyPart Name="Left Eye" ParentName="Head">
	<MaxHealth>3</MaxHealth>
	<IsRoot>false</IsRoot>
	<IsBranch>false</IsBranch>
	<CapacityFactors>
		<CapacityFactor>
			<CapacityName>Sight</CapacityName>
			<Factor>0.5</Factor>
			<WeakLink>false</WeakLink>
			<Influences>
				<DamageType>Any</DamageType>
			</Influences>
		</CapacityFactor>
		<CapacityFactor>
			<CapacityName>Pain</CapacityName>
			<Factor>0.7</Factor>
			<WeakLink>false</WeakLink>
			<Influences>
				<DamageType>Any</DamageType>
			</Influences>
		</CapacityFactor>
		<CapacityFactor>
			<CapacityName>Manipulation</CapacityName>
			<Factor>0.5</Factor>
			<WeakLink>false</WeakLink>
			<Influences>
				<DamageType>Any</DamageType>
			</Influences>
		</CapacityFactor>
	</CapacityFactors>
</BodyPart>

An example of a capacity modifier:

<CapacityMod Name="Steadfast">
	<CapacityName>"Pain"</CapacityName>
	<Description>"You handle pain better than most people."</Description>
	<Modifier>2.5</Modifier>
</CapacityMod>

Each body part can affect the capacities of a pawn. The eye body part affects the sight capacity by a factor of 0.5, which is to say that if a pawn has its eye destroyed, its sight becomes 50% worse. If both eyes are destroyed, its sight capacity falls to 0%, which affects its abilities in combat and so-on.

An example of a weapon:

<Weapon Name="Lead Pipe">
	<Usefulness>8</Usefulness>
	<Damage>8</Damage>
	<Range>0.6</Range>
	<AttackSpeed>1.2</AttackSpeed>
	<DamageType>Blunt</DamageType>
	<IsRanged>false</IsRanged>
	<MissText>%PAWN swings their lead pipe at %ENEMY, but misses</MissText>
	<DestroyText>%PAWN crushes %ENEMY's %PART</DestroyText>
	<DamageText>%PAWN clubs %ENEMY in the %PART with a pipe</DamageText>
	<KillText>%PAWN beats %ENEMY to death with a lead pipe</KillText>
</Weapon>

Usefulness determines whether a pawn should prioritize a weapon (for example, a lead pipe is vastly preferable to a flimsy stick).

An example of a character:

<Character Name="Johan">
	<Attributes/>
	<Aspects>
		<Aspect>Clumsy</Aspect>
	</Aspects>
	<Competencies>
		<Competency Name="Strength" Value="4"/>
		<Competency Name="Marksmanship" Value="7"/>
		<Competency Name="Vitality" Value="3"/>
		<Competency Name="Constitution" Value="5"/>
		<Competency Name="Dexterity" Value="4"/>
	</Competencies>
</Character>

There is also a built-in editor for existing characters, however it lacks the ability to modify the aspects assigned to a character.

The map is a dynamically generated mesh using the Unity terrain object. Patches of dirt and sand are added using simplex noise to determine which vertices have which texture. Objects are scattered on spots all over the map using raytraces. There’s a day/night cycle where the amount of light affects the visibility on the map, and therefore how effective some pawns will be with their weapons. There’s also a set of controls on the top left which allow the user to speed up time, pause, check the event log and open the stats of a specific pawn.

The action log allows the user to see exactly what is happening, in depth. The character inspector lets them see the vital stats of characters and their current action.


This is technically abandoned although with a bit more polish i think it would be something worth releasing. In its current state it still needs some work.

Hits N Giggles

A culminating group project done for a game dev course. It was a lot of fun to work on and was a resounding success.

Features:

  • Local multiplayer with support for 4 usb controllers as well as keyboard WASD/arrow keys.
  • 2 playable characters with their own unique look and different abilities.
  • A “comeback mechanic” where you get a special weapon when you have 25% health. the rabbit gets throwable bottles in place of his melee attack, the bear gets a hammer with more knockback and damage.
  • Robust physics prop/gibs system. Props can be thrown at other players and have their own unique properties. Crates will sometimes contain other props.
  • 2 functional maps, each with their own unique hazards and traps.
  • Music player that plays the music in the game music folder, you can replace the included music with your own if you want.

The alpha demo:

The final product:

You can download it here.

Space Frog

For an assignment I had to make an asteroids clone. I kept track of my progress with some videos. For fun i added some procedural parallax clouds.

Room Generation

Here are some screenshots of a room generation algorithm i wrote in action.

The idea behind it is simple enough but there are a lot of things that can go wrong in the process. It took the most time to make this algorithm robust since ~10% of the time it would generate disjoint rooms. Here is the process:

  1. Start with a grid of blue tiles.
  2. Hollow out some grey rooms randomly, using some constraints such as max/min room size. Rooms should not touch.
  3. Create corridors between rooms. For each room we make one or more corridors (also based on constraints that we can change) to another room. When creating corridors, we have to make sure the tiles on either side of the corridor are blue or else we end up with corridors merging. We also need to ensure the corridor doesn’t attach to a  room corner (since corridors are 2 tiles wide).
  4. Check each room and make sure it can be reached by all other rooms. If one room can’t be reached, discard all corridors and generate them again until a configuration is reached which satisfies this constraint.

 

The more variables you expose, the more interesting configurations you can get. The leftmost image has smaller rooms with a higher chance to have several corridors per room, the rightmost has larger rooms with less corridors.

Cellular Automata

This was a little test project I made to experiment with cellular automata.

Simplex noise can be a very useful tool for accomplishing the same result, but it’s nowhere near as customizable (or fun) as cellular automata.

Here is how it works (i had a rough idea of how this works beforehand but this is for those who might be interested):

1. Create a 2d grid of tiles. turn roughly 50% of them red, at random. Depending on the rules you choose for the cellular automata, you may need to tweak this to be closer to 40% or 60%.

2. Decide on the rules you want to use for each tile. To make this a little easier to understand, imagine that each tile is a living organism like bacteria or something. The organism will either die or expand to other tiles based on its rules. The classic “5-4” rule is as follows: a white tile becomes red if 5 or more of the 8 tiles surrounding it are red. A red tile becomes white if less than 4 of the tiles around it are red. We are basically saying: a bacteria starves to death if it is surrounded by less than 4 other ones, and an empty space spawns a new bacteria if it is surrounded by at least 5 others.

3. Apply the rules to each tile. In order to get desirable results, these rules need to be applied several times in a row. Over time, the cells will shift into a random, unique shape based on the rules you applied in each iteration.

That’s it. The above image is what i got from applying the 5-4 rule 5 times in a row to a grid of 50% white and red tiles.

…But it gets more interesting. We can change the rules to get vastly different results. We can also use different rules with each iteration. For example, we could apply a given rule 3 times, then change the rules and apply the new set of rules 5 times in order to get a totally unique result. The image in the bottom right shows some of the stuff i ended up with using different rule sets. You will also get different results depending on how many iterations you do. There’s an infinite amount of combinations of rules and iterations you can do which makes this a very cool method to use for generating worlds.

In my situation, i wanted to generate a world where there is only one main area (ie, no smaller disconnected white areas that can’t be reached from the main white area). In order to do this i have to first generate the world, then check each white area using a flood fill algorithm (kind of like the bucket fill tool in mspaint) to see what percentage of space in the world each area takes up. In the bottom left you can see this in action. The blue area is the main area and the green areas are the smaller detached areas we want to get rid of. The blue area takes up roughly 40% to 60% of the world space so it is easy to tell which ones are small and need to be discarded (the green ones). In the case that the main area takes up less than 40% of the grid we can always just scramble the grid and start over.

The most popular use of cellular automata is conway’s game of life. Check it out if you wanna play around with this stuff in your browser.

If you are interested in programming something using cellular automata, this page is extremely helpful.

Abandoned Game #3

This project was a sort of continuation of my other chunk-based grid project i created in MonoGame.

This one uses simplex noise combined with an ‘infinite’ chunk-based game grid. You can see where the chunks connect. There are 9 chunks in the grid and you start in the middle. If you move to an edge chunk, that chunk becomes the center and the chunks which are not immediately on the edge of it are erased and moved to become the new edges.

Combined with saving/loading the entities within a chunk, this means i could create massive procedurally generated persistent grids.

The 3 images show the difference between using different octaves with simplex noise (the leftmost image uses 8 octaves). I started work on generating cliffs (the orange outlines on the right image) but it’s going to take a different algorithm to properly generate cliff edges.

Here is some working on cliff generation, specifically marking the edges properly. To properly illustrate chunk boundaries, I made the chunk colors alternate between grey and white.

The top image is the initial cliff edge marking (any tan tile connected to a white tile becomes orange).

The second image shows the second pass where i convert all white tiles with 2 orange tile connections into an orange tile. This method actually gives worse results and causes large gaps between cliffs segments in different chunks.

The third image shows a tweaked version of the method used in the second. I am converting tan tiles to orange instead of white tiles to orange. It gives significantly more accurate results, still a few gaps to sort out though. I am missing a specific case related to chunk edges.

This simple method i am using works well. I originally used the marching squares algorithm to mark the edges of the tan blobs but it would have taken a lot of tweaking in order for it to give the proper results.

 

Abandoned Game #2

This was another project I started in MonoGame. The goal was to make a gigantic grid-based 2D game. I don’t remember many other specifics, but the basic premise of the project was pretty ambitious.

The basic camera code and grid generation code were the first things i completed.

Once i had a simple grid generated, i wanted to take it a step further and create a grid of grids.

The grid became an 8×8 2D array of chunks which are 256×256 tiles. At most, there were 4 chunks active (within camera view). All other tiles were considered inactive until the camera moved within their visible range.

The tiles were colored to show where chunks begin and end.

After getting the grid generation sorted out, i doubled the size of the tiles and added a cursor (the white square). I also implemented some basic selection code. In this example, i could turn a tile yellow by clicking it.

In the top left corner i placed a basic player pawn entity as well.

Next I started work on my pathfinding for actor entities.

When you select an actor then click a tile, it runs a pathfinding function which computes a path to the tile (in the form of a queue consisting of tile objects). Then the actor starts de-queuing each tile and transitioning from tile to tile until it empties the queue. If a tile becomes impossible to traverse, then the actor will stop and re-call the pathfinding function, rebuilding the queue of tiles.

At this point i had also added an asynchronous load screen since generating all the world tiles took a bit of time.

This is where this project hit a dead end. In this case it was just a lack of direction.

 

Generic Zombie Game

Another game i wrote in Lua around 2011(?).

It is a round-based zombie survival game, with rounds typically lasting 15 minutes (although often ending much sooner when all human players die). You earn cash by killing zombies which can be spent on weapons and supply airdrops. If you die, you become a zombie.

Some notable features:

 

• Challenging gameplay. A strong emphasis on teamwork and inventory management.

• A dynamic weather system. Thunder, lightning, particle-based rain and wind. The weather is randomized each round.

• Random events. They happen over the course of the round. Some are good, like scientists and supply crates appearing. Some are bad, like temporary radio blackouts. There’s even an event which causes a wicked storm using the weather system.

• Intelligent zombie NPCs that hunt you down. They can also break through doors, breakable walls and windows.

• A bunch of scripted weapons which implement scopes, ironsights, bullet penetration and more.

• Melee weapons, including a hammer which can be used to build barricades using wood planks.

• An inventory system that is very modular. You can add your own items with ease.

• 4 human classes and 4 zombie classes, each with their own perks.

• Fancy effects. Motion blur, postprocessing, realistic drunkness/infection/etc, blood spatter on your HUD, and probably more.

• Lots of gore effects. Blow the torso off of a zombie with a winchester, create showers of guts with explosives, instantly fry zombies with laser weapons and blow the heads off of zombies with pretty much any gun.

• Ailment system. If you are attacked by certain zombies you will start to bleed. If you are hit by zombies you become infected. You can also become irradiated from certain things.

• Replayability. Never play the same match twice. The infection antidote spawns randomly around the map throughout the game, and the evacuation helicopter has multiple landing zones.

• Stats. At the end of the round awards are handed out to players who have accomplished great and not-so-great things. If you’re one of those fellows who hides in a corner while his teammates do all the work then you will get publicly humiliated. If you are a skilled player then you’ll get a pile of accolades.

• Parameters that give the server owner complete control over most gameplay aspects.

• A custom entity loading system for maps which do not officially support the game script.

I originally wrote this game several years ago, before the original Left4Dead game was released by Valve Software. There are a bunch of gameplay videos on youtube, search for “ReDead Gmod” or something along those lines if you want to see more.

There are plenty of gameplay videos on YouTube as well.

The scripts are freely available: https://www.assembla.com/code/redead/subversion/nodes

The Stalker

This is a game script i wrote a couple years ago in Lua for Garry’s Mod, a mod which exposes the Source Engine (the engine used by Half Life 2, among other things) to Lua. I wrote the game around 2011. It took roughly 3 months to complete. In that time I had to program the game and also made a few maps for it using the Source SDK which took longer than expected to finish.

Being able to script a game using Lua bindings in a pre-existing engine is good fun since it’s relatively easy to get a working prototype up and running.

Here is a general description of the game:

A team of soldiers must hunt down a powerful, nearly invisible creature known as The Stalker. The Stalker has a number of abilities:

• Scream – A loud shriek that causes nearby soldiers to lose their hearing temporarily and disorients them. This attack uses 25% of your energy.

• Mind Flay – This attack invades the mind of the targeted player. They are heavily disoriented and take some damage from the attack. Perfect for picking off stragglers or confusing players who are very good at figuring out where you are. This attack uses 50% of your energy.

• Telekinesis – Control an object with your mind. You can choose the direction in which the object is thrown. A useful tool for distracting soldiers or causing damage with larger objects. This uses 75% of your energy.

• Blood Thirst – Your attacks absorb health for a short duration. Uses 100% of your energy.

• ESP – This ability is enabled/disabled by toggling your flashlight button as the stalker. When ESP is enabled, you can see where soldiers are through walls. However, while ESP is active, your energy will not replenish and your overall vision becomes darker.

The energy used by psychic attacks will slowly regenerate over time. In addition to having psychic abilities and being invisible, the Stalker is also very agile. It can jump to high areas, run faster than soldiers, and cling to walls. The Stalker’s health slowly drains over time but it regains health with each kill.

The soldiers have their own tools for hunting the Stalker. There are 4 different, equally balanced primary weapons to choose from, as well as 4 different secondary weapons and 4 utilities. Their flashlight runs off battery power and if your battery reaches 0% charge then there is a small delay before it starts recharging. The recharge rate for the battery is slower than its drain rate so you have to manage your flashlight use.

Primary Weapons:
• SG 552 – A highly accurate scoped rifle. Magazine holds 20 rounds.
• FN P90 – A SMG with a large magazine and a high rate of fire. Magazine holds 50 rounds.
• SPAS 12 – A powerful close range semi-automatic shotgun which can fire 6 rounds before reloading.
• FAMAS G2 – A 3-shot burst rifle. Magazine holds 30 rounds.

Secondary Items:
• Portable Sensor – A laser tripwire alarm which can be planted on any solid surface.
• USP Compact – A backup pistol with unlimited ammo.
• Seeker Drone – An autonomous drone which floats around and sounds an alarm if it detects the Stalker.
• Optic Range Scanner – A handheld scanner which augments your vision.

Utilities:
• Automedic System – An integrated morphine injector for your armor which heals you automatically when you are injured.
• Laser Module – A laser pointer attachment that fits any weapon.
• Extra Ammunition – Additional ammunition for your primary weapon.
• Dual Cell Battery – An improved battery which recharges faster and augments your flashlight.

Some screenshots:

Plenty of people have recorded videos of the game in action.

You can check out the code on assembla: https://www.assembla.com/code/the-stalker/subversion/nodes

Abandoned Game #1

It’s important to keep a log of the stuff you work on, even if it doesn’t pan out. I blogged about this game i was working on back in 2013 while i was in university, the following post is an amalgamation of everything i wrote pertaining to this game, edited for brevity and clarity.

This project started out in VS2010 using XNA and an open-source 2D physics engine called Farseer Physics but then VS2012 came along and Microsoft stopped developing XNA. XNA still works but it’s officially deprecated, so I migrated to Monogame which is basically a port of XNA that works on every platform (and works with VS2012 unlike XNA).

I didn’t really get any work done on this when i was messing around in VS2010. I had no idea what i was doing so most of my time was spent learning C# (which is a cool language) and figuring out the architecture of the Farseer Physics test samples. When I finally got around to installing VS2012 i had to figure out how to make Monogame work with Farseer Physics. After a while i sorted out the physics engine. The solution was trivial, just had to replace the XNA references with Monogame references and it built without any problems. So after I got that out of the way i hit my second road block. I couldn’t do anything with XNA content projects in VS2012. Monogame will soon support content projects but for now I have to use a separate content project in VS2010 and build that every time i add new assets (textures, etc) to my game.

So, once i got those two things out of the way i could actually start writing the game. I kind of cheated and used the Farseer Physics samples project as a reference when I started working on my game. So far I’ve implemented a similar screen management system (most games use multiple “screens” – menus and pause screens, etc.). And then there’s a lot of stuff behind the scenes that goes into actually setting up the “world” and spawning the low-gravity orange box you see in the first screenshot. It bounces around if you drag it with your mouse.

I guess my next task is to work on making the player object controlled by the WASD keys and make it so the player isn’t just a box that tumbles around (I assume i can just max out the damping on the box so it can’t rotate, or even just disable rotation). Then after that i suppose i’ll have to work on making the player object an animated entity with bones and joints and stuff.

In the picture there are 4 buttons in total, they support images and text (and a combination of both) but for now i’m just trying to get them to actually function like buttons. I think i’m just going to make my own text system using images for individual letters so i’m not actually drawing any actual text to the screen.

It’s hard to choose a starting point when you start from square 1, there are so many things to do and it’s hard to judge which features should take precedence. So for now I’m just going to try and get the basics of the interface sorted out and worry about everything later.

With some work I got the main menu and buttons working exactly how i wanted them to. Right now only the New Game and Exit buttons work. If you click New Game, it transitions to the game screen and spawns a player object. And the exit button speaks for itself. I think i’ll worry about getting a proper font and making the buttons look nice when it really matters. For now i want to flesh out the more important things.

This isn’t very exciting to look at but there’s a lot of stuff behind the scenes being completed! I wrote a basic EntityFactory and EntityManager class. Now i can go wild creating new entities.

I’ve also been working on a entity hierarchy. In my previous blogs i wasn’t actually using entity factories or my own entity classes so it took like 30 lines of code to just create one object, and then i had to write the code that renders the object on the screen. Now i can create an object in one line of code and I don’t have to worry about how it renders.

I need to figure out how to go about properly deleting entities. Right now, my EntityManager keeps a list of all the objects I’ve spawned into the world. If i delete an object then i also need to remove it from the EntityManager’s list (and if it’s a physics entity then i need to delete its physics object too).

Next, I finished an input helper component which should come in handy for several things. I can’t see how anyone can program a game without using a component-based architecture… It’s messy enough with everything compartmentalized, I can’t imagine how much of a mess it would be if it weren’t.

And here is more progress with player movement. Those two orange rectangles you see covering the blue bouncing rectangle are actually not colliding with anything, they are sensor bodies that tell me whether the player object is on the ground or touching a wall (which is why i can bounce off walls, that was intended). Normally they would be invisible, i’m just drawing them because i want to be sure they’re scaling properly based on the size of the physics entity they’re parented to.

I wrote an attribute system for entities and made them serializable. My next order of business is making a simple level editor. Instead of making a separate modding toolkit for this game i figure i might as well just build it in as a menu of its own.

I finished some concept art.

I Frankenstein’d the final product from several different sketches. I don’t own a scanner (i had to hold my webcam steady and take top down photos of each drawing) which explains the differences in color. If this looks like it was inspired by Earthworm Jim or something similar then that’s probably because it was.

For some reason i can’t draw normal hands to save my life. I also can’t draw hands directly from an arm, i have to draw them separately then splice them in and re-scale them using Photoshop. The gun in his left hand was also drawn like twice the size it needed to be.

The final product, converted in Photoshop and colorized without shading.

 

This is essentially all I really was able to complete on this little project before I lost interest. Around this time, Unity was growing in popularity and my university switched from MonoGame to Unity for all game development courses. Switching from MonoGame to Unity definitely helped highlight some of the things i disliked about MonoGame. Pretty much everything has to be programmed from scratch. This isn’t terrible if you know what you’re doing (I didn’t) and you want maximum control over every aspect of your game (I didn’t).

To say that I simply quit working on this solely because I lost interest would probably be an oversimplification. It was a combination of dislike for the game engine, lack of vision/direction for the game i wanted to make, and a lack of free time due to coursework. It was a good starting point for learning the architecture of games and figuring out how game engines really work under the hood.

 

Taming Random Numbers

Imagine you have a 120×120 grid of tiles. A tile can either be empty or solid. You want to procedurally arrange the grid such that the empty tiles form an interesting complex of caverns. You also want to be able to generate a near-infinite amount of different styles and variations of caverns, because variety is nice.

 

First, the basic concepts need to be set up. Every tile in the grid needs to know about the tiles that surround it. What is the X and Y position of the tile? How many tiles around it are solid? How many are empty? Is the tile to the left of this one solid or empty? Is this tile on the edge of the grid? All of these questions need to be answerable by an individual tile.

 

You also need to come up with a solution for how you’re going to tweak all of these tiles to get your result. This is where the concept of a filter (for lack of a better name) comes in. Every time the entire grid is modified, a filter will be handling the logic. By chaining several filters, you get your end result. A filter can be very simple. You could make a filter that finds every tile on the edge of the grid and makes it solid, or a filter that swaps all empty tiles to solid and vice-versa. You can also incorporate several commonly used tools in procedural generation into your filters, such as cellular automata. And so-on.

 

First, you start by randomizing the tiles. This gives you a rough starting point for shaping your caverns. Next, you apply some simple cellular automata rules to transform the noise into something more manageable. The cellular automata rule is simple: if a tile has 4+ solid tiles directly neighboring it (including diagonals), then it becomes solid. The same logic applies for empty tiles with 4+ empty surrounding tiles. In all other cases, the tile remains as it is.

In the animation you can see that step 1 is the random collection of tiles, while in the following steps a cellular automata rule is applied. The effect of the filter diminishes after the second or third step, so for practical purposes you just need to run that filter 3 times to smooth things out.

 

One obvious issue is that there are caverns that get generated with no way to move from one to another. What if the solid tiles are unbreakable?

Starting with a nicely smoothed out set of caverns, you could then add a filter which reduces the number of caverns to something more manageable. You could keep the 8 largest caverns and take all remaining caverns and make them solid. To maintain the same number of empty tiles, you could convert random solid tiles from the larger caverns to empty tiles based on how many empty tiles the now-removed caverns had. Now you have a guaranteed collection of 8 or less disconnected caverns and your grid has the same ratio of solid tiles to empty tiles. How can you make sure the caverns are all connected? One solution is to connect every cavern to the largest cavern by digging a trail to the large cavern. Now you can be certain that every empty tile on the grid can be reached by the player.

 

What if you aren’t satisfied with the distribution of caverns? What if you want to guarantee that the majority of the map has caverns of a specific width (more or less)? You could make a filter which finds every solid tile that has 5+ solid tiles in every cardinal direction, and make it empty. The same logic would conversely apply to empty tiles.

Step 3 on this image illustrates the outcome of applying this new filter. Solid masses of tiles suddenly have hollow interiors and large empty spaces suddenly have solid chunks of tiles filling them up. This filter seems to make a mess of the grid, however, so you would need to re-apply some other filters to clean it up. Reducing the number of caverns to something manageable then connecting all the caverns with another filter would give you desirable results.

 

Maybe you want the caverns to be more rectangular and less blob-shaped. You could add a filter that fills in small gaps and removes bumps.

Your options are limitless when you have control over the set of filters applied, and the ordering of these filters. The filters can even be fed different parameters to give much different results. Maybe you want to reduce the number of caverns in the grid to 5 instead of 8. This would use the same cavern reduction filter used previously, just with different criteria.

Having more filters at your disposal means you have more control over the end result, and also more interesting combinations to try.

 

What this conceptual grid of solid and empty tiles will be used for will be the topic of a future post.