public static NearestPointResult NearestPointOnCurve(Vector2[] b, Vector2 p) { // convert points to bezier form if (b.Length != 4) { throw new ArgumentException(); } /* Convert problem to 5th-degree Bezier form */ Vector2[] w = ConvertToBezierForm(p, b); /* Find all possible roots of 5th-degree equation */ double[] t_candidate = new double[W_DEGREE]; int n_soln = FindRoots(w, W_DEGREE, t_candidate, 0); /* Compare distances of P to all candidates, and to t=0, and t=1 */ double t; double dist, new_dist; Vector2 p1; /* Check distance to beginning of curve, where t = 0 */ dist = (p - b[0]).VectorLength2; t = 0; /* Find distances for candidate points */ for (int i = 0; i < n_soln; i++) { p1 = Bezier(b, DEGREE, t_candidate[i], null, null); new_dist = (p - p1).VectorLength2; if (new_dist < dist) { dist = new_dist; t = t_candidate[i]; } } /* Finally, look at distance to end point, where t = 1.0 */ new_dist = (p - b[DEGREE]).VectorLength2; if (new_dist < dist) { dist = new_dist; t = 1; } /* Return the point on the curve at parameter value t */ NearestPointResult r = new NearestPointResult(); r.NearestPoint = Bezier(b, DEGREE, t, null, null); r.tval = t; return(r); }
public static NearestPointResult NearestPointOnCurve(Vector2[] b, Vector2 p) { // convert points to bezier form if (b.Length != 4) throw new ArgumentException(); /* Convert problem to 5th-degree Bezier form */ Vector2[] w = ConvertToBezierForm(p, b); /* Find all possible roots of 5th-degree equation */ double[] t_candidate = new double[W_DEGREE]; int n_soln = FindRoots(w, W_DEGREE, t_candidate, 0); /* Compare distances of P to all candidates, and to t=0, and t=1 */ double t; double dist, new_dist; Vector2 p1; /* Check distance to beginning of curve, where t = 0 */ dist = (p - b[0]).VectorLength2; t = 0; /* Find distances for candidate points */ for (int i = 0; i < n_soln; i++) { p1 = Bezier(b, DEGREE, t_candidate[i], null, null); new_dist = (p - p1).VectorLength2; if (new_dist < dist) { dist = new_dist; t = t_candidate[i]; } } /* Finally, look at distance to end point, where t = 1.0 */ new_dist = (p - b[DEGREE]).VectorLength2; if (new_dist < dist) { dist = new_dist; t = 1; } /* Return the point on the curve at parameter value t */ NearestPointResult r = new NearestPointResult(); r.NearestPoint = Bezier(b, DEGREE, t, null, null); r.tval = t; return r; }