DominicHamon.com

Life is like a grapefruit

Getting started with DartBox2d

This post is deprecated. Please see this post for the latest version.

The latest Dart library to be released is one that might see a fair bit of use, if the Java and JavaScript versions are anything to go by. DartBox2d is the latest port of the immensely popular 2d physics engine seen in games across the web. It has a very similar interface to the Java version, so getting started shouldn’t be too hard for anyone familiar with that version.

That being said, here’s how to put together a simple application.

Getting the library

Go here and follow the instructions to get a local copy of the code.

The HTML page

Next, you need an HTML page to host the application. A simple boilerplate would look something like:

<html>
  <body>
    <script type="text/javascript" src="tutorial.dart.js"></script>
  </body>
</html>

The Dart code

At the top of the dart file, you need to name your application and import any libraries you want to use:

#library('tutorial');
#import('dart:dom');
#import('[path_to_dartbox2d]/lib/box2d.dart');

Now create a class for your application and a simple main method:

class Tutorial {
  ...
}

void main() {
  Tutorial.main();
}

This simple main method is what will be called when your application starts. It is calling a static method on your class that should now look something like:

class Tutorial {
  static void main() {
    final app = new Tutorial();
    app.run();
  }

  Tutorial() {
    initializeWorld();
    initializeCanvas();
  }
}

All we have left to do is to define the two initialization methods and the run method. First, let’s initialize the world:

class Tutorial {
  ...

  static final int BALL_RADIUS = 1;

  World world;

  void initializeWorld() {
    // Create a world with gravity and allow it to sleep.
    world = new World(new Vector(0, -10), true, new DefaultWorldPool());

    // Create the ground.
    PolygonShape sd = new PolygonShape();
    sd.setAsBox(50.0, 0.4);
      
    BodyDef bd = new BodyDef();
    bd.position.setCoords(0.0, 0.0);
    Body ground = world.createBody(bd);
    ground.createFixtureFromShape(sd);

    // Create a bouncing ball.
    final bouncingBall = new CircleShape();
    bouncingBall.radius = BALL_RADIUS;

    final ballFixtureDef = new FixtureDef();
    ballFixtureDef.restitution = 0.7;
    ballFixtureDef.density = 0.05;
    ballFixtureDef.shape = bouncingBall;

    final ballBodyDef = new BodyDef();
    ballBodyDef.linearVelocity = new Vector(-2, -20);
    ballBodyDef.position = new Vector(15, 15);
    ballBodyDef.type = BodyType.DYNAMIC;
    ballBodyDef.bullet = true;

    final ballBody = world.createBody(ballBodyDef);
    ballBody.createFixture(ballFixtureDef);
  }
}

And now we’re ready to initialize the canvas:

class Tutorial {
  ...
  static final int CANVAS_WIDTH = 900;
  static final int CANVAS_HEIGHT = 600;
  static final int VIEWPORT_SCALE = 10;

  HTMLCanvasElement canvas;
  CanvasRenderingContext2D ctx;
  IViewportTransform viewport;
  DebugDraw debugDraw;

  void initializeCanvas() {
    // Create a canvas and get the 2d context.
    canvas = document.createElement('canvas');
    canvas.width = CANVAS_WIDTH;
    canvas.height = CANVAS_HEIGHT;
    document.body.appendChild(canvas);
    ctx = canvas.getContext("2d");

    // Create the viewport transform with the center at extents.
    final extents = new Vector(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2);
    viewport = new CanvasViewportTransform(extents, extents);
    viewport.scale = VIEWPORT_SCALE;

    // Create our canvas drawing tool to give to the world.
    debugDraw = new CanvasDraw(viewport, ctx);

    // Have the world draw itself for debugging purposes.
    world.debugDraw = debugDraw;
  }
}

Now, all that’s left is to start the world running:

class Tutorial {
  ...
  static final num TIME_STEP = 1/60;
  static final int VELOCITY_ITERATIONS = 10;
  static final int POSITION_ITERATIONS = 10;

  void run() {
    window.webkitRequestAnimationFrame((num time) {
      step(time);
    }, canvas);
  }

  void step(num time) {
    // Advance the world.
    world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);

    // Clear the canvas and draw the frame.
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    world.drawDebugData();

    // Request another animation frame.
    window.webkitRequestAnimationFrame((num t) {
      step(t);
    }, canvas);
  }
}

Once you’ve put all this together, you’re ready to compile it to JavaScript.

I prefer the command-line frog compiler, but DartBox2d also compiles cleanly with dartc with warnings as errors and fatal type errors enabled, so feel free to use either. You can also use the Dart Editor to build your application, and that’s almost certainly the best route to take. Refer to the Dart language site for more details.

