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.

 

Breakpoint

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.

 

Watch

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

 

Local

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

myFunc()

main().

 

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;
    someFunction(i);
    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:

image

Or, you can run from the Debug menu:

image

 

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:

image

 

… 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:

image

 

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

 

image

 

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:

 

image

 

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.

image

 

Stepping over the corpses of your vanquished foes

 

 

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

 

image

 

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

image

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:

image

 

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:

 

image

 

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

 

image

 

You can hover over parameters to see their value:

image

 

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.

 

image

 

 

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:

image

 

A window like the following should appear:

image

 

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…

image

 

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:

 

image

 

Now line numbers will be displayed next to your code:

image

 

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:

 

image

 

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

 

image

 

Now you will have a new window, like so:

 

image

 

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():

 

image

 

 

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:

 

image

 

 

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:

 

image

 

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:

 

image

 

Or using the following commands from the Debug menu:

 

image

 

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{
public:
    int myInt;
    std::string myString;

    MyClass() :
        myInt(4), 
        myString("Hello World"), 
        myPrivateInt(5)
    {
    }

private:
    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:

 

image

 

If you run this code, you will see:

 

image

 

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!

 

image

 

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

 

image

 

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:

 

image

 

You can now change the value:

 

image

 

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:

 

image

 

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.

 

image

 

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:

 

image

 

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:

 

image

 

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

 

image

 

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

 

image

 

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:

image

 

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:

 

image

 

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

 

image

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:

 

image

 

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:

 

image

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

 

image

 

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.

 

image

 

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:

 

image

 

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:

 

image

 

 

On One Condition

 

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

Consider the following code sample:

 

image

 

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…

 

image

 

Now you can set the condition you will break on.

 

image

 

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

 

image

 

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

 

image

 

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

image

 

A window will open up like this:

image

 

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:

 

image

 

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

 

Starting/Stopping:

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:

image

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

image

 

Or using the Debug icon in the toolbar:

image

 

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

image

 

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:

image

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.

image

You can also toggle a breakpoint using the Run menu:

image

 

Step Into/Step Over/Step Out:

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

image

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:

image

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

 

Watch Window

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

image

 

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.

 

image

 

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.

image

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:

image

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

image

 

 

JavaScript in Chrome

 

Starting/Stopping:

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

image

 

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:

image

 

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

image

… 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:

image

 

 

Watch Window

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

image

 

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

image

 

Local Window:

Called Scope Variables in Chrome.  Located in same area:

image

 

Evaluate Expression:

See watch above.

 

Conditional Breakpoints:

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

image

Then type your conditional logic code:

image

 

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 , , , ,




3D Prototyping library GDX-proto released today

6. August 2014

 

jrenner/obfuscate( on reddit ) released his in development 3D engine, GDX-Proto earlier today.  In his own words:

 

GDX-Proto is a lightweight 3d engine built with two main objectives:

  • Provide an open source codebase showing how to do many basic and essential things for 3d games with libgdx, a cross-platform Java game framework.
  • Provide a simple, extensible 3d engine that takes care of lower-level things such as physics and networking.

 

While the current version is implemented as a First Person Shooter (FPS) demo, the code is highly adaptable for other uses, without too much work.

Overview of Features

Graphics
  • Basic 3d rendering using a slightly modified version of the default libgdx 3d shader. It takes advantage of the new libgdx 3D API.
  • 3D Particle system based on the new libgdx 3d particle system (version 1.2.1+, not included in 1.2.0)
Physics
  • The Bullet physics library is used for collision detection, but not for collision resolution. This allows for fast and efficient collision detection without the performance penalties of a fully simulated bullet world. A default collision resolution system is included in the Physics class, but it can be modifided to suit your needs.
  • Raycasting for projectile hit detection
Networking
  • Supports local or online play
  • KryoNet based
  • Mix of TCP and UDP where appropriate
  • Entity interpolation
  • Client prediction (for movement only, not yet implemented for projectiles)
  • Simple chat system
  • Supports libgdx headless backend for creating a headless server, such as on a VPS
  • Server transmits level geometry to client upon connection
  • "The server is the man": Most logic is run server-side to prevent cheats or hacking.
Other
  • Basic Entity system with DynamicEntities, represented by either Decals (Billboard sprites) or 3D models
  • Movement component class handles acceleration, velocity, position, rotation, max speeds
  • Subclasses of Movement: GroundMovement and FlyingMovement
  • Optional logging to file, see Log class

 

Right now it’s pretty early on.  It’s not actually a library as of yet, but instead a single project with a sample FPS.  In the future I believe it will be refactored into a more traditional library.  Right now though, it does provide a solid foundation for building a 3D game on top of LibGDX.  Right now, LibGDX provides only a relatively low level 3D layer and this project builds on top of it.

 

Getting started is extremely simple.  First clone the git:

git clone https://github.com/jrenner/gdx-proto.git

Then run the project:

gradlew desktop:run

 

image

 

You can navigate around using standard WASD keys.  For the Gradle averse that want to type the demo out, you can download a playable jar here.  The entire project is available on Github here.

Programming ,




How my upcoming vacation lead to a new game dev project

30. July 2014

 

It’s that time of year… time to put everything on hold for a while, get away for a bit and consume far too much food and drink.  Yes, GameFromScratch is about to go on vacation for a few days.  Bonus points if you can figure out where I am going from the picture below!

 

 

 

… anyways, being a game developer, do we ever really take vacation?  We are seemingly always thinking about how to accomplish something or other in our head.  This trip will no doubt be no different…

 

Actually, it will be different on one level.  I recently acquired a full sized iPad Air ( until now, I’ve only had a Mini ) and I am thinking about doing an entire series of creating games entirely on an iPad.  Let’s see just how much you can accomplish entirely on an iPad.  This means coding, game asset creation, everything on the iPad.

 

I’ve actually already purchased a number of items required.  I purchased a license of Codea back when I first got my iPad Mini, but I found the limited screen size to be a rather big annoyance.  I also have purchased several different drawing programs, including Paper, PhotoShop, ArtRage and iDraw.  I even have a functioning blog packaging, so I can right about the process.  Not really certain how I will tackle audio creation.  Another major downside is asset sharing…  this is one of the major limitations of iOS, sharing data between apps is pretty horrible.  The defacto workaround seems to be DropBox, but that depends entirely on how well the hotel’s Wifi works.  It could end up being a fun little side project.  Or it could be a complete waste of time… I guess we shall see.

 

Fortunately what it will be is a good LUA refresher, which I need for an upcoming and much larger project I am embarking on when I return.  More news on that later.

 

So anyways, that’s what I am about to do… if GameFromScratch.com goes silent until next Wednesday… guess that means the hotel wireless was pretty awful.  In which case, have a great week!

News, Totally Off Topic




Game Development Tutorial: Swift and SpriteKit Part 6 - Working with Physics Part 2

29. July 2014

 

Ok I think I ended up with an overly complicated title for this series once again…  This is the next part in the ongoing Swift with SpriteKit tutorial series.  In the previous part we hooked up a very simple physics simulation.  First starting with basic gravity then with a collision off the edge of the screen.  In this part we are going to look at some slightly more complicated collision scenarios.  This tutorial section is going to be a bit more code heavy than before.

 

In this first code example, we are going to have two physics guided balls on the screen.   This example will show how to “do something” when two objects collide.  Let’s hope right in:

 

import SpriteKit

 

class GameScene: SKScene, SKPhysicsContactDelegate {

    override func didMoveToView(view: SKView) {

        

        // Define the bitmasks identifying various physics objects

        let sphereObject : UInt32 = 0x01;

        let worldObject : UInt32 = 0x02;

        

        //Create a ball shape

        var path = CGPathCreateMutable();

        CGPathAddArc(path, nil, 0, 0, 45, 0, M_PI*2, true);

        CGPathCloseSubpath(path);

 

        // Create one ball

        var shapeNode = SKShapeNode();

        shapeNode.path = path;

        shapeNode.lineWidth = 2.0;

        shapeNode.position = CGPoint(x:self.view.frame.width/2,y:self.view.frame.height);

        

        // Set the ball's physical properties

        shapeNode.physicsBody = SKPhysicsBody(circleOfRadius: shapeNode.frame.width/2);

        shapeNode.physicsBody.dynamic = true;

        shapeNode.physicsBody.mass = 5;

        shapeNode.physicsBody.friction = 0.2;

        shapeNode.physicsBody.restitution = 1;

        shapeNode.physicsBody.collisionBitMask = sphereObject | worldObject;

        shapeNode.physicsBody.categoryBitMask = sphereObject;

        shapeNode.physicsBody.contactTestBitMask = sphereObject;

        

        // Now create another ball

        var shapeNode2 = SKShapeNode();

        shapeNode2.path = path;

        shapeNode2.position = CGPoint(x:self.view.frame.width/2,y:self.view.frame.height/2);

        

        shapeNode2.physicsBody = SKPhysicsBody(circleOfRadius: shapeNode.frame.width/2);

        shapeNode2.physicsBody.dynamic = true;

        shapeNode2.physicsBody.mass = 5;

        shapeNode2.physicsBody.friction = 0.2;

        shapeNode2.physicsBody.restitution = 1;

        shapeNode2.physicsBody.collisionBitMask = sphereObject | worldObject;

        shapeNode2.physicsBody.categoryBitMask = sphereObject;

        shapeNode2.physicsBody.contactTestBitMask = sphereObject;

        

        // Now make the edges of the screen a physics object as well

        scene.physicsBody = SKPhysicsBody(edgeLoopFromRect: view.frame);

        scene.physicsBody.contactTestBitMask = worldObject;

        scene.physicsBody.categoryBitMask = worldObject;

        

        // Make gravity "fall" at 1 unit per second along the y-axis

        self.physicsWorld.gravity.dy = -1;

        

        self.addChild(shapeNode);

        self.addChild(shapeNode2);

        

        // We implement SKPhysicsContactDelegate to get called back when a contact occurs

        // Register ourself as the delegate

        self.physicsWorld.contactDelegate = self;

 

    }

    

    // This function is called on contact between physics objects

    func didBeginContact(contact:SKPhysicsContact){

        let node1:SKNode = contact.bodyA.node;

        let node2:SKNode = contact.bodyB.node;

        

        // Node 1 is the object the hit another object

        // Randomly apply a force of 0 - 1000 on both x and y axis

        node1.physicsBody.applyImpulse(CGVector(

            CGFloat(arc4random() % 1000),

            CGFloat(arc4random() % 1000)));

        

        // Node 2 is the other object, the one being hit

        node2.physicsBody.applyImpulse(CGVector(

            CGFloat(arc4random() % 1000),

            CGFloat(arc4random() % 1000)));

    }

    

}

 

And when you run it:

 

Physics3

 

A lot of the code is very similar to our previous example, so I will only focus on what’s new.  The first thing you may notice is our class now implements SKPhysicsContactDelegate.  This provides a function, didBeginContact() that will be called when a contact occurs.  In this example, didBeginContact will only be called when a contact occurs between spheres, and not the edge of the screen.  I will explain why shortly.

 

The only other major change in this code is for each PhysicsObject in the scene, we now define a couple values, collisionBitMask, categoryBitmask and contactTestBitMask.  Earlier in the code you may have noticed:

        let sphereObject : UInt32 = 0x01;

        let worldObject : UInt32 = 0x02;

This is where we define our two bitmasks.  Bitmasking may be a somewhat new concept to you.  Basically its a way of packing multiple values into a single variable.  Lets use a simple 8 byte char as an example.  In memory, in terms of bits, a char is composed of 8 bits that can be either on or off.  Like this for example:

10011001

 

So using a single byte of memory, we are able to store 8 individual on/off values.  1 representing on, while 0 represents off.  Of course in variables we don’t generally deal with values in binary form, but instead we often use hexadecimal.  The value above, 10011001 as binary translates to 153 decimal or 0x99 in hex.  Now lets look at our defined values.  We are essentially saying

0001 is a sphereObject

0010 is a worldObject.

 

Now using bitwise math you can do some neat stuff. For example, using a bitwise AND, you can make an object out of both:

let worldSphere = sphereObject & worldObject; // result 0011

This allows you to pack multiple on/off values into a single variable.  Now a full discussion on bitwise math is way beyond the scope of this tutorial, you can read more about it here.  But the basics above should get you through this code example.

 

Basically in SpriteKit physics you define the “type” of an object using categoryBitmask.  So in this example we set the categoryBitmask of each of our spheres to sphereObject, and the world frame to worldObject.  Next you tell each object what it interacts with, like we did here:

        shapeNode2.physicsBody.collisionBitMask = sphereObject | worldObject;

        shapeNode2.physicsBody.categoryBitMask = sphereObject;

        shapeNode2.physicsBody.contactTestBitMask = sphereObject;

What we are saying here is this node will collide with sphereObjects OR worldObjects, but it is a sphereObject and will only contact with other sphereObjects.

Therefore, our contact delegate will only be called when two spheres contact, while nothing will happen when a sphere contacts the side of the screen.  As you notice from the balls bouncing off the side, the collision still occur.  By default, each collision and contact bit mask is set to 0xFFFFFF, which basically sets all possible bits to on, meaning everything contacts and collides with everything else.

 

The delegate function called each time a collision occurs between sphere objects is pretty straight forward:

    func didBeginContact(contact:SKPhysicsContact){

        let node1:SKNode = contact.bodyA.node;

        let node2:SKNode = contact.bodyB.node;

        

        // Node 1 is the object the hit another object

        // Randomly apply a force of 0 - 1000 on both x and y axis

        node1.physicsBody.applyImpulse(CGVector(

            CGFloat(arc4random() % 1000),

            CGFloat(arc4random() % 1000)));

        

        // Node 2 is the other object, the one being hit

        node2.physicsBody.applyImpulse(CGVector(

            CGFloat(arc4random() % 1000),

            CGFloat(arc4random() % 1000)));

    }

Basically for each node involved in the collision we apply a random impulse ( think push ) in a random direction between 0 and 1000 in both the x and y axis.

Speaking of applying force, let’s take a quick look at another example:

import SpriteKit

 

class GameScene: SKScene, SKPhysicsContactDelegate {

    

    var shapeNode:SKShapeNode;

    

    init(size:CGSize) {

 

        shapeNode = SKShapeNode();

        //Create a ball shape

        var path = CGPathCreateMutable();

        CGPathAddArc(path, nil, 0, 0, 45, 0, M_PI*2, true);

        CGPathCloseSubpath(path);

        

 

        shapeNode.path = path;

        shapeNode.lineWidth = 2.0;

 

        

        // Set the ball's physical properties

        shapeNode.physicsBody = SKPhysicsBody(circleOfRadius: shapeNode.frame.width/2);

        shapeNode.physicsBody.dynamic = true;

        shapeNode.physicsBody.mass = 5;

        shapeNode.physicsBody.friction = 0.2;

        shapeNode.physicsBody.restitution = 1;

        // this time we dont want gravity mucking things up

        shapeNode.physicsBody.affectedByGravity = false;

        

        super.init(size:size);

    }

    

    override func didMoveToView(view: SKView) {

 

        

        // Position the ball top center of the view

        shapeNode.position = CGPoint(x:view.frame.width/2,y:view.frame.height);

 

        // Now make the edges of the screen a physics object as well

        scene.physicsBody = SKPhysicsBody(edgeLoopFromRect: view.frame);

        

        self.addChild(shapeNode);

        

    }

    

    override func keyUp(theEvent: NSEvent!) {

 

        switch theEvent.keyCode{

        

        case126: // up arrow

            shapeNode.physicsBody.applyImpulse(CGVector(0,1000));

        case125: // down arrow

            shapeNode.physicsBody.applyImpulse(CGVector(0,-1000));

        case123: // left arrow

            shapeNode.physicsBody.applyForce(CGVector(-1000,0));

        case124: // right arrow

            shapeNode.physicsBody.applyForce(CGVector(1000,0));

        case49: // spacebar

            shapeNode.physicsBody.velocity = CGVector(0,0);

            shapeNode.position = CGPoint(x: self.view.frame.width/2,y:self.view.frame.height/2);

        default:

            return;

        }

    }

    

}

This sample is pretty straight forward, thus no animated gif. If the user presses up or down, an implies is applied along that direction. If the user presses left or right, a force is applied instead.  While if the user hits the spacebar, the sphere’s velocity is set to nothing and it is manually moved to the centre of the screen. One thing you might notice is implies moves a great deal more than force.  This is because force is expected to be applied per frame.  Think of it like driving a car.

An impulse is like i loaded your car into a gigantic slingshot and propelled you along at a blistering speed.

Force on the other hand is much more akin to you driving the car yourself.  If you take your foot of the gas, you rapidly decelerate.  If on the other hand you keep your foot down ( apply the same amount of force each frame ), you will move along consistently at the same speed.

As you see from the above example, you can also manipulate velocity and position directly.  Generally though this mucks with the physics simulation something severe, so generally isn’t recommended if alternatives exist.




Silo 3D modeller 2.3 released. Now available on Linux

28. July 2014

Silo 3D is a nice affordable 3D package I previously featured in the GameFromScratch 3D application list.  My comment at the time was:

 

SiloLogo

I highly recommend you check out the 30 day download, but caution you that the developer support is incredibly iffy.  When evaluating your purchase, ask yourself if the version you are evaluating is worth the price of admission WITHOUT any further patches or upgrades, as there may be none!

 

 

That comment was made over two years ago about version 2.2.  Today I received an email that version 2.3 was released.  By far an away the biggest feature is a port to Linux.  Here is the announcement of 2.3’s features:

 

 Nevercenter brings versatile Silo 3D modeler to Linux, updates codebase with new 2.3 release. 

Responding to the number one request from users, Nevercenter has brought its well-loved 3D modeling software Silo to Linux for the first time with the software’s new version 2.3 update. The update is free to registered users, and also includes bug fixes and improvements to the internal codebase which benefit the Windows and OS X versions. 

Silo's utility as a focused subdivision surfaces modeling solution will be greatly enhanced with support for Linux, the operating system of choice for many professional studios and, increasingly, individuals. "Silo is designed to be lightweight and flexible," said Nevercenter president Tom Plewe. "We want it to fit as seamlessly as possible into any workflow, and obviously this is a huge step in that direction." 

Silo's internals have also received significant updates including an updated windowing system and bug fixes across all platforms, as well as added support for .stl import. 

The free update is available now to all existing Silo 2 users. A license for Silo across all three platforms can currently be purchased for the sale price of just $109 via http://www.nevercenter.com/silo , where a trial version and more information can also be found.

 

From the forum discussion on CGSociety, the following are details of the update:

 

* Moved to more modern Qt 5.x

* Linux support (RHEL/CentOS 6, recent Fedoras, recent Ubuntus have been tested; not all distros will work)

* 64-bit support for Mac OS X and Linux

* STL import

* Bug fixes

 

So more a stability release than a feature packed one.  That said, it’s nice to see any signs of life at Silo, so hopefully we will see more in the future.  So is Silo worth checking out?  Two or three years ago I would have said most certainly.  The lack of changes coupled with the improvements we’ve seen in Blender make that a bit trickier.  That said, in a world were Modo is one of the cheapest options, and it’s over a grand!!! yes, low priced alternatives are certainly always welcome.  Of course, there is a 30 day trial available.

 

Oddly enough, Silo is also available on Steam for less money Silo is available on Steam for $79.  I’m not entirely certain if there is a difference between versions.  One license gets you all three supported platforms, which is nice.




Exporting from Blender to PS Mobile: Blender to Vita in under 5 minutes.

Exporting from Blender to PS Mobile: Blender to Vita in under 5 minutes.

30. April 2012

 

BlenderOnVita

We are now going to look at creating a fully textured model in Blender and exporting to a PlayStation Studio SDK project, a simple model viewer.  We create a very simple model, UV map, texture then export it.  At this point, we process it using the PS Studio ModelConverter tool, import it into PS Studio then finally run our code in the simulator.

 

The example model is as I said, brutally simple ( it’s simply a dice, er… die, also known as a textured cube ). However the process for exporting more complex models is exactly the same.  The process isn’t really all that difficult, especially if you know your way around Blender, but if you don’t know Blender all that well don’t worry, I’ve actually captured the entire process in video form.  This video covers exactly the same thing that the rest of this tutorial does, so if you have problems following one, refer to the other and vice versa.

 

 

Modeling, texturing and exporting from Blender to Sony PlayStation Suite SDK in under 5 minutes

 

 

The above video is actually encoded at 1080p and is probably almost illegible at anything less than 720p.  You can watch it on YouTube or Vimeo in full definition.  Again, the video demonstrates exactly what I am going to show below, except the source code.  So if you are the type that prefers to learn by watching, or the type that learns by reading, you get the best of both worlds here!  Alright, let’s get started.

 

 

If you already know how to model, texture and export in COLLADA format using Blender, I suggest you skip ahead to part 2, as the remainder of this section will be quite boring for you… it goes into detail, a lot of detail. Smile

 

 

If you haven’t already, fire up Blender.  We are going to work with the default cube, if you don’t have a default cube select the Add menu –> Mesh –>Cube.  The first thing we want to do is create a new image to texture our model.

 

In the properties panel to your right ( assuming you are using the default layout, which I will for the remainder of this tutorial ), locate the Textures tab and click it.  Like such:

 

image

 

 

Now change “Type” to Image:

image

 

Scroll down slightly to the Image section ( expand it if required ) and click New:

image

 

In the resulting dialog, we specify the texture details.  I am going to name it the ultra imaginative name “Texture” but fell free to call it whatever you want.  1024x1024 is massive overkill for what we are doing, but hey… I like overkill.  When done, click OK.

 

image

 

Now we want to apply some simple texture mapping to our 3D cube.  In the 3D view, make sure you are in “Edit Mode”, either by hitting Tab until selected, or via this menu:

image

 

Now that you are in edit mode, select all the faces of your mesh by hitting “a”.  Now in the Mesh menu, you want to select Mesh->UV Unwrap…->Follow Active Quads.

image

 

Simply click OK at the resulting dialog menu.  Now we want to switch to UV editing mode.  Locate the icon to the bottom left of your view, click it and select UV/Image Editor.

image

 

We now want to make our texture the active image.  Locate the “Browse image to be linked” button, click it and select texture from the list.

 

image

 

Now press A to select all of our faces, then using hit S to scale ( then mouse move, left click when done), followed by G to translate, until our UV coordinates are all over the black image, like so:

image

 

Now we want to quickly paint our dice faces on the texture within the UV coordinates.  From the menubar select Image->Image Painting.

image

 

Now left click to mouse paint the texture like the face of a die.  You can use the left hand panel ( press “N” if not visible ) to change the paint settings.  When done you should have something like this:

image

 

Now, back in the Image menu, unclick Image Painting.  Now we want to save our completed image.  In the same menu as before, select “Save as Image” or hit F3.  In the resulting dialog, locate the directory you want to save the texture to ( make it the same place you are going to save the model ), name it, then click Save as Image:

image

 

Now with that complete, we assign our image to our texture.  Back in the Texture panel ( to the right ), locate the Image section, click the Browse Image to be Linked button and select your texture.

image

 

Now scroll down lower in the Texture panel, locate Mapping, then select the Coordinates: dropdown and select UV.

image

 

Right below that, select the Map: dropdown and select UVMap.

image

 

 

 

All right, now we have a fully texture mapped model ready for exporting.  From the File Menu ( top right ), select File->Export->COLLADA(.dae).

image

 

 

In the resulting dialog, navigate to the same location where you saved your texture, name it ( I used box.dae ), optionally select “Export only selected” then click Export COLLADA.

 

image

 

 

And we are now done with Blender.

 

 

This section has already gotten quite long so I am going to break this post into two parts.

 

 

Continue on to Part 2.

Programming, Art , , , ,







blog comments powered by Disqus