Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

B-spline curve and surface, least squares conformal map - #7590

Merged
Fedr merged 21 commits into
masterfrom
bspline-surface
Nov 26, 2026
Merged

Fedr merged 21 commits into
masterfrom
bspline-surface

Conversation

@Grantim

@Grantim Grantim commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Makes the B-spline code and the conformal parametrization from the private helpers of saveMeshAsStep (#7581) public. #7581 can then call these functions instead of its own. The numerics follow #7581, with the differences listed below. Independent of the analytic fits in #7589.

New

MRBSpline.h, in double, with all arrays (knots, control points, the points, parameters and weights of the fits) in MR::Vector:

  • BSplineCurve: degree (1 to 7), knots, control points; valid(), eval( t ).
  • BSplineSurface: degrees, knots along u and v, control points; valid(), eval( uv, du, dv ) with optional partial derivatives, normal( uv ), project( p, uv, iterations ) by Gauss-Newton iterations with step control, kept in the domain. The number of control points along u and v is derived from the knots. valid() checks the degree and that the numbers of knots and control points agree; for not valid data eval and normal return zero vectors and project returns the given parameters, without reading beyond the arrays.
  • interpolateBSplineCurve( points ): curve of degree min( 3, n - 1 ) through all points, chord-length parameters in [0, 1], inner knots by averaging.
  • fitBSplineSurface( points, uvs, BSplineSurfaceFitSettings ): bicubic least squares fit to points with known parameters, with smoothing of the second differences of the control net and optional weights of the squared residuals. The differences are divided by the differences of the Greville abscissae, so bilinear functions of (u, v), planes among them, are not smoothed and are reproduced. The solution is unique if smoothing > 0 and no non-zero bilinear function of (u, v) vanishes at all points with positive weights.

Both return std::optional: std::nullopt for fewer than 2 curve points, two consecutive curve points equal or not finite coordinates of them, fewer than 4 control points along u or v, or a failed factorization (only with violated preconditions). The clamped uniform knots and the sparse solve they share are internal.

MRConformalMap.h: leastSquaresConformalMap( MeshPart ) returns Expected<VertUVCoords>, the least squares conformal map of a part, meant for a part with disk topology, with the two vertices most distant along its main direction pinned at (0,0) and (1,0). The part must be connected via the edges of its non-degenerate triangles: in a component without both pinned vertices the system is singular, which gives an error or meaningless coordinates there. Errors are returned for not finite coordinates, a not finite solution and a degenerate system (e.g. a vertex only in degenerate triangles, or no non-degenerate triangles; degenerate triangles give zero rows). It reuses PointAccumulator::getBestLinef and findDirMinMaxBruteForce for the pinned vertices and unfoldOnPlane for the triangles in their planes.

Differences from the helpers in #7581:

  • The surface type keeps no cache: the 60x60 grid that saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 uses to start projections without an initial guess, and the fit error, stay in the caller.
  • fitBSplineSurface multiplies the squared residual of each point by its weight; saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 effectively squares its weights, so it would pass 0.01 where it now passes 0.1.
  • fitBSplineSurface smooths by second differences divided by the differences of the Greville abscissae (scaled to (1, -2, 1) for equal differences), with the smoothing weight proportional to the sum of the weights of the points. saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 takes the differences by index, which bends exact planes with more than 4 control points along u or v (10x5 control points, points in an ellipse inside [0.06, 0.94]^2: by 1.6e-5 of the diagonal at the points and up to 0.06 outside them); now bilinear functions are reproduced to rounding. Fits of curved surfaces at the default smoothing change accordingly: with weights 1 and 0.1, points in an ellipse and 6x4 to 40x8 control points, by up to 4e-5 of the diagonal inside the ellipse and up to 0.15 outside it, near the corners of the domain.
  • leastSquaresConformalMap takes a MeshPart instead of separate point and triangle arrays, returns float coordinates like other UV maps, and does not rescale them into a margin square, which stays in the caller.
  • Sparse solvers instead of dense ones: interpolateBSplineCurve factorizes its square banded collocation system by Eigen::SparseLU (O(n) non-zeros instead of a dense n x n LU), and fitBSplineSurface sums the normal equations per knot span (memory independent of the number of points) and solves them by Eigen::SimplicialLDLT. The curve avoids normal equations, since they square the condition number, which grows with uneven chord lengths: on random chains with 30% of the steps shorter by 1e-4 to 1e-6, they missed the points by up to 6e-5 or failed, while the LU interpolates them to 1.2e-11 or better. For helices of 50 and 800 points the curve control points agree with the dense LU of saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 to 5e-16 (relative); on the uneven chains both LUs pass through the points, but their control points (up to 5e5 at 1e-6) differ by up to 1e-5 relative, as the conditioning of the problem allows. The speed was not measured.
  • project minimizes the linearized distance over the domain (the step by SymMatrix2d::pseudoinverse, then the better of the two border lines through the clamped step) instead of clamping both coordinates of the full step, so it finds closest points on the border when the derivatives are not orthogonal and does not stall on a collapsed row of control points. It starts from the initial parameters clamped to the domain.
  • project accepts a step only if the squared distance decreases by at least 1/4 of the decrease predicted by the linearization; otherwise it shortens the step 2 to 10 times, to the minimum of the parabola through the squared distances at both ends and the slope at the start. It stops when the predicted decrease is below the rounding error of the squared distance, 8 eps |r| (|p| + |r|). On the convex side, Gauss-Newton steps are 1 + distance / curvature radius times too long, and plain Gauss-Newton (saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581) can alternate between two wrong points. Above an arch of curvature radius 1, points at distances 1 to 50 converge within 3 to 10 iterations (to 1e-7 or better in the parameters); at 100 the parameters are 0.006 off after 12 iterations, and at 0.5 the convergence is linear (2e-5 after 12). Halving instead of the interpolation left the parameters 0.019, 0.058 and 0.105 off at distances 10, 25 and 100. In a simulation of the loop of saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 (6x4 and 10x5 fits to 2000 points, 8 rounds of project( p, uv, 4 ) from the previous parameters, also translated by 1e3 and 1e5), a projection costs 2.1-3.2 surface evaluations on average and at most 11 (4 in saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581). The parameters are found to about sqrt( 8 eps |r| |p| ) / |du|, e.g. 2e-9 for |p| ~ 3 at distance 0.01, and 2e-6 for |p| ~ 1.7e5 at distance 0.1.
  • normal( uv ) returns a zero vector where the derivatives are zero or parallel (as normalized() does in MeshLib); saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 used (0,0,1) there, which stays in the caller if it needs a fallback.

Tests

MRBSplineTests.cpp:

  • curve interpolation of a helix, of two points, of three points (degree 2), of four points (a cubic without inner knots), and of unevenly spaced points, among them two consecutive steps of 1e-5 (which the normal equations missed by 5e-6); std::nullopt for one point, equal consecutive points, all points equal, and infinite or NaN coordinates;
  • not valid curve and surface (degree above 7, wrong number of knots or control points): valid() is false, eval, normal and project return as described above;
  • surface fit of a plane (exact) and of a curved surface, an outlier with zero weight, and two shifted copies of a plane with weights 1 and 3 that must give the weighted mean; a bilinear surface with 6x4 and 10x5 control points from points only in an ellipse, reproduced in the whole domain; std::nullopt for numU = 3, numV = 3, and no points (a failed factorization);
  • projection of a point above the surface; onto the border of the domain of a plane with not orthogonal derivatives, also from a start outside the domain; from a collapsed row of control points; and of points at distances 3 and 25 above an arch of curvature radius 1, where the steps are 4 and 26 times too long;
  • conformal map of a region of a planar grid from makeRegularGridMesh: a similarity, vertices outside the region untouched, triangles not mirrored; of a non-developable fan of 6 triangles, against coordinates computed independently as the minimum of the Dirichlet energy minus the area of the map (the map agrees to 1.2e-8; unit weights of the triangles would be 7e-3 off); errors for a vertex only in a degenerate triangle, a region of only a degenerate triangle, and a NaN coordinate.

Locally (Windows, MSVC): the full MRTest suite passes in Release (770 tests) and Debug (769 tests; one test is Release-only). MRBSpline.cpp, MRConformalMap.cpp and the test compile with GCC 13 at -O2 with MeshLib's GCC warning flags and -Werror, with and without NDEBUG, and the B-spline tests (not the conformal map, which needs all of MRMesh) pass in a standalone GCC build, also with -mfma -ffp-contract=fast. Bindings, Clang and wasm are left to CI. The last commits (MR::Vector instead of std::vector, valid(), the failures of interpolateBSplineCurve, the not finite solution of the conformal map) were checked only by the tests of MRBSplineTests.cpp in a standalone MSVC Release build.

Generated with Claude Code

BSplineCurve and BSplineSurface (evaluation with derivatives, normal,
projection by Newton iterations), makeClampedUniformKnots,
interpolateBSplineCurve, fitBSplineSurface with BSplineSurfaceFitSettings,
and leastSquaresConformalMap of a mesh part with disk topology.
The numerics are taken from the private helpers of saveMeshAsStep (#7581).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Grantim and others added 18 commits November 25, 2026 19:30
BSplineSurface::project solves the Gauss-Newton step with SymMatrix2d::pseudoinverse
instead of a determinant clamped at 1e-30, which stalled where a derivative is zero,
and minimizes the linearized distance in the domain: when the step leaves the domain,
the better of the two border lines through the clamped step is taken, instead of
clamping both coordinates, which stopped at wrong points when u and v are not orthogonal.

leastSquaresConformalMap returns an error when the LDLT factorization fails,
e.g. for a vertex only in degenerate triangles; before, Eigen left the solution
uninitialized and returned it as a success.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
leastSquaresConformalMap finds the main direction with PointAccumulator::getBestLine
and the pinned vertices with findDirMinMaxBruteForce, numbers the unknowns with
makeVectorWithSeqNums, and returns VertUVCoords.
makeClampedUniformKnots is internal; the curve interpolation starts from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve solves the banded collocation system by SparseLU instead
of a dense LU, O(n) instead of O(n^3) for a chain of n points.
fitBSplineSurface sums the normal equations per knot span (all points of a span
share 16 basis functions, only the upper triangle is kept) and solves the sparse
system by SimplicialLDLT, so the memory no longer grows as (numU * numV)^2 and
does not grow with the number of points either.
Both keep plain results: their systems are not singular under the preconditions,
which are now documented and asserted (increasing curve parameters, i.e. no equal
consecutive points; for the fit, smoothing > 0 and 4 points in general position).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The part must be connected via the edges of its non-degenerate triangles; in a
component without both pinned vertices the system is singular, which gives an
error or meaningless coordinates there. Disk topology is what the map is meant for.
Not finite coordinates leave the vertices to pin undefined and now return an error
right away, instead of the check of the solution for finite values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… region

Projection with the closest point on the border of the domain of a plane with not
orthogonal derivatives, also outside in both u and v, and from a collapsed row of
control points; a 3-point curve of degree 2; weights multiplying the squared
distances; the conformal map of a region of a larger mesh, not mirrored, and its
errors for a vertex only in a degenerate triangle and for a NaN coordinate.
The unused MRConstants.h include is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With violated preconditions (equal consecutive points of a curve, too few or
degenerate points of a fit) the factorization fails, and Eigen's solve then reads
factors that were not computed (SparseLU, an access violation in Release) or
leaves the solution uninitialized (SimplicialLDLT). The control points are NaN
instead, and the header says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…span

interpolateBSplineCurve returns an empty curve for fewer than 2 points, and
fitBSplineSurface an empty surface for numU or numV less than 4, instead of
reading or writing out of bounds in Release; the asserts stay. The knot span is
found by std::upper_bound. Dead guards in the curve parameters and in the
smoothing weight are removed, the conformal map takes getBestLinef, and the
header says that normal is zero where the derivatives are zero or parallel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve solves the normal equations of its banded collocation
system by SimplicialLDLT, like the other sparse solves in MeshLib, instead of
the only SparseLU. Equal consecutive points may now give arbitrary control
points instead of NaN, which the header says. A test of a curve through
unevenly spaced points.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The second differences of the control net are divided by the differences of the
Greville abscissae, where the control points of linear functions sit, and scaled
to (1, -2, 1) for equal differences. They were by index, which is not zero for a
plane with more than 4 clamped control points along u or v, so the smoothing bent
exact planes (up to 0.06 of the diagonal outside 10x5 points in an ellipse).
Now bilinear functions of (u, v) are not smoothed and are reproduced. The
smoothing weight scales with the sum of the weights of the points instead of
their number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BSplineSurface::project accepts a Gauss-Newton step only if the squared
distance decreases by at least 1/4 of the decrease predicted by the
linearization, and halves it toward the current parameters up to 4 times
otherwise; the iterations stop when no step is left. On the convex side the
steps are 1 + distance / curvature radius times too long: plain Gauss-Newton
alternated between two wrong points, e.g. at distances 2.54 and 3.08 from a
half-cylinder of radius 1 instead of 2.00, and a step exactly 2 times too long,
which only keeps the distance, would converge very slowly. The evaluation at
an accepted point is reused for the next step, so only the evaluation of the
result and rejected steps cost more than before. Since steps below ~1e-9 do not
change the computed distance, off-surface parameters are found to about 1e-9.
Tests: a point 3 above an arch of curvature radius 1, and the collapsed row
starting away from its answer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BSplineSurface::project clamps the initial parameters to the domain: from
outside it, the steps were halved toward the start, and the result could stay
outside (on the skewed plane of the tests, (1.5, 0.65) instead of (1, 0.8)).
The step is halved without a limit, and the iterations stop when the predicted
decrease of the squared distance is below its rounding error,
8 eps |r| (|p| + |r|): once converged, a step that raised the computed distance
by an ulp was rejected after 5 evaluations. In a simulation of the loop of #7581
(6x4 and 10x5 fits to 2000 points, 8 rounds of project( p, uv, 4 ) from the
previous parameters, also translated by 1e3 and 1e5), the evaluations per call
drop from 7.3-8.5 to 2.1-3.2 with the same final fits. Test: a projection from
outside the domain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… fit

interpolateBSplineCurve and fitBSplineSurface return std::optional: nullopt for
fewer than 2 points, numU or numV less than 4, or a failed factorization,
instead of an empty curve or surface and NaN control points. The asserts of
these sizes go, since nullopt is now their documented result. One helper solves
both systems by SimplicialLDLT on the upper triangle; the control points are
bit-identical to before (helices of 40 and 800 points, uneven chains, fits).
Tests: a cubic through 4 points without inner knots, and the nullopt results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ate triangles

The third vertex of each triangle in the frame of its first edge comes from
unfoldOnPlane instead of an orthonormal frame built here. The right-hand side
is one Eigen vector with two rows per face, and degenerate triangles give zero
rows; without non-degenerate triangles the matrix is zero and its factorization
fails, so the separate error for that case goes (the header says "degenerate
system"). MREigenSparseCore.h is included as in the other sparse solves. The
coordinates are identical to before on the grid of the test and on a curved
strip, also with two degenerate triangles in its middle. Test: a region of
only a degenerate triangle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A rejected step of BSplineSurface::project is shortened to the minimum of the
parabola through the squared distances at both ends with the slope at the
start, but 2 to 10 times, instead of halved. Halving scales u and v together,
so far from the convex side, where the steps are 1 + distance / curvature
radius times too long, the other parameter lagged: above an arch of curvature
radius 1, the parameters were 0.019, 0.058 and 0.105 off after 12 iterations
at distances 10, 25 and 100. Now distances 1 to 50 converge within 3 to 10
iterations (8.7e-9 at 10, 1.1e-8 at 25); 100 is still 0.006 off. The
evaluations per projection in the simulation of the loop of #7581 stay at
2.1-3.2, at most 11 instead of 18. Test: a point at distance 25 above the arch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bsplineBasis takes no number of control points: it always equaled
knots.size() - deg - 1, which now bounds the span search. The curve and
surface results are bit-identical (control points, values and derivatives
also outside the domain, projections).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve factorizes the square collocation matrix by SparseLU
instead of its normal equations by SimplicialLDLT: those square the condition
number, which grows as the chord lengths get uneven. On random chains with 30%
of the steps shorter by r, the points were missed by up to 6e-9, 1e-5 and 6e-5
at r = 1e-3, 1e-4 and 1e-5 (and nullopt for some chains at 1e-5 and 1e-6);
now by at most 3e-14, 2e-13, 2e-12, and 1e-11 at r = 1e-6. One template solves
both systems after checking the factorization. Evenly spaced helices of 40 and
800 points give the same control points up to 2e-15 and 6e-14 (z up to 40).
Test: a chain with two consecutive steps of 1e-5, which the normal equations
missed by 5e-6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n [0, 1]^2

The header says what BSplineSurface::project does (Gauss-Newton with step
control from uv clamped to the domain, result in it, stopping at rounding
errors), and two lines in the .cpp keep the non-obvious parts: the 1/4
acceptance, the parabola and the scale of the cutoff. fitBSplineSurface
expects the parameters in the unit square; outside it the end polynomials are
extrapolated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dMesh, fit failures

The conformal map is checked on a fan of 6 triangles around a raised vertex
(312 degrees around it) against coordinates computed independently, as the
minimum of the Dirichlet energy minus the area of the map (and by Levy's least
squares in own frames): the library agrees to 1.2e-8, while unit weights of
the triangles are up to 7e-3 off, so on the planar grid alone any weighting
passed. The grid comes from makeRegularGridMesh and its region from the
vertices with x <= 5 by getInnerFaces. The fit returns nullopt for numV = 3
and for no points, whose zero matrix fails the factorization.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Grantim Grantim added the test-pip-build Build Python wheels (and discard them) label Nov 26, 2026
@Grantim
Grantim marked this pull request as ready for review November 26, 2026 08:26
Fedr and others added 2 commits November 26, 2026 11:48
…instead of NaN

BSplineCurve and BSplineSurface get valid(); eval, normal and project
return zero or given values for a degree above 7 or inconsistent sizes
instead of writing beyond fixed-size buffers. interpolateBSplineCurve
returns nullopt for equal consecutive or not finite points, which were
only asserted. leastSquaresConformalMap returns an error for a not
finite solution.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Knots, control points, the points, parameters and weights of the fits,
and the internal arrays.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test-pip-build Build Python wheels (and discard them)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants