Cocos2d-x Tutorial Series: Basic Sprites, Positioning, Parenting and Coordinate Systems

1. October 2014



Now that we have Cocos2d-x installed and configured and our project created, we are going to take a look at basic graphics operations.  This tutorial assumes you ran through the prior part and created a project already.  I am going to assume you have a working AppDelegate, so I will only focus on creating a new scene object.   The only changes you should have to make are to change your delegate to #include a different file and change the type of scene you call createScene() on.


Ok, let’s jump right in with with a simple example.  First we are going to need an image to draw.  Personally I am going to use this somewhat… familiar image:




It’s 400x360, with a transparent background named decepticon.png.  Of course you can use whatever image you want.  Just be certain to add the image to the resources directory of your project.




Ok, now the code to display it.



#pragma once

#include "cocos2d.h"

class GraphicsScene : public cocos2d::Layer
    static cocos2d::Scene* createScene();
    virtual bool init();  



#include "GraphicsScene.h"


Scene* GraphicsScene::createScene()
    auto scene = Scene::create();
    auto layer = GraphicsScene::create();
    return scene;

bool GraphicsScene::init()
    if ( !Layer::init() )
        return false;
    auto sprite = Sprite::create("decepticon.png");
    sprite->setPosition(0, 0);
    this->addChild(sprite, 0);
    return true;


Now when you run this code:



Hmmm, probably not exactly what you expected to happen, but hey, congratulations, you just rendered your first sprite!


So, what exactly is happening here?  Well after we created our sprite we called:

sprite->setPosition(0, 0);

This is telling the sprite to position itself at the pixel location (0,0).  There are two things we can take away from the results.


1- The position (0,0) is at the bottom left corner of the screen.

2- By default, the position of a sprite is relative to it’s own center point.


Which way is up?


One of the most confusing things when working in 2D graphics is dealing with all the various coordinate systems.  There are two major approaches to dealing with locations in 2D, having the location (0,0) at the top left of the screen and having the location (0,0) at the bottom left of the screen.  This point is referred to as the Origin.  It is common for UI systems, the most famous of which being Windows, to set the origin at the top left of the screen.  It is also most common for graphics files to store their image data starting from the top left pixel, but by no means is this universal.  On the other hand OpenGL and most mathematicians treat the bottom left corner of the screen as the origin.  If you stop and think about it, this approach makes a great deal of sense.

Think back to your high school math lessons ( unless of course you are in high school, in which case pay attention to your math lessons! ) and you will no doubt have encountered this graphic.


This is a graphic of the Cartesian plane and it is pretty much the foundation of algebra.  As you can clearly see, the positive quadrant ( the quarter of that graph with both positive x and y values ) is in the top right corner.  Quite clearly then, to a mathematician the value (0,0) is at the bottom left corner of the top right quadrant.


There are merits to both approaches of course, otherwise there would be only one way of doing things!


This will of course lead to some annoying situations, where one API for example delivers touch coordinates in UI space, relative to the top left corner, or when you load a texture that is inverted to what you actually wanted.


Fortunately, Cocos2d-x provides functionality to make these annoyances a little bit less annoying.  Just be aware going forward, that coordinate systems can and do change!  Also be aware, unlike some frameworks, Cocos2d-x does *NOT* allow you to change the coordinate system.  The origin in Cocos2d-x is always at the bottom left corner.


Sometimes positioning relative to the middle can be ideal, especially when dealing with rotations.  However, sometimes you want to position relative to another point, generally using the top left or bottom left corner.  This is especially true if for example you want to, say… align the feet of a sprite to the top of a platform.  Changing the way a sprite ( or any Node ) is positioned is extremely simple in Cocos2d-x.  This is done using something called an Anchor Point.  Simply change the code like so:


   auto sprite = Sprite::create("decepticon.png");
   sprite->setAnchorPoint(Vec2(0, 0));
   sprite->setPosition(0, 0);


And presto!



Now our sprite is positioned relative to it’s bottom left corner.  However, setAnchorPoint() might not take the parameters you expect it to.  Yes, you are passing it in x and y coordinates that represent the location on the sprite to perform transforms relative to.  However, we are dealing with yet another coordinate system here, sometimes referred to as Normalized Device Coordinates (NDC).  These values are represented by two numbers, one for x and one for y, from 0 to 1, and they are a position within the sprite.




If you are new to game programming, the expression "sprite" might be new to you.   The expression was termed way back in 1981 by a Texas Instruments engineer describing the functionality of the TMS9918 chip.  Essentially a sprite was a bitmap image with hardware support to be movable.  Early game hardware could handle a few sprites, often used to represent the player and enemies in the world.  In real world examples, in Super Mario Brothers, Mario, the mushrooms, coins and such would be sprites.

These days, “Sprite” is basically a bitmap image ( or portion of a bitmap, we’ll see this later ) along with positional information.  These days the concept of hardware sprites doesn’t really exist anymore.


I am making this sound entirely more complicated than it actually is.  Just be aware the value (0,0) is the bottom left corner of the sprite, (1,1) is the top right of the sprite and (0.5,0.5) would be the mid point of the sprite.  These coordinate system is extremely common in computer graphics and is used heavily in shaders.  You may have heard of UV coordinates, for positioning textures on 3D objects.  UV coordinates are expressed this way. 


