First in a new year

1 01 2015

We survived through another revolution around our beautiful yellow sun.

I’ve not updated this blog as much as I wanted or as much as I needed.

I did, however, opened up a separate site for talking about Unity stuff. Can find it here.

It’s been a tough year to be honest. But we push through and carry on. May the code mines of 2015 prove richer yields than those of yesteryear. And may the coffee rivers flow free.

But when I get home to you I find the things that you do, will make me feel alright





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)
{
 try
 {
  var files = GetProjectFiles();
  var files_path = GenerateExeArgs(files);
  var exe_path = GenerateExePath();
  Process.Start(exe_path, files_path);
 }
 catch (Exception e)
 {
  Console.WriteLine(e.Message);
 }
}
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”





Musing

27 08 2014

What have I been up to?

Not much, some of my writing on Unity can now be found on Gamesutra rather than here (sticking to my guns about that). Other than that, designing/developing a small turn-based hexagon-mapped top-down science fiction game about space. So yeah, going to dedicate my next few posts to MonoGame, tabletops, maybe some RPG systems, coroutines? Dunno. Maybe. Mostly code though. 

“All the white horses are still in bed”





Kickstarter

27 04 2014

Buck, that thing I’ve been working on for the past year with Gal is now live on Kickstarter. Come on over, drop us a line, drop us a dollar and have fun!
https://www.kickstarter.com/projects/1515615186/buck-a-game-about-a-real-dog





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.

[Flags]
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
{
  // BUGGY BUGGY BUGGY! DO NOT USE!
  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”