LibGDX 1.3 released

9. August 2014

 

LibGDX, the cross platform, Java based, open source gaming library for iOS, Android, HTML5 and Desktop has just reached version 1.3.  The details of the new release:

image

 

  • API Addition: Added Input.isKeyJustPressed
  • API Addition: multiple recipients are now supported by MessageDispatcher, see https://github.com/libgdx/libgdx/wiki/Message-Handling#multiple-recipients
  • API Change: State#onMessage now takes the message receiver as argument.
  • API Addition: added StackStateMachine to the gdx-ai extension.
  • API change: ShapeRenderer: rect methods accept scale, more methods can work under both line and fill types, auto shape type changing.
  • API change: Built-in ShapeRenderer debugging for Stage, see https://github.com/libgdx/libgdx/pull/2011
  • Files#getLocalStoragePath now returns the actual path instead of the empty string synonym on desktop (LWJGL and JGLFW).
  • Fixed and improved xorshift128+ PRNG implementation.
  • Added support for Tiled’s animated tiles, and varying frame duration tile animations.
  • Fixed an issue with time granularity in MessageDispatcher.
  • Updated to Android API level 19 and build tools 19.1.0 which will require the latest Eclipse ADT 23.02, see http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-23 for how things are broken this time…
  • Updated to RoboVM 0.0.14 and RoboVM Gradle plugin version 0.0.10
  • API Addition: added FreeTypeFontLoader so you can transparently load BitmapFonts generated through gdx-freetype via AssetManager, see FreeTypeFontLoaderTest.java
  • Preferences put methods now return “this” for chaining
  • Fixed issue 2048 where MessageDispatcher was dispatching delayed messages immediately.
  • API Addition: 3d particle system and accompanying editor, contributed by lordjone, see pull request 2005
  • API Addition: extended shape classes like Circle, Ellipse etc. with hashcode/equals and other helper methods, see pull request #2018
  • minor API change: fixed a bug in handling of atlasPrefixes, see pull request 2023
  • Bullet: btManifoldPoint member getters/setters changed from btVector3 to Vector3, also it is no longer pooled, instead static instances are used for callback methods
  • Added Intersector#intersectRayRay to detect if two 2D rays intersect, see pull request 2132
  • Bullet: ClosestRayResultCallback, AllHitsRayResultCallback, LocalConvexResult, ClosestConvexResultCallback and subclasses now use getter/setters taking a Vector3 instead of btVector3, see pull request #2175
  • 2d particle system supports pre-multiplied alpha.
  • Bullet: btIDebugDrawer/DebugDrawer now use pooled Vector3 instances instead of btVector3, see pull request #2174

 

 

You can download the LibGDX setup app here.  Of course, GameFromScratch.com has a complete set of LibGDX tutorials to get you started.

Programming, News ,




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 ,




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

25. July 2014

 

Now we are going to look at using Physics in our Spritekit based game.  If you’ve worked with a physics engine before, a lot of this is going to feel very familiar.  One of the key differences from many other engines is SpriteKit handles updating the graphics as well as the physics.  It’s a fairly involved process, so I am going to split this across multiple posts.

 

The first one is going to be short and sweet.  We are going to configure the physics of a sphere, a SKShapeNode.  It is simply going to exist and let gravity take it’s course.  Code time:

 

import SpriteKit

 

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)

        

        var shapeNode = SKShapeNode();

        var path = CGPathCreateMutable();

        CGPathAddArc(path, nil, 0, view.bounds.height/2, 45, 0, M_PI*2, true);

        shapeNode.path = path;

        shapeNode.lineWidth = 2.0;

        

        shapeNode.physicsBody = SKPhysicsBody(circleOfRadius: 45.0);

        shapeNode.physicsBody.dynamic = true;

        

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

        self.physicsWorld.gravity.dy = -1;

        self.addChild(shapeNode);

    }

}

 

And once run:

 

 

Well, that was simple enough, let’s take a quick run through the code.

 

We start off by creating an SKShapeNode.  This shape node is defined by a CGPath.  You can think of a CGPath as a set of drawing instructions.  In this case it consists of a single arc that draws a circle.    Once our path is created we set it to be our shapeNodes path.  We set the lineWidth to 2 to make it a bit more visible.

 

