Skip to content

Visualize Your Ideas With Code

fix(2d): handle floating point errors in acos (#381)

Jacob5bca8fd0bbdc
diff --git a/packages/2d/src/curves/CircleSegment.ts b/packages/2d/src/curves/CircleSegment.ts
index 2846cb4f..db4933b9 100644
--- a/packages/2d/src/curves/CircleSegment.ts
+++ b/packages/2d/src/curves/CircleSegment.ts
@@ -1,5 +1,6 @@
import {Vector2} from '@motion-canvas/core/lib/types';
import {Segment} from './Segment';
+import {clamp} from '@motion-canvas/core/lib/tweening';
export class CircleSegment extends Segment {
private readonly length: number;
@@ -13,7 +14,7 @@ export class CircleSegment extends Segment {
private counter: boolean,
) {
super();
- this.angle = Math.acos(from.dot(to));
+ this.angle = Math.acos(clamp(-1, 1, from.dot(to)));
this.length = Math.abs(this.angle * radius);
}
diff --git a/packages/2d/src/curves/getPolylineProfile.ts b/packages/2d/src/curves/getPolylineProfile.ts
index a32bd2b8..6e2d4ed5 100644
--- a/packages/2d/src/curves/getPolylineProfile.ts
+++ b/packages/2d/src/curves/getPolylineProfile.ts
@@ -2,6 +2,7 @@ import {Vector2} from '@motion-canvas/core/lib/types';
import {CurveProfile} from './CurveProfile';
import {LineSegment} from './LineSegment';
import {CircleSegment} from './CircleSegment';
+import {clamp} from '@motion-canvas/core/lib/tweening';
export function getPolylineProfile(
points: Vector2[],
@@ -33,7 +34,7 @@ export function getPolylineProfile(
const centerToEnd = end.sub(center);
const startVector = centerToStart.normalized;
const endVector = centerToEnd.normalized;
- const angleBetween = Math.acos(startVector.dot(endVector));
+ const angleBetween = Math.acos(clamp(-1, 1, startVector.dot(endVector)));
const angleTan = Math.tan(angleBetween / 2);
const safeRadius = Math.min(
diff --git a/packages/core/src/tweening/interpolationFunctions.ts b/packages/core/src/tweening/interpolationFunctions.ts
index 90ea4488..df4f4bd3 100644
--- a/packages/core/src/tweening/interpolationFunctions.ts
+++ b/packages/core/src/tweening/interpolationFunctions.ts
@@ -178,7 +178,9 @@ export function arcLerp(
flip = !flip;
}
- const normalized = flip ? Math.acos(1 - value) : Math.asin(value);
+ const normalized = flip
+ ? Math.acos(clamp(-1, 1, 1 - value))
+ : Math.asin(value);
const radians = map(normalized, map(0, Math.PI / 2, value), ratio);
let xValue = Math.sin(radians);