Game Design, Programming and running a one-man games business…

Auto-balancing and load-testing Ridiculous Space Battles

Its been a while since I blogged… Anyway I have not been completely idle. As well as booking a long-desired holiday to CHINA (oh yes!) I have still been working on this weird project that I cannot decide if its a retirement hobby or a proper serious game launch, and that would be my pretentious re-imagining of Gratuitous Space Battles, which I am appropriately calling ‘Ridiculous Space Battles’.

The game is very playable right now. It has a ton of content, and it runs great, and it looks fab. But it does not have data for the campaign games, and does not have the challenge system coded into it yet. I might at some point decide to put the challenge system off for a bit, and release it with skirmish and campaign games into Early Access. I really do keep changing my mind on that. This game has been very cheap to make, and I am under no pressure to release, so to be honest it feels kinda weird being able to do anything I like with it!

Anyway, something I have always wanted for my games was a pre-release debug build functionality to have them run hundreds or thousands of games and automatically provide data that would let me balance the initial stats before actual humans start to play it. Now if you are a relatively new developer, its easy to just sling out lines like “Yeah just code a headless mode that randomly designs ships and fleets and have them fight each other a million times to collect stats”. This is the sort of thing swaggering indie devs throw out in a reddit thread as advice, as though that single sentence contains all the required skill, code and effort.

Its not that simple.

Now if you have a much simpler ‘problem-space’, then it gets massively easier, but just the process of coding random ship designs and random fleet deployments is a major engineering effort in itself. Getting the game to be able to put together a ‘legal’ in game-terms design isn’t too tricky, but ensuring it produces sensible designs is another things entirely. There is nothing to stop the entire deployed fleet consisting of a hundred ships that only have anti missile defence weapons and zero offensive capability, for example. That would be a valid fleet design, but useless for auto-balancing. Worse, it would imply in the stats that missiles are useless, without the caveat of ‘yup but that strategy can never win a battle’.

Its a massive minefield of issues like this, an frankly I have not addressed any of them yet. My current code designs each ship in a fleet individually right now, so the chances are such anomalies would be highly unlikely. However, the point stands that a ‘random’ fleet design is not ideal. And thats before we start placing those ships in formations, and assigning orders to them based on their designs. I’ve done a bunch of wok on that, but its still not ideal.

The actual easy bit was the stats collection and amalgamation into a nice spreadsheet at the end. My game is very stats-based (its an auto-battler after all), so the code to track all those stats was already in game. What took a bit longer was the wrapper code to run through a battle with a random fleet, record stats, and then do the next battle. This *sounds* easy, but when a game has been designed on the basis of the user clicking buttons, circumventing that without errors can be buggy. I didn’t just simulate mouse clicks because I needed to totally skip the deployment UI for each battle. Otherwise I am flushing a ton of textures and loading a whole pointless UI between every battle, slowing down the auto-run process.

The real delay in this stuff has been two-fold. I need to code some sort of basic genetic algorithm for ship design, and I also encountered loads of bugs. Lets do the bugs first. Its easy to think ‘dude, you shouldn’t have bugs in your code’, but harder to make that a reality when you have a game as complex as RSB. There are over 720 source files for the game and the same amount again for the engine, and the code is fiendishly complex. Plus the actual GAME is fiendishly complex. For example, I encountered a crash bug while typing this (The game was churning auto-balance in the background). It was a crash bug where the game lost focus, then recovered focus (I had moved to another window), and it crashed in the shader for Target Painter weapons.

You might think ‘what a noob, you obviously dont re-init your shaders’, but nope, I do. This is obviously something specific to THAT shader. I have tested the game a lot, but apparently never alt-tabbed away exactly when the game was drawing a target-painting effect. Given how many different systems and visual effects the game has, its no wonder I have not churned through all the possibilities yet. This is one of the major benefits of writing this autobalance code. I am soak-testing my game, running thousands of battles and trying every permutation possible, and it throws up a ton of asserts and warnings and crashes, all in obscure and exciting places. I DO test new features when they are added, but testing them in every permutation of battle is impossible. I’d need 50 people working in QA.

