Managing Content and the Joys of Smart Pointers

Hello everyone, I figured I’d write a post about something I’ve been working on for the last week or so, partly as a bit of advice for some budding programmer wanting to write a bit more low level games programming stuff, but also to try and explain why it has been several weeks since I last posted about a small prototype I’ve been working on, and why I have been posting less stuff on Twitter than usual.

To put it basically, a lot of C++ work, mostly involving Gemstone Keeper. I decided to go back to it one more time after a lot of bugs and feedback came in. By the time I’ve posted this, Gemstone Keeper has been updated to version 1.0.3, which includes bug fixes, UI updates and two new enemy types.

j7fcaz6

 

While most of this wasn’t planned (most of this would have happened much earlier if I was notified on Steam within days of it being reported), but it had been on mind for a particular reason.

To put it simply, I have been updating my C++ game framework, the Vigilante Game Framework. This is the framework that I had built up alongside the game it was made for, Gemstone Keeper, before open-sourcing it in the hopes that it could be improved for more projects. I noticed a problem with the content management system, and as such I had spent the last two weeks researching and implementing a new way that would make it more optimal while keeping it stable. Because of this, Gemstone Keeper will soon be updated with this improvement among other bug fixes, and any future games using the VFramework will feature this too.

dytc50n


Here is the original code for loading and setting an sf::Texture in my content system, according to the repository for Gemstone Keeper this was initally written around Feburary 2016, and aside from one change in April this remained how it was:

bool VContent::LoadTexture(const sf::String& name, sf::Texture &texture)
{
   if (FindTexture(name))
   {
      texture = textureDir[name];
      return true;
   }
   else
   {
      if (texture.loadFromFile(name))
      {
         VLog("%s loaded", name.toAnsiString().c_str());
         textureDir.insert(textureDir.begin(), std::pair<sf::String, sf::Texture>(name, texture));
         return true;
      }
   }

   VLog("Error loading texture: %s", name.toAnsiString().c_str());
   return false;
}

The approach should be fairly straightforward:

  • If a texture exists, set it to the texture object and return true.
  • If it doesn’t exist, load it using the texture object. Return true if load is successful.
  • If it cannot load, return false.

However there is one problem, setting the texture object doesn’t set the reference, despite passing the object in as a reference (hence the &). Instead it creates a copy, with a new texture ID and references.

Performance wise, this doesn’t have much of an issue, however memory wise there could be a concern with creating several sprites with the intention of using the same texture, but it isn’t. The intent of a content manager is to load, unload and store a single instance of an asset, with any objects merely referencing that content. I investigated a number of approaches (and spoke with eXpl0it3r of the SFML team) to find the right one.

The approach I finally went with required the following changes:

  • The load function should return the object itself as a non-pointer reference, not a bool. This is to ensure that if the loading or finding process goes wrong, the program should let you know and fail. The reason for a non-pointer is to ensure you wouldn’t return a NULL object. Returning a reference makes sure not to return a newly created copy.
  • If it cannot be loaded, an exception should be thrown. Exception handling is an ideal alternative to responding to function returning false, because it’ll make a function closing on failure much easier.
  • The texture should be stored as a unique pointer.

The reason for a unique pointer, instead of a regular or “raw” pointer, is to ensure that the object only has one true owner, and that once it’s dereferenced (either by closing the game or unloading it) it’ll be properly destroyed and unable to be used by other objects, all with little to no difference in performance. While a unique pointer cannot have more than one reference, the raw pointer can still be obtained and used, just make sure that once the content is unloaded there aren’t any active objects still referencing it.

This is what the texture loading function looks like now (from the Github Repository):

sf::Texture& VContent::LoadTexture(const sf::String& name)
{
   auto found = textureDir.find(name);
   if (found == textureDir.end())
   {
      std::unique_ptr<sf::Texture> texture = std::unique_ptr<sf::Texture>(new sf::Texture());
      if (texture->loadFromFile(name))
      {
         VBase::VLog("%s loaded", name.toAnsiString().c_str());
         textureDir[name] = std::move(texture);
      }
      else
      {
 #ifndef __linux__
         throw std::exception(("Error loading texture: " + name.toAnsiString()).c_str());
 #else
         throw ("Error loading texture: " + name.toAnsiString());
 #endif
      }
   }

   return *textureDir[name];
}

