Archive for the ‘Uncategorized’ Category

DIY Webserver Using PureMVC++

Tuesday, December 22nd, 2009

To test out my newly ported PureMVC++ implementation I decided to write an example webserver. I’ve always wanted to write one, and I didn’t realize just how easy it is (to make a VERY rudimentary version).

The server parses your http request and then spits it back out at you, with some nice html.
Screen shot 2009-12-22 at 2.35.47 PM
That’s it! Source code is here:
http://github.com/efnx/PureMVC-Plus-Plus/tree/master/example/httpserver/

PureMVC++ – A C++ MVC framework (ported from AS3)

Friday, December 18th, 2009

I had some time over the past month to port the popular PureMVC application architecture from AS3, to C++. I learned a ton about C++ and it turned out to be a rather smooth process. The code is up on github.

Differences in the C++ version

Notification names and types are ints!
At first I used strings for notification names and types, just like in other ports. I did this until I was writing the first sample application. At that moment I realize in C++ you can’t switch on strings! There’s no support for writing a switch statement on the type std::string. I simply didn’t know that. So code like this just won’t compile:

switch ("somestring")
{
    case "notthisone":
        trace("not gonna happen");
        break;
       
    case "northisone":
        trace("also not gonna happen");
       
    case "somestring":
        trace("this one gets evaluated");
        break;
       
    default:
}

C++ only allows you to switch on ints, so to save us from having to write something like this:

if(note->getName() == "notthisstring")
    cout << "not gonna happen";
else if(note->getName() == "northisstring")
    cout << "also not going to happen";
else if...

I decided to make note names and types ints. This way we can enumerate our notification names and types like so:

class n_name
{
public:
    enum name
    {
        NIL,
        STARTUP,                // triggers the app startup sequence
        SET,                    // sets something
        GET,                    // makes a request to get something
        DISPLAY,                // display something
        QUIT                    // quit the app
    };
}

and then handle the notification with ints:

int name = note->getName();
switch(name)
{
    case n_name::STARTUP:
        cout << "Startup the app!";
        break;
    case n_name::QUIT:
        cout << "Shutdown...";
        break;
    default:
}

IFacade no longer contains a registerCommand method
I tried my best to figure out a way to implement stateless commands in C++. The way the AS3 version accomplishes this is by passing around references to classes. In that port handling references to classes in an abstract way is easy because AS3 has built in type introspection. In order to do the same thing in C++ we’d have to depend on something from the boost library. That’s not an option. Instead I gave Facade a templated method to replace IFacade’s registerCommand (conveniently called registerCommand). So instead of calling registerCommand(noteName, CommandClassName), one makes a call like this: registerCommand<CommandClassName>(noteName). This calls a special template function created by the compiler that adds CommandClassName to a templated Observer, which is added to the View’s observer list.

That covers it for now. In the coming weeks I’ll probably be adding example code to this post, as well as example applications to the repo. If you’re interested in the project, keep up to date with the repo at github and soon we’ll have a repo at PureMVC.org. I’ve added some temporary documentation for you to use as well.

AS3 – Creating a Convex Polygon from Unordered Points

Monday, September 21st, 2009

Let’s pretend you have an application that lets users create shapes to be used in a physics simulation and that the user must click on the screen to set the vertices of the shape. Many physics engines only support convex polygons, or shapes that don’t have inlets, bites, or coves, basically shapes that don’t have inward facing edges. With this limitation we have to be able to restrict [read as "guide"] the user to make only convex polygons. For this we are going to need an algorithm that takes an unordered set of points and finds the convex hull that encloses those points. This way the user can click and add points at random, if desired, and your program will keep track of what points create a convex polygon, while the others are thrown away [or dealt with however you see fit].