So the last aspect of all this is genetic algorithms. I intend to try a bit of this but no go mad. Right now, I can only tell if ‘fast missiles’ are overpowered by looking at the amount of damage they do, over 100 battles, compared to their cost and weapon module size. If they DO look a bit overpowered, then maybe they should be selected more, to assess whether they are clearly a super-weapon, or if thy just happened to always get matched against fleets that had poor missile defence. Perhaps I need a system that takes the top ten weapons from the previous 100 games and biases towards them so I can concentrate on collecting data for them. Perhaps also do the same with the BOTTOM ten weapons so I can see if they were just badly represented due to random match-up.

And of course all of this is ignoring non-weapon modules. I should probably test the ‘survival rate’ or ‘survival time’ of ships with each armour and shield module or other defensive module like a decoy projector or cloaking device. Maybe these are hugely overpowered? I have not even begun to look at that yet.

One piece of excellent news though. My game is VERY good at pruning its memory usage and definitely has no leaks. I’m watching the area chart in the visual studio debug view as I type and its currently using 234MB (lolz) and rarely goes above 400MB in big battles. This is a vast improvement on my other games, or early builds of RSB that were leaky.

So there you go, I AM still coding, but not in a hurry, and I hope the end result is worth it :D. Don’t forget to add RSB to your steam wishlist if the game sounds interesting to you!

Ridiculous Space Battles Progress

Ok so, I know this is probably not a big deal, or a new thing… but I have spent so long with this blog casually embedding youtube video links, that it took until today in 2026, and my desire to do what I can to de-couple my life as much as possible from US tech companies for me to discover that you can just natively embed an mp4 in wordpress! So anyway… I present the new race-selection screen animation effect in Ridiculous Space Battles!

and yes… before you comment, I know there is a bug with a texture changing wrongly when I scroll to the left. I’ll fix that tomorrow! I am however, pretty happy with this code, and this look. Coding stuff like this is harder than it looks, because to have everything seem smooth and crisp, you have to basically render all of those windows to an offscreen copy (with alpha) and then copy them as scaled sprites to the screen. That sounds simple, but its a lot of management, as you keep swapping render targets, and have to very smoothly transition from ‘offscreen pre-rendered sprite’ to proper rendered and full featured window.

Trust me, its a pain. It took a whole weekend. Well… it took all the hours I worked this weekend (which was not a lot TBH…). Anyway, that is one new thing that is in Ridiculous Space Battles. Another change was the re-colouring and some adjusting of the deployment screen to make it more user-friendly and less BRIGHT COLORS:

This definitely looks better. You can also see that the range indicators from my last blog post are in there with less angry colors too. The next big thing on my list is to balance the various weapons, and in fact before that, I need to code systems that really quickly run a lot of battles super-fast for me to gather stats. That will be a whole rabbit hole of code, but should be fun.

So to recap, the things left to do before early access or alpha-testing are to balance the modules, to put together the campaign fleets, to test the campaign, and to implement and test online challenges. No doubt lots of bug fixes and optimisation to do too, but I love the optimisation bit :D.

Coding a load-balanced multithreaded particle system

Background: I am coding a 2D space-based autobattler with ridiculous levels of effects called ‘Ridiculous Space Battles‘. I code my own engine, for fun, in directx9 using C++ and Visual Studio.

Because I love coding, yesterday I found myself wondering how well the multithreading in my game was holding up. So I fired up the trusty Concurrency Visualizer in Visual Studio. I love this tool and have used it a lot on previous games. One of the biggest demands on the CPU for my game is particle processing. There are a LOT of explosions, and other effects, and a crazy number of particle emitters (thousands of emitters, hundreds of thousands of particles). Obviously this would normally be a code bottleneck, so I have a task-based generic multithreading engine that handles it. The main thread builds up a bunch of tasks, the threads grab the next task on the list, and the main thread will wait until the task list is empty. If there are still tasks in the queue, the main thread will do one as well. So how did things look?

Disastrous!

So what is going wrong here? I have a generic ‘marker’ set up to show the span of the main thread’s drawing of the game (GUI_Game::Draw()). Inside that, a bunch of unlabeled stuff happens, but I added spans to show when the multithreaded task called UPDATE_PARTICLE_LIST is called. There are two massive things going wrong here. Firstly, there are only two other threads joining in to process the particles, and secondly one of those updates seems to take 20x as long as the other. Worse still, its the one the main thread chose… so its a huge bottleneck. Technically this is still a speedup, but its marginal. How have I fucked up?