Once you’ve compiled to JavaScript, make sure that your html file is referencing the generated file correctly and load it up in a browser. If all went well, you should see a green box with a peach ball bouncing on it.

Posted on 2012/01/11 in web | Tagged box2d, dart, dartbox2d, physics | Leave a comment

It’s the little things

Today, Google announced a new Beta release of Chrome. This is not unusual; it happens every six weeks or so, but in this case the announcement blog post was authored by me.

That really isn’t a big deal in the grand scheme of things, I know; there’s stuff all over the web with my name on. But this is the first time I get to be a part of the public face of Google, and I’m so proud to be working here that it’s a really big deal to me.

I could have written this as part of my Google+/Twitter post pointing to the Chrome blog, but that felt too much like bragging. Hopefully by posting it to my obviously personal site I can retain some appearance of humility. Only an appearance, mind you, because I’m an author on the Chrome blog and you’re not, nyer, nyer. Ahem.

Posted on 2012/01/05 in personal | Tagged chrome, google | Leave a comment

Porting Colossal Cave Adventure to Native Client

Native Client (NaCl) is a new technology built in to Chrome that allows native code (read C++) to be compiled into a form that is then executed within the browser. Several impressive ports have already been completed, including ScummVM, OGRE, and Unity 3D. A host of other open source libraries have also been ported and are available in the naclports repository.

I am really excited about what this could mean for the future of the web as a platform for technology; even old crusty low-level coders like me can get in on this internet thing all the young people are talking about. I had the opportunity recently to take part in a hackathon centred around Native Client and took the opportunity to port a game that should need no introduction: Colossal Cave Adventure.

For those who just want to try it out, you’ll need Chrome 14 as a minimum and you can find it in the Chrome web store right here. If you just want to see the source, which is open of course, you’ll find that here. Please understand that this was written over the course of a few hours so it is not necessarily as elegant a solution as it might be given more time. Perhaps I will return to it and clean it up later.

There were a number of hurdles I had to overcome to complete this port and it might be interesting to others so this post will cover the issues and my approaches to them.

There were three key components to getting the code to work under Native Client:

Static data

The problem

The original source contains a utility advent0 that takes the text messages from a set of .txt files and creates look-up tables that match a message with a byte offset. At run-time, these look-up tables are used to seek through the .txt files and read the message out using fseek and fread. This is not feasible under Native Client as this interface to file I/O is not (yet?) supported. Other ports have successfully used forms to allow users to upload files that are required, but that also is not applicable to this app.

The solution

A new utility was created (advtxt_to_c) that converts the .txt files into arrays of c-style strings. These are then statically linked into the executable so that instead of using byte offsets, the run-time can access the message array directly. This does increase the final executable size, but only by about 64kb. For reference, the total executable size is on the order of 4Mb, most of which is library code.

stdin/stdout

The problem

The original source obviously relies heavily on printffputc, etc to write to stdout. Under Native Client these will end up in the console logs rather than appearing on screen. Using fgets and scanf to get input from the user are equally incorrect.

The solution

The solution to this was to write a thin wrapper around any console output. At this point, I also split the output into three:

All of these functions call through to the Native Client module which then calls through to JavaScript methods.

Screen printing is used whenever the output should go to the, well, screen and in this case is appended to a textarea on the host HTML page. Console output is redirected to the JavaScript console where they can be read using the Developer Tools built in to Chrome, and error messages are added to a special span on the host HTML page that shows up red and fades over time. The game is also restarted whenever an error is produced, which is a far better approach than the original exit(-1).

Input from stdin was fixed by adding a method to the Native Client module that would call a callback when an ‘input’ message was passed from the JavaScript with a string parameter that comes from a text box on the HTML host page. This required some further changes as an synchronous call becomes an asynchronous call. See the next section for more on that.

Synchronous calls

The problem

As well as console output, the original source depended on fgets for reading user input. This is a synchronous call which has no analogue on the Native Client side. In fact, the whole game was originally written with an assumption that the game loop would block waiting for user input which, well, doesn’t work out all that well.

The solution

As mentioned above, fgets has been replaced by a call to the Native Client module that registers a callback to be called when the user submits text through the input control on the HTML page. The places that called fgets and assumed a synchronous return therefore had to be split into two functions. In some cases, they had to take in function pointers to call after the input had been received.

The main gameloop, that was essentially while (true) { turn(); }, has been replaced by a single call to the turn function that contains a single tick of the gameloop. When input is expected and received, a callback is called that once again calls the turn function.

