Wednesday, September 29, 2010

Workaround and Hacks

‹prev | My Chain | next›

Tonight, I continue working through a new feature in animate-frames plugin for raphaël.js. This plugin iterates through a series of raphaël/SVG frames as the frames move about the paper. I am using this in my (fab) game to draw and animate players as they move about the game room:



I found last night that it is not possible to animate position changes of elements drawn from the path() method (which my players are). I would like to animate collisions between elements.

My plan tonight is to hide all of the frames, then draw a replacement circle that bounces. At the end of the bounce, I will remove the bounced circle and re-show one of the frames. To accomplish this, I add a third parameter to the animate() method in animate-frames—the same parameter that is in core raphaël describing the easing:
    animate: function(new_attrs, ms, easing) {
}
If that argument is not present, I will fallback to the old behavior (strict translation of coordinates). If that argument is present, then I do as I describe above:
    animate: function(new_attrs, ms, easing) {
if (new_attrs.cx || new_attrs.cy) {
var x = new_attrs.cx || this.getCenter().x
,y = new_attrs.cy || this.getCenter().y;
if (easing) {
this.hide_all_frames();
// replace the frames with a circle at the same location
var c = this.paper.circle(this.getCenter().x,
this.getCenter().y,
20);
var self = this;
c.animate({cx: x, cy: y}, ms, easing, function () {
// when the animation of the circle is done, remove
// the circle, move the frames to the end point and show
// the first frame again
c.remove();
self.translate(x, y);
self.show_frame(self.list[0]);
});

}
else {
this.translate(x, y, ms);
}
}
}
That almost works.

The circle appears, but the frames do not disappear. They stick around and keep moving.

After a bit of a search, I track the problem down to the stop() method in the Player class. Specifically, when a player stops (e.g. when it is about to bounce), the raphael object is not being told to stop:
Player.prototype.stop = function () {
//TODO -- re-enable
// this.avatar.stop();

this.x = this.avatar.getBBox().x;
this.y = this.avatar.getBBox().y;
};
Hunh. That's weird. I wonder why it is disabled....

After re-enabling, I find out why it was disabled—there is no stop() method in animate-frames. So I add one:
    stop: function() {
var frames = this.list;
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frames[i][j].stop()
}
}
I really need to break down and create a Frame class. I iterate over frames and frame elements far too often.

I will leave refactoring for another night. For now, I would be happy just to get things working.

Happily, that was the last change needed:



I could definitely make that animation a little nicer, but, for a proof of concept it will suffice. Tomorrow, I will prettyfy things a bit—both the animation and the code.


Day #241

Tuesday, September 28, 2010

Can't Animate Raphaël path Positions

‹prev | My Chain | next›

I made some good progress last night making animate-frames more raphaël.js-like. Before I push those changes back into the main repository, I would like to explore easing in the animate() method.

Ultimately, the animate() method in animate-frames is calling the translate_object() method, which animates movement with animateAlong():
    translate_object: function(frame, x, y, ms, easing) {
// offset between end coordinates and current location
var x_diff = x - frame[frame.length-1].getBBox().x;
var y_diff = y - frame[frame.length-1].getBBox().y;

for (var i=0; i<frame.length; i++) {
var obj = frame[i];
// calculate path starting from absolute coordinates and moving
// relatively from there by the offset
var p = "M " + obj.getBBox().x + " " + obj.getBBox().y +
" l " + x_diff + " " + y_diff;

// animate along that path
if (ms && ms > 50)
obj.animateAlong(p, ms);
else
obj.translate(x_diff, y_diff);
};
}
My first instinct is to add and easing parameter to animateAlong(). Sadly, according to the documentation (and the code), the method signature only takes path, ms, rotate, and callback (invoked after the animation completes).

Dang.

So maybe I can use animate() instead of animateAlong():
         // animate along that path
if (ms && ms > 50)
obj.animate({x: x + x_diff, y: y + y_diff}, ms, easing);
// ...
But when I do that, my players don't move at all. Grr.. what gives?

To find out, I break the problem down to basics. Using a raphaël paper object, r, I create a circle and animate its center x-coordinate:
c = r.circle(200, 200, 10).attr({stroke: "#333", "stroke-width": 4, "fill": '#333'})
c.animate({cx: 0}, 5000)
That works. The circle moves from 200, 200 to 0, 200 over the course of 5 seconds.