Some background to my rendering algorithm is needed: The game has 2 blend modes for particles. A ‘Burn’ mode, that saturates color and is used for fire, lasers, sparks etc, and a ‘Normal’ mode for smoke and debris etc. The particle effects are batched as much as possible, but I cannot mix those blend modes in a draw call. Also, some particles are below the action (the ships) and some above, to give a semi-3D look and make it look like the explosions engulf the ships. So this means particle emitters fall into one of 4 lists: NormalBelow, BurnBelow, NormalAbove, BurnAbove. This is all fine and works ok. In action, the game looks like this:

Because you can freeze frame and scroll around, everything has to be properly simulated, including particle effects currently offscreen. Anyway it all works, and I have FOUR particle emitter lists. So naturally, to load-balance everything, I gave one list to each thread and considered the job done.

BUT NO.

It turns out that those 4 groups are not equal in size. They are laughably unequal. The ‘BurnAbove’ list contains all of the fire and spark emitters on all of the pieces of all of the hulks from destroyed ships, plus sparks from fiery plasma torpedoes, expended drone explosions, and missed or intercepted missile explosions. Thats MOST of the particles. When I checked, about 95% of particles are ‘BurnAbove’. I had 4 lists multithreaded, but they were not vaguely really load balanced.

Once I realized that the solution was theoretically easy, but fiddly to implement and debug. I decided I would add a new load-balanced list system on top. I created 8 different lists, and when an emitter was created it was added to the ‘next’ list (the next value circled round through all 8), and told what list it was in. When it was deleted, it was removed from the appropriate list. Note that ‘deleted’ is a vague term. I delete no emitters, they get put into a reusable pool of dead emitters, which complicates matters a lot…

So in theory I now have a nice load-balanced series of 8 lists that contains every particle emitter that is currently live. The original 4 lists are still valid and used for rendering and blend mode data, but this ‘parallel’ list system existed alongside it, purely to handle load-balancing. What this means is, that a load-balanced-list may contains particles from all 4 render groups, but this does not matter as I am running update code on them, not rendering!

It didn’t work.

Crashes and bugs and corrupt data ahoy. I worked on it for ages, then watched a movie to try and forget it. Then this morning, after some digging, it was all fixed. What actually was going wrong was related to smoke plumes. Because there are a lot of smoke plumes, and they always reuse the same particle config data, they exist in a separate system, updated separately. I had forgotten this! And what was happening was my new load-balanced lists stupidly included these emitters when they should have been kept out of it. The emitters would expire and be deleted in the multithreaded code, then later accessed by the plume code. CRASH.

I worked it out this morning before breakfast! I was very pleased. You might be thinking, what about the only 2 threads thing? LOL I had hard coded the game to use maximum of 4 threads, probably as a debug test. Idiot. I just changed it to be 10 and everything worked:

This is more like it. I wasted ages trying to get the dumb concurrency visualiser to show my custom thread names instead of ‘Worker Thread’ but apparently thats the category. Not much help. FFS show us the thread names! (They work in the debugger). But anyway, that image above is a snapshot inside a busy battle for the GUI_Game::Draw() showing how UpdateParticles tasks get spread over 8 threads. I’m still not sure why that sixth thread misses out on a task, which gets nabbed by the main thread…

Anyway, the point is it works now, and in theory updating particles is 8x faster than it would be with single threading. I do need to apply the multithreading to a lot more of the game code to get the best possible results. I am testing this on a fairly beefy GPU and CPU (Ryzen 9 5900X 12 Core @3.7GHZ and RTX 3080) in only 1920×1080 res. I want the game to look awesome at 5120 res or on a five year old cheap laptop, so plenty more to do.

If for some reason this tips you over the edge to wishlist the game, here is the link :D.

Optimizing load times

I recently watched a 2 hour documentary on the ZX spectrum, which means little to people from the USA, but it was a really early computer here in the UK. I am so old I actually had the computer BEFORE that, which was the ZX81, just a year earlier. The ZX81 was laughable by modern standards, and I expect the keyboard I am using has more processing power. It had an amazing 1kb of RAM (yes kb, not MB), no storage, no color, no sound, and no monitor. You needed to tune your TV into it and use that as a black and white monitor. Its this (terrible) PC I used to learn BASIC programming on.