Next we define the physicsBody.  Every SKNode has a SKPhysicsBody.  The SKPhysicsBody is the nodes’ representation in the physics engine.  When defining a physics body you pick the shape that most matches your underlying shape.  In this case it’s a no brainer to use a circle.  There are constructors available for rectangles, polygons, edges, etc.  Of all the options however, the circle is the least processing intensive.  So if you need just a rough physical representation, prefer the more simple types ( circle, then rectangle ) and leave the more complex types until required.  The key thing here is the dynamic property.  This is what tells SpriteKit to include your SKNode in the physics calculation.  If this isn’t set, nothing is going to happen!

 

Finally we set the gravity value dy to -1.  This means gravity moves by a delta of -1 unit per second on the y axis.  Notice the concept of “unit” here, it is very import.  When dealing with SpriteKit ( and many other Physics engines ), a unit is completely arbitrary.  So you may ask “1 what?”.  The answer is, 1 whatever… just be consistent about it.  In your code you could choose 1 to be a millimetre, an inch, a foot, a lightyear.  A lot of it comes down to the type of game you are working on.  One thing to keep in mind here though, massive ranges in value are not a good thing…  so don’t mix units.  For example, trying to represent something in millimetres and kilometres in the same simulation is a sure recipe for disaster!

 

Now let’s give our ball something to collide with… that being the edge of the window.  While we are at it, let’s add a bit of bounce to our step:

 

import SpriteKit

 

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

 

        //Create the ball

        var shapeNode = SKShapeNode();

        var path = CGPathCreateMutable();

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

        CGPathCloseSubpath(path);

        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 = 1;

        shapeNode.physicsBody.friction = 0.2;

        shapeNode.physicsBody.restitution = 1;

        

 

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

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

        

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

        self.physicsWorld.gravity.dy = -1;

 

        self.addChild(shapeNode);

    }

}

 

And run this:

 

 

 

Not, the jerkiness you see isn’t from the physics, but instead the animated gif.  Getting that to encode to a reasonable size was oddly a bit of a battle.

 

The key difference here is first of all, we set the edges of the screen as a physics object for our ball to collide against.  A key thing to remember with SpriteKit, every thing is a SKNode, even the scene itself!

 

Next we set a couple key physics properties for our ball, mass, friction and restitution.  Mass is the weight of the object… going back to the age old question, what falls faster… a ton of feathers, or a ton of bricks?  Friction is how two surfaces react to each other, generally used when simulating “sliding” and is fairly irrelevant in this example.  Restitution is the key value.  For lack of a better explanation, restitution is the bounciness of the objet.  Lower value, less bounce, higher value, higher bounce.  A value higher than 1 will result in an object actually gaining momentum after a collision ( aka, going higher UP then it fell from before bouncing ).

 

Next up we will work on actual collisions.

Programming , ,




Playing around with Three.JS -- Part Two of a not quite a tutorial series

23. July 2014

 

In Part One we looked at the basics of working with the Three.js graphics library.  We got as far as creating a camera and a textured 3D object.  Now is the true test of ease of use… getting a 3D model exported from Blender and displayed in our browser.  HTML libraries face an even bigger burden, as their access to the local file system isn’t as seamless as most other games.  Simply opening up an FBX or DAE file isn’t an option.  Let’s take a look at how ThreeJS works around this issues.

 

 

First’s thing first, I needed a Blender Blend file to work with.  This actually lead me down this road, resulting in a post about taking a Blend file from the web and making it game ready.  Anyways, I did.  I started with this file, merged the geometry, UV mapped it, and baked the Blender materials to a single texture map.  I am not entirely sure if I can share the resulting file or not, so you may have to provide your own Blender file or follow the linked tutorial to generate one of your own.

 

Anyways, this is what we are starting with…

image 

 

Let’s see how close we can get with Three.js.

 

The first obvious question is… how the hell do we get this model in to Three.JS from Blender?

Well, the answer is a plugin.  Follow the installation direction, however in my case the path was wrong.  For Blender 2.71, my actual plugin directory is C:\Program Files\Blender Foundation\Blender\2.71\scripts\addons\io_mesh_threejs.

 

There is one very critical thing to be aware of here… when downloading the files from Github, be certain to download the RAW format:

image

 

This particular mistake caused me a bit of pain, don’t make the same mistake!

 

Once you’ve copied each of these three files, configure the plugin in Blender.  If Blender is running, restart it.

