Billiard simulation - part 1: model and animation

April 28, 2013 at 6:25 PMMichele Mottini

The simulation model is pretty straightforward: the table is just a rectangle, represented by the coordinates of its top left corner and its width and height; the balls are spheres, represented by the position of their center \(\vec p_k=(x_k, y_k)\), their velocity \(\vec v_k=(v_k, w_k)\) and their radius \(r_k\) – where \(k\) is the index identifying the ball.

Billiard table with balls

I kept the radius as a property of each ball instead than a global parameter, to be able to model balls of different size.

This is just the geometrical part of the model; I’ll introduce additional parameters for the physics part (mass, friction, restitution) as I develop the physics model.

The animation logic is simple as well: the screen needs to be updated with a certain frequency – let’s say 30 times a second to provide a smooth display. To do this a timer calls an update function every \(\Delta t = 1/30\) seconds, and this function computes the new positions of all the balls and then re-draws everything.

The update function has to compute the change of the balls positions in the \(\Delta t\) seconds elapsed since the last update. For a ball moving freely this change is simply its velocity times \(\Delta t\). The balls do not move freely though: they can hit other balls or the sides of the table, and every time there is a collision the velocity of the colliding balls(s) changes. The complete update algorithm then is:

  1. Compute the time \(t_{min}\) of the first collision(s)
  2. If \(t_{min}\)  is equal or greater than \(\Delta t\) then move all the balls freely for \(\Delta t\) seconds and we are done (no collisions to consider)
  3. Otherwise: move all the balls freely for \(t_{min}\) seconds
  4. Compute the new velocities of all the balls that collide
  5. Repeat from (1), reducing \(\Delta t \) to  \(\Delta t – t_{min}\)

Next time: detecting collisions.

Posted in: Programming

Tags: , ,

Phrase of the week

April 28, 2013 at 5:15 PMMichele Mottini

economists can . . . link almost any unexpected effect with any favorite cause. That is one reason they are held in lower esteem than engineers.

The Economist in ‘Climbing, stretching and stumbling’ – China section of the April 20th 2013 issue.

Posted in: Opinion

Tags: , ,

Billiard simulation – introduction

April 23, 2013 at 6:57 PMMichele Mottini

I failed with the Udacity course (see previous episode), but I still want to improve my JavaScript / HTML5 / canvas skills. 

I am a software developer by trade, but a physicist by training: physics was my passion before computers sort-of-displaced it. I always had an itch to get back into it.

Hence the idea of writing physics simulation code running in a browser, and billiard seems a reasonably simple but interesting case.

The plan is to write a series of posts here describing the development of the simulation, writing about both the physics and the software parts. It will be a work-in-progress kind of thing: I don’t have a finished program that can be described from A to Z; I am going to describe the various pieces as I implement (and possibly ditch) them.

The ambition is to start with classical mechanics and then ‘graduate’ to relativity and/or quantum mechanics. It would be interesting to have a relativistic simulation and be able to play with \(c\) and see how the classical behavior changes into the relativistic one.

The simulation will run entirely in the browser, without a server part. The code will be in TypeScript, compiled into JavaScript for deployment.