Anyway, one of the features of ZX81/Spectrum days was loading a game from an audio cassette, instead of the alternative, which is copying the source code (line by line) from a gaming magazine and entering the ENTIRE SOURCE CODE of the game if you wanted to play it. Don’t forget, no storage, so if your parents then wanted to watch TV and made you turn it off, you had to type the source code again tomorrow. I can now type very fast… but the documentary also reminded me of another horror of back then, which was the painfully slow process of loading a game.

These days games load…a bit quicker, but frankly not THAT much quicker, especially given the incredible speed of modern hard drives, and massively so when talking about SSDS. Everything is so fats now, from SSD to VRAM bandwidth, to the CPU. Surely games should be able to load almost instantly…and yet they do not. So today I thought I’d stare at some profiling views of loading a large battle in Ridiculous Space Battles to see if I am doing anything dumb…

This is a screengrab from the AMD UProf profiler. My desktop PC has an AMD chip. I’ve started the game, gone to the ‘select mission’ screen, picked one, loaded the deployment screen, then clicked fight, let the game load, and then quit. These are the functions that seem to be taking up most of the time. Rather depressing to see my text engine at the top there… but its a red herring. This is code used to DISPLAY text, nothing to do with loading the actual game. So a better way to look at it is a flame graph:

I love flame graphs. They are so good at presenting visual information about where all the time is going, and also seeing the call-stack depth at various points. This shows everything I did inside WinMain() which is the whole app, but I can focus in on the bit I care about right now which is actual mission loading…

And now its at least relevant. It looks like there are basically 3 big things that happen during the ‘loading battle’ part of the game, and they are “Loading the ships” “Loading the background” “Preloading assets”. The GUI_LoadingBar code is given a big list of textures I know I’ll need in this battle, and it then loads them all in, periodically stopping to update a loading progress bar. Is there anything I can do here?

Well ultimately, although it takes a bit of a call stack to get there, it does look like almost all of the delay here is inside some direct9 functions that load in data. I am very aware of the fact that directx had some super slow functions back in directx9, in its ‘d3dx’ API, which I mostly replaced, but ultimately I am using some of that code still, specifically D3DXCreateTextureFromFileInMemoryEx…

Now I have already tried my best to make stuff fast, because I’ve made sure to first find the texture file (normally a DDS format, which is optimised for directx to use) on disk, and load the whole file into a single buffer in RAM before I even tell directx to do anything. Not only that, but I do have my own ‘pak’ file format, which crunches all of the data together and loads it in one go, which presumably is faster due to less windows O/S file system and antivirus accessing slowdowns. However I’m currently not using that system… so I’ll swap to it (its a 1.8GB pak file with all the graphics in) and see what difference it makes…

Wowzers. It makes almost no difference. I wont even bore you with the graph.

And at this point I start to question how accurate these timings are, so I stick some actual timers in the code. In a test run, the complete run of GUI_Game::Activate() takes 3,831ms and the background initialise is just 0.0099. This is nonsense! I switched from instruction based to time-based sampling in uprof. That doesn’t now give me a flame graph, but it does also flag up that the D3DX png reading code is taking a while. The only png of significance is the background graphic, which my timers suggest is insignificant, but I think this I because it was loaded in the previous screen. I deliberately free textures between screens, but its likely still in RAM… I’ll add timers to the code that loads that file.

Whoah that was cool. I can now put that into excel and pick the slowest loaders…

Loaded [data/gfx/\backgrounds\composite3.png] in 73.0598
Loaded [data/gfx/\scanlines.bmp] in 20.0463
Loaded [data/gfx/\planets\planet6s.dds] in 11.8662
Loaded [data/gfx/\ships\expanse\expanse_stormblade_frigate_damaged.dds] in 10.7132
Loaded [data/gfx/\ships\ascendency\g6battleship.dds] in 9.3622
Loaded [data/gfx/\ships\ascendency\g5frigate.dds] in 6.9765

OMGZ. So yup, that png file is super slow, and my bmp is super slow too. The obvious attempted fix is to convert that png to dds and see if it then loads faster. Its likely larger on disk, but requires virtually no CPU to process compared to png so here goes… That swaps a 2MB png for a 16MB (!!!!) dds file, but is it faster?

NO