Therefore, if you want to position the sprite using it’s mid point, you would instead do:

sprite->setAnchorPoint(Vec2(0.5, 0.5));


Another important concept to be aware of is a sprite’s positioning is relative to it’s parent.  Up until now our sprite’s parent was our layer, let’s look at an example with a different Node as a parent.  This time, we are going to introduce another sprite, this one using this image:




It’s a 200x180 transparent image named autobot.png.  Once again, add it to the resources folder of your project.  Now let’s change our code slightly:

bool GraphicsScene::init()
    if ( !Layer::init() )
        return false;
    auto sprite = Sprite::create("decepticon.png");
    auto sprite2 = Sprite::create("autobot.png");
    sprite2->setAnchorPoint(Vec2(0.0, 0.0));

    sprite->setPosition(100, 100);
    sprite2->setPosition(0, 0);
    this->addChild(sprite, 0);
    return true;


And when we run this code:



There’s a couple very important things being shown here.  Until this point, we’ve simply added our Sprite to our Layer, but you can actually parent any Node to any other Node object.  As you can see, both Sprite and Layer inherit from Node, and Node’s form the backbone of a very important concept called a scene graph. 


One very important part of this relationship is the child’s position is relative to it’s parent.  Therefore sprite2’s (0,0) position is relative to the origin of sprite1 ( not the anchor, origin and anchor are not the same thing and only anchors can be changed ), so moving sprite2 also moves sprite1.  This is a great way to create hierarchies of nodes, for example you could make a tank out of a sprite for it’s base and another representing it’s turret.  You could then move the base of the tank and the turret would move with it, but the turret itself could rotate independently.



A scenegraph is a pretty simple concept. It's basically the data structure used to hold the contents of your game. In Cocos2d-x, the scene graph is simply a tree of Node dervived objects. There exists Scene node that is pretty much an empty node with the intention of adding other nodes to it. You then add various nodes to it, nodes to those nodes, etc. An overview of how you can use this system in Cocos2d-x is available here.


So what do you do when you want to get a node’s position in the world, not relative to it’s parent?  Fortunately Node has that functionality built in:

Vec2 worldPosition = sprite2->convertToWorldSpace(sprite2->getPosition());


worldPosition’s value would be (100,100).  There is also an equivalent function for getting a world space coordinate in node space.


So, in summary:

  • The world is composed of Node objects, including Scene, Sprite and Layer
  • The screen origin is at the bottom left corner of the screen, always
  • Nodes are positioned, scaled and rotated relative to their anchor point
  • The default anchor point of a sprite is (0.5,0.5), which is it’s mid point
  • Anchor points are defined with a value from (0,0) to (1,1), with (0,0) being bottom left corner and (1,1) being the top right
  • Nodes can have other nodes as children.  When the parent moves, the child moves with it
  • Child node’s origin is the bottom left corner of their parent
  • Anchor point and origin are not the same thing
  • Sprites can only have other sprites as children ( EDIT – No longer true!  There can however be some performance ramifications. Will discuss later )


So that covers the basics of dealing with graphics.  Now that we know how to position and parent nodes, next time we will look at something a bit more advanced.


Programming , ,

Debugging 101 Tutorial or How to bring sanity to an insane world

8. August 2014


I write a great many tutorials targeting newer developers and as a direct result I am exposed to a fair number of programming related questions.  I don’t mind in the least by the way, it’s why I run this site.


However, I notice one very common thread among those questions…


They often could have been solved with just a few minutes in the debugger.


Then it dawned on me.  Lots of newer programmers likely don’t know all that much about debugging.  Many are probably resorting to printing to the console to see how their program works.  For good reason too…  if you pick up say… a C++ book, it’s about the language, not the tooling.  Of course, there are dedicated books such as Beginning Visual C++ 2013 or the Eclipse IDE: Pocket Guide, but these tend not to be books beginners start with.  Hell, for someone just starting out, figuring out where the language begins and the IDE ends is challenging enough!


Which is all a shame, as basic debugging skills will make your life a hell of a lot easier.  Not only will it make solving problems much easier, but it will help a great deal in understanding how your language works.  Plus the most tragic part of all, it’s actually very simple and often incredibly consistent across tools and programming languages.


So, if you have no prior debugging experience, give me 20 minutes of your time.  I guarantee you it will be worthwhile, or your money back!



I am going to use a couple different languages/IDEs int this tutorial, but as you will see, the process is remarkably similar regardless to what language you use.  I am primarily going to start with Visual Studio, then illustrate how you can perform similar actions in other environments.  First a quick glossary of terms you are going to hear.



Glossary of terms


These are a few of the terms we are going to be covering during this tutorial.  Don’t worry over much if the following descriptions don’t make a lot of sense, it should be clearer by the time you finish.



This one is critical, these are instructions that tell your code HEY, STOP RUNNING, I WANT TO LOOK AT SOMETHING HERE!  We will be using breakpoints extensively.  You can generally add/remove/enable/disable breakpoints.