Next I try drawing an object with SVG path information—the same way that the objects inside my animations are being drawn:
o = r.path("m 27.970621,11.503807 c 0.09878,4.794487 -3.625825,9.254299 -8.244694,9.888541 C 15.282994,22.185422 10.583894,19.322284 9.1090954,14.943452 7.4780985,10.605964 9.2934491,5.2861677 13.201573,2.948285 c 3.892493,-2.53638571 9.452051,-1.6375587 12.397375,2.008774 1.523084,1.7954543 2.381825,4.1636216 2.371673,6.546748 z").attr({fill: '#090'})
o.animate({cx: 50}, 5000)
That does not work. The player stays at its original coordinates.

I can animate certain other attributes, such as the fill color:
o.animate({fill: '#00f'}, 5000)
From this, I conclude that it is not possible to animate location elements on objects drawn via paths. That is not too surprising based on my earlier investigation. Not surprising, but still disappointing.

I am not quite ready to abandon easing. I really want to use it to animate collisions (the "bounce" easing is particularly nice). Since I cannot animate-with-easing the SVG paths that make up my frames, I think that I ought to be able to hide the frames, show another object that can be animated. That is not perfect, but it ought to suffice for my purposes.

I will get started on that tomorrow.


Day #240

Monday, September 27, 2010

Better Raphaël Plugins

‹prev | My Chain | next›

Up tonight, I try to get a few more raphaël.js methods into raphael-animate-frames. This plugin for raphael.js cycles through a series of frames, giving the appearance of animating. Additionally, the frames can move together and do other things that normal raphael.js objects can. There are many raphaël things that it cannot do. I am going to start tonight by trying to add an animate() method.

The documentation for animate explains that not all attributes can be animated. I will push that to the extreme and say that only 2 elements can be animated: cx and cy (center x and center y).

Some attributes just do not make sense to be animated. Do the attributes apply to all elements in an animation frame or only some? Actually, reading through the list, I ought to be able to support many eventually, but for now, I just need cx and cy:
Player.prototype.bounce_to = function(x, y) {
this.stop();

var self = this;
this.avatar.animate({cx: x, cy: y}, 500, "bounce");
setTimeout(function(){ self.mid_bounce = false; }, 1000);

this.x = x;
this.y = y;
};
I can get a quick and dirty implementation of that by making animate() a simple wrapper around the translate() method:
    animate: function(new_attrs, ms) {
if (new_attrs.cx || new_attrs.cy) {
this.translate(new_attrs.cx || this.getCenter().x,
new_attrs.cy || this.getCenter().y,
ms);
}
}
I will not get easement by using translate(), but it will suffice for tonight.

Up next, I need animate-frames to support a node attribute so that I can get decent collision detection. That turns out to be relatively easy:
    add: function(frame_list) {
for (var i=0; i<frame_list.length; i++) {
this.list.push(this.draw_object(frame_list[i]));
}
this.node = this.list[0][this.list[0].length-1].node;
}
The this.list[0] references the first frame of elements. Using this.list[0].length-1 gives me the last elment drawn in the frame. This seems a reasonable thing—the last thing drawn in a frame is very likely going to be the most prominent feature which makes it ideal to serve at the node attribute.

With that, I can set a boolean on the node indicating that it is the "player" node. If the player node collides with another player node, then collision detection kicks in:
Player.prototype.attach_avatar = function(avatar) {
var self = this;
this.avatar = avatar;

// ...

avatar.node.is_player_circle = true;

// ...

avatar.onAnimation(function(){
// find the colliding element (c_el)

if (!self.initial_walk &&
!self.mid_bounce &&
c_el.is_player_circle &&
c_el != self.avatar.node) {
self._bounce_away(c_x, c_y);
}
});
};
That is a fine stopping point for tonight. I will pick back up with easing tomorrow.


Day #239

Sunday, September 26, 2010

My Dogfood Stinks

‹prev | My Chain | next›


Having resurrected the animate-frames fork of my (fab) game last night, I am ready to play again with my raphaël.js plugin: animate-frames. If I recall correctly, it is very much a work in progress, but is in good enough shape for a demo.

Unfortunately, the my (fab) game code has evolved significantly since last I played with this code. For one thing, the animate-frames plugin does not have a single node on which various attributes can be set:
//... 

// Mark node as player element (for collision detection)
avatar.node.is_player_circle = true;

// ...
For now, I will simply comment out references to node.is_player_circle. I can go back later to get collision detection working well.

