Skip to content

Commit

Permalink
optimise and test sphere2.collisionArea
Browse files Browse the repository at this point in the history
  • Loading branch information
axelpale committed Oct 15, 2023
1 parent 37cf07d commit b296a15
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/sphere2/collisionArea.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ module.exports = (c, cc) => {
return Math.PI * rr2
}

if (d > r + rr) {
// Circles too distant. Just for optimization.
return 0
}

const area = r2 * Math.acos((d2 + r2 - rr2) / (2 * d * r)) +
rr2 * Math.acos((d2 + rr2 - r2) / (2 * d * rr)) -
0.5 * Math.sqrt((-d + r + rr) * (d + r - rr) * (d - r + rr) * (d + r + rr))
Expand Down
6 changes: 6 additions & 0 deletions test/sphere2/collisionArea.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ module.exports = (ts) => {
'concentric spheres overlap'
)

t.equal(
sphere2.collisionArea({ x: 0, y: 0, r: 1 }, { x: 1.5, y: 1.5, r: 1 }),
0,
'spheres too far'
)

t.almostEqual(
sphere2.collisionArea({ x: 0, y: 0, r: 1 }, { x: 1, y: 0, r: 1 }),
// overlap = 2 * segment
Expand Down

0 comments on commit b296a15

Please sign in to comment.