The Graham Scan Algorithm is a process of ordering a random set of points and then calculating jumps to the points in that set that constitute a convex polygon. In this algorithm there are three steps. First is to find a corner point, usually the topmost, leftmost point in the set. The second step is to order all other points by the polar angle between the corner point and the point in question. The last step is to traverse the set, taking each proceeding subset of three points (n, n-1, n-2) to determine whether the angle made by these three points is a left turn, right turn, or a straight line. If the turn made is our desired turn [which is usually left - but in Flash it's right, due to the flipped y-axis] then we add that point to the convex hull. If the turn is not our desired turn, we get rid of that point and move on.

Here is an example that shows first the data set drawn from point to point. Each successive line gets progressively whiter. In the second step we find the corner point, order the other points and then show the outer polygon.

Example

Example

Here’s the code for the class:

/**
 *  Use this class freely - 2009 blog.efnx.com
 */


package
{
    import flash.geom.Point;
   
public class GrahamScan extends Object
{
    /**
     *  The Graham scan is a method of computing the convex hull of a finite set of points
     *  in the plane with time complexity O(n log n). It is named after Ronald Graham, who
     *  published the original algorithm in 1972. The algorithm finds all vertices of
     *  the convex hull ordered along its boundary. It may also be easily modified to report
     *  all input points that lie on the boundary of their convex hull.
     */

   
    public function GrahamScan()
    {
        super();
    }
   
    /**
     *  Returns a convex hull given an unordered array of points.
     */

    public static function convexHull(data:Array):Array
    {
        return findHull( order(data) );
    }
    /**
     *  Orders an array of points counterclockwise.
     */

    public static function order(data:Array):Array
    {
        trace("GrahamScan::order()");
        // first run through all the points and find the upper left [lower left]
        var p:Point = data[0];
        var n:int   = data.length;
        for (var i:int = 1; i < n; i++)
        {
            //trace("   p:",p,"d:",data[i]);
            if(data[i].y < p.y)
            {
                //trace("   d.y < p.y / d is new p.");
                p = data[i];
            }
            else if(data[i].y == p.y && data[i].x < p.x)
            {
                //trace("   d.y == p.y, d.x < p.x / d is new p.");
                p = data[i];
            }
        }
        // next find all the cotangents of the angles made by the point P and the
        // other points
        var sorted  :Array = new Array();
        // we need arrays for positive and negative values, because Array.sort
        // will put sort the negatives backwards.
        var pos     :Array = new Array();
        var neg     :Array = new Array();
        // add points back in order
        for (i = 0; i < n; i++)
        {
            var a   :Number = data[i].x - p.x;
            var b   :Number = data[i].y - p.y;
            var cot :Number = b/a;
            if(cot < 0)
                neg.push({point:data[i], cotangent:cot});
            else
                pos.push({point:data[i], cotangent:cot});
        }
        // sort the arrays
        pos.sortOn("cotangent", Array.NUMERIC | Array.DESCENDING);
        neg.sortOn("cotangent", Array.NUMERIC | Array.DESCENDING);
        sorted = neg.concat(pos);
       
        var ordered :Array = new Array();
            ordered.push(p);
        for (i = 0; i < n; i++)
        {
            if(p == sorted[i].point)
                continue;
            ordered.push(sorted[i].point)
        }
        return ordered;
    }
    /**
     *  Given and array of points ordered counterclockwise, findHull will
     *  filter the points and return an array containing the vertices of a
     *  convex polygon that envelopes those points.
     */

    public static function findHull(data:Array):Array
    {
        trace("GrahamScan::findHull()");
        var n   :int    = data.length;
        var hull:Array  = new Array();
            hull.push(data[0]); // add the pivot
            hull.push(data[1]); // makes first vector
           
        for (var i:int = 2; i < n; i++)
        {
            while(direction(hull[hull.length - 2], hull[hull.length - 1], data[i]) > 0)
                hull.pop();
            hull.push(data[i]);
        }
       
        return hull;
    }
    /**
     *
     */

    private static function direction(p1:Point, p2:Point, p3:Point):Number
    {
        // > 0  is right turn
        // == 0 is collinear
        // < 0  is left turn
        // we only want right turns, usually we want right turns, but
        // flash's grid is flipped on y.
        return (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x);
    }
}

}

PHP – Nested Tuple

Friday, September 4th, 2009

Here’s a quick nested tuple [list of head and tail, where tail is the list minus the head]. I wrote this for a current project I’m working on. It works with any parameters except one array. If you only pass one array, it will convert your one array into a list of Tuples.

<?php
/**
 * Tuple is a list of variables. Really it is a head and a tail, where the tail
 * is also a Tuple. (Tuple(n)=head + Tuple(n-1))
 */


class Tuple
{
    public $head;
    public $tail;
   
    public function __construct($args = null)
    {
        if(! (is_array($args) && func_num_args() == 1))
        {
            // get all the arguments and package them as an array
            $args = func_get_args();
        }
       
        // take the first element and use that as the head of the list
        $this->head = array_shift($args);
        // if there are still args left, make a new list and use that as tail
        if(count($args)>0)
        {
            // pass the remainder
            $this->tail = new Tuple($args);
        }
       
    }
}

?>

Here’s some usage and output:

<?php
$list = new Tuple(1, 2, 3, 4);
print_r($list);

That prints out:

Tuple Object
(
    [head] => 1
    [tail] => Tuple Object
        (
            [head] => 2
            [tail] => Tuple Object
                (
                    [head] => 3
                    [tail] => Tuple Object
                        (
                            [head] => 4
                            [tail] =>
                        )

                )

        )

)

30 30 Second Songs In 30 Days

Tuesday, June 30th, 2009

My friend Judah and I are going to collaborate on an album of 30 30 second songs, and will be releasing it August 1st, 2009.

The Universal Law of Deadlines

Monday, June 29th, 2009

A friend and I were talking about deadlines, as we’re often thrown into a rushed project together, and I came up with this equation which seems to accurately model a coming deadline in the information industry.

Scivally-Nagler’s Law

workload + stress = 1/(deadline - now);

Hannspree HF237 + Macbook Pro 2.16Ghz

Wednesday, June 17th, 2009

I bought a new monitor today – a Hannspree 23″. I only paid about $180 for it, so it seemed like a sweet deal. TOTALLY WRONG. This thing hurts my eyes it’s so sh*tty. Some pixels are sharp, others are blurry. It’s like the monitor itself is stretching and interpolating the pixel points from my video card. Text is UNREADABLE on most resolutions and no amount of settings fidgetry seems to fix it. The pixels just don’t line up. This thing is auto-dithering my pixel art. I’m taking it back tomorrow and getting my money back. I’d rather have a used, scuffed up LCD from two years ago. Tried and true.

New Hosting

Wednesday, April 29th, 2009

Over the past month or so I’ve been having some hosting issues – my cats would attack the server, some how it would get unplugged, etc. So now I’ve switched everything over to hosting at Mediatemple.net, which seems pretty awesome so far. So here’s to no more downtime, 404s or 500s and hopefully instead we’ll get some 808s. *cheers*

Wordpress Auto-Update Script For A Linux Server

Monday, March 16th, 2009

I wrote a little update script for my server to auto update my wordpress installation and figured it might help some other people as well. To use it you simply supply as arguments to the script three things:

1. the directory where your wordpress install lives
2. the name of the backups you’d like to create for that directory
3. the version of the wordpress install you’d like to upgrade to

For example, on my server I use this command to update my wp version:

sudo ./updateWordpress.sh /path/to/wordpress/installation efnx 2.7.1
[enter password]
[watch output]

done!

Here is the code to my script:

#!/bin/bash
DIR2UPDATE=$1
NAME=$2
VERSION=$3

echo "Beginning update of $DIR2UPDATE to version $VERSION..."

if [ -d wordpress_svn ]
then
    day=`date | cut -d" " -f3`
    tme=`date | cut -d" " -f4`
    hour=`echo ${tme} | cut -d":" -f1`

    fileday=`ls -lh | grep wordpress_svn | cut -c 37-39`
    filehour=`ls -lh | grep wordpress_svn | cut -c 40-41`

    if [ ${fileday} != ${day} ]; then
            echo "SVN directory not up to date, [ file's date ${fileday} != today ${day} ] deleting and updating"
        rm -rf wordpress_svn/*
        cd wordpress_svn
            svn co http://svn.automattic.com/wordpress/tags/${VERSION} .
    else
            if [ "$filehour" != "$hour" ]; then
                    echo "SVN directory not up to date, [ file's hour ${filehour} != now ${hour} ] deleting and updating"
                rm -rf wordpress_svn/*
                    cd wordpress_svn
                    svn co http://svn.automattic.com/wordpress/tags/${VERSION} .
        else
                    echo "SVN directory is up to date, skipping update"
                cd wordpress_svn
        fi
    fi

else
    echo "Creating new svn directory and checking out version $VERSION...";
    mkdir wordpress_svn;
    cd wordpress_svn;
    svn co http://svn.automattic.com/wordpress/tags/${VERSION} .;
fi

cd ..

if [ -d wordpress_int ]
then
    echo "Removing old intermediate container...";
    rm -rf wordpress_int;
fi

echo "Creating new intermediate container..."
mkdir wordpress_int
echo "Moving version $VERSION files into intermediate container..."
cp -rpf wordpress_svn/* wordpress_int

echo "Moving config and custom files from $NAME into intermediate container..."

cp -p ${DIR2UPDATE}/wp-config.php wordpress_int
cp -rpf ${DIR2UPDATE}/wp-content/* wordpress_int/wp-content/
cp -p ${DIR2UPDATE}/.htaccess wordpress_int
echo 'Updating svn for wp-content'
svn update wordpress_int

echo "Backing up $DIR2UPDATE..."
mkdir ${NAME}_backup
#mv -f ${DIR2UPDATE}/* ${NAME}_backup   # if you'd like to mv instead of cp
cp -rpf ${DIR2UPDATE}/* ${NAME}_backup
tar -czvf ${NAME}_backup.tar.gz ${NAME}_backup
rm -rf ${NAME}_backup

echo 'Removing svn data from intermediate container...'
rm -rf `find wordpress_int/ -type d -name .svn`
echo "Moving intermediate container contents to $DIR2UPDATE..."
cp -rpf wordpress_int/* ${DIR2UPDATE}

Or you can just download the script here [rightclick + 'save as']->
updateWordpress.sh

My current inactivity.

Tuesday, January 13th, 2009

Hey all, I’ve been visiting my blog less and less these past few months, and as a result I have the lowest traffic rates in over a year. It’s all because of a rather good event. I’ve been recruited by a web firm in San Rafael, CA, called Synapse Group, to develop some undisclosed projects which have been taking all of my development time. When I code flash + web services all day, I hardly feel like spending my waning night hours coding my own flash projects. Rightfully so I’ve taken up more C++. I’ve found solice in OpenFrameworks, a bundle of classes that wrap OpenGL, rtAudio, FreeType, FreeImage and QuickTime together in a “user-friendly” [read: reduced programming headache] format. Earlier last year I found OF, then decided to dive into OpenGL and rtAudio on my own, but now I’ve gone back, why re-invent the wheel?
So, expect some C++ projects to get thrown up here soon. One thing I would really like to do, is get a Flash API-like display list system running in OpenGL. I have a crude working concept of OpenGL, but it suffices to display my 2D musings. Any gurus out there available for pointers? No pun intended.