This one is incredibly well named.  Basically these are variables you’ve said you want to keep a watch on the value of.



Think of these like Watch expressions the IDE automatically made for you.  Basically every variable in local scope will be listed as a local.  Not all IDEs do this, but most do.


Expression Evaluation

This is powerful.  Basically you can type some code and see what result it returns, while your code is running.  Generally you do this once a breakpoint has been hit causing your code to pause and your debugger to be shown.


Call Stack

This is the hierarchy of function calls you are currently in.  For example, if you called myFunc() from main(), your callstack would look like




Don’t worry, this should make sense shortly.



C++ and Visual Studio Debugger


I am going to start with Visual Studio/Visual C++ then show other platforms later on.  Once again, most of the process you see here is applicable to other environments.


Let’s start with this ultra simple code example:

void someFunction(int & inValue)
    inValue = 43;

int main(int argc, char ** argv)
    int i = 42;
    return 0;


The code is extremely simple. We create a simple int, assign it a value, then pass it into a function that will assign it a different value. Now time to do some basic debugging.


The first thing you need to do is start debugging.  In Visual Studio, there are a couple ways to do this.  First thing, in C++, you need to tell it that you are building for debugging.  You see, when you make a debug build a few different things happen.  There are little bits of information added to your code that make the debugger work.  There are some other changes too, like memory being zeroed out, but those are beyond what we are talking about here.  The take away is, you need to build for debugging, then run the debugger, although generally this task is one and the same for you the developer. 


From the Visual Studio toolbar, you can do both:


Or, you can run from the Debug menu:



As you can see, F5 is also an option.  It’s worth noting, debug code generally runs a bit slower and bigger, so when you are finished development, you want to compile for release.


Ok, so that’s how we start the debugger, but in this code sample, it will simply start, run, then finish.  That’s not very exciting.



Enter the breakpoint!


Ok, now we are going to enter the wonderful world of breakpoints, your new best friends.  Let’s start by setting a breakpoint on our first line, where we declare i.  There are a number of ways of setting a breakpoint.  In the IDE you can right click the line of code you want to break on then select Breakpoint –> Insert Breakpoint, like so:



… for the sake of this tutorial, please just ignore Tracepoints, at least for now.


You can also set a breakpoint in the Debug menu, using Toggle Breakpoint, or by hitting F9:



The line of code you just set a breakpoint on should now have a red bullet in the margin:




Go ahead and press F5 to debug your program.  Things will go much differently this time, your code will stop executing on the line with the breakpoint.  You can hover your mouse over a variable to see it’s value:




In this case, you will see that the value is gibberish.  This is because i hasn’t been assigned yet.  Notice the little yellow arrow on the left hand side?  This is the line of code you are currently executing.



Stepping over the corpses of your vanquished foes



Now we need to navigate in the debugger.  This is done using a couple simple commands:




Step Into, Step Over and Step Out.  These are also available in the toolbar:


As you can see, you can also use the hotkey F11 and F10.  These keys change from program to program... if they didn’t, that would just make life too easy, wouldn’t it?


Now as to what these do…

Step Into, steps into the currently running line of code.  For example, if you are on a function, it will step into that function.  I will show this in a second.

Step Over jumps to the next line of code in the same scope.  Step out, jumps up on the callstack.  Again, I will explain this in a second. 


So what we want to do now is Step Over, and now it should look like this:



The little yellow arrow will now have advanced to the next line of code.  Notice now if we hover over the value of i, it is now 42 like we would have expected.  That is because the line of code has now executed.  This is a very important thing to realize… the line of code your breakpoint stopped on hasn’t executed yet.  So if you want to see what value is assigned to a variable, you generally want to set the breakpoint to the next line of code.


Now we want to “Step Into” the current line of code.  That is, we want to see what happens when someFunction() executes.  If we chose “Step Over”, we would jump to the next line ( return 0; ).  There is another important thing to realize here… even if you Step Over some code, it is still being run like normal, it just isn’t showing you it in the debugger.  That said, we want to see someFunction() in action, so choose Step Into or choose this icon:




Now the line of code jumps to the beginning of someFunction():




You can hover over parameters to see their value:



You can continue stepping in and over code like normal, or if you are done looking at someFunction ( or some other function someFunction calls ), you can choose Step Out to jump up on the callstack.





Callstack me, maybe?  No, I didn’t just make that pun did I?



Callstack… there’s that word again.  Now that we are actually in a bit of a call stack, let’s take a look at what I mean.


In Visual Studio, make sure the CallStack window is being shown.  This is controlled using Debug->Window->CallStack or CTRL + ALT + C like so:



A window like the following should appear:



The key to the name is “STACK”.  Think about it like a stack of plates at a cafeteria.  Each time a function is called, it’s like putting a plate on the stack.  The bottom most plate/function is the oldest, while the top most is the newest.  In this case, the call stack tells us that on line 9, in the function main, we called someFunction() and are currently running on line 2.  Speaking of “lines”, you have the option of toggling them on or off in Visual Studio ( and most other IDEs ).