Now select File->User Preferences:

image

 

In the resulting dialog select Addons, then in the search box type “three”.  If it installed correctly it will show on the right.  Click the checkbox to enable the plugin.

image

 

Now if you check the File->Export menu, you should see Three.js as an option.

image

 

When exporting you can clearly see there are a ton of options:

image

 

The options I selected above is for just exporting the mesh and materials.  No animation data, lights, cameras, etc… Scaling and Flip YZ all depend on the orientation of your game engine.

 

This exporter creates a JSON js like this one:

 

{

	"metadata" :
	{
		"formatVersion" : 3.1,
		"generatedBy"   : "Blender 2.7 Exporter",
		"vertices"      : 8,
		"faces"         : 6,
		"normals"       : 2,
		"colors"        : 0,
		"uvs"           : [24],
		"materials"     : 1,
		"morphTargets"  : 0,
		"bones"         : 0
	},

	"scale" : 1.000000,

	"materials" : [	{
		"DbgColor" : 15658734,
		"DbgIndex" : 0,
		"DbgName" : "Material",
		"blending" : "NormalBlending",
		"colorAmbient" : [0.6400000190734865, 0.6400000190734865, 0.6400000190734865],
		"colorDiffuse" : [0.6400000190734865, 0.6400000190734865, 0.6400000190734865],
		"colorEmissive" : [0.0, 0.0, 0.0],
		"colorSpecular" : [0.5, 0.5, 0.5],
		"depthTest" : true,
		"depthWrite" : true,
		"mapDiffuse" : "crate.jpg",
		"mapDiffuseWrap" : ["repeat", "repeat"],
		"shading" : "Lambert",
		"specularCoef" : 50,
		"transparency" : 1.0,
		"transparent" : false,
		"vertexColors" : false
	}],

	"vertices" : [1,-1,0,1,0,1,-1,0,0,0,-1,0,1,0,0,0,1,1,-1,1,0,0,0,0],

	"morphTargets" : [],

	"normals" : [0.577349,0.577349,0.577349,0.577349,0.577349,-0.577349],

	"colors" : [],

	"uvs" : [[0.988679,0.99767,0.988677,0.016243,0.007251,0.016244,0.007252,0.
	997671,0.989755,0.017099,0.989755,0.998526,0.008328,0.998526,0.008328,0.017099,
	0.990714,0.989755,0.009287,0.989755,0.009286,0.008328,0.990713,0.008328,0.
	000516,0.993662,0.981943,0.993661,0.981942,0.012235,0.000516,0.012235,0.987766,
	0.997568,0.987766,0.016141,0.006339,0.016141,0.006339,0.997568,0.986807,0.
	986807,0.986807,0.005381,0.00538,0.00538,0.00538,0.986807]],

	"faces" : [43,0,3,2,1,0,0,1,2,3,0,0,1,1,43,4,7,6,5,0,4,5,6,7,0,0,1,1,43,0,4,5,1,
	0,8,9,10,11,0,0,1,1,43,1,2,6,5,0,12,13,14,15,1,1,1,1,43,2,3,7,6,0,16,17,18,19,1,
	0,0,1,43,3,0,4,7,0,20,21,22,23,0,0,0,0],

	"bones" : [],

	"skinIndices" : [],

	"skinWeights" : [],

  "animations" : []


}

 

In theory things should just work, but since when did gamedev give a damn about theory?  Suffice to say I ran into a bit of a problem fully documented here.  The bug actually had nothing to do with Three.js, it was actually caused by my IDE WebStorm.

 

Anyways… once I figured out the problem, the code to load a model was extremely straightforward:

 

///<reference path="./three.d.ts"/>

class ThreeJSTest {
    renderer:THREE.WebGLRenderer;
    scene:THREE.Scene;
    camera:THREE.Camera;

