Friday Afternoon

11 11 2016

It’s been a hectic week and I’ve not managed to post a normal update on Sunday like I wanted but such is life I guess. This post is going to be fairly short as well I suspect. So, what happened?

Well, Donald Trump got elected. This has nothing to do with writing code but it was a fairly monumental event. Hopefully he’ll do better than his predecessor; concerning the middle east, I doubt he could do worse.

Everything else about this week had to do with chasing down minor bugs in the code and chasing after some bureaucratic bullshit concerning my father.

What did I manage to achieve this week?

Firstly we’ve replaced all interactive text prompts in the game with icons. And in order to do this I extended our basic sprite component to allow for atlasing (ie. the practice of having several distinct images within one texture and allowing users/systems to access them in an easy way). This in turn made it possible to quickly generate a texture atlas containing all input icons. And now the systems will automatically recognise and display the appropriate interaction input icon based on the player’s bound keys.

Secondly I had to fix some issues which came about from our new scene transitioning system (added a proper loading screen, support for an animated icon and an easier to use fade in/out system). The strangest bug that happened was that the pause menu broke. I guess that’s what happens with interconnected systems in the end. One change affects another. Luckily I’m not debugging on blind and I do have some automated tests…

Anyway, that’s it for now.

everybody knows that the dice is loaded, everybody rolls with their fingers crossed

Editing Project Files

19 11 2014

I find myself in a common situation where I want to open all of the .csproj files in my source directory for editing. My editor of choice is Sublime Text and I’ve got a customized environment to help me locate all of my development tools via common paths (I think I wrote about that in another post, if not I’ll write about how I set up the environment in the next post). I could write a batch file to handle that via the Windows cmd, but I figured how hard could it be to write a small tool in C#.

It wasn’t hard at all and took about 20 minutes. For me it’s a win. So without further ado, here’s the main parts of the code.

public static void Main(string[] args)
  var files = GetProjectFiles();
  var files_path = GenerateExeArgs(files);
  var exe_path = GenerateExePath();
  Process.Start(exe_path, files_path);
 catch (Exception e)
private static string[] GetProjectFiles()
 var root = Directory.GetCurrentDirectory();
 var files = Directory.GetFiles(root, "*.csproj", SearchOption.AllDirectories);
 if (files.Length == 0)
  throw new FileNotFoundException("No .csproj files found under current directory");
 return files;
private static string GenerateExeArgs(IList files)
 var files_path = "";
 for (var i = 0; i != files.Count; ++i)
  var filename = files[i];
  files_path += " " + filename;
 return files_path;
private static string GenerateExePath()
 var sublime_dir = Environment.GetEnvironmentVariable("sublime_dir");
 if (sublime_dir == null)
  throw new NullReferenceException("could not find the %sublime_dir% variable");
   var exe_path = Path.Combine(sublime_dir, "edit");
 return exe_path;

Alright. Not too much to comment on that. Note that I do have a sublime_dir environment variable already declared. And the use of Process.Start() to run the executable.

“I fell for you like a child, Oh, but the fire went wild.”

Counts your lines!

5 10 2014

Type, type, type… Compile… Coffee… Type, type, type…

Eight hours and thirtey commits later. Blink. Stretch.

“Hmmm… How much code did I write exactly?”

It’s not really a useful question to be honest. The quality of my (and your) codebase is measured and quantified by better values than the infamous “Lines of Code”. Bill Gates was attributed with saying that measuring programming progress by lines of code is like measuring the progress on a Boeing by measuring its weight [not a direct quote]. And I agree. But sometimes it’s still fun to weigh things.

My first thought was running the analysis tools in Visual Studio. The numbers they crunch go further than simple LOC and weren’t really that interesting. My second thought was google. But alas, too many results and not enough time to go through them. It was then that I realized. Hey, let’s reinvent the wheel!

With that in mind I started a new console project (this is going to be written in C#) and decided to being with the simplest thing possible. Checking if I can read all files under my current directory and output how many code files there are.

public static class Program
  public static void Main(string[] args)
    var root = Directory.GetCurrentDirectory();
    var paths = Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories);
    Console.WriteLine("Found {0} code files", paths.Length);

That works. Note in particular that we’re searching just for “.cs” files. And under all directories.

Next we need to actually count all lines in the files.

  var line_count = 0;
  Console.WriteLine(":: Counting Lines of Code...");
  foreach (var path in paths)
    using (var reader = new StreamReader(path))
      while (!reader.EndOfStream)
        line_count += 1;
  Console.WriteLine("Found {0} lines of code in {1} files", line_count, paths.Length);

And that should be it, except it isn’t. Our little program will now count all lines in all files. ALL lines. I don’t want all lines. I want to count code lines. But wait, what do I mean by code? For our purpose with this tool we’ll take it to mean any line that is neither empty nor a comment. To do this we’ll introduce a new method to query whether a given line is considered for counting.