The process of toggling line numbers on/off, isn’t incredibly straight forward.  That said, line numbers can be incredibly handy, so lets do it.  First select the menu Tools->Options…



Then in the resulting dialog on the left hand side scroll down until you find Text Editor->C/C++->General, then click the checkbox next to Line Numbers.  Obviously if you are using Visual Studio and a language other than C++, you need to pick the appropriate language:




Now line numbers will be displayed next to your code:



Ok… back to the callstack.  Double clicking an entry in the callstack brings you to that line of code.  In this trivial example, the utility is questionable.  However, when working with a real project, where the callstack might span multiple source files, it becomes a very quick and easy way to jump between source files and for seeing how you ended up where you are.  This obviously is a hell of a lot more useful when someFunction() is possible called from thousands of different locations for example.



Locals, no more witty titles after that last witless one…


Now let’s take a look at locals, a concept I mentioned earlier.  This is basically all the local ( non-global ) functions in the current scope.  While debugging inside someFunction, like so:




Open up the locals window.  Like before it can be toggled using the menu Debug->Windows->Locals:




Now you will have a new window, like so:




This is a list of all variables in the local scope.  Inside someFunction() there is only one value, it’s parameter inValue.  Here you can see that the current value is 42 and it’s data type is int reference.  As you step through someFunction, as values chance, they will be updated in the locals window. 


Step out of someFunction ( Shift + F11, or using the icon or menus listed above ), and you will see the locals change to those of main():





Now you see something somewhat unique to C and C++ ( and other languages with direct memory management ).  The value passed in, argv, is a pointer to a pointer of type char.  This is to say, it points to a pointer that points to the memory address of a char data type.  If that is greek to you at this point, don’t worry about it.  You will notice though that the locals window has done a couple very cool things.


First, you see a hex value:





This is the actual address of the pointer in memory.  After all, that is what pointers actually are, locations in memory.  This is incredibly useful in debugging, even if you yourself don’t use pointers, code you depend on might.  Look out for values like 0x0000000 or 0xFFFFFFFF.  If you look at the value of a pointer and it’s one of those values, your object wasn’t allocated or has been deleted.  These are some of the most common bugs you will find in C++ code.


The other neat thing that visual studio did was this:




The debugger was actually smart enough to go look at the data actually stored at the memory address this pointer points at.  Very handy.  You may also notice the triangle to the left of argv.  This is because there is more information available.  We will see this a bit more later.



Ok, now what?


So… what do you do once you have found what you were looking for?  You have a couple options.  Here they are from the debug toolbar:




Or using the following commands from the Debug menu:




One thing to keep in mind, when your programming is running, the options and menu’s available in Visual Studio are different.  For example, if you want to create a new project, you need to Stop Debugging before the menu options are even available.



Playing God with your Program


Ok, let’s rewind a bit and go back to the locals menu.  This time we are going to use a slightly different code example.


#include <iostream>
#include <string>

class MyClass{
    int myInt;
    std::string myString;

    MyClass() :
        myString("Hello World"), 