Unfortunately, I run into a another problem—the remove() method, used when a player is dropped, is not defined in animate-frames:
Player.prototype.quit = function() {
this.avatar.remove();
this.label.remove();
delete this.x;
delete this.y;
delete this.id;
};
This, I can address relatively easily by adding a method that removes all frames being animated as well as each element in each frame:
    remove: function() {
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frame[j].remove();
};
}
}
This is browser code, so I cannot rely on forEach(). Actually, this is a indication that I ought to be using coffeescript.

At any rate, it works.

Until I hit another problem—collision detection does not work at all. Players simply pass through each other. Eventually, I track this down to the initial_walk attribute on a player. Collision detection does not kick in until the first walk in the room is complete.

The only place that I see initial_walk even mentioned as being set to false is a comment:
Player.prototype.walk_to = function(x, y) {
// ...

// TODO self.initial_walk = false after walk has started

// ...
};
It has been a while since I last fiddled with the animiate-frames stuff, so I am not even going to bother digging through the history of how I got in this state. Instead, I have a peak back in master since I know that collision detection is working in there. Sure enough, it is set:
Player.prototype.walk_to = function(x, y) {
// ...

var self = this;
this.avatar.animateAlong(p, time, function(){
self.initial_walk = false;
});

// ...
};
Grr... that (animateAlong()) is another method that I do not have in animate-frames. I can simulate what I need with setTimeout()—2 seconds after the player first starts walking in the room, wait 2 seconds then mark the initial walk as done:
  var self = this;
setTimeout(function() {self.initial_walk=false;}, 2*1000);
Sadly, that is not the last of my woes. Last up is the lack of support for the animate() method when the players bounce away from a collision:
Player.prototype.bounce_to = function(x, y) {
this.stop();

var self = this;
this.avatar.animate({cx: x, cy: y}, 500, "bounce");
setTimeout(function(){ self.mid_bounce = false; }, 1000);

this.x = x;
this.y = y;
};
Blech. I workaround this tonight by using the translate() method, but ick. This has been a tough night eating my own dog food. In order, I wanted the node attribute, the animateAlong() method and the animate() method. I am not sure how realistic the node attribute is, but I really ought to be able get the animateAlong() and animateAlong() methods in there.

Tomorrow.


Day #238

Saturday, September 25, 2010

A Fork of a Fork of a Fork

‹prev | My Chain | next›

I have a problem. A git problem.

A ways back, I got my animate frames plugin for raphaël.js working in my (fab) game. It was beautiful. Unfortunately, it was all very organic.

I forked the animate-frames stuff off a vows.js fork. It got me to the point that I could extract the animate frames out, but I never got it to the point that I could merge it back into master. I ultimately abandoned the fab.js work that drove the vows.js stuff that eventually spawned the animate frames work. But now I want just the animate frames stuff.

So how do I get that without the old fabjs and vowsjs stuff tagging along? It is only a half dozen commits, so I could cherry pick them. Since this seems like something that I will have to do again where cherry picking is not feasible (e.g. where there are many more than 6 commits involved), I think I will spend at least a little time trying to find another way.