public static bool ValidateLineIsCode(string line)
  if (string.IsNullOrEmpty(line))
    return false;var unspaced_line = line.Replace(" ", "");
  if (string.IsNullOrEmpty(unspaced_line))
    return false;

  if (unspaced_line.Length == 1)
    return false;

  var ch = unspaced_line[0];
  if (ch == '/')
    return false;

  return true;

And yeah, it’s not perfect but for my coding standards it’s pretty good and gives me a decent metric (albeit a useless one) for LOC.

It was always summer and the future called; We were ready for adventures and we wanted them all

String to Bitmask

12 09 2014

Going to be a short post and unlike other times when I’ve said it and then went on to having a series of four posts, this time I mean it.

So, first, what brought this on?

Well, having tired somewhat of Unity‘s implementation I’ve decided to play around and write my own Entity.Component.System framework. For a game (of which I shall write about at a later date when there’s something playable).

In the process of writing it I’ve come to the conclusion that I need to twiddle some bits and because I’m quite pedantic it means I need to write tests for this.

Given my unit testing framework (NUnit) I’ve run into some issues when using the “TestCase” attribute. This (and other considerations) resulted in me digging through some old utilities and presto! Converting a string representation to a bitmask. A quick cleanup (it was written in C) and, presto! Let me introduce you all to the new utility on the block.

public static class GenerateBitmaskFromString
 public static Bitmask Perform(string line)
  var mask = 0L;
  for (var i = line.Length - 1; i >= 0; --i)
   if (line[i] == '1')
    mask |= 1L << ((line.Length - 1) - i);
  return new Bitmask(mask);

The Bitmask object itself is a simple struct wrapper around an Int64 or Int32 (depending on the platform) which provides some extra twiddling (is that… is that a word?) functionality.

I’m assuming knowledge of bit shifting and binary logic by people reading this. And also note that the order of character processing is reversed since given strings are usually in the form of “0000001” with their first character being the left most (ie. length-1) while bits are shifted rightwise.

Well, that’s it. Not very epic or grand but useful nonetheless.

He said, “We haven’t had that spirit here since nineteen sixty nine”

Enum Tricks

31 03 2014

Short post. It’s 1.18am and my two main projects are both running high which means a lot less time for anything else.

A couple of little tricks for flag enumerations; nothing fancy but useful.

Say we have an enum representing the components of a Vector3 object.

public enum VectorComponent
  None = 0,
  X = 1,
  Y = 2,
  Z = 4,
  XY = X | Y,
  XZ = X | Z,
  YZ = Y | Z,
  XYZ = X | Y | Z,

Notice I’ve added the entire set of component combinations to the enum values; usually this isn’t feasible and we’d have to rely on runtime behaviour for adding and subtracting flags. In this case however, where the set is small, closed and well known, adding the value permutations is – in my humble opinion at least – the right thing to do.

Where were we? Ah yeah, let’s say we have an instance of said enumeration with the X component set.

var components = VectorComponent.X;

Now, how do I know (at a later date) whether someone’s added another component flag to my simple component value?

public static VectorComponentExtensions
  public static bool Contains(this VectorComponent current, VectorComponent value)
    return (current & value) == value;

Quick aside again. I’ve opt to use extension methods. I didn’t have to, could have used a static utility class which accepts a normal input value but, I like extension methods for these kind of cases (do try to minimize them though).

And getting back to our enumeration…
Wasn’t that just the cutest little query ever? What else can we do?
Let’s say that now I’ve used the VectorComponent enumeration to lock a particular component of a position value. Like thus:

var locked_components = VectorComponent.Z;

How do I know which components are still free to be manipulated?

public static VectorComponentExtensions
  public static VectorComponent GetReversed(this VectorComponent current)
    return current == VectorComponent.None ? VectorComponent.XYZ : ~current;

  // Correct method using the XOR operator.
  public static VectorComponent GetReversed(this VectorComponent current)
    return current^VectorComponent.XYZ;

So that’s it for now. Late night. Small snippets of code and the Charlie Daniels Band in my ears. I’ll see you all in the next update. Soonish… honest 😀

“I may be half man, but the other half’s devil, And you’re just exactly like me”

Unity2D – Sprites 3

13 01 2014

Actually I kind of forgotten where I left off. I really need to start attaching code files. Might create a shared repository for all this stuff over at Bitbucket. Anyway; yes, sprites in Unity. Have I mentioned that this has nothing to do with the new Unity2D update which the lovely boys and girls over at the Unity team just released? Did I also mention that the Unity2D update is mostly not really that useful?