    int myPrivateInt;
int main(int argc, char** argv)
    MyClass myClass;
    std::cout << myClass.myString;
    return 0;


Now let’s try setting a breakpoint on the final line of main, like so:




If you run this code, you will see:




You will have to ALT+TAB over to it, since debugger has given focus to Visual Studio.


Now lets look at some of the funky things you can do to a running program.  Now let’s set another breakpoint, this one on the cout line.  Remember, the code on the line you’ve breakpointed hasn’t been run yet!




Now restart or debug your program again.  It will hit the first breakpoint right away.  Now go look at the locals window again:




As you can see, data types composed of other data types, like myClass can be expanded to show all the other values that compose it.  Now let’s do something kinda neat.


You can change the values of a program as it is running.  Sorta…  For basic data types, it’s extremely straight forward.  For example, to change the value of myInt while debugging, simply right click it in the locals window and select Edit Value, like so:




You can now change the value:




From this point on ( during this debug session ), that value is now 42.  Of course, if the value is changed in code, it will of course be updated.  This allows you to tweak values interactively and see how it will affect your program’s execution.


With objects however, it is slightly more complicated.  In the previous case, we edited myInt which is a member of myClass.  But we couldn’t simply edit MyClass directly, as the debugger has no idea how.  Therefore you can’t just right click myString and select edit.  The debugger simply doesn’t know how to edit this data type ( this isn’t true for non-C++ languages ).  You can however modify the values that make up the string, like so:




As you can see, myString is of type std::basic_string, which is composed of an array of character values that make up the string.  So we can edit the character values to say… lower case our string.




Once again, Visual Studio is smart enough to understand the datatype.  So we could either enter the value ‘w’ or the ascii code 119.  Now if you continue execution of your program it will automatically run to the next breakpoint.  And if you look at the output, you should see:




One very important thing to note here… all of these changes are temporary.  They only last as long as the current debugging session.  The next time you run your program, it will run like normal.



I’m sick of these damned breakpoints


In that last example, when we selected Continue, we jumped to the next breakpoint, like so:




As you add more and more breakpoints to your code, they can make stepping through it incredibly annoying.  So, what can we do about that?


Well the first thing we can do is disable it.  Right click the red dot and select Disable Breakpoint, or select the line and hit CTRL + F9




And the breakpoint will be disabled.  Now it will show up as a hollow circle:




This allows you to re-enable it later, but until you do, the debugger will completely ignore the breakpoint.  You can re-enable it the same way you disabled it.  Right clicking and selecting enable, or by hitting CTRL + F9.



You can also remove a breakpoint complete in a couple ways.  First you single left click the red dot, and it will be removed.  The F9 key will also toggle a breakpoint on and off completely.  You can also right click and select Delete Breakpoint ( see shot above ).


Sometimes you want to remove or disable/enable them all at once.  You can do this using the debug menu:



Breakpoints are your friend, learn to love them!


I’m Watching You!


Now we are going to look at two final concepts, watches and expressions.  Let’s start with watches.

Until this point, we’ve only been able to look at variables declared in the local scope.  That’s all well and good, but what happens when we want to watch a value declared in a different scope?  Don’t worry, the debugger’s got you covered!


Consider this simple code example and breakpoint:




At this point in execution, your locals will look like:



That said, stringInADifferentScope has already been declared and allocated… how would you look at this value?


Well, there are two ways.  As you may be able to guess from the preamble, they are watches and expressions.  A watch is a variable you are keeping an eye on, even if its not currently local.  You can set a watch while debugging code by right clicking the variable and selecting Add Watch:




Now you can look at watches in the watch window using the menu Debug->Windows->Watch->Watch 1 ( or CTRL+ALT+W then 1 ).  You can have up to 4 sets of Watch windows in Visual Studio.  Now you can inspect the value of watched variables at any time:



If you watch a variable that isn’t in scope, it tells you:




When the variable notInScope comes back in scope, it’s value can be retrieved by hitting the refresh icon.


The other option is Evaluate Expression, which is called QuickWatch in Visual Studio.  It’s an incredibly cool feature.  You can invoke QuickWatch while debugging by right clicking and selecting QuickWatch…  or by pressing Shift + F9.




This opens a dialog that allows you to enter whatever value you want into the Expression tab, then press Re-Evaluate and it will look up the value:




The Add Watch button allows you to add the selected Expression to the watch window we just saw.


The cool thing about this you can actually call some functions on your object and get the results:





On One Condition


Back to breakpoints for a second, then I am done I promise.

Consider the following code sample:




This is a very common bug scenario, but you really don’t want to run through the debugger 100K times do you?  Generally with these kinds of errors, its only the last couple of iterations you want to look at.  Fortunately we have something called a conditional breakpoint.  This, as the name suggests, will only break if a certain condition is met.


Add a breakpoint like normal.  Add it to the line inside of the loop.  Now right click the red dot and selection Condition…




Now you can set the condition you will break on.




The breakpoint icon will now have a white plus in it:




Next time you run the code, it will only trip when the condition is hit:




Unfortunately, in Visual Studio, conditional breakpoints can make your code ungodly slow, so only use them when absolutely required.  In other languages and IDEs, this isn’t always the case.  I honestly think this is a bug in Visual Studio, as the above code should not require several seconds to evaluate, even with the additional overhead. 



One of the keys to happiness is a bad memory


One other thing that can be incredibly useful, especially in C++ is to look at a location in memory.  This functionality isn’t always available, depending on the language you are using.  In Visual C++, it’s incredibly easy and useful.  In the previous example, we filled an array of char with 100K exclamation marks ( at least, once we remove the = sign from <= :) ).  Let’s say we wanted to look at memory for data.


In the Debug->Windows menu, select Memory->Memory 1



A window will open up like this:



That is showing what’s in memory, starting at the address 0x00287764.  What you want is the address of the variable data.  In the address box enter the value &data.  (For non-C++ programmers reading this, & is the address of operator, which returns the memory location of a variable ). 


Now you will see:




As you can see, data is located at 0x006D781C and is full of exclamation marks ( shown on the right ), which is represented by ascii character code 21 ( as shown on the left ).  Looking at memory can often help you find nasty bugs.



Debugging in other languages/IDEs


The instructions above were obviously C++ and Visual Studio related, but you will find other than the windows looking a bit different, some slightly different names and different hot keys, the process is almost identical.  Instead of going through the same process for every language, I will instead point out where all of these things are located or what they are called.




Java in Eclipse



Just like in Visual Studio, there is both a debug and run mode.  In order to debug in Eclipse you need to run using debug.  There is a menu option available:


You can also right click your project in the Package Explorer and select Debug As->Java Application.



Or using the Debug icon in the toolbar:



When you debug in Eclipse, you will be prompted to open in Debug perspective:



A perspective is simply a collection of windows and toolbars to accomplish a given task… such as debugging.  You can switch between perspectives using the top bar:


Or using the menu Window->Open Perspective.



Setting a Breakpoint:

You can set a breakpoint in a number of ways in Eclipse.  In a source window, you can right click the side column and select Toggle Breakpoint ( or CTRL+SHIFT+B ).  This adds a breakpoint, or removes on if there is one currently added.


You can also toggle a breakpoint using the Run menu:



Step Into/Step Over/Step Out:

While running in Debug perspective, you can perform stepping using the toolbar:


You can also resume and stop your program using this toolbar.  The icons are Step In, Stop Over and Step Out, from left to right.


You can also step using the Run Menu:


You can also use F5/F6/F7 to control stepping.


Watch Window

In Eclipse, Locals and Watch are in the same view, “Variables”. 



Variables should be available automatically when you launch into Debug perspective.  However you can also open It using the menu Window->Show View->Variables.  Or Alt+Shift+Q, then V.




Local Window:

See above.


Evaluate Expression:

Evaluate expression is called “Expressions” in Eclipse and is available using the same menu you used to open Variables.


Once again, you can dynamically execute code and see the results using Expressions.


Conditional Breakpoints

To set a conditional breakpoint in Eclipse, add a breakpoint like normal.  Then right click the dot and select Breakpoint Properties:


Then in the resulting dialog, check condition and enter your condition logic in the box below:




JavaScript in Chrome



In Chrome ( and other browsers, IE, Opera, Safari and Firefox are all very similar in functionality ), there is no such thing as debug or release, unless I suppose you count minified code.  Simply set a breakpoint in your JavaScript and refresh the page.  You will however have to open Developer Tools to be able to set a breakpoint.  Do this by clicking the Chrome menu button, selecting Tools->Developer Tools



Or as you can see above, press F12 or Ctrl + Shift + I.  Memorize that key combo, trust me…


Setting a Breakpoint:

To set a breakpoint, in the go to a source file:



Then in the source listing, right click on the left column and select Add Breakpoint:


… bet you can guess how to set a Conditional Breakpoint… ;)

You can also toggle a breakpoint using CTRL + B.


Step Into/Step Over/Step Out:

Step Over: F10

Step Into: F11

Step Out: Shift + F11


Or you can use the toolbar:




Watch Window

Window is located on the right hand side of the developer tools and is called Watch Expressions:



Expressions and Watches are combined into the same interface.  You can simply add a new one by clicking the + icon, then type code accordingly:



Local Window:

Called Scope Variables in Chrome.  Located in same area:



Evaluate Expression:

See watch above.


Conditional Breakpoints:

Just like adding a regular breakpoint, but instead choose Conditional Breakpoint.


Then type your conditional logic code:



WebStorm / JavaScript


Ok.. I’m just being lazy here.  I remember I already wrote an article about debugging in WebStorm… recycling is good, no? ;)


Debugging your app in WebStorm


It actually covers 100% of what we just talked about above, except of course the memory view, as it isn’t applicable.


Ok, Done talking now


As you can see, across tools the experience is very similar.  Some IDEs are worse ( Xcode… ), some are very limited ( Haxe in FlashDevelop ), but generally the process is almost always exactly the same.  Of course, I only looked at a couple IDEs but you will find the experience very consistent in several different IDEs.  It’s mostly a matter of learning a few new hotkeys and window locations.


One area that is massively different in command line debuggers, such as gdb.  You are still doing basically the same things, just no nice UI layer over top.  A discussion of gdb debugging is way beyond the scope of this document and there’s tons of information out there.  Heck, there are books written on the subject!


Hopefully that process was useful to you.  A while back I posted an example where the debugger saved my ass if you want to see this actual process in action.  Debugging should be a part of your development process, it will make your life a hell of a lot easier, and your hair a hell of a lot less white.


Let me know if that wasn’t very clear, this tutorial may actually require a step by step video companion to go along with it.  If so, please let me know.

Programming , , , ,

Trying to run our C++ tutorial on a new Visual Studio version and getting a MSVCR100D.dll missing error

14. May 2014


I’ve had a few users run into this error when trying to run the GameFromScratch C++ Game Dev tutorial:




The program can’t start because MSVCR100D.dll is missing from your computer.  Try reinstalling the program to fix this problem.


Fortunately this can be pretty easily fixed, simply download and install the Visual Studio 2010 runtime redistributable.  You can download it here.




The binaries I include with the SFML tutorial of SFML 1.6 are compiled for Visual Studio 2010 and aren’t compatible with Visual Studio 2012/2013.  Normally this is just a matter of recompiling SFML 1.6 in the newest version of Visual Studio, then linking against those Lib/DLL files.  However this process certainly isn't straight forward as the SFML 1.6 code base was actually targeting for Visual Studio 2008 and amazingly enough, depending on some external libraries compiled for Visual C++ 2005!


To be honest, if you are running through this tutorial series, by far the easiest solution is to install Visual C++ 2010 Express.  It can be installed side by side with newer versions.


If there is enough demand, I can try to make 2013 compatible binaries that you can include with your project.

Programming ,

The Unreal Engine 4 Rosetta Stone

21. April 2014


Comprehending any large code base is never a simple factor.  This is especially true of C++ with hits heavily used (and abused) typedef system.  The Unreal Engine has a very well defined and consistent naming convention but trying to crack it can take a bit of effort, as it’s explained piecemeal throughout the documentation. RosettaStone That is, until I found the Coding Standard document, which frankly is the very first page a C++ programmer working with UE4 should start with.  This document is the titular Rosetta Stone, the method that makes reading UE code possible.