    constructor() {
        this.renderer = new THREE.WebGLRenderer({ alpha: true });

        this.renderer.setSize(500, 500);
        this.renderer.setClearColor(0xFFFFFF, 1);

        document.getElementById('content').appendChild(this.renderer.domElement);

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(75
            , 1
            , 0.1, 1000);

        this.camera.position = new THREE.Vector3(10, 0, 10);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0));


        // New code begins below
        // Create a loader to load in the JSON file
        var modelLoader = new THREE.JSONLoader();

        // Call the load method, passing in the name of our generated JSON file
        // and a callback for when loadign is complete.
        // Not fat arrow typescript call for proper thisification.  AKA, we want 
        this to be this, not that
        // or something else completely
        modelLoader.load("robot.jsm", (geometry,materials) => {
            // create a mesh using the passed in geometry and textures
            var mesh = new THREE.SkinnedMesh(geometry,new THREE.MeshFaceMaterial(
                       materials));
            mesh.position.x = 0; mesh.position.y = mesh.position.z = 0;
            // add it to the scene
            this.scene.add(mesh);
        });

        this.scene.add(new THREE.AmbientLight(new THREE.Color(0.9,0.9,0.9).
                       getHex()));
        this.renderer.render(this.scene, this.camera);
    }

    render() {
        requestAnimationFrame(() => this.render());
        this.renderer.render(this.scene, this.camera);
    }

    start() {
        this.render();
    }
}

window.onload = () => {
    var three = new ThreeJSTest();
    three.start();
};

 

And when you run it:

image

 

Mission accomplished!  The astute reader may notice the file was renamed robot.jsm.  That was to work around the problem I mentioned earlier.

 

 

 

This isn’t actually the only option for loading 3D models into Three.js, there are actually a series of loaders available as a separate download from the Github site.  It is however certainly the easiest one!  The next few steps took me two full days to fight my way through!  Some of the blame is on TypeScript, some is on me and of course, CORS reared it ugly head as well.  Oh, and to add to the fun, a recent change in Three.js introduced an error in the version of ColladaLoader.js I downloaded. This was one of those trials that Google was no help with, so hopefully this guide will help others in the future.  Anyways… on with the adventure!

 

We are actually about to run smack into two different problems with using a Three.js plugin.  The first one is TypeScript related.  You see, the ColladaLoader plugin is not a core part of Three.js.  In JavaScript, this is no big deal.  In TypeScript however, big deal.  You see, until now we have been relying on the generated .d.ts file from StrictlyTyped for defining all of the types in Three.js from JavaScript in their corresponding TypeScript form.  However, since this is a plugin and not a core part of Three.js, this means the d.ts file has no idea how ColladaLoader works.

 

Ultimately this means you have to had roll your own Typescript definition file. I had to struggle a bit to find the exact TypeScript syntax to map ColladaLoader so it will run in TypeScript within the THREE namespace with proper callback syntax.  First off, create a file called ColladaLoader.d.ts   Now enter the following code:

 

///<reference path="./three.d.ts"/>

declare module THREE {
    export class ColladaLoader{
        options:any;
        load(
            name:string,
            readyCallback:(result:any)=> void,
            progressCallback:( total:number,loaded:number)=> void);
    }
}

 

 

I should probably point out, I only implemented the barest minimum of what I required.  In your case you may have to implement more of the interface.  Also note I also took the lazy approach to defining options.  By returning any, my code will compile in TypeScript, but I do lose some of the type checking.  The alternative would have been to define the Options type and I am way too lazy for that.  The above definition enable me to call the load() method and set options, which is all I actually needed.  I don’t even want to talk about how long it took me to puzzle out those 10 lines of code so that the generated code actually matched THREE.js!

 

OK, we now have ColladaLoader.d.ts defined let’s look at code to use ColladaLoader to load a DAE (COLLADA) file:

 

///<reference path="./three.d.ts"/>
///<reference path="./ColladaLoader.d.ts"/>


class ThreeJSTest {
    renderer:THREE.WebGLRenderer;
    scene:THREE.Scene;
    camera:THREE.Camera;
    loader:THREE.ColladaLoader;
    light:THREE.PointLight;

