PhysicsToy productivity

I’ll just admit it – I hate writing CSS. Therefore, I baked Twitter Bootstrap into PhysicsToy. The result is prettier and gives more of a tool feeling.

At the same time I shuffled around the menus. Before, all menus were stacked in a hierarchy and it became hard to use. The new version has a context based left menu box, and it is far superior to a hierarchy.

To get the context menu working, I put some work into the selection system. When clicking on the WebGL canvas, the coordinates are converted to physics space, then I do an overlap test to check if something in the physics world was hit. If this is the case, it’s reported to the outer angular app, which adds the item to a selection list. It will update the context menu accordingly, and tell the WebGL renderer to draw borders on the selected items.

If two bodies are selected, the context menu shows buttons for adding a constraint or a spring. This is much more useful than creating a spring and then go through two body lists to find the connected bodies.

Mouse dragging does not work yet – however arrow key moving works. Even if several bodies are selected.

I also added duplication – useful if you need to create many similar bodies.

All of these new features speeds up the workflow in PhysicsToy. Go create something.

Share Button

Holy cow, I made an Android app!

Been thinking of releasing a game on Google Play for a while and I finally did it! I made the game in Goo Create during the last goofy friday and released it as an app the day after.

The game is called Tap Truck and the goal is to drive a monster truck to the finish line without tipping over.

Get the app on Google Play or play it in your browser.

And now the tech part. I exported the project from Create as a webpage. Slightly modified it and uploaded it to Ludei online compiler. I got an .apk file back which I could sign and upload to Google Play.
Should make a tutorial for this. Let me know if you’d like that!

Share Button

New projects page!

I found myself showing Vines when trying to elevator pitch myself. Mini videos are great for show the gist of a product. Therefore, I compiled most of my recent Vines to gif and collected them here.

Skärmavbild 2015-03-22 kl. 14.08.47

Share Button

Making Vines on OSX

I recently got a few questions on how I make and upload my screencaps to Vine. Here’s the recipe!

1. Screencap using QuickTime

QuickTime on OSX has support for video screencaps. Open QuickTime and go to File / New screencap. Pick a part of your screen and press record. Make sure that your screen selection is nearly square for the best vine experience! Also, make sure that width >= height, otherwise Vine won’t accept it.

To get an almost square selection, I resize my browser window with Chrome devtools open until I see that the inner browser width equals the inner height. Then I make the screen selection for the video.

Making a square screencap

2. Trimming

It’s easy to trim the video in QuickTime. Just press command+t and you can use the UI to trim your video. Make sure that the total time of the video is less than 6.5 seconds.

QuickTime trimming

3. Exporting

Usually it’s okay to export in 1080p, but make sure that you don’t pass the max file size of 5Mb. Click File / Export / 1080p… and see what you get.

Note that if you choose to remove the sound from the video (see next step), the file size will be very small.

4. Optional: removing sound

Sometimes sound is not needed in the Vine. I use ffmpeg with the following command to lower the volume to zero:

ffmpeg -i -af 'volume=0' -strict -2

5. Upload to Vine using VineClient

You can upload the Vine using the VineClient add-on for Google Chrome. Install, log in, press Upload and follow the instructions.

Note that if you check the “Keep aspect ratio” checkbox, you’ll get black stripes at top and bottom of your Vine. Uncheck it if you know that your video is nearly square.

6. Sharing on Twitter

Don’t make the mistake of sharing to Twitter via VineClient. In that case your Vine will not get displayed inside your tweet. The reason for that is because VineClient uses an own Vine URL that Twitter doesn’t recognize. Instead, go to, find your Vine there and share it.

Vine in Twitter

Note that the Vine URL in the tweet got hidden! This only happens if you put the URL last in your tweet.

That’s all! Now go make some awesome Vines.

Share Button

p2.js progress!

My 2D physics engine has gone a long way since I started the project on github. It’s been integrated in one of the biggest 2D HTML5 game frameworks, Phaser. It’s been starring in the official Google IO experiment for 2015. I’m just very happy and wanted to express it.

Share Button

PhysicsToy – halfway there…