Understanding their naming conventions will help you a great deal when trying to work through code samples.  A few of their choices strike me as a bit unusual, especially if you were raised on Hungarian like I was.  Here are the naming convention:

  • The first letter of each word in a name (e.g. type or variable) is capitalized, and there is usually no underscore between words. For example, Health and UPrimitiveComponent, but not lastMouseCoordinates or delta_coordinates.

  • Type names are prefixed with an additional upper-case letter to distinguish them from variable names. For example, FSkin is a type name, and Skin is an instance of a FSkin.

    • Template classes are prefixed by T.

    • Classes that inherit from UObject are prefixed by U.

    • Classes that inherit from AActor are prefixed by A.

    • Classes that inherit from SWidget are prefixed by S.

    • Classes that are abstract interfaces are prefixed by I.

    • Most other classes are prefixed by F, though some subsystems use other letters.

  • Type and variable names are nouns.

  • Method names are verbs that describe the method's effect, or describe the return value of a method that has no effect.

Variable, method, and class names should be clear, unambiguous, and descriptive. The greater the scope of the name, the greater the importance of a good, descriptive name. Avoid over-abbreviation.

All variables should be declared one at time so that a comment on the meaning of the variable can be provided. Also, the JavaDocs style requires it. You can use multi-line or single line comments before a variable, and the blank line is optional for grouping variables.

All functions that return a bool should ask a true/false question, such as "IsVisible()", or "ShouldClearBuffer()". All boolean variables must be prefixed with a "b" character (e.g. "bPendingDestruction", or "bHasFadedIn").

A procedure (a function with no return value) should use a strong verb followed by an object. An exception is if the object of the method is the object it is in; then the object is understood from context. Names to avoid include those beginning with "Handle" and "Process"; the verbs are ambiguous.

Though not required, we encourage you to prefix function parameter names with "Out" if they are passed by reference and the function is expected to write to that value. This makes it obvious that the value passed in this argument will be replaced by the function.


This explains all the AClass and UProperty you will encounter through out the code, and explains the far to common FSomethings you see in the code..


There are a few things I find unwieldy about these choices.  First, I am so used to instances starting with lower case that this seems like Anathema to me.  Second, if you are going to prefix with all capital letters, why not BBoolValue instead of bBoolValue, this seems inconsitent to me.  Next, why F for types? Finally why SWidget and S instead of Widget and W?  WButton makes a ton more sense than SButton for example.


At the end of the day it doesn’t really matter, the most important thing is to be consistent, which they have.  Now with a thorough understanding of their naming convention, groking the code is a heck of a lot easier.


Also of great important are the C++ type usage guidelines.  This is both a power and flaw of working with C++, there are more types than grains of sand in the desert, so knowing which to use is critical.


Portable Aliases for Basic C++ Types

  • bool for boolean values (NEVER assume the size of bool). BOOL will not compile.

  • TCHAR for a character (NEVER assume the size of TCHAR)

  • uint8 for unsigned bytes (1 byte)

  • int8 for signed bytes (1 byte)

  • uint16 for unsigned "shorts" (2 bytes)

  • int16 for signed "shorts" (2 bytes)

  • uint32 for unsigned ints (4 bytes)

  • int32 for signed ints (4 bytes)

  • uint64 for unsigned "quad words" (8 bytes)

  • int64 for signed "quad words" (8 bytes)

  • float for single precision floating point (4 bytes)

  • double for double precision floating point (8 bytes)

  • PTRINT for an integer that may hold a pointer (NEVER assume the size of PTRINT)

Don't use the C++ int type in portable code, since it's dependent on the compiler how large it is.


So if you are just starting out with C++ programming in Unreal, start here, it will make the journey a lot easier.


Finally C++ 11 guidelines are also important.  C++11 support across compilers is by no means universal but many of the features of C++11 are pretty damned useful.  Keep in mind, these guidelines are for Unreal staff working on the engine, not the end user working with the engine, so if you are say… only using Visual C++ 13, then feel free to use whatever features you want.  If you want to target as many platforms as possible though, you should be mindful of these instructions:


C++ 11 and Modern Language Syntax

Unreal Engine is built to be massively portable to many C++ compilers, so we're careful to use features that are compatible with the compilers we can imagine supporting. Sometimes features are so useful that we'll wrap them up in macros and use them pervasively (such as the 'override' keyword), but usually we'll wait until all of the compilers we could imagine supporting are up to the latest standard.

We are utilizing certain C++ 11 language features that appear to be well-supported across modern compilers, such as the "auto" keyword, range-based-for and lambdas. In some cases we're able to wrap up usage of these features in preprocessor conditionals (such as rvalue references in containers.) However, certain language features we may opt to avoid entirely until we're confident we won't be surprised by a new platform appearing that cannot digest the syntax.

Unless specified below as a modern C++ compiler feature we are supporting, you should refrain from using compiler-specific language features unless they are wrapped in preprocessor macros or conditionals and used sparingly.

The 'auto' Keyword

