Skip to content

Implement closest_point for Segment[23]d. #20130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions crates/bevy_math/src/primitives/dim2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,38 @@ impl Segment2d {
self.reverse();
self
}

/// Returns the point on the [`Segment2d`] that is closest to the specified `point`.
#[inline(always)]
pub fn closest_point(&self, point: Vec2) -> Vec2 {
// `point`
// x
// ^|
// / |
//`offset`/ |
// / | `segment_vector`
// x----.-------------->x
// 0 t 1
let segment_vector = self.vertices[1] - self.vertices[0];
let offset = point - self.vertices[0];
// The signed projection of `offset` onto `segment_vector`, scaled by the length of the segment.
let projection_scaled = segment_vector.dot(offset);

// `point` is too far "left" in the picture
if projection_scaled <= 0.0 {
return self.vertices[0];
}

let length_squared = segment_vector.length_squared();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering about precision here. Since the value is scaled by the segment length it's potentially quite large already, and squaring it could lead to precision issues. On the other hand normalizing first wastes cycles for the early out case. Thoughts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You really cannot get a better precision than this. Because the actual length is computed as the square root of length_squared (which is computed through the pythagorean theorem), in fact one of the reason I'm using the length squared here is to skip on the square root operation that would end up being redundant here.

Due to how f32 numbers work, they have roughly the same amount of precision (as in, how many digits are correct) regardless of scale. So the number just being large is not a problem, problems arise when one tries adding together large numbers and small numbers, because then the small number gets lost in the rounding error of the large number. Or a better example: When subtracting two large numbers, and the result is a small number: The small number is going to be largely influenced by rounding on the large ones.

However if the operations are only multiplication or division, or addition of numbers of similar magnitude, then this is not a concern. (Ofc other concerns such as f32 error accumulation apply.)
As an example: The t parameter at the end will always* have around 5 digits of precision, since it's computed as a quotient of two numbers which have a similar* error.

There's practically no additions in this algorithm, except:
Vec3::dot, Vec3::length_squared and the vector operations at the end.

As I've said Vec3::length_squared is really the best measurement of length we can obtain.
The vector operations at the end are fundamentally constrained by the precision of the input points, if your points have coordinates on the order of 1megaunit, then they will have an error on the order of units, so the output of this method will obviously have a similar error. If you scale the whole thing down, the error also scales down.

The potentially most problematic component is Vec3::dot, where the situation of "subtracting two very close large numbers" might occur, if you have a point 1Mu far away from your line segment, which is a bunch shorter, and the point is roughly orthogonal to the line segment, then projection_scaled, might have a surprisingly large error, compared to the magnitude of length_scaled.

But I consider the limitations of Vec3::dot when dealing with extremely long nearly orthogonal vectors to be beyond my scope.

Nonetheless, you do make a good point, I appreciate that people are thinking about the precision issues during review.

// `point` is too far "right" in the picture
if projection_scaled >= length_squared {
return self.vertices[1];
}

// Point lies somewhere in the middle, we compute the closest point by finding the parameter along the line.
let t = projection_scaled / length_squared;
self.vertices[0] + t * segment_vector
}
}

impl From<[Vec2; 2]> for Segment2d {
Expand Down Expand Up @@ -2288,6 +2320,52 @@ mod tests {
assert_eq!(rhombus.closest_point(Vec2::new(-0.55, 0.35)), Vec2::ZERO);
}

#[test]
fn segment_closest_point() {
assert_eq!(
Segment2d::new(Vec2::new(0.0, 0.0), Vec2::new(3.0, 0.0))
.closest_point(Vec2::new(1.0, 6.0)),
Vec2::new(1.0, 0.0)
);

let segments = [
Segment2d::new(Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add one very long segment?

Segment2d::new(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)),
Segment2d::new(Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)),
Segment2d::new(Vec2::new(1.0, 0.0), Vec2::new(1.0, 5.0 * f32::EPSILON)),
];
let points = [
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(-1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(-1.0, 0.0),
Vec2::new(5.0, -1.0),
Vec2::new(1.0, f32::EPSILON),
];

for point in points.iter() {
for segment in segments.iter() {
let closest = segment.closest_point(*point);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.point1()),
"Closest point must always be at least as close as either vertex."
);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.point2()),
"Closest point must always be at least as close as either vertex."
);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.center()),
"Closest point must always be at least as close as the center."
);
let closest_to_closest = segment.closest_point(closest);
// Closest point must already be on the segment
assert_relative_eq!(closest_to_closest, closest);
}
}
}

#[test]
fn circle_math() {
let circle = Circle { radius: 3.0 };
Expand Down
81 changes: 81 additions & 0 deletions crates/bevy_math/src/primitives/dim3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,38 @@ impl Segment3d {
self.reverse();
self
}

/// Returns the point on the [`Segment3d`] that is closest to the specified `point`.
#[inline(always)]
pub fn closest_point(&self, point: Vec3) -> Vec3 {
// `point`
// x
// ^|
// / |
//`offset`/ |
// / | `segment_vector`
// x----.-------------->x
// 0 t 1
let segment_vector = self.vertices[1] - self.vertices[0];
let offset = point - self.vertices[0];
// The signed projection of `offset` onto `segment_vector`, scaled by the length of the segment.
let projection_scaled = segment_vector.dot(offset);

// `point` is too far "left" in the picture
if projection_scaled <= 0.0 {
return self.vertices[0];
}

let length_squared = segment_vector.length_squared();
// `point` is too far "right" in the picture
if projection_scaled >= length_squared {
return self.vertices[1];
}

// Point lies somewhere in the middle, we compute the closest point by finding the parameter along the line.
let t = projection_scaled / length_squared;
self.vertices[0] + t * segment_vector
}
}

impl From<[Vec3; 2]> for Segment3d {
Expand Down Expand Up @@ -1532,6 +1564,55 @@ mod tests {
);
}

#[test]
fn segment_closest_point() {
assert_eq!(
Segment3d::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 0.0))
.closest_point(Vec3::new(1.0, 6.0, -2.0)),
Vec3::new(1.0, 0.0, 0.0)
);

let segments = [
Segment3d::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0)),
Segment3d::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0)),
Segment3d::new(Vec3::new(1.0, 0.0, 2.0), Vec3::new(0.0, 1.0, -2.0)),
Segment3d::new(
Vec3::new(1.0, 0.0, 0.0),
Vec3::new(1.0, 5.0 * f32::EPSILON, 0.0),
),
];
let points = [
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(1.0, 0.0, 0.0),
Vec3::new(-1.0, 1.0, 2.0),
Vec3::new(1.0, 1.0, 1.0),
Vec3::new(-1.0, 0.0, 0.0),
Vec3::new(5.0, -1.0, 0.5),
Vec3::new(1.0, f32::EPSILON, 0.0),
];

for point in points.iter() {
for segment in segments.iter() {
let closest = segment.closest_point(*point);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.point1()),
"Closest point must always be at least as close as either vertex."
);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.point2()),
"Closest point must always be at least as close as either vertex."
);
assert!(
point.distance_squared(closest) <= point.distance_squared(segment.center()),
"Closest point must always be at least as close as the center."
);
let closest_to_closest = segment.closest_point(closest);
// Closest point must already be on the segment
assert_relative_eq!(closest_to_closest, closest);
}
}
}

#[test]
fn sphere_math() {
let sphere = Sphere { radius: 4.0 };
Expand Down
Loading