To use the functions in this format, I had to change a lot of objects around the game. Textures, Images, Fonts and SoundBuffers all changed to use raw pointers, and the returned values from the functions are converted to functions as well.

texture = &VGlobal::p()->Content->LoadTexture(filename);
sprite.setTexture(*texture);

This ensured that the object being set is has the same reference as the object being returned, no more copying data, no more instantiating new objects to handle the copy.

I’ve also turned a lot of other objects into unique pointers, particularly the objects in VGlobal, which is intended to only have one instance of. It’s ideal since these ones are all destroyed at the end, and in a scenario where an object could be replaced with another one, the unique pointer can destroy the old one in order to replace the new one.

Other small changes I’ve made to update the framework includes all objects that load textures now having an optional area rectangle. This was mainly put in if multiple sprites use the same texture, but different atlases. Best example would be in the LoadGraphic and setSize functions of VSprite, where the default parameter will ensure the whole texture is used, else the animation system will restrict the render area of the sprite to that rectangle. While sf::Texture does have the ability to load a rectangle area of a texture to an object, I feel like this only adds a separate texture, instead of the one loaded and taken from VContent. At some point I’d like to use this more for Gemstone Keeper and other games, as I see reducing the texture count and having more render calls using the same texture would have additional benefits, no matter how small.

Hopefully more changes like these will benefit games I make with this framework, I’d also like to use more smart pointers, maybe shared pointers for my general objects, but for the time being, I’ve got a project to get back to.

Advertisements

All the jams!

I was meaning to post this sooner, but along with work piling up and losing track, I did quite a few game jams. Three in particular: RemakeJam, Jamchester and Ludum Dare.

  

I’ll mention Running The Marathon first, because I only finished the game two days ago from posting. This was made for Ludum Dare 39, which makes it the 10th Ludum Dare I participated (and 9th I submitted a game independently). This was a bit of a last minute entry because until Saturday evening, I had no intention of making something for LD. What changed my mind was a game idea I was coming up with as a joke, running a marathon and making sure you don’t run out of energy. What I ended up with was a bit of a joke on the Track & Field concept, by having rapid button presses make your chances at success worse. Because of how little time I worked on this, the background animations and sounds are lacking, although I do think the running animation on the player turned out okay.

4i8mLl.gif

As is the tradition of Ludum Dare, voting will be going on by all participants for a total of three weeks. Any Ludum Dare entrants can go to the game’s Ludum Dare event page to vote and comment.

Next I’ll talk about Dash Dodge, which was developed for Jamchester 2017, a professional games jam that I took part in last year. This year, I was in a team which consisted of another programmer & sound designer (Jessica Winters) and two artists ( and ). All in all, this was a great team to work with, and we had a heavily planned out game about combatting bosses using only dashing, with a time travel element, although we may have over-anticipated our goals a bit. Needless to say, we made a game with a nice visual style and some neat mechanics thrown around. Hopefully at some point in the future I would like to work with these three again at some point.

Finally, there is 8-Bit Theater: Black Mage is in a Shooting Game. This game, developed for RemakeJam, is a remake of a previous game of mine. In particular, this is a remake of the first game I ever made from back in 2010. What was great about working on this is that I still have the original source project and most of the original assets and notes, although I did have to dig through Google for a copy of GameMaker 8.1 in order to view the original project. Sadly because of lack of time (I rarely allow full days of focus for these game jams, I’ve noticed), I just about managed to remake the original two levels and boss. This wasn’t for naught though, as way back when it took me over a year to reach this far, and this time I managed to achieve the same amount in less than a week. I also took advantage of my own game framework to try out some technical challenges, such as parallax scrolling.

Game Jams are fun, I like taking part in them for those short bursts of game ideas and development challenges. Sadly participating is made more difficult when my day-job takes priority, but when I get a chance to take part I’d like to take full reigns!

Now time for some voting and other challenges!

Gemstone Keeper – Quest to Linux Part 3 – Gemstone Keeper

Finally, after beginning soon after the game’s Windows release on Steam, and well over a month after I initially wrote my first post about this topic, I’m finally done with porting Gemstone Keeper to Linux (for the most part) and ready to write about what I’ve learned from porting it over. Since both the Framework and Level Generator have been ported, getting the whole game to compile and run wasn’t as confusing as the last two, but that didn’t stop it being tedious.

Continue reading

Gemstone Keeper – Quest to Linux Part 2 – GenLevelTools