Posted on 2011/09/20 in web | Tagged chrome, NaCl, Native Client | Leave a comment

I think I’m going bald

There comes a time in most men’s lives when they look at their father’s and grandfather’s hair lines and think about when they will lose their hair. I was pleased to see that the men on my father’s side of the family maintained a strong widow’s peak, though their hairline receded. My hair started receding, and my forehead growing, since my early teens, so I felt pretty confident that I would at least keep most of my hair.

My wife and I had a deal that should I start to lose my hair, she would let me know when it was time to start shaving it off to retain some dignity. About six months ago, she started to look at my hair and quirk an eyebrow. I knew it was time for one more hairstyle before never being able to support one again. So for once I went in to a hair dresser with an idea of a hair style I wanted, and left feeling really good about my hair. A couple of months later I went in again and noticed that my hair dresser was taking a lot more effort to work my hair forward. I left feeling significantly worse.

This week, I realised that the front of my hair, what I thought would be the strong peak of my hair into old age, had become fuzzy and thin. Before it could become isolated into the dreaded unicorn style, it was time to take action.

This is the last hair style I will ever have, and I’m ok with that.

Posted on 2011/05/14 in personal | Tagged dominic | 3 Comments

Happy Muttville Senior Dog Rescue Day

It’s Muttville Senior Dog Rescue Day in the City of San Francisco.

As a failed foster parent of a Muttville rescue 1 I can’t recommend or praise Muttville highly enough for the work they do with senior dogs who have been abandoned by their families.

Rescuing a senior dog can be fraught with difficulty as they often come with problems, but it can also be extremely rewarding as all they really want is warmth, love, and food 2. Muttville recognises this and works hard with their volunteers and foster families to find homes for these forgotten old pooches.

It is wonderful that the City of San Francisco has chosen to celebrate and recognise their hard work, and I’m proud to be a part of the Muttville community.

  1. Failed as in I ended up adopting the little bugger. ↩︎
  2. And shoft toilet paper, if Cohen is to be believed. ↩︎

Posted on 2011/05/10 in personal | Tagged dog rescue, muttville, pooch | Leave a comment

Why I am a terrible reviewer

I like everything. I mean, I don’t love everything, but I get enjoyment out of almost everything I experience, whether it’s a book, comic, album, or movie. Of course, I enjoy some more than others, and I revisit some of them again and again, but I find it really hard to name something that I actively dislike.

This is evident in my ratings of songs in iTunes, my ratings of film and TV on Netflix, and the ratings I assign to things I review at Guerrilla Geek. Now part of that is probably selection bias; I’m likely to watch a film or listen to an album that I have either been recommended or that’s from an artist I know that I like already. This also means I am not experiencing completely new things as much as I tend to stick with what I know which is something that I moan about to friends often, but rarely do anything about. As I’ve grown older the time I am able to put in to seeking out new music or new authors has shrunk quite a bit.

 

 

My hope was that the digital revolution of music and written media would once again enable me to browse through lists as I once would browse through records and books at my local stores. This has not been the case, and I’m not sure it ever will be, due to the lack of tactile feedback: There’s something about running ones finger over the spines of books or flicking CD cases that is lost when scrolling through a list on a screen.

The same is true of video games: If I spend a couple of days at a weekend engrossed in a game, as I used to, I enjoy it at the time but feel like I missed out on an opportunity to do something else once I’m back at work. I have therefore started to focus on playing demos of games or Arcade titles (and I’m not the only one); bite-size chunks of video games that give me the enjoyment of playing a game without the commitment that sucks away my evermore precious free time. I had a conversation the other day with someone else of about my age who does a job similar to me, and we bemoaned the hours we put into building and upgrading PCs just to play the latest game. Both of us have forsaken that world for one of simplicity and ease — that of consoles and downloadable titles — and I think this is a common trend.

The time that I spend listening to music and reading books has not changed significantly, however. I think this is because listening to music is something that I can, and will, do while doing other things. Walking the dogs, exercising, traveling to work, even while I’m at work, are all opportunities to listen to music. But rarely new music. New music demands respect from me and a focus of attention that I can’t give when multitasking. I still like to read album notes when exploring an album for the first time, and I will never ever put it into shuffle rotation until I’ve listened all the way through it at least once. I am trying Pandora as a way to find new music, but I get frustrated when there’s a song that I really like and I can’t easily click through to the whole album and listen start-to-finish.