Recently, I’ve been working on a 2D physics editor called PhysicsToy. It makes it possible to create these kinds of simulations, without coding:

Before I get bored and want to start a new cool hobby project, I wanted to report the current status of the web app.

Frontend: Angular.js and Pixi.js

I used the p2.js debug renderer and polished it up a bit. Then I added some Angular.js magic. I’ve wanted to learn Angular for a while, and PhysicsToy was a great project to use it in. I hooked up Angular and connected it to a simple list-like menu. Then added some code for updating the p2.js world as the angular data changes. Viola, PhysicsToy was born.


Backend: Node.js and Postgres on Heroku

Another thing I wanted to try was Postgres. I’ve been using MySQL in other projects, but why not try something new, and at the same time choose open source.
Postgres didn’t let me down. It offered a JSON data type, which is convenient for my Angular scene data. Postgres seems more consistent and in general more thought through than MySQL, even though they are based on the same SQL language.

Before pushing the data to Postgres, I do some validation using JSON-schema. I use an interesting solution for version handling of the JSON: I store the scene data as it is and never upgrade it in the database, but I do on-the-fly upgrading when serving to the clients. The benefits of this solution are that the original scenes can be in all servers forever. And it’s ideal when the app is under development, with a constantly changing data model. The only bad part is that the upgrading takes some server juice.

Had a fun time coding this, I hope that it will grow to something big!

Share Button

Upgrading to OSX 10.10 Yosemite

When upgrading my Macbook Pro 15″ Retina to Yosemite, Homebrew, Postgres and RabbitMQ broke. But, they were quite easy to get running again.


If you didn’t upgrade homebrew before you upgraded to Yosemite (why should you?), you might have a broken homebrew. None of the brew commands work. To get it working again, follow these steps.

First, update homebrew via git:

cd /usr/local/Library;
git pull origin master;

Next, use homebrew to update and clean your installed packages:

brew update;
brew prune;
brew doctor;

Homebrew should now work.



When installing Yosemite, some Postgres folders are removed for some reason, and these folders are required for Postgres to run.

$ postgres -D /usr/local/var/postgres
FATAL: could not open directory "pg_tblspc": No such file or directory

To fix this, and prevent Yosemite to remove the folders again, run:

mkdir -p /usr/local/var/postgres/{pg_tblspc,pg_twophase,pg_stat_tmp}/
touch /usr/local/var/postgres/{pg_tblspc,pg_twophase,pg_stat_tmp}/.keep



RabbitMQ would not start for me, for some reason.

Status of node 'rabbit@xxx' ...
Error: unable to connect to node 'rabbit@xxx': nodedown

Checking the broker log, it said “cannot_delete_plugins_expand_dir”:

Error description:

This was clearly a permission problem, easily solved by setting the rabbitmq user as owner for the directory.

chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/


Share Button

How much garbage is my JavaScript producing?

While reading this article about garbage collection in JavaScript, a question popped up in my head… How can I test how much garbage a piece of code is producing?

I’ve written a small snippet that can measure this for you. What you need is a recent version of Google Chrome.

To be able to measure the memory heap size, we need to enable it in Chrome. Chrome can give you access to the state of the JavaScript heap (the memory allocated to JavaScript objects), but to get it to work you’ll need to start it with the –enable-precise-memory-info flag:

chrome --enable-precise-memory-info

Or, on OSX:

open -a "Google Chrome" --args --enable-precise-memory-info

Now, create an HTML file containing the following code.

    var before = window.performance.memory.usedJSHeapSize;
    // Start
    // (put your code here)
    // End
    var diff = window.performance.memory.usedJSHeapSize - before;
}, 100);

This will write the number of bytes allocated between "// Start" and "// End" to console every 10th of a second.

My current version of Chrome (40.0.2214.115) is producing 40 bytes to run this function, that is why I remove 40 bytes from the output number. You may need to change this depending on your Chrome version and settings.

If you run this script, you will notice that the first output numbers are


The first numbers are there probably because of initialization garbage. After a little while, the initialization garbage is gone and we see that the number of allocated bytes in the loop is 0.