Last time on Quest to Linux, I went through porting the Vigilante Game Framework to Linux, but the quest isn’t over yet. The next big task is porting Gemstone Keeper’s level generator and editor, the GenLevelTools, since I need to be able to get the caverns from somewhere.

https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png

GenLevelTools, aka the Procedural Level Editor, is a tool/library set that enables proceudrally generated grid-based levels to be modified and previewed in a level and used in games, while independent from any specific game engine or renderer. It was originally developed for my University Thesis on Procedural Level Generation and I later did a talk about it at the International Roguelike Developer Conference in Nottingham. The library is written in C++, so language specific quirks like forward slashes and for loops apply, so the main challenge this time around is the level editor, which uses Allegro 5 as well as the GUI library GWEN.

Allegro 5 is a C framework, although you can still use it for C++. Fortunately like SFML, it’s easy to set up for Linux since it’s part of one of Ubuntu’s repositiories. GWEN is a GUI library that was developed by Garry Newman (of Garry’s Mod). It was the easiest to set up for Windows but I had a few problems with the Linux version, as the gmake scripts rely on finding certain libraries and ending the entire scripts if those libraries cannot be found. This is different from running the scripts for Windows, which create Visual Studio projects that you can apply the libraries yourself. After tweaking the scripts and the source files a bit, I managed to get the GWEN and GWEN Allegro Renderer to build.

Aside from the main changes that I mentioned in the last post (using correct slashes, for loops) there weren’t that many changes I needed to make. I did have to add a lot more include statements, since despite being standard library stuff, GCC doesn’t immediately know what functions like memset, modf, floorf or ceilf among others off the bat, unlike Microsoft Visual Studio. After all these changes the library was able to compile smoothly. To make absolutely sure that it works within Linux, I wanted to build and run the editor, hence why I wanted to set up Allegro and GWEN. I managed to compile it with little effort, but something went wrong…

The editor crashed almost immediately, and the only reason I was able to show the following above was because I tried running the editor without the GWEN GUI rendering in the scene. It didn’t help that Code::Blocks debugger wasn’t working initially, and the closest I got as an error was below.

Fortunately I was able to configure Code::Blocks debugger to work, and was able to find the route cause of the crash being from the GWEN Allegro Renderer being unable to load the font, which is odd because the font I used (Lucida Sans) was able to load fine in my editor code, but fortunately GWEN provides an open source font (Open Sans) that runs just fine. So now with the GUI render up and running, I can test the editor!

I’ve been able to compile the library as both a binary and static build, as well as the editor. I could also compile the unit testing and C# wrapper for it too, but since I mainly wanted to get this done for Gemstone Keeper, I’ll leave it like this for now. Time for the main course!

Gemstone Keeper – Quest to Linux Part 1 – Vigilante Framework

So with Gemstone Keeper on Steam for Windows only, I thought I’d try my hand at getting a game to build to Linux the proper way. This series of posts will hopefully document each part of porting Gemstone Keeper to run on Linux.

https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png

The last time I made a game with Linux support was Secret of Escape, which used the Node-webkit to run HTML5 games to desktop applications. Node-Webkit essentially was a separate, precompiled application that functioned like a limited web-browser using the Chromium engine, all Construct2 did was build a HTML5 game and structured it in a file structure that made the application run the game. This way, porting the game to Windows, Mac and Linux took very little effort. This essentially means that developing for Linux was a completely new thing for me before releasing Gemstone Keeper.

The first stage was porting the Vigilante Game Framework. This is the underlaying C++ framework that uses SFML to develop games with state management, collision, visual effects and audio effects among others. It was partially inspired by HaxeFlixel, although with some of my own approaches that rely on C++ and SFML, as well as my own features (such as circle collision, multipass post process effects and a custom text renderer). Getting this to work on Linux would help me with setting up SFML and having a good idea of how Linux development worked.