So I head to google and find suggestions to use git merge (probably wouldn't work in my case) and, more interestingly, git checkout (it never would have occurred to me to try that).

But ultimately, I come across the advice to rebase --onto. Using that, I can rebase a branch, animate-frames in this case, to master, starting from the vowsjs fork. The command for that is blessedly simple:
cstrom@whitefall:~/repos/my_fab_game$ git rebase --onto master vowsjs animate-frames
First, rewinding head to replay your work on top of it...
Applying: Pull in the latest raphael-animate-frames
Applying: Switch room to raphael-animate-frames for drawing player avatar.
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
Auto-merging javascript/room.js
CONFLICT (content): Merge conflict in javascript/room.js
Failed to merge in the changes.
Patch failed at 0002 Switch room to raphael-animate-frames for drawing player avatar.

When you have resolved this problem run "git rebase --continue".
If you would prefer to skip this patch, instead run "git rebase --skip".
To restore the original branch and stop rebasing run "git rebase --abort".
The command may be simple, but a lot has gone on in master since the animate-frames work. Happily that turns out to be the only problem. I address the issue in the javascript/room.js, put it back into the rebase staging area with git add javascript/room.js, then send rebase back on it merry way:
strom@whitefall:~/repos/my_fab_game$ git add javascript/room.js
cstrom@whitefall:~/repos/my_fab_game$ git rebase --continue
Applying: Switch room to raphael-animate-frames for drawing player avatar.
Applying: Use the raphael-animate-frames.js lib
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
Auto-merging html/board.html
Applying: Replace circle avatar calls with svg-frames equivalent
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
Auto-merging javascript/player.js
Applying: Use latest raphael-animate-frames
Applying: Use center() in raphael animate frames
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
Auto-merging javascript/player.js
With that, I have my animate-frames branch believing that it was forked from master only a few days ago:



The whole point of this is so that I can play with animated players on top of my node-dirty work from last night. I remain fairly certain that I am ready to move on with node-dirty instead of CouchDB, but a bit of play will help get the remaining doubt down to an acceptable minimum.

So I create a dirty-svg branch (naming is even more fun with dirty than with CouchDB!) and merge the animate frames branch into to it:
cstrom@whitefall:~/repos/my_fab_game$ git merge animate-frames 
Merge made by recursive.
html/board.html | 1 +
javascript/player.js | 30 +++-----
javascript/raphael-animate_frames.js | 136 ++++++++++++++++++++++++++++++++++
javascript/room.js | 58 ++++++++++++++-
4 files changed, 202 insertions(+), 23 deletions(-)
create mode 100644 javascript/raphael-animate_frames.js
Since both are (now) very recent forks from master, the merge goes through without objection. And, just like that, I am ready to start playing with animated-frame players on top of a node-dirty backend.

Tomorrow.


Day #237

Friday, September 24, 2010

Down and node-dirty

‹prev | My Chain | next›

Having exhausted (for the moment) my exploration of the upcoming fab.js version 0.5, I feel ready to move onto the next big thing in my (fab) game. First, I merge my topic branch back into master and push everything to the github repository. With that, I am ready to get dirty:
cstrom@whitefall:~/repos/my_fab_game$ git co -b dirty
Switched to a new branch 'dirty'
Yup. In this branch, I am going to replace my beloved CouchDB with Felix Geisendörfer's node-dirty as the player store.

First up, I install it via npm:
npm install dirty
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm info fetch http://registry.npmjs.org/dirty/-/dirty@0.9.0.tgz
npm info fetch http://registry.npmjs.org/gently/-/gently-0.8.0.tgz
npm info install dirty@0.9.0
npm info install gently@0.8.0
npm info activate dirty@0.9.0
npm info activate gently@0.8.0
npm info build Success: dirty@0.9.0
npm info build Success: gently@0.8.0
npm ok
It ends with "ok" so it worked :)

Next, I work through the player store object replacing node-couchdb calls with node-dirty calls. The player get() method used to be a wrapper around the node-couchdb getDoc() method:
   get: function(id, callback) {
Logger.debug("[players.get] trying to get: " + id);
db.getDoc(id, function(err, res) {
if (err) {
Logger.warn(JSON.stringify(err));
}
callback(res);
});
}
Now it can send the results of a node-dirty get() directly to the supplied callback:
   get: function(id, callback) {
Logger.debug("[players.get] trying to get: " + id);
callback(db.get(id));
}
Really, there is no need for the get() method to be async (callback-based) anymore. It could just as easily block for the node-dirty get(). I leave it as-is to minimize API changes—at least for now.

In addition to getting players, I need to update the saving of them as well. The node-couchdb saveDoc():
        db.saveDoc(player);
...becomes a node-dirty set():
        db.set(status.id, player);
In the node-couchdb version, I could rely on the id attribute in the document to store the proper ID in CouchDB. In node-dirty, I need to be explicit.

Lastly, I need to be able to drop players. In the node-couchdb version, I had to get the player before it could be removed (to satisfy optimistic locking):
  drop_player: function(id) {
Logger.info("players.drop_player " + id);
this.faye.publish("/players/drop", id);

this.get(id, function(player) {
Logger.debug("[players.drop_player] " + inspect(player));
if (player) db.removeDoc(id, player._rev);
});
}
There is no need for that in node-dirty. To be precise, there is no support for locking in node-dirty, which could certainly prove an issue at some point. For now, I will put that concern aside and remove players with a simple rm() call:
  drop_player: function(id) {
Logger.info("players.drop_player " + id);
this.faye.publish("/players/drop", id);
db.rm(id);
}
With that, I am ready to fire up my game. Sadly, I find:
Caught uncaughtException: Error: Cannot find module 'constants'
at loadModule (node.js:275:15)
at require (node.js:411:14)
at Object.<anonymous> (/home/cstrom/.node_libraries/.npm/dirty/0.9.0/package/lib/dirty/dirty.js:6:17)
at Module._compile (node.js:462:23)
at Module._loadScriptSync (node.js:469:10)
at Module.loadSync (node.js:338:12)
at loadModule (node.js:283:14)
at require (node.js:411:14)
at Object.<anonymous> (/home/cstrom/.node_libraries/.npm/dirty/0.9.0/package/lib/dirty/index.js:1:80)
at Module._compile (node.js:462:23)
My uncaught exception handler catches another one:
// Don't crash on errors
process.on('uncaughtException', function (err) {
console.log('Caught uncaughtException: ' + err.stack);
});
It prevents the crash, but the question remains: how do I prevent the exception in the first place. If node cannot find the 'constants' module, perhaps I can install it from npm?
cstrom@whitefall:~/repos/my_fab_game$ npm install constants
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm ERR! ! 404 !
npm ERR! ! 404 ! It seems like 'constants' is not in the registry
npm ERR! ! 404 ! You should bug the author to publish it.
npm ERR! ! 404 !
npm ERR! Error: 404 Not Found: constants
...
npm not ok
Guess not.