Its 208ms compared with 73ms earlier. But frankly this is not an accurate test as some of this stuff may be cached. Also when I compare pngs of the same size, I’m noticing vast differences between how long they take to load:

Loaded [data/gfx/\backgrounds\composite11.png] in 113.9637
Loaded [data/gfx/\backgrounds\composite3.dds] in 208.7471
Loaded [data/gfx/\backgrounds\composite5.png] in 239.3122

So best to do a second run to check…

Loaded [data/gfx/\backgrounds\composite11.png] in 112.8554
Loaded [data/gfx/\backgrounds\composite3.dds] in 84.9467
Loaded [data/gfx/\backgrounds\composite5.png] in 108.4374

WAY too much variation here to be sure of whats going on. To try and be sure my RAM is not flooded with data I’d otherwise be loading, I’ll load Battlefield 2042 to use up some RAM then try again… Interestingly it only takes up 6GB. Trying again anyway…

Loaded [data/gfx/\backgrounds\composite11.png] in 114.0210
Loaded [data/gfx/\backgrounds\composite3.dds] in 85.6767
Loaded [data/gfx/\backgrounds\composite5.png] in 105.8643

Well that IS actually getting a bit more consistent. I’ll do a hard reboot…

Loaded [data/gfx/\backgrounds\composite11.png] in 104.3017
Loaded [data/gfx/\backgrounds\composite3.dds] in 207.8332
Loaded [data/gfx/\backgrounds\composite5.png] in 141.2645

Ok so NO, a hard reboot is the best test, and swapping to DDS files for the huge background graphics is a FAIL. These are 2048 x 2048 images. At least I know that. The total GUI_Game::Activate is 7,847ms. That png is only about 1-2% of this, and it makes me wonder if converting all the dds files to png would in fact be the best solution to speed up load times? The only other option would be to speed up DDS processing somehow. Having done some reading, it IS possible to use multithreading here, but it looks like my actual file-access part of the code is not vaguely the bottleneck, although I’ll split out my code from the directx code to check (and swap back to a png…)

Creating texture [data/gfx/\backgrounds\composite11.png]
PreLoad Code took 1.0205
D3DXCreateTextureFromFileInMemoryEx took 111.4467
PostLoad Code took 0.0001
Creating texture [data/gfx/\backgrounds\composite3.png]
PreLoad Code took 28.4150
D3DXCreateTextureFromFileInMemoryEx took 71.1481
PostLoad Code took 0.0001
Creating texture [data/gfx/\backgrounds\composite5.png]
PreLoad Code took 0.9654
D3DXCreateTextureFromFileInMemoryEx took 105.2158
PostLoad Code took 0.0001

Yeah…so its all the directx code that is the slowdown here. Grok suggests writing my own D3DXCreateTextureFromFileInMemoryEx function, which sounds possible but annoying.

Ok…mad though it sounds, I’ve done that. Lets try again!

Creating texture [data/gfx/\backgrounds\composite11.png]
PreLoad Code took 0.8327
D3DXCreateTextureFromFileInMemoryEx took 103.4365
PostLoad Code took 0.0001
Creating texture [data/gfx/\backgrounds\composite3.png]
PreLoad Code took 0.6053
D3DXCreateTextureFromFileInMemoryEx took 73.9393
PostLoad Code took 0.0002
Creating texture [data/gfx/\backgrounds\composite5.png]
PreLoad Code took 0.9069
D3DXCreateTextureFromFileInMemoryEx took 105.0180
PostLoad Code took 0.0001

Am I just wasting my life? at least I now have the source code to the DDS loader because it is MY code bwahahaha. So I can tryu and get line level profiling of this stuff now… I’ll try the visual studio CPU profiler:

Thanks Microsoft. But there may be more…

The Visual studio flame graph is saying that actually the raw reading from disk of the file IS a major component of all this, and so is a memcpy I do somewhere… Actually its inside the fast DDS loader, so the flame graph is confusing. The DDS loops doing memcpy calls for each line of data. This is very bad. With a big file, there will be 2,048 calls to memcpy just to read it in. Surely we can improve on that? and yet its clear thats what D3DXCreateTextureFromFileInMemoryEx is doing, as seen earlier. Hmmmm. And now people have come to visit and I have to stop work at this vital cliffhanger…