Surprisingly, getting the framework to build on Linux ended up being the easiest part, because someone else already did it! I posted the framework to GitHub, and passed around the GitHub page to Twitter and Reddit, and SirFrankalot on the /r/gamedev subreddit was able to fork it and get it to work in Linux, and provided both written notes and a pull request to carry his changes over! The details can be found here, but these are the main points I wanted to get across:

  • Using Correct Slashes: When using Windows Explorer and Visual Studio, folders or directories will usually be represented with a backwards slash (\). If you are only developing on Windows, this wouldn’t be a problem. However Linux and Mac both always use a forward slash (/), so for portability you should use that. Using forward slashes also has the advantage of not having to deal with escape sequences, since programming languages use a backwards slash (such as \n, \t and \\).
  • For-Loops: These kinds of loops are good for looping a specific number of times using a defined iterator. If that iterator is a list of object or variables, you use a foreach loop, assuming your programming language of choice has that. When using Visual Studio, I found there is a foreach loop in the form of for each (type x in y) where x is a reference to an object in the list, and y is a container like an array or vector. Turns out this way is purely a Visual Studio extension, and the portable foreach loop is for (type x : y).
  • XInput: Microsoft XInput is the API used for Xbox 360 and Xbox One controller, which means that it’s works for Windows only, at least that’s what you would assume. Linux has both libudev and linux/joystick.h, which allows some Linux OSes to access XInput functionality. This would mean a complete rewrite, so SirFrankalot simply made all XInputDevice functions return false. I later found someone wrote a Gamepad API was maintained long enough to allow Xinput Controllers to work on Windows and Linux using the same functions. I’ve since added this on as an optional feature that can be set using a preprocessor.

https://upload.wikimedia.org/wikipedia/commons/3/3f/Logo_Linux_Mint.png

Next was using an IDE, I decided to use Code::Blocks because I have used it before, although it’s still much of a change of Visual Studio. Not to mention I was using a virtual machine, a VirtualBox with Linux Mint 18.1, and for whatever reason my configuration causes it to crash with no warnings. I also had to set up a load of dependancies, although using the terminal to get them is much easier than browsing for libraries online.

 

In the end I managed to build the SFML tutorial code and a few moments later, VFrame could compile! Aside from some small issues with 3D graphics, it was running almost just like it did on Windows!

Next time, it’ll be my ramblings as I port over the library that makes Gemstone Keeper’s caverns large and random, the GenLevelTools!

Ludum Dare 38 – littleBLASTplanet

Last weekend was Ludum Dare 38, not only is it the 38th main game, as well as the 8th or 10th one I’ve taken part in (whether or not you take into account failed attempts), but it also marks the 15 Year Anniversary of the competition/jam as a whole! Not only is it celebrated with another jam, but with a brand new website. For now you can still access the old website, but game submissions are currently being handled entirely on the new site.

ldjamalpha

The theme this time around was Small World, so I (like a lot of devs) made a game either around a small game world or a tiny planet. I went with the latter and drew up a run ‘n gun shooter on a little planet.

 

Sadly I had plans with my friends on Saturday so I didn’t start work on the game until around 8PM GMT, so development felt more rushed than a full games jam but I managed to make what I set out to design: littlePLANETblast

Similar to my past Ludum Dare projects, I used HaxeFlixel. It’s straightforward to use, multiplatform (Flash, HTML, Windows and Android maybe…) and it’s still being maintained so there have been several improvements. I’ve provided the game’s source code on Github so feel free to have a look to see how the game works.

The first problem I had to solve to make this game work is how to make a sprite orbit a planet. HaxeFlixel has a FlxVector object for vector math, so using that with a sprite’s acceleration meant having the sprite fall towards the centre of a circular planet was pretty easy, but how do you get the sprite to stop on the planet’s surface?

HaxeFlixel has no circular collision, only rectangtle collision. When I wrote my own C++ framework for Gemstone Keeper, which took inspirations from HaxeFlixel, I included Circular collision by giving each object a Radius property and writing my own circle overlap and separation functions. This would have been too much work for the time I had, so I wrote a hack method for a derived sprite class that always checked and updated the distance between a sprite’s centre and the planet’s centre, and if the distance was less than both the planet’s radius and sprite’s radius combined, then the game pushes the sprite up to the edge of the planet. This circle collision method is only applied between a sprite and the planet, and since rectangles don’t rotate then all sprites had to be perfect squares.

Bullets were one of the only sprites that weren’t built to orbit the planet, instead simply moving in an angle that combines the firing direction with the player’s current angle. I’ve had some feedback that said that the bullets should also be affected by gravity. I decided against it because it would make enemies on the planet easier to hit, while enemies in the sky would be harder to aim, not to mention the game loses a strategy element because of where bullets travel.

 

I went with three base enemy types: Rockets, Spikes and Robots.

