Detaching a running process from a bash shell

When I run a command on a machine that I am ssh’ed into, most of the time I want to kill the connection but have the command continue to execute.

There are several ways to detach a process from the current shell:

The first is to start the process with:

nohup command &

However, I usually start a command and forget to detach it initially. An easy way to detach a currently running process from a shell is like this:

Ctrl-Z
bg
disown %1

These methods daemonise a running process and make the process ignore the SIGHUP command so that when you close you shell or ssh connection, the command continues to run. For more information check out the man pages for disown and nohup.

Getting Box2D Physics Working in Xcode

Here is an easy way to get up and running with Box2D in Xcode 3.2. I recently had to install Box2D and thought I might share my method for installing and creating an example Xcode project.

First, If you haven’t already got it, download MacPorts from this website as this makes installing libraries a breeze – http://www.macports.org/

Next, open up a terminal and type “sudo port install box2d”
This command downloads and starts to install the box2d libraries. The default installation places the library files in /opt/local/lib and the header files in /opt/local/include.

Once the install has finished, open up a new Xcode project and choose Application > Command Line Tool > c++ stdc++

Next, we are going to add the include and header search paths. In the top menu click Project -> Edit Active Target -> Build and under the search paths heading change the header search path to /opt/local/include and the library search path to /opt/local/lib. Note: DON’T set the recursive checkbox to true. I had problems with this, so it’s probably best to avoid it.

In the same window, click on the General tab and add a file to the “Linked Libraries” Click “add other” and navigate to /opt/local/lib/libBox2D.a

Finally, add the hello world source (this is from the original distribution)