Now, let's allocate something in the loop and see what happens. If I, for example, allocate a plain object inside the above loop, like this,

    var before = window.performance.memory.usedJSHeapSize;
    var obj = new Object();
    var diff = window.performance.memory.usedJSHeapSize - before;
}, 100);

then the output is


We conclude that a plain JavaScript object takes 56 bytes to allocate.

You can use this code snippet to measure how much GC load different pieces of code allocates in your game loop. Why not try this JSFiddle here to get started? Good luck!

Share Button

p2.js – 2D JavaScript physics

I recently started on a small 2D physics engine project that I for now call p2.js. It contains just the basics, spheres, particles, planes. They can interact either through frictionless contacts or spring forces.


There are a few reasons why I wanted to roll my own engine, however, the most important one for now was the question about using typed arrays or not. Now I’ve got the answer to that.
I followed Brandon Jones simple instructions on how to use the typed arrays correctly, and as one of his slides implies, I was indeed barfing rainbows when seeing the results. Okay, maybe not barfing rainbows, but I must agree that I was a bit surprised.

In total I get a performance gain of about 30% when using Float32Array instead of vector objects such as {x:2,y:1}. This number, 30%, is just a very rough estimate, because it depends on a lot of different parameters. However, my implementation made it relatively easy to switch between these. Another thing that I noticed was that switching between ordinary Arrays and Float32Array didn’t affect performance much at all, though there are a few other advantages of using the latter.

The key to using Float32Arrays is to avoid creating new ones. In the physics engine case this can get a bit tricky since there are things added and removed to the simulation in every timestep. A good example is the contacts. When two geometries collide I need a new ConactEquation instance in the engine. This is basically a holder for a number of vectors, so making a new instance every time it is needed is a no go. To solve this I made sure these objects are reused in between every timestep, and if there are excess objects, I store them for later use.

The scene you see in the image above is a simulation of 900 circles trapped in container consisting of 3 planes. The number of solver iterations is 10. I can get reasonable results by using fewer iterations too. Rendering is made in a small 2D demo renderer I built with Three.js.

I’m going to make a demo page for the engine soon, though for now only the code is available.

Share Button

The split solver in Cannon.js

As I had recently implemented some graph traversing code, I was keen on using it in Cannon.js. You may think, why use graph algorithms in a physics engine? The idea is a bit tricky but I’ll try to explain.

In the usual contact solving case, we iterate over all contacts in the system. For each iteration, we transfer impulses from one body to another. In the example case of stacked boxes, iterating like this will make the top box “feel” impulses from the bottom box as the impulse travel through the stack (this depends on how many times we iterate over the system and what iteration order we use, though that’s another problem).

Many solvers have a “tolerance” parameter and it is used to check when to stop iterating. If the total error (read: contact overlap) is small, then the solution is good enough and we can stop. The tolerance is compared to the *sum* of all errors in the system.

Say we have one stack of boxes on a static plane and a sphere on the same plane. The total error will include both the errors from the stack and from the sphere. We will stop iterating over all the contacts when the total error is below the tolerance limit. Say we reach M iterations. This means we compute stuff M times on each of the N contacts in the system (a total of N*M computations).


Now what if we split the system into two independent systems, one for the stack+plane and one for the sphere+plane, and run the solver once for each of the two systems? The stack will probably still need M iterations, but the interesting thing is that the sphere will only need one. Why? Because the case of a single contact does not need to propagate impulses, and it can directly report the exact solution.


So, in the big system we need M*N computations and in the split system we need M*(N-1). That’s great! And this strategy works for many other systems too. In most cases, we can get away cheaper by using a split solver.

But what about the graph algorithm, you may say. It is used to find the independent sets in the system. Yes, it will add some complexity. However, that computation needed is not as hard as the solve part, and it has linear complexity (with respect to the number of contacts and bodies). The solving complexity depends on the number of contacts times the number of iterations. The number of iterations should be linearly dependent on the number of contacts to be able to propagate all impulses across the system, and so we end up with a quadratic solving complexity.

There is another advantage with the split solver: the subsystems can be solved in parallel. But that is another story!

The CANNON.SplitSolver class is available in the cannon.js/dev branch, and here is a live demo where you can toggle split for a scene.

Share Button