Robots functions no differently from the player, except that it moves in a fix direction and smaller ones bounce by constantly jumping. Spikes has the same orbiting system, but it’s planet radius is much smaller to allow it to go into the planet. I use FlxTween and the FlxTimer to allow the spikes to move in sequence. Rockets simply spawn outside the screen at an angle and move towards the centre of the planet. If a rocket touches the planet then it would be destroyed, resulting in an instant game over.

I also added an escape object, which changes the planets side and makes the level a little bit more harder. This was for variety, so you wouldn’t have to stay on the same planet. If I had a bit more time I would have included more animations on the planet itself.

Speaking of the planet, that was one of the first objects I applied polished graphics to. To give it a more detailed pattern, I used the built in Cellular Automata function, and applied the pixels to the circle. Since it uses a random seed, the pattern is different on each playthrough.

The planet’s destruction is a particle effect that uses the planet sprite’s texture, a technique I used a lot in Gemstone Keeper. However one gripe was that I had to make a derived FlxEmitter class that could allow me to set how many frames I wanted based on the particle’s frame size.

Along with proper sprites, smoke was added to the spikes so that the game can provide a one second warning before spikes hit. I also added a distance check to avoid some unfair spike deaths. Finally I added a second camera mode incase the first one wasn’t interesting enough. The follow camera simply rotates with the player so they can stay in one spot while all the other objects rotated around. It did mean having to create a new Camera for UI elements, since objects can only be parallax scrolled by position.

The last elements I added were the title screen and audio. Sound effects were produced with BFXR and music with Abundent-Music’s Procedural Music Generator. Audio is one of my weakest skills so these procedural tools made that quick and simple, although I probably wouldn’t enter myself into the audio category for them.

I figured I add a smaller version of the planet in the title screen and have the player sprite on a bigger world to give a vague sense of a setting, with emphasis that the player is fighting on tiny planets and not just a giant on a regular sized planet.

And that’s basically how I made littleBLASTplanet. If I had more time I probably would have created more enemies and made proper transitions between planets. Aside from that I’m pretty happy with the results, particularly hacking the physics to getting jumping and moving around a 2D planet to be possible.

Voting for the game begins on Wednesday Friday, so if you took part in Ludum Dare, please check it out!

Gemstone Keeper on Steam Right Now

https://i0.wp.com/i.imgur.com/EprkPSq.gif

Check out the Steam Store, and you’ll see that Gemstone Keeper has a page where you can add to your wishlist, purchase the game and write a review for it. I greatly appreciate seeing people buying the game and giving it a good review, it really means a lot after realising that this game has been in development for nearly two years (May 2015 – April 2017). Reviews in particular are important because I’d like to collect a list of issues and make fixes, and hopefully add a bit more to the game over the course of a year. Gemstone Keeper will also be shown at Insomnia 60 at the Birmingham NEC and maybe a few more events if people find an interest.

In particular I want to thank Vincent Rubinetti for his contributions for the game. While he was the person I had in mind to do the soundtrack from the point I listened to his music in INK, I was a bit nervous about approaching him with the demo I had. However after a few emails back and forth, we made an agreement and we were underway for producing a great accompanyment to the game’s visual art style and atmosphere.

https://i2.wp.com/i.imgur.com/ajrVcHB.gif  https://i2.wp.com/i.imgur.com/24gcQz8.gif

In addition, I’d like to apologise for leaving this two days late; I couldn’t plan ahead because I spent the last few days sending out emails and twitter DMs in the hopes to get the game looked at by people; I fixed bugs and adding some last minute features such as damage numbers appearing whenever you hit something with your bullets and being able to type the seed you want to use in Score Mode.

On the launch day, I was at Rezzed, where I did talk to a few people about my game, but mainly walked around and tried out a selection of great titles. By the time 6pm rolled around, I hung out at an after party and chatted to a few developers.

Then the day after was my birthday, so I figured I would post on social media, but spend most of the time away from the game and more with friends and family to celebrate and relax.

https://i2.wp.com/i.imgur.com/prEWNzt.gif https://i2.wp.com/i.imgur.com/Fi4QFr6.gif https://i2.wp.com/i.imgur.com/DTZmFdO.gif

As for my future plans, aside from this game’s maintenance, I’m hoping to return to smaller games for a while. In particular I want to try a few more game jams and experiment a bit more, I have a few ideas I want to try out, and now I have a little less pressure on me to work a bit on them.