I recently discovered that yes, you can read the node.js source code, so that is what I do. And I find that ENOENT can be accessed from process.binding('net'):
node> process.binding('net').ENOENT
2
After replacing the constants.ENOENT references with process.binding('net').ENOENT, everything works! So I do the right thing and submit a pull request for the real node-dirty.

That one minor (and easily resolved) issue aside, the move to node-dirty was pure win. I no longer require a separate CouchDB server to run my (fab) game, and it seems as though it will be more than sufficient to meet my needs—the game will crap out long before 1 million players start to impact node-dirty.

I am still a bit concerned about record locking, but I will leave that question for another day.

Day #236

Thursday, September 23, 2010

Conditional (fab) HTML Apps

‹prev | My Chain | next›

Up tonight, I would like to get rid of the idle timeout alert() in my (fab) game. I have already done this once when I was playing with express. Now I would like to do the same on version 0.5 of fab.js.

First up, I update the good-bye function in the client to redirect (instead of alert()-ing) to the login page with an appropriate message:
    var goodbye = function() { 
window.location = window.location.protocol + '//' +
window.location.host +
window.location.pathname +
'?message=You have been logged out.' ;
};
player_list = new PlayerList(me, room, {onComplete: goodbye});
In the express.js version of the code, I had used flash/session to accomplish this. There is no flash in fab (yet), so query strings will have to suffice.

With that, I need to grab the message out of the query string and insert it into the HTML. Since I am using (fab) HTML apps to render the HTML, I need to make the message display a (fab) app as well:
  (route, /^\/board/)
( HTML )
( head )
( BODY )
( info )
( FORM, { id: "login", method: "get" } )
// form stuff
()
( DIV, { id: "room-container" } )()
() // BODY

() // HTML
()
Fortunately, I am getting pretty good at this:
function info(write) {
return write(function(write, head) {
Logger.info(inspect(head));
return write;
});
}
Well, maybe not too good. I know how to write a (fab) app that gets called with a response (write) stream. I also know that returning that response stream with a callback will allow any other upstream apps (e.g. the FORM and other HTML apps) to write to the response stream as well. Lastly, I know that the callback in this situation is called with the response stream, the request header (head) and the request body (which I do not need).

What I do not know (or at least do not remember off the top of my head) is where in the head the URL and query string are buried. To find out I access the /board resource with a query string of foo=bar and see what Logger.info tells me:
[INFO] { method: 'GET'
, headers:
{ host: 'localhost:4011'
, connection: 'keep-alive'
, accept: 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
, 'user-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.8 Safari/534.7'
, 'accept-encoding': 'gzip,deflate,sdch'
, 'accept-language': 'en-US,en;q=0.8'
, 'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}
, url:
{ href: '//localhost:4011/board?foo=bar'
, slashes: true
, host: 'localhost:4011'
, port: '4011'
, hostname: 'localhost'
, search: '?foo=bar'
, query: 'foo=bar'
, pathname: ''
, capture: []
}
}
Ah, in the url.query property. I know how to extract query parameters. node.js provides a querystring parse function to accomplish this:
function info(write) {
return write(function(write, head) {
var q = require('querystring').parse(head.url.query);
if (q.message)
write('<div id="info">' + q.message + '</div>');

return write;
});
}
And it turns out, that is all I need. When the idle timeout is broadcast, the goodbye function is called in the client, which redirects to the login page with a message and I see:



Easy enough! I think I am finally getting the hang of the new version of fab.js.

Day #235