## Billiard simulation–part 7: sound

June 15, 2013 at 11:18 AM

Another way to make the simulation a bit more realistic is to produce some sound when balls hit each other and when they hit the side of the table.

Playing a sound in the browser turns out to be super-easy – create ‘Audio’ objects loading sound files:

  private audioBallBall = new Audio("sounds/ball-ball.mp3");
private audioBallSide = new Audio("sounds/ball-side.mp3");

and play them in the loop that process the collisions:

      // Compute the new velocities after the collisions
for (var i = 0; i < firstCollisions.collisions.length; i++) {
var collision = firstCollisions.collisions[i];
switch (collision.type) {
case "x":
this.audioBallSide.volume = Math.min(this.maxSpeed, Math.abs(collision.b1.v)) / this.maxSpeed;
this.audioBallSide.play();
collision.b1.v = -collision.b1.v * this.parameters.sideRestitution;
break;
case "y":
this.audioBallSide.volume = Math.min(this.maxSpeed, Math.abs(collision.b1.w)) / this.maxSpeed;
this.audioBallSide.play();
collision.b1.w = -collision.b1.w * this.parameters.sideRestitution;
break;
case "b":
var dx = (collision.b1.x - collision.b2.x);
var dy = (collision.b1.y - collision.b2.y);
var relativeSpeed = Math.abs((collision.b1.v - collision.b2.v) * dx + (collision.b1.w - collision.b2.w) * dy) / Math.sqrt(dx*dx + dy*dy);
this.audioBallBall.volume = Math.min(this.maxSpeed, relativeSpeed) / this.maxSpeed;
this.audioBallBall.play();
collision.b1.collide(collision.b2, this.parameters.ballRestitution);
break;
}
}

The volume is adjusted to decrease as the collision speed decreases, with 100% volume corresponding to some (rather arbitrary) maximum speed. I did not investigate the actual physics – I suspect that the sound volume does not simply decrease linearly with the speed, but it sounds good enough.

The audio files are loaded asynchronously by the browser, so in theory they should be played only after receiving a notification that loading completed (see here for example), but being very small file this is not really necessary.

I recorded myself the two different sounds used for ball-ball and ball-side collisions – hitting two different surfaces with a pen, not very realistic but good enough for now (probably the title of this post should be ‘good enough’). I used Audacity to record the sound and cut them – I didn’t do any other editing.

There are libraries of sound effects that can be bought quite cheaply, including billiard sound – see this for example, but they appear to be more complex sounds, not suitable for just a single impact.

UPDATE

The code above contained a bug in the computation of the relative speed for ball-ball collisions, now fixed.

Posted in: Programming

Tags: , ,

## Phrase of the week

June 9, 2013 at 7:21 AM

...activist investors seeking to crack Japan have fared only slightly better than the Christian missionaries of the 16th century (who were crucified).

The Economist in 'Goodbye, Mr Bond?'

Posted in: Opinion

Tags:

## Billiard simulation–part 6: balls rotation

June 2, 2013 at 11:09 AM

The simulation is two-dimensional: the table and balls are seen from straight above. Drawing the balls as simple circles produces a very un-realistic effect though; to improve things it is necessary to render in some way the rotation of the balls. The easiest way to do this is to add some feature to a ball surface – like a white circle – and change its position and size as the ball rotates.

A point on the surface of a ball is identified by two angles $$(\varphi, \vartheta)$$:

As the balls moves, it rotates by an angle $$\delta = \Delta s / r$$, where $$r$$ is the ball radius and $$\Delta s = \sqrt{\Delta x^2 + \Delta y^2}$$ is the distance travelled. The direction of the movement is the direction of the ball velocity, so this is the situation as seen ‘from above’:

where $$\alpha = \arctan(w/v)$$. Let’s rotate the $$x, y$$ axes by the angle $$\alpha$$, so that the movement is along the new $$\bar x$$ axis: to do it simply subtract $$\alpha$$ from $$\varphi$$. Using these new coordinates the situation as seen ‘from the side’ is:

(the $$\bar y$$ axis goes away from you ‘through’ the screen). The initial coordinate of the point are:

$$\bar x = r \sin \vartheta cos (\varphi-\alpha)$$

$$\bar y = r \sin \vartheta sin (\varphi-\alpha)$$

$$z = r \cos \vartheta$$

after the ball moves the $$\bar y$$ coordinate is the same, whereas $$\bar x$$ and $$z$$ are rotated by $$\delta$$ clockwise:

$$\bar{x}’ = \bar x \cos\delta + z \sin\delta = r \sin \vartheta cos (\varphi-\alpha) \cos\delta + r \cos \vartheta \sin\delta$$

$$\bar y’ = r \sin \vartheta sin (\varphi-\alpha)$$

$$z’ = –\bar x \sin\delta + z \cos\delta = –r \sin \vartheta cos (\varphi-\alpha) \sin\delta + r \cos \vartheta \cos\delta$$

The angles after the ball moves are then:

$$\varphi’ = \alpha + \arctan \frac{\bar y’}{\bar x’} = \alpha + \arctan \frac {\sin \vartheta sin (\varphi-\alpha)} {\sin \vartheta cos (\varphi-\alpha) \cos\delta + \cos \vartheta \sin\delta}$$

$$\vartheta’ = \arccos \frac{z’}{r} = \arccos(-\sin \vartheta cos (\varphi-\alpha) \sin\delta + \cos \vartheta \cos\delta)$$

and here is the corresponding code:

  /**
* Updates the ball position and orientation, applying the current velocity for a specified time interval
* @param t the time interval to use. The velocity is considered constant, so the time interval must be
* small compared to the rate of change of the velocity
*/
updatePosition(t: number) {
var dx = this.v * t;
var dy = this.w * t
// Update the ball position
this.x += dx;
this.y += dy;
var ds2 = dx * dx + dy * dy;
if (ds2 > 0) {
// Update the ball orientation
var delta = Math.sqrt(ds2) / this.radius;
var sinDelta = Math.sin(delta);
var cosDelta = Math.cos(delta);
var alpha = Math.atan2(this.w, this.v);
var sinTheta = Math.sin(this.theta);
var cosTheta = Math.cos(this.theta);
var phiAlpha = this.phi - alpha;
var sinPhiAlpha = Math.sin(phiAlpha);
var cosPhiAlpha = Math.cos(phiAlpha);
this.phi = alpha + Math.atan2(sinTheta * sinPhiAlpha, sinTheta * cosPhiAlpha * cosDelta + cosTheta * sinDelta);
this.theta = Math.acos(-sinTheta * cosPhiAlpha * sinDelta + cosTheta * cosDelta);
}
} // updatePosition

A circle drawn on the surface of the ball that is centered at the point $$(\varphi, \vartheta)$$ looks like a circle when $$\vartheta=0$$, and then get progressively ‘squashed’ as $$\vartheta$$ increases, until is disappears when $$\vartheta>\pi/2$$:

The circle is actually a spherical one, that should be projected on a horizontal plane to compute the exact shape to be drawn; approximately though the circle becomes an ellipse as $$\vartheta$$ increases – with the axis in the direction from its center to the center of the ball decreasing with $$\cos \vartheta$$. Using this approximation the code to draw the ball is this:

  /**
* draw: draws the ball
* @param ctx the canvas rendering context to use to draw the ball
*/
draw(ctx: CanvasRenderingContext2D) {
ctx.save();
// Move the coordinates to the center of the ball - simplifies everything else
ctx.translate(this.x, this.y);
// Gradient from the ball color to black, used to shade the ball color to give an illusion of depth
// Gradient from white to black, used to shade the white circle to give an illusion of depth
// Draw the ball: a circle filled with the ball color shading to black
ctx.beginPath();
ctx.fill();
if (this.theta < Math.PI / 2) {
// Draw the white circle if it is visible
var d = this.radius * Math.sin(this.theta);
var cosTheta = Math.cos(this.theta);
var s = this.circleRadius * cosTheta;
if (d - s < this.radius) {
var cosPhi = Math.cos(this.phi);
var sinPhi = Math.sin(this.phi);
// Clip to the ball's circle - do not want to draw parts of the white circle that fall outside the ball borders
ctx.clip();
// Move the coordinates to the center of the white circle
ctx.translate(d * cosPhi, d * sinPhi);
// Compress the coordinates by cosTheta in the direction between the center of the white circle and the center of the ball
ctx.rotate(this.phi);
ctx.scale(cosTheta, 1);
// Draw the white circle
ctx.beginPath();
ctx.arc(0, 0, this.circleRadius, 0, 2 * Math.PI);
ctx.fill();
}
}
ctx.restore();
} // draw

Note how the code uses gradients to fill the ball and the white circle to give a more ‘tridimensional’ look.

Aside: these first experiences of using the HTML canvas are very positive: the API is complete, easy to use and works well in multiple ‘modern’ browsers

Posted in: Programming

## Phrase of the week

June 2, 2013 at 9:50 AM

The resource that is in shortest supply is usually time, since there is no way to create more of it.

Raymon Chen in Microspeak: booked

Posted in: Opinion

Tags:

## Phrase of the week

May 26, 2013 at 10:06 AM

A committee is an animal with four back legs.

John le Carré in ‘Tinker, Tailor, Soldier, Spy'.

Posted in: Opinion

Tags:

## Billiard simulation–part 5: friction

May 26, 2013 at 9:03 AM

The velocity of the balls progressively decreases due to three different effects: loss of energy during collisions, friction with the table (rolling friction or rolling resistance) and friction with the air (drag).

The loss of energy during collisions is already accounted for by the coefficient of restitution used in the collisions formulas.

The general formula for the rolling friction is:

$$F_{rr} = c_{rr}N$$

where $$F_{rr}$$ is the resulting rolling friction force, $$c_{rr}$$ is the coefficient of rolling friction – that depends on the materials of the ball and the table – and $$N$$ is the downward force exerted by the ball on the table. $$N$$ is equal to the mass $$m$$ of the ball times the gravitational acceleration $$g$$: $$N = mg$$. The deceleration $$a_{rr}$$ of the ball due to the rolling friction is the friction force divided by the mass of the ball: $$a_{rr}=F_{rr}/m$$. Combining these two equation the rolling friction deceleration is:

$$a_{rr} = c_{rr}g$$

The formula for the air drag is:

$$F_d = \frac{1}{2}\rho_a v^2 c_d A$$

where $$F_d$$ is the resulting drag force, $$\rho_a$$ is the air density, $$v$$ is the ball speed, $$c_d$$ is the drag coefficient and $$A$$ is the cross-sectional area of the ball. The deceleration $$a_{d}$$ of the ball due to the air drag is the air drag force divided by the mass of the ball:

$$a_d = \frac{F_d}{m} = \frac{F_d}{\frac{4}{3}\pi\rho_b r^3}$$

where $$\rho_b$$ is the density of the ball and $$r$$ is its radius. The cross-sectional area of the ball is $$A=\pi r^2$$ – putting all this together the air drag deceleration is:

$$a_d = f_d \frac{v^2}{r}$$

where the air drag factor $$f_d$$ is defined as

$$f_d = \frac{3\rho_a c_d}{8\rho_b}$$

The drag coefficient $$c_d$$ for a sphere varies quite a bit with the velocity of the object – see here for example, but overall the air drag is quite small, so even using a constant would not change the result much; hence given the air density and the ball density $$f_d$$ can be considered a constant as well.

Assuming that the time interval used to update the simulation is small compared with the rate of change of the ball velocities, the speed after the interval is simply the original speed decremented by the deceleration times the interval:

$$v_t = v_0 – (a_{rr}+a_d)t$$

The resulting code is:

  /**
* Updates the ball velocity, applying rolling resistance and air drag for a specified time interval
* @param t the time interval to use. Only first-order effects are considered, so the time interval
* must be small compared to the rate of change of the velocity
* @param airDragFactor total air drag factor computed from the ball and air densities and the
* air drag coefficient (assumed to be constant)
* @param rollingResistanceDeceleration total rolling resistance deceleration computed from the
* rolling resistance coefficient and the gravitational acceleration
*/
updateVelocity(t: number, airDragFactor: number, rollingResistanceDeceleration: number) {
var speed2 = this.v * this.v + this.w * this.w;
if (speed2 > 0) {
var airResistanceDeceleration = airDragFactor * speed2 / this.radius;
var totalDeceleration = airResistanceDeceleration + rollingResistanceDeceleration;
var speed = Math.sqrt(speed2);
var newSpeed = speed - totalDeceleration * t;
if (newSpeed <= 0) {
// The ball stopped
this.v = 0;
this.w = 0;
} else {
// Update the speed, keeping the velocity direction the same (the air drag and rolling resistance
// forces are in the exact opposite direction of the velocity)
this.v = this.v * newSpeed / speed;
this.w = this.w * newSpeed / speed;
}
}
} // updateVelocity

Posted in: Physics | Programming

## Phrase of the week

May 19, 2013 at 7:24 AM

Apple Computer is now unlikely to survive its current crisis

Brad de Long in The Corporation as a Command Economy (originally written in 1997)

Posted in: Opinion

Tags:

## Billiard simulation–part 4: more collisions, and a problem

May 19, 2013 at 6:07 AM

The last part covered the collisions between balls, what about collisions with the sides of the table? If the balls are not spinning and there is no ball-table friction the component of the ball velocity that is parallel to the table side remains the same, and the component perpendicular to the side changes direction and intensity based on the coefficient of restitution. Using primed letters for the velocity after the collisions, the formula for a collision with the left or right side is:

$$v’ = –cv$$

$$w’ = w$$

where $$c$$ is the ball-table coefficient of restitution (that in general is different from the ball-ball one). The formula for a collision with the ‘top’ (as seen on the screen) or ‘bottom’ side is:

$$v’ = v$$

$$w’ = -cw$$

With this last piece, the complete update code is:

  update(dt: number) {
while (dt > 0) {
var firstCollisions = this.detectCollisions(dt, 0, 400, 0, 300);
if (firstCollisions.t > 0) {
// The balls move freely up to the time of the first collision: update their positions
for (var i = 0; i < this.balls.length; i++) {
var ball = this.balls[i];
ball.updatePosition(firstCollisions.t);
}
}
// Compute the new velocities after the collisions
for (var i = 0; i < firstCollisions.collisions.length; i++) {
var collision = firstCollisions.collisions[i];
switch (collision.type) {
case "x":
collision.b1.v = -collision.b1.v * this.parameters.sideRestitution;
break;
case "y":
collision.b1.w = -collision.b1.w * this.parameters.sideRestitution;
break;
case "b":
collision.b1.collide(collision.b2, this.parameters.ballRestitution);
break;
}
}
// Continue with the remaining time
dt -= firstCollisions.t;
}
this.draw();
} // update

where ‘detectCollisions’ is a function that uses the code described previously to detect the first collision – or collisions – that occur within the specified interval. It returns an object containing the time of the collision and an array of the balls that collide. Each element of this array has two members ‘b1’ and ‘b2’ containing the colliding balls (‘b2’ is null for collisions with the sides) plus a ‘type’ member that indicates if the collision is with the left or right sides (“x”), with the top or bottom sides (“y”) or between two balls (“b”).