    constructor() {
        this.renderer = new THREE.WebGLRenderer({ alpha: true });

        this.renderer.setSize(500, 500);
        this.renderer.setClearColor(0xFFFFFF, 1);

        document.getElementById('content').appendChild(this.renderer.domElement);

        this.scene = new THREE.Scene();;

        this.camera = new THREE.PerspectiveCamera(75
            , 1
            , 0.1, 1000);

        this.camera.position = new THREE.Vector3(5, 0, 5);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0));

        // Create a loader
        this.loader = new THREE.ColladaLoader();

        // Add a point light to the scene to light up our model
        this.light = new THREE.PointLight();
        this.light.position.set(100,100,100);
        this.light.intensity = 0.8;
        this.scene.add(this.light);

        this.renderer.render(this.scene, this.camera);

        // Blender COLLADA models have a different up vector than Three.js, set 
        this option to flip them
        this.loader.options.convertUpAxis = true;

        // Now load the model, passing the callback finishedLoading() when done.
        this.loader.load("robot.dae",
            (result) => this.finishedLoading(result),
            (length,curLength)=>{
                // called as file is loading, if you want a progress bar
            }
        );
    }

    finishedLoading(result){
        // Model file is loaded, add it to the scene
        this.scene.add(result.scene);
    }
    render() {
        requestAnimationFrame(() => this.render());
        this.renderer.render(this.scene, this.camera);
    }

    start() {
        this.render();
    }
}

window.onload = () => {
    var three = new ThreeJSTest();
    three.start();
};

 

 

Finally of course we need to export our COLLADA model.  Using Blender, you can export using File->Export->Collada menu option.  These are the settings I used:

image

 

And when you run it:

image

 

That said, there is a really good chance this isn’t what is going to happen to you when you run your project.  Instead you are going to probably receive a 404 error that your dae file is not found.  This is because, unlike before with the JSON file being added directly to your project, this time you are loading the model using an XML HTTP Request.  This causes a number of problems.  The first and most likely problem you are going to encounter is if you are running your application locally from your file system instead of a server.  By default XHR requests do not work this way ( no idea why, seems kinda stupid to me ).  There is a switch that allows chrome to run XHR local requests ( link here ) using --allow-file-access-from-files.

 

In my case the problem was a little bit different.  I use WebStorm, which includes a built in web server to make this kind of stuff easier.  This however raises a completely different set of problems…  CORS  Cross Origin Resource Sharing.  In a very simple description, CORS is a security method for making XML HTTP Requests across different servers.  That said, how the heck do you set it when you are working with a built in stripped down development server?  Fortunately WebStorm have thought about that.

 

Assuming you are using Chrome and have the Webstorm plugin install, in the Chrome address bar, go to chrome://extensions.

image

 

Click the Options button.

image

Now simply add 127.0.0.1 to the allow list and press Apply. 

 

Now if you run from Webstorm, no more 404 errors.

 

A moment about TypeScript

 

I’ve been using TypeScript a fair bit lately and this is the first time I’ve run into major problems with it.  But the experience is enough that I can safely say…

 

TypeScript is not appropriate for new developers to use!

 

Simply put, unless you have a decent amount of experience with JavaScript, you really shouldn’t use TypeScript.  You will have to read the generated code at some point in time, and if you don’t full understand the code it generates, you are doomed.  The minute definition files arent available to you the experience becomes a hell of a lot less fun.  The process of mapping TypeScript types to existing JavaScript libraries is not trivial and requires you to have a pretty good understanding of both languages.  Especially when the library you are trying to define uses a number of clever JavaScript tricks, which basically… is all of them.  The fact there isnt a reliable tool out there for generating at least boilerplate .d.ts files from .js files is a bit of a puzzle to me.

 

Next, I also have to say TypeScript’s handling of this is just as mind bogglingly stupid as JavaScript’s.  That fat arrow ( => ) functions are used to capture local context, until used as an anonymous method, at which point they capture global (window) context, forcing you to resort to function() is downright perplexing.  I simply couldn’t get anonymous callback functions to have the proper this context no matter what syntax combination I tried.  Infuriatingly, the _this value Typescript automatically contains was set to the right value.

 

One other major downside I noticed about the language with my recent struggles is the newness of the language is very much an annoyance.  When researching bugs or workarounds you quite often find things that are reported as bugs, reported as changed,  or reported and never responded to.  This isn’t a bash on the language as it’s really only a problem that time can solve.  However, for a new developer, dealing with a language where a great deal of the material out there is potentially wrong because of language changes, that is certainly a challenge.  All languages change over time of course, but young languages change more and more dramatically.

 

Don’t get me wrong, I am not off Typescript, even though it spent a good part of the last two days pissing me off.  At least until ECMAScript 6 is the norm I can see a great deal of value in using TypeScript for large projects.

 

For beginners though, with little JavaScript experience… forget about it.  It’s going to cause more headaches than it’s worth.

Programming , ,