Trolling aside, let’s see where I was.
Hmmm…. Sprites… Meshes… GameObjects… Ah yeah, making sprite-like objects in the editor.

Alright, with the first approach done I’d like to go for the third approach since it’s only slightly more complex. In fact, it’s not even slightly more complex so we’ll get it out of the way right now. Remember how in our first attempt we’ve created the sprite node. All we need to do now is simply create another node and parent the sprite node to it.

var selected_texture = (Texture2D) Selection.activeObject;
var sprite_node = new GameObject("Hero");
var graphic_node = NewSpriteNode.Make(selected_texture);
graphic_node.transform.parent = sprite_node.transform;

And voila, we have a proper transform hierarchy where the graphic_node itself acts as the pivot point of the sprite since it’s position is localized to the sprite_node’s space. And if we really want to be sexy here we can always set the graphic_node’s hide state and not even see the resulting hierarchy ugliness.

The second approach is more interesting and more complex since it involves custom inspectors (which Unity for some strange occultish reason decides to call Editor).

So the first thing we need to do is create a ‘Sprite’ behaviour which will help us control the underlying mesh via its associated inspector/editor. What goes into this behaviour you ask? Let’s see what we want from our sprite and let’s keep it simple for now; pivot and scale.

public class Sprite
  : MonoBehviour
  public Vector2 Pivot;
  public Vector2 Scale;

With that in tow we shall continue onward with our spriting adventure next time.

“Some day you’ll return to me; Your valleys and your farms; And you’ll no longer burn To be brothers in arms”

Unity2D – Sprites 2

25 10 2013

Hey what do you know, sprites are catching up.

Alright, where did we leave off on?

public static class NewSpriteObject
  public static GameObject Make(Texture2D texture)
    throw new NotImplementedException(); 

Remember my definition of a sprite object? no? oh well, if I could re-read the previous post so can you 😛

let’s continue.

It’s really not as simple as I’ve portrayed it and off the top of my head I can think of several paths to take to achieve the end goal. First of which, the simplest, is to generate a node which contains all the information required to render a mesh and texture/material and manipulate its data through Unity’s normal transform. The second approach is to generate the same node with the same data but reroute the transform information to update the underlying mesh. Third we could create a parent node (let’s call it the sprite node) and a child node (let’s call that one the graphic node) which would contain the mesh/material data and manipulate them via the sprite itself. We could also combine the approaches and mix’n’mash between transform manipulation and direct vertex updates.

But which road to choose??
Heck, it’s not like I’ve got a word count here, let’s go with all of ’em and see where we end up.

Ok. First approach. Let’s create a node, attach the correct components and call it a day. The sequence of method calls would look something like this;

public static GameObject Make(Texture2D texture)
  var sprite_node = new GameObject("Sprite");
  var mesh_filter = sprite_node.AddComponent<MeshFilter>();
  var mesh_renderer = sprite_node.AddComponent<MeshRenderer>();

  var mesh = NewSpriteMesh.Make(;
  mesh_filter.sharedMesh = mesh;

  var material = NewSpriteMaterial(texture);
  mesh_renderer.sharedMaterial = material;

  sprite_node.transform.localScale = new Vector3(texture.width, texture.height, 1.0f);
  return sprite_node;

So, what’s right about this approach and what’s less right?
It’s pretty simple, pretty easy and gives use what we need at the most basic level. A node that renders our texture in game. The main drawback of this approach is our lack of a pivot point control over the mesh (not to mention having negative scale if we want to flip it).

But wait! This code does not work. What is this magic called NewSpriteMaterial? (I’m going to assume you know what the NewSpriteMesh class is by now).

The NewSpriteMaterial isn’t any more complicated.

public static class NewSpriteMaterial
  public static Material Make(Texture2D texture)
    var material = new Material(Shader.Find("SpriteShaderName"); = "sprite-material";
    material.mainTexture = texture;
    material.mainTextureOffset =;
    material.mainTextureScale =;
    return material;

The shader used doesn’t have to be any more complicated than Unity’s transparent shader if you want.

One thing I would like to point out, before finishing this post, is the usage of ‘shared’ mesh and material. This can lead to subtle issues like copy/pasting sprites where all the sprite nodes actually share the same material (Unity does this as an optimization – which I really wish I had more control over) and one change to the material will lead to it propagating to all other nodes. You’d think that using the regular, ‘mesh_renderer.material’ will solve this but at edit-time Unity will emit an error/warning and leak memory. On the same note, because we’ve not actually saved either mesh or material if we delete all nodes which reference them we’re looking at another memory leak (this can be fixed by pressing play and stop which forces Unity to garbage collect unreferenced objects). I will post code later for simple asset serialization.

And that’s it for the first approach. Not too difficult, very rewarding and easy to implement.

“Land of immortals I wait for my day, to reach the wisdom of your skies”