/*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#include <Box2D/Box2D.h>
#include <cstdio>

// This is a simple example of building and running a simulation
// using Box2D. Here we create a large ground box and a small dynamic
// box.
// There are no graphics for this example. Box2D is meant to be used
// with your rendering engine in your game engine.

int main(int argc, char** argv)
{
B2_NOT_USED(argc);
B2_NOT_USED(argv);

// Define the gravity vector.
b2Vec2 gravity(0.0f, -10.0f);

// Do we want to let bodies sleep?
bool doSleep = true;

// Construct a world object, which will hold and simulate the rigid bodies.
b2World world(gravity, doSleep);

// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);

// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world.CreateBody(&groundBodyDef);

// Define the ground box shape.
b2PolygonShape groundBox;

// The extents are the half-widths of the box.
groundBox.SetAsBox(50.0f, 10.0f);

// Add the ground fixture to the ground body.
groundBody->CreateFixture(&groundBox, 0.0f);

// Define the dynamic body. We set its position and call the body factory.
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
b2Body* body = world.CreateBody(&bodyDef);

// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);

// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;

// Set the box density to be non-zero, so it will be dynamic.
fixtureDef.density = 1.0f;

// Override the default friction.
fixtureDef.friction = 0.3f;

// Add the shape to the body.
body->CreateFixture(&fixtureDef);

// Prepare for simulation. Typically we use a time step of 1/60 of a
// second (60Hz) and 10 iterations. This provides a high quality simulation
// in most game scenarios.
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;

// This is our little game loop.
for (int32 i = 0; i GetPosition();
float32 angle = body->GetAngle();

printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}

// When the world destructor is called, all bodies and joints are freed. This can
// create orphaned pointers, so be careful about your world management.

return 0;
}

That’s it! Compile and have fun! Check out the box2d project on google code for other examples and documentation – http://code.google.com/p/box2d/

Simple Image Saving code c++

A major annoyance for me is saving images from c++. I can’t really find any libraries that I like, they are either too complex for the task or they don’t do what I want them to do. So I have created my own, extremely lightweight image library.

All you need to run this is two files, the cpp file and the header. I chose .tga because it is one of the easiest, straightforward formats to save to.

Here is some example code of saving an image with this library:


#include "Image.h"

int main(int argc, char **argv) {
   //declare image
   short width = 256;
   short height = 256;

   TGAImage *img = new TGAImage(width,height);

   //declare a temporary color variable
   Colour c;

   //Loop through image and set all pixels to red
   for(int x=0; x<width; x++)
      for(int y=0; ysetPixel(c,x,y);
      }

   //write the image to disk
   string filename = "/Users/daniel/test.tga";
   img->WriteImage(filename);

   return 0;
}

This outputs a red image like so:
Anyway, have fun using this in your projects,
Here is the download link for the source: Download
For more information on the TGA file format visit the following links:
http://paulbourke.net/dataformats/tga/ 
http://en.wikipedia.org/wiki/Truevision_TGA

Hardware Instancing with XNA (minecraft style)

Lately I have been really enjoying a game called Minecraft. It’s an indie game made by one guy, I highly recommend it!

I have ported the heightmap generation code in one of my earlier posts to C# and using XNA I have been creating a minecraft style rendering for fun. My first approach was a brute force, render everything test. As you might have guessed, that didn’t turn out so well when rendering a decent sized terrain. The method I am using now is hardware instancing without any kind of occlusion culling at the moment. I am getting a decent frame rate (about 80fps for 20000 models) for the moment and I am going to continue on improving this method. The example that is linked at the bottom of this article shows how to perform hardware, and shader instancing.

Here’s a video of it in action:

Links:

Minecraft

XNA Mesh Instancing

Chips Challenge Remake / First Tile Based Game

I am starting to learn XNA at the moment, so I am doing what everyone does when they learn a new language – remake their favourite game! I am making a simple remake of the windows version of Chips Challenge using the sprites from the open source clone of the game which can be found here – http://www.muppetlabs.com/~breadbox/software/tworld/ . Although this remake is by no means a full remake or compatible with the original, I am posting the source code so that someone else can learn from this experience. Keep in mind that this is my first game in XNA, so the code is a bit sloppy but it works.

Some of the features that I implemented for this tile based game are level saving and loading, an advanced menu system, power ups, a timer class, event handling and game state management. This remake is a simple one layer approach, as opposed to the original two layer version. I am implementing features as I go along and have finished the first level and I am working on the next levels. Progress might go a bit faster after I create a level editor, because hand coding levels is no fun! The core functionality of this game was completed in a day as a programming challenge that I set myself. The extra features / tiles took an extra day of coding (that I put off for far too long). At the moment, the code is quite messy, there are a few ugly hacks (especially the input detection), but I am working on improving it, adding a full input manager and possibly some enemies that move etc.

In the future I am looking at uploading more games that I can prototype quickly (for programming practice). So look forward to other classic remakes and newer stuff as well.

Here is a screen shot.

For people that are thinking of creating a tile based game, I suggest taking the time to make it work with the Tiled Map Editor level format. The Tiled Map Editor is a quick and easy way for creating tiled based levels (square and isometric). The tiles can have attributes associated with them which makes the code to load and save levels much cleaner. Wish I had used Tiled!

So check out the source code for this game and give it a bit of a play!

Download Here

Listening for Global Keypresses in OSX.

While working on some new projects recently, I found it difficult to find any good information about how to listen for global keypresses in OSX using a mix of objective-c++ and c. The following code is the result of several hours of searching and frustration, hopefully it can save someone else the same pain.

The method I used to listen for global keypresses is using Event Taps from the Quartz framework. The user must either run this code as root, or have enabled access for assistive devices.

#include <ApplicationServices/ApplicationServices.h>
CGEventRef
myCGEventCallback(CGEventTapProxy proxy, CGEventType type,
                  CGEventRef event, void *refcon)
{
    // Paranoid sanity check.
    if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp))
        return event;

    // The incoming keycode.
    CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField(
                                       event, kCGKeyboardEventKeycode);

    //Keypress code goes here.

    // We must return the event for it to be useful.
    return event;
}

int
main(void)
{
    CFMachPortRef      eventTap;
    CGEventMask        eventMask;
    CFRunLoopSourceRef runLoopSource;

    // Create an event tap. We are interested in key presses.
    eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));
    eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
                                eventMask, myCGEventCallback, NULL);
    if (!eventTap) {
        fprintf(stderr, "failed to create event tap\n");
        exit(1);
    }   

    // Create a run loop source.
    runLoopSource = CFMachPortCreateRunLoopSource(
                        kCFAllocatorDefault, eventTap, 0);

    // Add to the current run loop.
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
                       kCFRunLoopCommonModes);

    // Enable the event tap.
    CGEventTapEnable(eventTap, true);

    // Set it all running.
    CFRunLoopRun();

    exit(0);
}

Compile the above code either using Xcode or GCC with the following –

gcc -Wall -o globalkeypress globalkeypress.c -framework ApplicationServices

In the next couple of days I will upload some code that shows how to move the mouse and simulate mouse clicks.

I’m Famous!

ScienceWA has run a story about my work and my supervisor! First published science magazine article!

They also bring up the upcoming planetarium show, so I guess now that it’s in writing that I should get a move on and finish my parts for it. The show will focus mostly on the creation and evolution of the galaxy showing how the hydrogen gas changes shape over time and how dark matter interacts with it. There is also going to be a fly-through of the 6DF galaxies and a 360 degree interview with Alan Duffy. We are trying to get a 3d fly-through of a similar galaxy to this one:

Check it out here – http://www.sciencewa.net.au/topics/technology/189-News/3139-the-hitchhikers-guide-to-building-a-galaxy

I also managed to sneak about five or six pictures of mine into the iVec annual report.

Link is here (15MB PDF) – http://www.ivec.org/AnnualReport/2009/iVEC_Annual_Report_2009-2010.pdf

SideBySide video player

Often I find the need to play two videos side by side without borders or separate windows. Until now, I have been converting two videos into a single video which takes forever.

So I wrote a simple little cocoa OSX app to load up and play two videos side by side. It doesn’t have heaps of features, but it does exactly what I need so I am posting this incase anyone else could use it.

This application uses QTkit to play videos so the file size is tiny. (Only 57KB!)

Here’s a screenshot:

I used an icon set from http://dryicons.com in this application under the free license terms.

Download here: http://www.divshare.com/download/12662727-93a

Dark matter

I have been working on displaying the dark matter from the HDF5 data sets that I have been working on for my astronomy work. Over the last couple of days, I got the loading from HDF5 working and the translation into my local coordinates. The volume is changed from point coordinates to voxel coordinates, then scaled and clamped to the bounding box size. This has to be done because the camera slowly zooms in over the course of the animation and some of the gas / dark matter can leave the simulation.

The first result was encouraging, but wasn’t what I expected. In the following image, the green points is the dark matter volume displayed in Drishti.

The problem was that Drishti sucks at displaying dynamic range. The internal possible range of values is limited to the size of an unsigned char (0-255). While this would limit the memory usage, I wish there was an option to use short int, or even float because in the image above, all the dark matter points are physically there but the dynamic range is too high to accurately display them. This may have implications on how my other volumes are being displayed as well. I realised that dark matter for this simulation doesn’t have a mass associated with it and doesn’t share mass between voxels either. To check that the points were actually there, I fired up stereo2 and took an image of the raw points.

So the points are there, my code and Drishti just weren’t displaying them properly. I fixed the dynamic range issue by setting voxels that contained dark matter points to 1. The end result is shown below, and what is expected. Hopefully I can get some awesome movies going with the dark matter as well.