Why TypeScript instead than plain JavaScript? I always used strongly typed languages (C#, C++, Pascal, C), and JavaScript seems a bit too loose to me, especially for bigger projects. TypeScript seems a very good solution: offers strong typing, classes and modules, but it is very similar to JavaScript and can use native JavaScript libraries.

The snippets of code I am going to place here will most likely run unchanged – or with very minor changes - as pure JavaScript, so whoever is interested in the simulation and physics part won’t have to learn TypeScript just to follow the implementation.

The simulation I developed so far can be seen here, the source code is on GitHub here. Everything is still very very rough – hopefully it will improve.

Posted in: Programming | Physics

Tags: ,

Udacity HTML5 game development course

April 18, 2013 at 6:13 PMMichele Mottini

…I dropped it after completing five of the eight units.

I kept reading about these new free on-line courses. I want to improve my JavaScript / HTML5 / canvas skills. I saw that Udacity was offering a new  HTML5 Game Development course. It seemed perfect – and is free! – so I  gave it a try.

The course is organized as a walk-through of the development of the GRITS video game – a technology demonstration by Google. Good idea: better to work on something specific instead than explaining things in general.

The course is split in eight units, each on a specific subject: use of the canvas, atlases, handling input and so on. Good as well.

Each unit is composed of short videos – and when I say short I mean it: never longer than 3 minutes, and often under a minute. Here is the first problem: it is difficult (impossible?) to explain anything of real substance in such a short time, so what you get are small snippet of information without much real meat.

The second problem is that there are not that many videos – the total time of all the videos for an entire unit is in the order of 10-15 minutes. This means that in the entire course you are getting something like a total of a couple hours (at most) of lessons.

Then there are the quizzes! After almost every video you have to complete a quiz. Most of the quiz involve writing some JavaScript code, that is then automatically tested. You write the code directly in the browser.

Writing code in the browser as part of a fairly large project is not that easy, so they ‘dumbed down’ the tests a lot: often you have to write no more that 10 lines of code following comments placed in the code itself (‘Write a loop that does such and such. Insert your code here’). On top of this the automatic tests use fairly simplistic test cases. The result is that the quizzes are an exercise of writing syntactically correct small JavaScript snippets; they do not test if you really understand (or not) what you are supposed to be learning. Finally, often the quiz code does not match the instructions – or even the comments inside the code itself – so you have to guess what is being asked.

A couple of other things (and then I stop, promise):

There is no explanation of the overall structure of the program, you look at the various pieces in isolation. Makes everything more difficult to follow – and it would have been an interesting subject in its own right.

The code itself look a bit weird, for example there are methods of a class that has a global instance that access directly the global instance instead than the current one:

var TILEDMapClass = Class.extend({
    currMapData: null,

    parseMapJSON: function (mapJSON) {
        gMap.currMapData = JSON.parse(mapJSON)


var gMap = new TILEDMapClass();

No explanation given – but surely looks wrong to me.

As I wrote at the beginning: I stuck with it for some weeks, but in the end I dropped out.

Posted in: Opinion | Programming

Tags: , ,

Free as in speech

April 13, 2013 at 12:32 PMMichele Mottini

I don’t completely get the enthusiasm for open source software, to try to understand it better I had a look at the Web site of the Free Software Foundation. I found it…puzzling? objectionable? …crazy? Not sure what’s the right word.

Start with this:

The corporations behind proprietary software will often spy on your activities and restrict you from sharing with others.

The assumption seems to be that proprietary software is developed by (evil) Megacorp Inc and used by Jane Consumer or Joe Small Business. This is ridiculous: most software is developed by small companies and used by other companies – including large ones. Amongst the first 100 US corporation by revenue only two are software developers – Microsoft (37) and Oracle (82). I’d bet that for most line of business application the norm would be small(ish) software companies selling to much larger customers (it has always been the case with my own software business).

Then there is this:

The freedom to study how the program works, and change it so it does your computing as you wish (freedom 1). Access to the source code is a precondition for this.

Nice. Let’s go ahead and use this freedom – here is the list of the 100+ top-level directories containing the OpenOffice source code and here you are warned:

Let's be honest. The size, age and complexity of OpenOffice's C++ codebase makes coding a challenge. This is not a trivial codebase to learn.

Who can honestly say that access to these sources will allow Jane Consumer – or even Bob C++ Programmer – to ‘change it so it does …as you whish’?

Of course it is a different matter if the USER of the software is Megacorp Inc – that has the resources to actually do something with the sources: fix bugs, make improvements, adapt it. Think of Google or Facebook - big businesses that use a lot of software and sell advertisement: they surely benefitted from the availability of Linux, PHP, Python and so forth.

Aside: the free software definition apparently applies to all possible software, but – just as an example - would it really be a good thing if anyone was able to tinker with the software embedded in their cars? No mention of this nuances though.

Finally, there is this:

“Free software” does not mean “noncommercial”. A free program must be available for commercial use, commercial development, and commercial distribution. Commercial development of free software is no longer unusual; such free commercial software is very important.

That is very true – there are a number of businesses based on distributing and supporting free software. But if the software itself is freely distributed these businesses would never be able to charge much – the marginal price will be the cost of distribution and support, disregarding development – and this will hurt software development companies (that – see above - are mostly small and mid-sized, not Megacorp Inc.). The free availability of Git allows GitHub to exists – but hurts Perforce and SourceGear.

Summary: free software – benefits the big at the expense of the small. And Jane Consumer, in the meantime, switched to an iPad.

Posted in: Opinion

Tags: ,

Windows Live Writer crashing

April 13, 2013 at 11:23 AMMichele Mottini

I installed Windows Live Writer to have something better to write blog posts, but it was systematically crashing on startup.

The crash was an ‘APP CRASH’ in nvdxgiwrap.dll called by wlstartup.exe.

After some failed attempt I managed to solve the problem disabling the NVIDIA display card (start Device Manager, right-click on NVIDIA under ‘Display adapters’ and select ‘Disable’).

Once I did this Live Writer started up fine, completing the installation process. Afterwards I was able to re-enable the NVIDIA card and Live Writer kept working. Apparently the problem was just in the startup that runs when Live Writer is started the first time.

My setup is a Dell Latitude E6420 laptop running Windows 7 Professional 64 bits with Service Pack 1 and an NVIDIA NVS 4200M video card with the latest drivers – version

Posted in: Blogging

Tags: , ,

Overloading in TypeScript - part 2

April 12, 2013 at 3:44 PMMichele Mottini

In the previous post I dealt with overloading constructors. The exact same system can be used to overload class methods - this code:

class DateHour {

  private date: Date;
  private relativeHour: number;

  . . .

  init(year: number, month: number, day: number, relativeHour: number);
  init(date: Date, relativeHour: number);
  init(dateOrYear: any, monthOrRelativeHour: number, day?: number, relativeHour?: number) {
    if (typeof dateOrYear === "number" && monthOrRelativeHour && day) { = new Date(dateOrYear, monthOrRelativeHour, day);
      this.relativeHour = relativeHour;
    } else {
      var date = <Date> dateOrYear; = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      this.relativeHour = monthOrRelativeHour;

defines an 'init' method with two overloads, one taking a year/moth/day triplet and the other a date object. The one and only implementation is hidden by the overloads, and checks the type of the parameters to determine which of the two overloads to implement.

Finally, the same system can be used to overload stand-alone functions:

function initDateHour(year: number, month: number, day: number, relativeHour: number);
function initDateHour(date: Date, relativeHour: number);
function initDateHour(dateOrYear: any, monthOrRelativeHour: number, day ? : number, relativeHour?: number) {
  if (typeof dateOrYear === "number" && monthOrRelativeHour && day) {
    // Handle the year/moth/day case    
  } else {
    // Handle the date object case

Part 1

Posted in: Programming

Tags: ,

Highlighting TypeScript code

April 10, 2013 at 6:05 PMMichele Mottini

The previous post was about TypeScript, and I am probably going to write more about it.

The default code highlighter that comes with BlogEngine.Net - based on Alex Gorbatchev's Syntax Highlighter - does not support TypeScript, so I had a go at adding it.

It turns out to be very easy: you need to add a 'brush' JavaScript code file defining the highlighting rules for the language. Given that TypeScript is very similar to JavaScript I just took the JavaScript one and adapted it.

To make BlogEngine.Net pages recognize the new language I added the reference to the new brush in scripts\syntaxhighlighter\shInit.js. Finally I added the new language name in the 'Insert code' form of the HTML editor. That's it.

If anyone is interested here are the files: (3.19 kb)

Simply un-zip in the BlogEngine.Net root directory preserving the paths - the files will go to the right place.

I issued a pull request in Syntax Highlighter GitHub repository - but there are quite a number piled up, so I don't know if it is going to be integrated.


Posted in: Blogging | Programming

Tags: ,

Overloading in TypeScript - part 1

April 8, 2013 at 6:12 PMMichele Mottini

Coming from a C#/C++ background I was baffled by the handling of overloading in TypeScript. Having to write a class that could be initialized from either a date or a year/month/day triplet I went for two overloaded constructors:

class DateHour {

  private date: Date;
  private relativeHour: number;

  constructor (year: number, month: number, day: number, relativeHour: number) { = new Date(year, month, day);
    this.relativeHour = relativeHour;

  constructor (date: Date, relativeHour: number) { = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    this.relativeHour = relativeHour;


...that does not work: TypeScript does not accept the two different constructors. The specifications do mention overloading though, so what gives?

The problem is that JavaScript does not know anything about overloading - and so TypeScript cannot generate multiple definitions of the same function differing only by their signature.

What TypeScript can do is to define multiple overloads that all map to the same function body; the class above should be defined like this:

class DateHour {

  private date: Date;
  private relativeHour: number;

  constructor(year: number, month: number, day: number, relativeHour: number);
  constructor(date: Date, relativeHour: number);
  constructor(dateOrYear: any, monthOrRelativeHour: number, day?: number, relativeHour?: number) {
    if (typeof dateOrYear === "number") { = new Date(dateOrYear, monthOrRelativeHour, day);
      this.relativeHour = relativeHour;
    } else {
      var date = <Date> dateOrYear; = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      this.relativeHour = monthOrRelativeHour;

The two overloads are still there, but as simple signature declarations, and the actual implementation of the constructor accepts a superset of the parameters of the two overloads - and determine what to do checking the type of the first parameters.

The clever bit is that in such a case the overloaded signatures hide the implementation one - auto-complete shows only two constructors: 

 and these calls are marked as invalid by the TypeScript compiler:

var start = new DateHour(2013, 0);

var current = new DateHour(new Date(), 1, 4, currentRelativeHour);

even if they match the constructor implementation. The class behaves exactly as if it had the two constructors defined in my first failed attempt.

 Part 2


Posted in: Programming

Tags: ,

Setting up the blog

April 6, 2013 at 12:09 PMMichele Mottini

Besides writing the blog I'd like to play a bit with the platform itself, so I wanted blogging software I can work with and not just a shrink-wrapped hosted solution.

I am a .NET/C#/Windows developer, so I looked for .NET-based stuff.

At first I tried FunnelWeb: it is a modern .NET MVC application, geared for programmers (uses Markdown for the posts for example).  It is quite basic in terms of features, requires a SQL database and the community / support does not seem very active, so I dropped it.

I switched to BlogEngine.Net: it is not MVC, but it is a more mature and full-featured product, with a bigger and more active community. As a further plus (for me) it does not require a SQL database.

BlogEngine.NET is the brainchild of Mads Kristensen, the author of the - essential - Web Essentials Visual Studio add-in.

Selected the software, I needed a hosting service. Some initial searches led me to this gallery of hosting services supporting .NET; after some further not-very-scientific searches there I settled to SmarterAsp.NET. The amount of choice is quite overwhelming: I was not expecting so many different hosting services.

So far I am happy with SmarterAsp: they offer a 60 day trial, the setup was easy and the dashboard used  to manage your sites is pretty nice. It might be a tad slow, I am not sure yet.

SmarterAsp offers a number of pre-configured application that can be installed automatically - including BlogEngine.NET, but for some reason their installation script configures it to use a SQL database instead than the file system. That seems overkill for my needs, so I ended up doing a manual installation, that in any case is very easy.

Last step: select a domain name. seemed too long, I frequently use 'mimo' as my handle, but is already taken, so I went for I bough it directly via SmarterAsp, and I was good to go almost immediately.


Posted in: Blogging