Saturday, August 10, 2013

Structs in Code Contracts and Vector Optimizations

After spending hours trying to get my code to verify properly on a Vector2 struct, I have finally given up the goat. Not only was I running into some subtle issues that I couldn't get to the bottom of, but a coworker convinced me that having a mutable vector object was a good idea. So in the end, it just made sense to scrap the idea and switch it over.

That done, everything is verifying beautifully. The only things that aren't verified are things that CC would have problems with anyway, and that I could probably only truly verify with Spec#.

Now that I'm over those hurdles, I can explain the other reason why I made the switch. After a lunchtime discussion that threatened to devolve into napkin sketches, I finally grasped the concept Derek was trying to explain. It goes something like this:

In any given second of the application, the physics engine will be called something  like 100 times. Which means lots of vectors will be needed for the application. Say there's even only 100 vectors being created by each step. That's 10,000 vectors per second being created and destroyed. In C#, structs are value types, meaning they pass by value and not by reference. Every method that needed a vector would cause the object to be copied and, though it isn't big, this isn't necessary. Instead, the program should pool vectors, pulling old, unused vector objects from a collection, mutating the x and y values to suit the needs of the calculation and then putting them back in the collection when they are no longer being used. Theoretically, instead of creating 10,000 objects (or more) a second, this should allow me to instantiate no more than 100 vector objects, no matter how many times per second my physic engine is doing work. Even though structures are optimized for performance in C#, pooling them should prevent an insane amount of work from being performed under the hood.

Another (tiny) optimization I made is to lazily perform the length computation. Since it involves a square root operation, I want to only calculate it on demand. For collision detection reasons, I'm instead storing the length squared value. Another coworker (John) turned me on to this idea. For most things, I won't even need to get the actual length and storing the "c squared" value of the Pythagorean theorem will allow me to skip a costly operation when I need to.

Well, that's all for now. If anyone has any other suggestions, or and clues to how I can get structures to work for me with Code Contracts, leave a comment. I'd love to see what other people are doing with it.

Friday, August 2, 2013

My First Code Contracts Bug?

Over the past few weeks (really, since I've finished all this cool set up type stuff), I've been using Code Contracts to verify my physics engine. Until yesterday, everything was going smoothly.

And then I managed to find a bug.

And, like all bugs, it took me a frustratingly long time to get to the bottom of it.

The idea of Code Contracts, in case you don't know, is that you can write code that will be checked for correctness at compile time (sometimes) and at run time (during those other times). You also get to determine what is correct for a given method or class. It's like writing unit tests for every possible valid input value for a method and having all the tests pass.

For instance, lets say you have a method addOne that takes an integer and returns that value incremented by one:

public int addOne(int input)
{
  return input + 1;
}

Easy enough, right? Now, lets say you want to restrict the input values to 0 or greater. Code Contracts lets you specify that like so: 

public int addOne(int input)
{
  Contract.Requires<ArgumentException>(input >=0, "Input must be greater than 0!");

  return input + 1;
}

This contract will generate an ArgumentException at run time with the given message if the input doesn't meet the precondition for the method (input >= 0).

This is fine, even a bit cool (sure beats writing if-then-throw blocks!) but what else can we do? Well, lets say we want to guarantee that the return value will be the input value + 1. We can write the following:

public int addOne(int input)
{
  Contract.Requires<ArgumentException>(input >=0, "Input must be greater than 0!");
  Contract.Ensures(Contract.Result<int>() == input + 1);

  return input + 1;
}

During the build process, the verifier will  go through the code and see that, yes, the method will indeed meet the stated condition. If you were to say, have the method return input - 1 while leaving the postcondition the same, the verifier would warn you that something was wrong.  Cool, huh?

I think so. Like all software, however, this has some bugs. One of the important parts of verification is that it needs to be easy and it needs to be able to verify methods that are inherited from super types as well as those derived from other types with other methods that are verified.

I've been trying like crazy to get a simple == operator to work between two structs. The first is my Vector2 struct, the second is Edge. Vector2 has an X, a Y and a Length (which is derived from X and Y) while Edge is simply two Vector2s, V1 and V2.

My Vector2 == operator simply compares the X's and the Y's and returns whether they are both equal to each other. This compiled fine with no warnings. My Edge struct, trying to compare the Vector2s using the same principle, consistently generated a "Ensures unproven" warning, no matter how I tried to resolve it.

I finally broke down and wrote two classes that represented what I was doing with the structs. By trial and error I determined the following really annoying thing about Code Contracts. Composition works from within class objects but not other structures.

TestComposite Class: No Errors
TestComposite Struct: Errors
Could this be the first bug I've found in Code Contracts? I'm sure it's possible. If this were some sort of design feature, I would think it would have been documented somewhere. Unless I'm doing something so incomprehensibly stupid that it's just a rule of thumb (please, point this out to me if this is the case). I'll probably be posting to the Microsoft Dev forum about this at some point, just to get a definitive answer. At least I know how to work around it, which means I should be pushing a new update sometime soon.

Keep an eye out for a new article on setting up Jenkins to automatically deploy build artifacts to CodePlex. I think I'm going to take a bit of a break from CC before I try to dive deep again.

Happy hacking!

Thursday, July 25, 2013

Yes, M'Lord! Jenkins CI and AWS

A few weeks ago, I had a crazy idea: use the free tier of services that AWS provides to build a cloud based, accessible from anywhere development environment.

Had this development been in Java, this may have been feasible. Given this project requires Windows 2012 Server to build (because I need Code Contracts), that left me with not even close to enough hard disk space to install even Visual Studio Express.

How else could I use this amazing technology? Enter Jenkins:


Now, I know that creating a CI server may seem a bit out of the purview of this project, but it's so damn COOL! For those not in the know, Jenkins (available at http://jenkins-ci.org/) is an open source continuous integration server. Meaning, you can set Jenkins up to automatically pull down the most recent code changes and do stuff with it, whether this stuff be compiling, running tests, deploying the artifacts to a demo server or emailing people when a build fails.

So, what more perfect use could I put a free AWS server to?

Setting this up was moderately complicated so I'll outline the steps below:


  1. Set up your AWS instance with Windows 2012 Server.
  2. Install .NET 4.5 and Windows 8 SDK, all available from Microsoft's download site.
  3. Copy the MSBuild folder from C:\Program Files (x86)\MSBuild on your development machine to the same location on the AWS instance. This step is really only needed if your project is going to include any features for Windows 8 app development.
  4. Install Code Contracts.
  5. Install Jenkins using the MSI installer and follow the set up.
  6. Add TCP port 8080 to the Security Group associated with your AWS instance.
  7. Create an Elastic IP and associate it with your AWS instance.
  8. In a browser, navigate to port 8080 of the EIP you created above: http://<your EIP>:8080. You should be greeted by Jenkins.
  9. Install the MSBuild plugin, and a plugin to deal with whatever type of repository you have for your code base. Set up these plugins as per their instructions.
  10. Create a job that polls the repo and create a build step that builds the solution file for your project when it detects changes.
Optionally, you can set up Jenkins to email you on build failure, but there are plenty of tutorials on the net on how to do this.

I must say, I'm mightily impressed with how easy it is to set up Jenkins, what a cool piece of software! Okay, it's time for me to really get serious about coding, until next time!

Thursday, July 4, 2013

AWS stands for AWesome Sauce



Quick update here: AWS is awesome. In between work tasks (waiting for tests to run, waiting for compilation, etc.) I've been playing with the free AWS stuff that Amazon is currently offering, specifically EC2. I've managed to create my own cloud based Windows 2012 server instance and am running VS2012 Express on it.

How. Cool. Is. That?

Once I get a clone of my project on this VM, I'll be able to remotely work on my code from any Windows machine (using Remote Desktop Connect). Even though the free speeds and disk space aren't great, it'll be more than perfect for getting a quick couple of lines out here and there and pushing them up to my repo so that I can pull them down on my actual development machine.

But, when I start raking in the dough, I won't have to do that. I may actually be able to forgo having a development machine altogether and just let Amazon manage my stuff for me. Sure, I'll have to pay for it (I believe the hourly rates are somewhere between 2 and 7 cents). But this will be perfect if I ever decide I can go back to using a netbook for all my online operations.

I could conceivably even code from a tablet or a PHONE! Especially in those times when I have a flash of inspiration about a particular project and need to code it out. As in, right now. This happens more often than one would think.

The future is really here.

Monday, July 1, 2013

Setting up VS2012, Git, and CodePlex

I figured that even though I found the process to be fairly straight forward, someone out there would benefit from a step by step about it.

  1. First things first: install Git. This is probably the step that some of my coworkers would cringe at. While CodePlex apparently has extensions for use with Mercurial, the set up page mentions that the Mercurial stuff doesn't work as well. I didn't try it personally (even though I'm more of a Mercurial guy), so this post won't cover it. This Google Code project has great installation instructions for TortoiseGit: https://code.google.com/p/tortoisegit/
  2. Next, Microsoft has made a handy Git plugin for VS2012, available here: http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c. This enables access to a Git repository from directly within VS, something that I found handy while using Eclipse and Mercurial. The plugin is fairly straightforward, neat and clean looking, so I'd have to recommend it.
  3. Go to your CodePlex project's source code tab. This assumes you've already made a project, but if you haven't it's not that hard (and it's free!) so go do it already! Click the Clone button and you should get a pop up similar to the following (taken from the CodePlex Git setup site available here, conveniently the same address I pulled the following picture from). Copy the address they conveniently highlight for you, you'll need it later.
  4. Open up Visual Studio and load whatever solution you want to add to CodePlex repository. If you haven't created the project or solution yet, or if there's something else you want to do, this page will probably be helpful. Right click on the project in the Solution Explorer.
  5. Select "Add Solution to Source Control..." and then select Git.
  6. Once this is set up, click the commits button for the repository. The first time you do this, VS will ask for an address for your repository. This is where you paste in the address that CodePlex gives you in Step 3. (Picture linked from http://blogs.msdn.com/b/visualstudioalm/archive/2013/02/06/set-up-connect-and-publish-using-visual-studio-with-git.aspx)


And that's it! You should be off and coding in no time. Once you commit, and push, the changes should go directly into your CodePlex repository and you should be able to see them in CodePlex's source browser. I hope you found this helpful, feel free to leave questions/comments below. Happy coding!

Sunday, June 30, 2013

Game Concept

After much deliberation, I've finally decided on a game to create. My requirements were pretty varied, so I wanted to make sure I thought everything out before starting to code. The concept is simple: you have a ball, you have a hilly landscape. When the game starts, your ball begins rolling down the hill. The user interaction is also simple: tapping the screen (or clicking a mouse) will cause the ground and sky to flip, leaving the ball where it is. This will have the effect of causing what was an uphill slope to become downhill again.



This, combined with momentum, will allow the player to constantly keep the ball moving, perhaps even jump the ball to collect certain kinds of items. Plus, I just thought the idea was neat. (Before anyone asks, yes, this was partly inspired by Mechanic #001: Negative Space over at the Three Hundred blog.)

I felt that creating a simple 2d physics engine that could do the kinds of calculations this game requires would be both complex enough to satisfy my professor's desire that this be a non-trivial piece of programming and easy enough to get done with whatever time I can muster up in the next 6 months. (Although, there is a bit of concern on the part of some of my coworkers that even this is too ambitious.) A physics engine would also give me about a billion things to write Code Contracts for; my Vector2 implementation already has 81 pre and post conditions that are verified on build and so far that class has only very minor functionality (overloaded ==, !=, *, length (magnitude) and some convenience methods for getting the vector as a 2 element array).

The other reason why this appeals to me is that I will have the opportunity to write the first and (as far as I can tell) only Code Contract verified physics engine for C#, talk about a resume enhancer!

I've gotten the first bits on CodePlex, check out the project here. I would say feel free to contribute, but I probably won't be accepting pull requests until after I've been graded (for reasons that should be fairly obvious).

Side note: setting up VS2012 with Git and hooking this all up to CodePlex was a dream. I don't know if it was simply that I've learned much about source control tools in my experience with Google Code and Mercurial, or if it's just really easy with VS2012, but I had none of the problems I was expecting. I can see why people use CodePlex with Visual Studio projects.

Tuesday, May 7, 2013

The Countdown Begins!

As of the time of this writing, I have a little more than six months to fully design, develop, specify, verify demo and deploy a Windows 8 game app, lending this blog the name "T Minus 6." I've already done a little bit of research and I have some pretty solid goals in mind. So, onto the details:

  • This project must use Code Contracts. This was first and foremost, as it is an area of interest for me and my project adviser. This decision means I have to use C# as well, which led me to...
  • This project will result in a Windows 8 app. With app development being all the craze, what better way is there to showcase that specification is ready for prime time than by developing a Windows 8 application?
  • The app will be a game. This is really a self imposed requirement, just to keep the project interesting and to (hopefully) give me the experience of deploying the app and seeing what it takes to do all the things associated with app development.
  • The app will use XAML exclusively as the way it displays graphics. It shouldn't be too hard to use storyboards to build animations, and there is at least one good physics engine out there for it, as far as I can tell, anyway.
  • I will be following an agile process. I'm familiar with it, it will structure my development, and it will allow me to assess the progress of development as I reach my December deadline.
I still have yet to come up with an idea. I want to make it more entertaining (to code) than yet-another-Mario or yet-another-Tetris, while ensuring I can deliver by the deadline. This could mean several things: producing a single level of a level based game, producing a really super simple game idea, introducing procedurally generated elements or levels, etc. Part of my "Sprint 0" will be settling all these questions, but for now I'm doing only research.

I'm positive I want to use Mercurial as my version control system, but still trying to see what the merits are of Codeplex vs Git or Google Code. Seems that many Windows 8 developers are all using Codeplex, so that might be why I'm considering it, but I'm more familiar with Google Code, so we'll see.

Anyway, if you are interested, keep following. Posting may be sporadic, but I intend to include notes on breakthroughs, code samples, "what I'm working on," "what I'm struggling with," and other types of things on a semi-regular basis. Part of my sprint review process will also culminate in posts, which will probably be more lengthy. If you have any questions, feel free to comment! I'm looking forward to seeing what kind of audience actually takes an interest in this, if I even generate one, so come one, come all, and enjoy the show!