Books, of course, demand attention. The difference there is that reading a book is my ground state. When I have nothing else to do, I will turn to a book first. For a while this wasn’t true: I would open my email, check Twitter, check my news aggregator, check Twitter again… But I’m back on the books again mostly thanks to the convenience of owning a nook with a sizable chunk of my book library installed on it. I have even started to use the nook to find new books. It’s very easy to grab a free sample of a book and download it, and on finding that it’s a good read, to buy it with a single click. It still feels very clinical to me though and I find myself going to my local book store to find new books instead, but just buying them on the nook. And then I feel guilty for not patronizing the local book store. At least I’m finding new things again.

But even when I’m reading something to review it rather than having picked it myself, no matter what it is, I enjoy it. I can tell when something isn’t to my taste, but I have a positive experience reading or listening. When I come to write the review, I will find things to like about it much easier than I find things to dislike. Perhaps I’m just not critical enough to be a good reviewer, or maybe those that are more critical have to try hard to find things to criticize too. I do think that my opinions are skewed by the sheer joy I get from devouring media.

I haven’t decided yet if it’s a problem that I’m not more critical of things and that I seem to enjoy everything. It makes my life a happy place to be even if it makes me an ineffectual reviewer. Just don’t expect many ratings below three stars in my reviews.

Posted on 2011/04/26 in personal | Tagged books, movies, music, reviews | Leave a comment

Jag kan tala Svenska

I haven’t written anything here in a while because my creative juices have been drained by my new position writing over at Guerrilla Geek.

Last week I was in Sweden. Ostensibly for a family thing, but also to take a break and spend some time with Mirto‘s family. I’ve been there once before, about nine years ago, and both times I’ve felt oddly at home there. I say oddly as I have no connection to Sweden other than my wife having been born there. Given that I’m blonde with blue eyes, and have familial connections to both Yorkshire and Normandy, there’s a good chance that far back in my genealogy someone in my family tree encountered a Viking in a, you know, biblical manner. However it’s unlikely that my genes felt the connection.

On the subject of having the appearance of a Swede1, there were a few tense moments during the week where a native would speak to me in Swedish expecting me to understand, but speak to my wife in English assuming she was a tourist. An arctic wind blew through the room during those moments.

There are some similarities in the environment of Stockholm to where I grew up in Jersey. It too had granite cliffs and was surrounded by water and the constant crying of seagulls was a regular sound throughout the year. Of course, it was a little warmer where I grew up, and I spent more time on the beach than I would be comfortable doing in Sweden. The population of Stockholm is approximately the same as my home, though that population is focused in an urban centre rather than spread over a rural island.

Don’t get me wrong, I love living in San Francisco and cannot see a time when I’ve done everything there is to do here or get bored with the city. And if I ever do, well there’s a big ol’ country out there to explore. However there is something about Sweden that just feels more like home. Maybe it was the rain and sense of gentle irony.

 

  1. As in a Swedish person, not a rutabaga ↩︎

Posted on 2011/04/20 in personal | Tagged sweden, vacation | Leave a comment

eBook user Bill of Rights

This post started as a comment on this post, but it became really long, so you should read that first and then come back to read my thoughts. I’ll wait.

I have a problem with the approach outlined in this post. I understand the issues, and am frustrated that media ownership has become media leasing across the board from music, to movies, and now books. I want to own something when I pay money for it unless it is explicit that I am entering into a rental agreement. Electronic books, digital copies of movies bundled with Blu-Ray copies, and music from online retailers, are not advertised as rentals but as purchases. Of course there is the small print, the EULA, the Terms and Conditions, that to varying degrees specify the rights of the purchaser in regards to use of the product, but I am not aware of any that are explicitly rental agreements and that is exactly what they are becoming.

So on to books.

Let’s be clear: Traditional books suffer from the same copyright issues as digital media. There is nothing stopping me from buying a book, reading it, copying huge chunks of it, and publishing my own book plagiarizing the work. Similarly, I can, should I have the time and patience, copy the pages, bind them, and sell them myself. Or is there? Of course there is. There are existing legal processes in place for dealing with copyright infringement outside of the digital realm. It is important that we work to make publishers and distributors see that there is no difference between the traditional and digital spaces. It may be harder to track the perpetrator of copyright infringement, and it may be easier for the crime to be perpetrated, when dealing with digital media but the legal framework is already there. Changing the relationship between the publisher and the purchaser by setting limits on lending or sharing, or limiting how I can store and access the media I have purchased is equivalent to, and as ridiculous as, replacing bookshops with libraries and printing books using ink or paper that deteriorates on each read or after a fixed amount of time.

If any publisher tried to do this to traditional books they would be faced with an almighty uproar from the public and laughed out of business.

So on to the eBook User’s Bill of Rights.

I applaud Sarah Houghton-Jan’s efforts to raise the volume of protest regarding this issue. I applaud all bloggers and writers who are trying to raise awareness of this issue. But I do not think this is the right way to go about it for one simple reason:

Traditional media consumers do not require a Bill of Rights.

By setting up a Bill of Rights we are strengthening the belief that digital media consumption is different to traditional media consumption and requires special treatment. This is one of the foundations for the argument for Digital Rights Management and is a false premise. The right way to push back on this issue is to show that digital media and traditional media are equivalent and the users’ rights are equivalent. We do not have or need a Bill of Rights for traditional media and should not need one for digital media.

I agree with the central tenet of Houghton-Jan’s Bill of Rights, and I am also sympathetic to those who suffer copyright infringement, but it is important to find the similarities between traditional and digital media rather than highlighting the differences. We need to show how ridiculous a concept DRM is and encourage the legal system to find ways to protect ownership of copyright that make sense for all media irregardless of delivery system.

That, or maybe it’s time to question the notion of copyright as a fundamental truth.

 

Posted on 2011/02/28 in personal | Tagged books, drm, ebooks, rant | Leave a comment

Don’t believe what you read

I’m an atheist. More than that, if I find out that you believe in a higher power there’s a good chance that I will think less of you. I’ve tried not to, really I have, but if I learn that you need to believe in a supernatural being to make sense of the world instead of allowing yourself to see how truly magnificent it all is and how wondrous the rules that govern our Universe are to make it all possible without requiring some bearded engineer in the sky, I can’t help it.

This is why I currently have a problem at work. I work with some of the smartest people I’ve ever met. I’ve thought that before at previous jobs but, no offense to those of you I’ve worked with in the past, they had nothing on the people I interact with every day. Around my offices are whiteboards, presumably meant for collaborative discussions or maybe just for janitors to solve our problems for us, I don’t know. The one nearest me, however, is being used by someone to spread The Word. Missives such as “God is love” and “Jesus loves you” have been appearing daily 1.

So what can I do? I don’t know who’s doing it so I can’t have a chat with them, and even if I did I don’t expect them to understand my offense. I could belittle the comments by adding my own snarky comments, but that’s likely to just create contention rather than making the author understand anything. I could erase them, but it’s not my place to censor others, and in previous days when the board has been erased the author has just re-written them. I have been trying to ignore it but it really gets to me every day that I walk past and see it.

This has come to a head today because the people I sat next to at breakfast said grace before eating. I know, I know, it’s not like they said or did anything deeply offensive in the grand scheme of things, but seeing and hearing that ritual today, in a workplace built on science and rationality, when I’m already on edge thanks to the writings, seemed more than anachronistic; it seemed illicit, even subversive.

It’s entirely possible that I’m massively over-reacting and just need to shake my head and walk on by. However, I wonder what the reaction from others would be if instead of “God” or “Jesus” it said “Allah” or “Mohammed”.

I also realize in writing this that I am somewhat hypocritical, though I can reason my way out of it to protect my ego. A couple of months ago some Buddhist monks were in the building creating and destroying a mandala. I took no offense to their presence and certainly enjoyed the beauty of their creation. Why should I be more offended by Christian messages on a white-board than by a more visible presence of monks performing a multi-day ritual? My reasoning is that what the monks were doing was spiritual to them, but could be seen in non-religious tones by me. The messages on the white-board, however, are clearly an effort to force religion into peoples’ lives.

I think I’m going to continue to do nothing but rant quietly in my corner of the internet. Besides, if I can’t write about this stuff on my blog, where can I write about it?

  1. The most recent one refered to 2012 as “the End”. ↩︎

Posted on 2011/02/18 in personal | Tagged religion, work | 1 Comment

My traveling companion

It was nine years ago today that @mirtos and I met. Not for the first time, that had been two years earlier, but this time with an understanding that we were going to spend some time together, getting to know each other.

Fast forward five years and we’re living in Vancouver and getting married, in the front room of our apartment, in our socks.

Fast forward another two years and we’re living in San Francisco, having been in Singapore for most of the intervening time, pursuing new careers and sharing an apartment with two dogs.

It has been a crazy adventure but I wouldn’t have enjoyed it as much, or even gone on it, without my best friend, who happens to be my wife, to share it with.

Happy anniversary doesn’t even come close.

Posted on 2011/02/15 in personal | Tagged anniversary | Leave a comment

Recent Posts

Archives

Search

Search

Copyright © Dominic Hamon 2021. WordPress theme by Ryan Hellyer.