The 'auto' keyword is supported by all compilers UE4 targets and you are encouraged to use it in your code where it makes sense to do so.

Remember you can and should use const, & or * with auto just like you would with the type name. With auto, this will coerce the inferred type to be what you want.

We encourage use of the auto keyword for iterator loops (eliminates boilerplate), and also when you are initializing a variable to a new instance (eliminates redundant type name.) Some of the other uses are more contentious, but feel free to use it however you want for now and we can learn and improve best practices as we go.

Tip: If you hover over a variable in Visual Studio, it will usually tell you the inferred type.

Range Based For

This is allowed in all engine and editor code and encouraged where it can help to keep the code easier to understand and more maintainable.

Lambdas and Anonymous Functions

Lambdas are now allowed, however we are cautious about use of stateful lambdas that capture stack variables -- we're still learning about where those are appropriate. Also, stateful lambdas cannot be assigned to function pointers which we tend to use a lot. We expect to update this documentation in the future as we establish best practices.


So, basically ranged based for loops, stateless lambdas good, stateful lambda bad and auto is a maybe.  For the remaining features that aren’t cross platform like override, they’ve provided preprocessor conditionals to work with them.  I really wish they listed them all here though.

Programming ,

LINQ for C++ with cpplinq

4. April 2014


When it comes to programming languages, I literally use dozens, but when it comes down to an all other things being equal decision my go to language of choice tends to be C#.  One of the big plus sides of C# is the wonderful LINQ ( Language Integrated Query ).  LINQ makes heavy use of lambda (closures) a feature lacking until recently in C++.  Now with lambda expressions part of the C++ language LINQ for C++ is now a possibility.  It exists as a single hpp file you add to your project.


If you aren’t already familiar with LINQ, here is a simple example in C#.  It’s a simple scoreboard that sorts the results by name, then by score, then totals and averages all of the scores.  As you can see, it’s a very compact and clean way to access data.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
    class Entry
        public Entry(string name, int score)
   = name; 
            this.score = score;

        public string name { get; set; }
        public int score { get; set; }

    class Program
        static void Main(string[] args)
            List<Entry> scoreEntries = new List<Entry>();
            scoreEntries.Add(new Entry("mike", 42));
            scoreEntries.Add(new Entry("bob", 99));
            scoreEntries.Add(new Entry("doug", 99));
            scoreEntries.Add(new Entry("steve", 12));

            var sortedByName = scoreEntries.OrderBy(item =>;
            Console.WriteLine("Sorted by score");
            sortedByName.ForEach(item => { Console.WriteLine( + " " + item.score); });

            Console.WriteLine("\nSorted by name");
            var sortedByScore = scoreEntries.OrderBy(item => item.score).ToList();
            sortedByScore.ForEach(item => { Console.WriteLine( + " " + item.score); });

            var totalOfScores = scoreEntries.Where(item => item.score > 0)
                .Sum(item => item.score);

            var averageScore = scoreEntries.Average(item => item.score);
            Console.WriteLine("\nTotal of scores == " + totalOfScores + " Average Score == " + averageScore);



Now let's take a look at the C++ version using cpplinq:

#include <string>
#include <list>
#include "cpplinq.hpp"
#include <iostream>

class Entry{
        Entry::Entry(std::string name, int score){
            this->name = name;
            this->score = score;

        std::string name;
        int score;

int main(int argc, char **argv)
    std::list<Entry> scoreEntries;
    scoreEntries.push_back(Entry("mike", 42));
    scoreEntries.push_back(Entry("bob", 99));
    scoreEntries.push_back(Entry("doug", 99));
    scoreEntries.push_back(Entry("steve", 12));

    using namespace cpplinq;
    auto sortedByName = from(scoreEntries)
        >> orderby_ascending([](const Entry & entry){ return;  })
        >> to_vector();
    auto sortedByScore = from(scoreEntries)
        >> orderby_descending([](const Entry & entry){ return entry.score;  })
        >> to_vector();

    std::cout << "Sorted by name" << std::endl;
        >> for_each([](const Entry & entry){ std::cout << << " " << entry.score << std::endl; });

    std::cout << std::endl << "Sorted by score" << std::endl;
        >> for_each([](const Entry & entry){ std::cout << << " " << entry.score << std::endl; });

    auto totalOfScores = from(scoreEntries)
        >> select([](const Entry & entry){ return entry.score; })
        >> sum();

    auto averageScore = from(scoreEntries)
        >> select([](const Entry & entry){ return entry.score; })
        >> avg();

    std::cout << std::endl << "Total of scores == " << totalOfScores << " average score == " << averageScore << std::endl;
    return 0;


A few obvious differences.  Cpplinq statements start with the from methods defining the type of data source to perform on.  In this case I used the default from() which takes a standard C++ STL type.  There are also from__array() and from_range() for working with arrays and iterators respectively.  Next the . (dot) operator has been replaced with the >> operator.  Of course the lambda syntax is different as well ( C++’s is much uglier ), otherwise at the end of the day, it is very similar to LINQ in both look and execution.


If you are new to C++ and are struggling to wrap your head around the uses for lambdas, give cpplinq a shot and you will quickly see their value!