Here is the ‘detectCollisions’ code:

  private detectCollisions(dt: number, minx: number, maxx: number, miny: number, maxy: number) {
var result = {
t: dt,
collisions: <{ type: string; b1: Ball; b2: Ball; }[]>[]
}
var addCollision = (t, collision) => {
if (t === result.t) {
// The new collision happens at the exact same time of the current one, it has to be added to the list
result.collisions.push(collision);
} else {
// The new collision happens before the current one, so it replaces the entire list
result.collisions = [collision];
result.t = t;
}
}
for (var i = 0; i < this.balls.length; i++) {
// Collisions with the sides
var ball = this.balls[i];
var t = ball.sideXCollisionTime(minx, maxx);
if (t && t <= result.t) {
addCollision(t, { type: "x", b1: ball, b2: <Ball>null });
}
t = ball.sideYCollisionTime(miny, maxy);
if (t && t <= result.t) {
addCollision(t, { type: "y", b1: ball, b2: <Ball>null });
}
// Ball-ball collisions
for (var j = i + 1; j < this.balls.length; j++) {
var otherBall = this.balls[j];
t = ball.collisionTime(otherBall);
if (t && t <= result.t) {
addCollision(t, { type: "b", b1: ball, b2: otherBall });
}
}
}
return result;
} // detectCollisions

As promised in the title this code has a problem though: it works fine in most cases but fails when there are multiple ball-ball collisions at the same time.

Have a look at this: the ball coming from the left hits the two balls at rest at the same time, but the code evaluates the collisions one at a time: it first consider the collisions with the ball at the top, updating the velocity of the moving ball to move down, and then uses this velocity to compute the second collision. The result is clearly wrong: the moving ball should bounce straight back, and the result should not depend on the order of the balls.

I have no solution for this at the moment being.

Posted in: Physics | Programming

## Billiard simulation–part 3: collision between two balls

May 13, 2013 at 1:27 PM

..or more formally: elastic collision of spheres in two dimensions.

Let’s start with a simple case: ball 1 moving with velocity $$(\bar v_1, \bar w_2)$$ hitting ball 2 at rest. To make things even easier ball 1 and ball 2 are aligned horizontally at the moment of impact – i.e.  they have the same $$y$$ coordinate:

In our model (at the moment being at least) balls are not spinning, and there is no ball-ball friction, so the force between balls in such a collision is only along the horizontal line connecting their centers. This means that the vertical components of the velocities before and after the collision are the same:

$$\bar{w}’_1 = \bar{w}$$

$$\bar{w}’_2 = 0$$

- where the primed values are the ones after the collision. The horizontal components of the velocities on the other hand are related by the ball-ball coefficient of restitution $$c$$:

$$\bar{v}’_2 - \bar{v}’_1 = c(\bar{v}_1 - \bar{v}_2) = c\bar{v}_1$$

($$\bar{v}_2$$ is zero). The horizontal momentum must be the same before and after the collision:

$$m_1\bar{v}’_1 + m_2\bar{v}’_2 = m_1\bar{v}_1$$

- where $$m_1$$ and $$m_2$$ are the masses of the two balls. Combining these two equation gives:

$$\bar{v}’_1 = \frac{m_1 – cm_2}{m_1+m_2}\bar{v}_1$$

$$\bar{v}’_2 = \frac{(1+c)m_1}{m_1+m_2}\bar{v}_1$$

that is the result for this simple case: the velocities after the collision in terms of the (known) velocities before the collision.

What abut the general case in which both balls move and are not aligned?

This second case can be converted in the simple one with a coordinate transformation: subtract the velocity of the second ball from all velocities – i.e. use the frame of reference of the second ball - and rotate the axis by the angle $$\alpha$$:

$$\bar{v} = (v-v_2)\cos\alpha + (w-w_2)\sin\alpha$$

$$\bar{w} = -(v-v_2)\sin\alpha + (w-w_2)\cos\alpha$$

where $$(v, w)$$ is an arbitrary velocity and $$(\bar{v}, \bar{w})$$ is the corresponding transformed velocity. The angle $$\alpha$$ is*:

$$\alpha = \arctan \frac{y_1– y_2}{x_1 – x_2}$$

where $$(x_1, y_1)$$ and $$(x_2, y_2)$$ are the positions of the two balls.

The inverse transformation is:

$$v = \bar{v}\cos\alpha - \bar{w}\sin\alpha + v_2$$

$$w = \bar{v}\sin\alpha + \bar{w}\cos\alpha + w_2$$

Now the procedure to solve the general case is: transform the original velocities in their ‘bar’ equivalent; apply the formula of the simple case; apply the inverse transformation to go back to the velocities in the original coordinate system (without ‘bar’). These steps produce the following results:

$$v’_1 = \frac{1}{m_1+m_2}\Big[\big(m_1-m_2(c\cos^2\alpha-\sin^2\alpha)\big)(v_1-v_2)-(1+c)m_2\sin\alpha\cos\alpha(w_1-w_2)\Big]+v_2$$

$$w’_1 = \frac{1}{m_1+m_2}\Big[-(1+c)m_2\sin\alpha\cos\alpha(v_1-v_2) + \big(m_1-m_2(c\sin^2\alpha-\cos^2\alpha)\big)(w_1-w_2)\Big]+w_2$$

$$v’_2 = \frac{(1+c)m_1}{m_1+m_2}\cos\alpha\Big[(v_1-v_2)\cos\alpha + (w_1-w_2)\sin\alpha\Big] + v_2$$

$$w’_2 = \frac{(1+c)m_1}{m_1+m_2}\sin\alpha\Big[(v_1-v_2)\cos\alpha + (w_1-w_2)\sin\alpha\Big] + w_2$$

The first two equations are quite unwieldy, but adding and subtracting $$v_1$$ from the first one and $$w_1$$ from the second one, and then doing some algebra produces:

$$v’_1 = –m_2a\cos\alpha+ v_1$$

$$w’_1 = –m_2a\sin\alpha+ w_1$$

$$v’_2 = m_1a\cos\alpha+ v_2$$

$$w’_2 = m_1a\sin\alpha+ w_2$$

where

$$a = \frac{1+c}{m_1+m_2}\Big[(v_1-v_2)\cos\alpha + (w_1-w_2)\sin\alpha\Big]$$

A nice symmetric solution – and correct to boot.

Assuming that all the balls have the same density, their mass is a fixed constant times their radius cubed. In the formulas above the masses appear always as a quotient, so they can be replaced with the balls’ cubed radiuses.

The final code is this:

  /**
* Updates the velocities of this ball and another one after a collision
* The coordinate of the balls must be at the collision point.
* @param otherBall second colliding ball
* @param restitution coefficient of restitution for a ball-ball collision
*/
collide(otherBall: Ball, restitution: number) {
var dx = this.x - otherBall.x;
var dy = this.y - otherBall.y;
var dv = this.v - otherBall.v;
var dw = this.w - otherBall.w;
var alpha = Math.atan2(dy, dx);
var sinAlpha = Math.sin(alpha);
var cosAlpha = Math.cos(alpha);
var a = (1 + restitution) / (m1 + m2) * (cosAlpha * dv + sinAlpha * dw);
this.v = -m2 * a * cosAlpha + this.v;
this.w = -m2 * a * sinAlpha + this.w;
otherBall.v = m1 * a * cosAlpha + otherBall.v;
otherBall.w = m1 * a * sinAlpha + otherBall.w;
} // collide

(*) That ‘naïve’ formula for $$\alpha$$ does not work when $$x_1-x_2$$ is zero, nor it handles the various possible combination of signs of the numerator and denominator, but in the code all that is handled by Math.atan2().

Posted in: Physics | Programming

## Phrase of the week

May 12, 2013 at 12:47 PM

It is not a correct deduction from the principles of economics that enlightened self-interest always operates in the public interest. Nor is it true that self-interest generally is enlightened

John Maynard Keynes in 'The end of laissez-faire'

Posted in: Opinion

Tags: