Skip to content

Fit CAD ​

fit_cad(mesh, path) turns the fitted patches of a closed triangle skin into a CAD solid: every patch that fit_primitives accepted becomes a plane, sphere, cylinder, cone or torus face trimmed by the patch boundary, a rolling-ball fillet or blend (of one radius or a radius varying along it) or a helical thread face its own feature face, a chamfer, a conic blend, a tapered or variable-pitch thread or a corner where blends meet its own face too, any other patch no primitive explains a freeform B-spline face, the faces are sewn into a solid that OpenCASCADE checks, and the solid is written as STEP. It is the last step of skin to CAD, after segment and fit_primitives. It runs on OpenCASCADE, which the PyPI wheels and the release binaries include, and falls back, in a build without it, to a kernel-free native backend that writes the fitted primitives as analytic STEP faces.

python
import meshioplusplus as mp

skin = mp.repair(mp.read("part.stl"))
seg = mp.segment(skin, curvature_tolerance=1.0, min_patch_cells=20)
fit = mp.fit_primitives(seg, tolerance=2e-3)

solid, report = mp.fit_cad(fit, "part.step", return_report=True)
report["valid"], report["num_cylinder"], report["num_demoted"]
report["volume_ratio"], report["max_deviation"]   # against the skin
report["backend"]                                 # "occt" or "native"

mp.fit_cad(mp.read("bracket.stl"), "bracket.step")  # segments and fits it first

The turned part of skin to CAD as a CAD solid: two planes, a cylinder, a torus fillet, a cone and a spherical dome, re-meshed and coloured by face type

Unlike the faceted step writer, whose solid is one flat face per triangle, the STEP file fit_cad writes carries CYLINDRICAL_SURFACE, CONICAL_SURFACE, SPHERICAL_SURFACE and TOROIDAL_SURFACE faces a CAD tool can select, dimension and edit. A skin without segment:patch is segmented first with method="primitive", which ends a patch where the plane, cylinder, cone, sphere or torus its facets lie on changes (so a rounded end comes apart from the flat it is tangent to), and fitted at the same absolute tolerance, 1e-3 of the bounding-box diagonal; a skin with patches but no fit:patch_* table is fitted with the default options. A CAD-exported STL, whose points lie exactly on its surfaces, comes out as one face per surface, not a patchwork. A noisy scan wants a curvature test and a min_patch_cells in the tens, so segment it yourself, or pass those to the CLI with --segment-method angle.

How the solid is built ​

  • Faces. A patch whose fit was accepted, and whose type is in types, becomes one face on its fitted surface. A patch no primitive explains is tried, in order, as a rolling-ball fillet between two analytic faces (fillets), as a helical thread face (threads; then of varying pitch or on a taper), as a chamfer or conic blend between two analytic faces (fillets) and, with freeform (the default), as a B-spline face; once the freeform faces exist, a patch between two fitted faces, one of them freeform, is tried as a rolling-ball blend against them, and a corner patch among three or more fitted faces as a vertex blend (fillets). Every other surface cell (a type left out, a freeform fit that failed, a cell with no patch) becomes planar faces, each edge-connected group of coplanar facets one face with its holes as inner loops.
  • Edges. Where two patches meet, the mesh edges between them form chains from one junction (a point where three or more patches meet) to the next; a closed chain is split in two. Between two analytic faces the edge is the branch of the two surfaces' exact intersection that lies within the tolerance of the chain, when exact_edges is set and one does (a plane meeting a cylinder gives a circle). Otherwise, notably where a fillet meets its wall tangentially and no intersection is stable, the edge is a B-spline through the chain, smoothed and moved onto both surfaces, kept only if it stays within the tolerance of both. Beside a facet, the edge is the mesh's own straight edge.
  • Vertices. A junction among analytic faces only is moved onto all of their surfaces; one beside a facet keeps the mesh position.
  • Solid. Each face gets parameter-space curves that are continuous around its loops (so a boundary running along a cylinder's seam or a torus's equator does not fall apart), OpenCASCADE adds the seams and repairs the faces, sews them and closes each shell into a solid, one per edge-connected piece of the skin. A patch with no boundary at all, a whole sphere or torus, is its surface's natural face.

Refining the patches first ​

With refine_segmentation=True (C++ mRefineSegmentation, v17.11.0; off by default, so the output is what it was before the option existed) the patches are refined by refine_patches before the solid is built, after any segmentation and fit fit_cad runs itself: a variational shape approximation (Cohen-Steiner, Alliez and Desbrun 2004, with the primitive proxies of Wu and Kobbelt 2005) moves patch boundaries to the surfaces, splits a primitive out of a patch no primitive explains by seeded RANSAC (Schnabel, Wahl and Klein 2007) and merges neighbours one primitive explains, so a fillet strip an angle segmentation gave to the plane beside it, or a cylinder cut in two at a smooth edge, becomes the analytic face it is. The refinement's options are max_refine_iterations (10), refine_epsilon (1e-3, the least gain in explained area worth another iteration), normal_weight (1), allow_merge and allow_split (on), ransac_seed (a fixed default, so the output is reproducible) and refine_tolerance with relative_tolerance (1e-3 of the bounding-box diagonal). The report then holds refined, refine_iterations, num_refine_splits, num_refine_merges and the area share primitives explain before and after (initial_explained_area_fraction, explained_area_fraction), and the returned mesh carries the per-patch refine:* field data. On an angle-segmented turned part the refinement raises the explained area from 38% to 100% and every surface becomes an analytic face of a valid solid.

The refinement knows primitives only: a patch it finds no primitive for within its tolerance stays unexplained here (tried as a freeform face) even when the fit table, by fit_primitives' looser measure, names one, and a blend or a corner the feature fits explain whole may come out cut into strips. So the OpenCASCADE backend builds the solid from the refined patches and from the patches as given, and keeps the refined one unless the other is better: valid where it is not, then fewer facet faces, fewer demotions, fewer faces. refinement_kept in the report says which; the refinement's counts describe what it did either way, and its refine:* field data comes along only when it was kept. Refinement therefore never makes the OpenCASCADE result worse by that measure, and costs a second build. The native backend, which has no feature fits, always keeps the refinement.

Constrained primitives ​

fit_primitives fits each patch on its own, so the cylinder, cone, torus and dome of a turned part each get an axis of their own that differs from the others in its last digits, or by the noise of a scan, and the planes at its shoulders are almost, not exactly, perpendicular to it. A CAD tool reads those faces as unrelated surfaces, and the edges between them are intersections of surfaces that do not quite meet where they should. With constrain_primitives=True (C++ mConstrainPrimitives; off by default, so the output is what it was without it; both backends) the primitives are fitted together before either backend builds a face, after any segmentation, fit and refinement fit_cad runs itself (detail/primitive_constraints):

  1. Coaxial groups. In patch-row order, a cylinder, cone or torus joins the group of the first earlier one whose axis it is parallel to and lies on, within what moves its patch by twice its tolerance; a sphere joins a group whose axis passes through its centre. A group of two or more is refitted jointly by Levenberg-Marquardt: one axis for all, and each member's own parameters along it (a cylinder's radius, a cone's apex height and half-angle, a torus's centre height and radii, a sphere's centre height and radius). The members then share the axis direction bit for bit (a cone's pointing into the cone, so possibly negated), and their axis points lie on one line.
  2. Planes. In row order, a plane whose normal is parallel to a reference direction (the axes first, then the planes already seen) takes that direction as its normal, and one perpendicular to one or two references is made exactly perpendicular to them; its offset is refitted. The shoulders of a turned part take its axis as their normal, and a box's six faces come out pairwise parallel and mutually perpendicular.
  3. Equal radii. Cylinders, spheres and tori (by their minor radius) whose radii differ by less than the tolerance take their point-weighted mean, so a pattern of holes drilled with one tool has one radius.

A change is kept only when its patch still passes the test fit_primitives accepted it under (its RMS distance and its share of points within the patch's tolerance) and its largest distance stays within the tolerance the faces are demoted at, or no larger than it was; otherwise the primitive leaves the group and keeps its own fit. So the pass itself never demotes a face, and a primitive that is not on the shared axis (a cross-drilled hole, a boss beside the axis) is left alone. OpenCASCADE builds the solid from the constrained surfaces, though, and a tangent junction the unconstrained surfaces kept can fail to build: on the noisy turned part of seed 7 in the Python fixtures, the torus fillet and its wall demote two faces. So the solid is kept constrained only where it demotes no more patches than the unconstrained one; otherwise the unconstrained solid is returned, with the counts at zero, and a warning says so. The usual case costs one build; a fallback costs up to three. The pass is serial and walked in row order, so its result does not depend on the thread count. The report adds num_constrained_primitives (patches whose primitive changed) and num_constraint_groups (coaxial groups, parallel-normal families and equal-radius sets of two or more), and the native backend, whose result is the skin itself, returns the constrained fit:patch_* table.

Measured on the golden fixtures of test_fit_cad_goldens.cpp, both backends (OpenCASCADE 7.6.3): on the noisy turned part tilted off the coordinate axes (ConstrainedPrimitivesShareOneAxis), the axes and normals fitted one by one disagree by up to 0.009 degrees and the dome's centre lies 1e-4 off the wall's axis; constrained, the six primitives share one axis direction bit for bit (a cone's negated), every face is kept, and the face count is unchanged. On the untilted noisy turned part OpenCASCADE's largest deviation falls from 0.0128 to 0.0123. The filleted plate's six planes and two cylinders are made exactly parallel and perpendicular (6 primitives in 3 groups) and the threaded rod's cylinders, cones and planes share their axis (7 in 3), with the same faces, facets and demotions as without the option; the box, capped cylinder, saddle box, wavy band and rounded box have nothing to constrain, their planes' normals being exact already. The pass itself takes milliseconds.

This is the fourth phase of iterative skin to CAD; what it leaves out (parallel but separate axes, angles other than right ones, symmetric patterns) is listed with the measured and parked notes.

Freeform faces ​

A patch fit_primitives left unexplained (no accepted primitive, or one with non-finite parameters) gets a B-spline surface fitted to it, so a smooth blend, a dent or a styled panel becomes one CAD face instead of hundreds of facets:

  1. A parametrisation. The patch is flattened over its best-fit plane (principal components) or, when that folds, unrolled around a cylinder: the axis is the direction its normals are most perpendicular to (the smallest eigenvector of Σ nnᵀ), the radius a least-squares circle fit of the points around it, the angle cut at the widest gap. A flattening whose triangles do not all keep one orientation is not a parametrisation and is not used. A patch that folds over both (a doubly curled one, or a band closed around an axis) is, with freeform_split (the default), split into pieces that one of them does parametrise.
  2. A height field. The offset from the plane or the cylinder is resampled on a grid over the flattened bounding box, interpolated inside the patch's triangles and continued from the nearest boundary point outside them, so the surface extends past the patch's trim.
  3. The fit. GeomAPI_PointsToBSplineSurface fits the grid (iso-parametric, C2, degrees up to freeform_degree, default 3, valid 3–8). The grid starts near √n points a side and doubles up to freeform_max_control (default 64, valid 4–1024) until every patch vertex lies within half the tolerance and every facet centre within the tolerance; a patch that never gets there, or a skin too coarse for any smooth surface to pass within it, stays faceted.
  4. The face. The surface is oriented by the facet normals and goes through the same trimming, sewing, check and demotion as an analytic face; its fit_cad:type is 6 (kFitCadBsplineType), and the report's num_bspline counts it.

freeform=False keeps every unexplained patch faceted.

Splitting curled patches ​

A patch that folds over both flattenings is halved at the area-weighted median of n · e, where e is the direction its normals spread along most (the principal axis of the area-weighted Σ nnᵀ): a cut along an iso-line of the normal, a smooth curve on a smooth surface. Each half is split into its edge-connected components, and a component that still folds is halved again, up to four times. Each piece that now flattens becomes its own freeform face under a new patch label, numbered after the largest existing one in the order of its lowest facet, so fit_cad:patch tells the pieces apart; a piece under 16 triangles, or one still folding at the fourth halving, stays faceted. The edges between pieces are approximated B-splines like any other tangent junction. The split is deterministic and needs no OpenCASCADE (detail/patch_flatten); num_split_patches counts the pieces, and freeform_split=False keeps such a patch faceted, as before.

A capped band whose radius waves along its axis: the wall, closed around the axis, is split into two freeform B-spline faces between two planar caps

General freeform faces ​

With freeform_general=True (C++ mFreeformGeneral, v17.11.0; off by default) a patch the plane and unrolled-cylinder fit leaves unexplained gets a second, general attempt before it is split or faceted, so every face the earlier fit built stays as it was:

  1. A disc parametrisation. A patch with one boundary loop is mapped to the plane by least-squares conformal maps (Lévy, Petitjean, Ray and Maillot, ACM TOG 2002, doi:10.1145/566654.566590), its two farthest boundary vertices pinned, or, if that flips a triangle, by mean-value coordinates with the boundary on a circle (Floater, CAGD 2003), which is bijective for a disc; the map is turned so its bounding box is the smallest. Both are solved by OpenCASCADE-free sparse iterative solvers whose results do not depend on the thread count.
  2. The fit. A cubic B-spline on uniform knots over that box is fitted by least squares to the vertices and, at a quarter of their weight, the facet centroids, with a thin-plate term near zero where the samples are and strong where none are, so the surface runs on past the patch as the least-bending extension. Each iteration then corrects the samples' parameters by projecting them onto the surface (Hoschek's parameter correction) and fits again; when that gains less than 10% it takes a damped tangent-distance step (Wang, Pottmann and Liu, ACM TOG 2006, doi:10.1145/1138450.1138453), and when that stalls too it inserts a knot at the middle of every knot span whose samples are still too far, as long as the span holds enough samples. It stops at the target (freeform_tolerance, a quarter of the tolerance by default, at the vertices; the tolerance at the centroids), at max_freeform_poles per direction (40) or after max_freeform_iterations (30), keeping the best state it reached.
  3. The face. OpenCASCADE gets only the poles and knots (Geom_BSplineSurface, never GeomAPI_PointsToBSplineSurface), and the face is accepted by the test every freeform face passes, half the tolerance at a vertex and the tolerance at a facet centre, then trimmed, sewn, checked and, if it fails, demoted like any other.

A patch that is no disc, or that the fit cannot explain, is halved along its normals' spread, up to max_freeform_splits times (2), and each half tried in turn; whatever is left is facets. freeform_smoothing (1e-12, relative to the sample count) is the thin-plate weight over the spans that hold samples. The report counts num_freeform_general (of the B-spline faces, those this path built), num_freeform_refinements (their knot insertion rounds) and avg_freeform_poles. A closed wavy band whose halves the grid fit cannot reach at four grid points a side comes back as two general B-spline faces instead of nearly six thousand facets.

Freeform modes ​

freeform_mode (C++ mFreeformMode, v17.12.0) chooses how a patch no primitive, fillet, blend, chamfer or thread explains becomes a face. "legacy", the default, is everything above, byte for byte. The other modes build on the general freeform faces (they imply freeform_general and extend_surfaces), climb an escalation ladder before a patch is demoted, and give every demotion a reason:

ModeWhat it adds
"adaptive"each freeform patch as one adaptive B-spline face, or pieces of one; with the native backend too
"network"the patch network: a quad layout of each freeform region, fitted as B-spline patches that share their edge curves exactly, G1 across them; a patch it cannot fit falls back to an adaptive face
"auto"adaptive faces first, the network for what they leave and, with OpenCASCADE, for an adaptive face its checks demote

The adaptive face ​

  1. Discs first. A patch that is not a disc is cut along its topology before anything is halved (detail/cut_graph): an annulus by two shortest paths between its loops, a sphere with more holes by a cycle of shortest paths through every loop, a closed genus-0 patch along the median level of the geodesic distance difference to its two farthest vertices. A patch of higher genus is halved across its longest extent.
  2. The parametrisation ladder (freeform_parameterization: "auto", "projection", "lscm", "harmonic"): the best-fit plane, then the cylinder unrolled around the axis the normals are most perpendicular to, each kept only when it folds no triangle; then least-squares conformal maps; then mean-value coordinates with the boundary on a circle. Every map is turned so its bounding box, the spline's domain, is the smallest.
  3. The fit: the general fit's cubic B-spline, with the poles of a face capped at freeform_max_control_points (default 400, valid 16 to 1048576) on top of max_freeform_poles per direction, and a domain five per cent wider than the patch's, so the face runs on past its trim as the least-bending extension.
  4. The rungs: the given budgets, then twice the poles per direction and twice the iterations (refine knots), then, under "auto", conformal maps and mean-value coordinates explicitly (re-parametrise), then the topology cut and the halving (split), and last re-segmentation. escalation_steps counts the rungs a patch climbed.
  5. Acceptance. Every vertex within half the tolerance and every facet centre within the tolerance, by projection onto the surface, and, with validate_by_surface_sampling (the default), the surface's Greville points and a grid per knot span inside the trim within the tolerance of the patch. A clean patch is never held looser. Only on a skin that shows noise (each vertex's residual from the quadric through its two-ring, above a twentieth of the tolerance), whose strict fit fails with residuals that do not correlate across the patch's edges, does a rung try again at min(4.5 sigma, 3 tol): a scanned skin is no more accurate than its noise, as a coarse tessellation is no more accurate than its chordal sag, and a structured misfit is shape, not noise.

The native backend writes the accepted faces as B_SPLINE_SURFACE_WITH_KNOTS faces bounded by polylines on the skin's points, so adaptive needs no OpenCASCADE; brep_checked is then false. With OpenCASCADE the faces are trimmed, sewn and checked like any other, and a failing round demotes the freeform faces involved before an analytic neighbour, so no mode leaves a face legacy would have kept.

The fit's schedule and objective ​

Two options (unreleased, freeform plan steps 3 and 4; both backends) change how the adaptive and general freeform faces' B-spline fit (detail/bspline_fit) spends its iterations; their defaults keep every output as it was. The patch network and the hierarchical refinement keep their own fits.

  • freeform_fit_schedule="continuation" (C++ FitCadFreeformFitSchedule::Continuation). The thin-plate weight starts at 1e-4 of the sample count, so the first surfaces are smooth, and falls two decades whenever parameter correction (each iteration's refit at the samples' projected parameters) stops gaining 10%, down to freeform_smoothing; those falls do not count against max_freeform_iterations. Only then are knots inserted, each at the residual-weighted median of its span's samples beyond the target (kept a sixth of the span from either end) rather than at the span's middle. Once the targets are met, interior knots are removed one at a time, the one whose spans hold the smallest residual first, while the refitted surface still meets them (a removal by refitting rather than by Piegl and Tiller's algorithm A5.8, since the samples, not the old surface, are what the face must follow).
  • freeform_objective (C++ FitCadFreeformObjective): "default" is the fit as before (point distance with parameter correction, a damped tangent-distance step when that stalls); "pdm" keeps to point distance; "tdm" tries the tangent-distance step first in every iteration; "sdm" tries a squared-distance step first in every iteration. That is Wang, Pottmann and Liu's curvature-based squared distance (ACM TOG 25(2), 2006, doi:10.1145/1138450.1138453) extended to surfaces: each sample's error is (S - x)ᵀ M (S - x) with M = n nᵀ + Σ aᵢ tᵢ tᵢᵀ over the principal directions tᵢ at its foot point, aᵢ = d kᵢ / (d kᵢ − 1) where the sample lies on the far side of the centre of curvature (d kᵢ < 0, d its signed distance along n) and 0 on the near side, a damping μ |S − x|² and the thin plate as in the tangent-distance step (bspline_principal_curvatures gives kᵢ and tᵢ from the fundamental forms). PCL's on_nurbs (BSD) was read as a reference; nothing of it is used.

Every step is kept only when it lowers the largest sample distance, so neither option makes a face that met its target fail it, and both are deterministic. The KPI table compares them with the defaults.

Re-segmentation ​

A segmentation can merge two faces across a crease it smoothed over (a sharp edge under its angle somewhere along its length) or a scan's noise; no single surface fits the result, and halving it only moves the crease into smaller pieces. With resegment_rounds above 0 (default 2), a patch whose adaptive fit misses and that holds three or more edges sharper than 30 degrees is first cut along them, before the topology cut and the halving (at most resegment_rounds times along one line of pieces, and counting only the sharp edges that run in from the patch's boundary or close round, not the scattered ones a curved region's facets make): into the pieces between them where they close, and otherwise into two by variational shape approximation on the L2,1 normal metric (Cohen-Steiner, Alliez and Desbrun, "Variational shape approximation", SIGGRAPH 2004, the energy refine_patches uses). A network patch that falls back to an adaptive face skips that early cut: its layout already placed its sides. After the adaptive faces and the network, every region still left as facets is cut the same way, up to resegment_rounds times, and its pieces climb the adaptive rungs again. The two proxies are seeded farthest apart in normal and grown through one priority queue that takes every gentler edge, in steps of ten degrees, before a sharper one, so the pieces meet at the sharpest ridge between their seeds; up to ten Lloyd steps follow, then the cut is smoothed so no piece keeps a spur, and a piece under four facets is merged into a neighbour. num_resegmented counts the cuts.

On the car-hood box with its top and one side merged into one freeform patch (tests/cpp/test_fit_cad_modes.cpp), the native adaptive mode leaves 0.27 of the area as facets without the rung and none with it, auto 0.13 and none, and network 0.026; with OpenCASCADE, auto goes from 0.21 to 0.16 and adaptive is 0.18, the rest lost to the hood top's corners. On skins with handles the rung cuts what the topology cuts leave: with resegment_rounds=0 and with the default, the sphere with a handle (sphere_with_handle(24)) leaves 0.50 and 0.40 as facets in adaptive and 0.136 and 0.087 in network, and the double torus (double_torus(24)) 0.93 and 0.20 in adaptive and 0.17 and 0.14 in network.

Report and records ​

Outside legacy the report adds:

KeyMeaning
freeform_modethe mode that ran
brep_checkedOpenCASCADE's B-rep check ran (false for the native backend)
facet_area_fractionthe share of the skin's area left as facets, the measure the modes lower
num_freeform_adaptiveadaptive B-spline faces
num_network_patches, num_network_edges, num_extraordinary_vertices, max_g1_angle_degthe patch network's patches, shared edge curves, vertices where other than four patches meet, and the largest angle between neighbouring normals along a shared edge
max_g1_angle_away_deg, max_g1_angle_at_ev_deg, num_coupled_regionsthat angle away from the extraordinary vertices and next to them only, and the regions the coupled G1 solve was kept for (unreleased)
num_resegmented, num_escalationsregions re-segmented on the ladder, and rungs climbed in all
max_freeform_distance, rms_freeform_distancethe largest and the RMS vertex distance from a freeform face
facesone record per patch tried as a surface

A record holds patch, face (the B-rep face, -1 when demoted), kind (the fit_cad:type), param_method (none, plane, cylinder, lscm, mean_value, square), demotion_reason (none, param_not_injective, hausdorff_exceeded, trim_failed, sew_failed, brep_check_failed, too_small, non_disc, kernel_mesh_coarse, budget_exceeded or other), num_ctrl, iterations, refinements, escalation_steps, max_dist, rms_dist, reverse_max_dist and max_g1_angle_deg. The same table is the fit_cad:face_table field data, an (n, 13) float64 array with its columns in that order and the enums as their integer values. In legacy the C++ FitCadResult carries all of it, and the Python report and the field data are as before.

The faceted area ​

facet_area_fraction on the freeform fixtures (tests/cpp/fit_cad_fixtures.hpp, tolerance 2e-3 of the diagonal; MESHIOPLUSPLUS_FIT_CAD_KPI=1 runs the full set):

FixtureNative, legacyNative, adaptiveNative, networkNative, auto
monkey saddle0.19500 (16 network patches)0
car hood0.37500.005 (25 network patches, 10 adaptive faces)0
Catmull-Clark valence 3100 (40 network patches, 8 extraordinary vertices)0
FixtureOpenCASCADE 7.6.3, legacyadaptivenetworkauto
monkey saddle0.19500 (16 network patches)0
car hood0.3750.1120.141 (20 network patches)0.126
Catmull-Clark valence 310.9370 (40 network patches, a valid solid)0

The monkey-saddle and S-band boxes' sides follow their tops in proportion (v17.12.0). They used to keep their height while the top sank below its first row of side points, which folded that row over: OpenCASCADE rightly rejected the folded sides in every mode, legacy included, and the native legacy share was 0.182.

On the topology-optimised hook of the CAD-quality notebook (22,236 triangles, a tolerance of 0.816), freeform_general leaves 0.247 of the area as facets; adaptive leaves 0.002 (99 faces), network 0.004 (164 faces) and auto 0.013 (301 faces), each a valid solid within the tolerance (27, 18 and 29 minutes, run one after another on a four-core machine that was also compiling).

The native backend writes every face the fit accepts; OpenCASCADE must also trim, sew and check it. Two rungs of the ladder therefore come after the B-rep is built, in the round that checks it: an adaptive face the checks demote is quartered across its longest extent and each quarter fitted again (down to the tile depth, in at most max_demotion_rounds such rounds), and under auto it first goes into the network of its region, whose patches that miss are fitted as adaptive faces in turn. The edge between two B-spline faces is built from the chain moved onto both rather than from their intersection, which is slow, unstable where they meet tangentially and no truer to the skin. The hood's top, segmented together with a side across a 25-degree crease, fails its corners in the adaptive mode until it is quartered.

The patch network ​

network (and auto, for what the adaptive faces leave) groups the unexplained patches into edge-connected regions and builds each as one network, in both backends:

  1. The cross field and the layout (detail/cross_field, detail/quad_layout). The smoothest cross field of the region (Knöppel, Crane, Pinkall and Schröder, "Globally optimal direction fields", SIGGRAPH 2013) is aligned with its boundary and its creases, and its singularities' indices sum to the Euler characteristic. The layout cuts along the creases (layout_snap_to_features) and the topology (discs first), splits a piece at its one singularity along the separatrices traced from it, turns a three-cornered piece into three quads round its centre and a disc without real corners into an O-grid, and refines to layout_target_patch_size (relative to the diagonal, default 0.1; at least about 48 triangles a patch) in strips that conform across shared sides. Valences stay within layout_max_valence_deviation (2) of four. The cube cage's limit surface becomes 24 patches with its eight valence-3 vertices and no T-junction; regions of genus one and two get valid layouts, with T-junctions where their topology cuts meet.
  2. Shared edges (detail/patch_network, detail/bspline_curve). Every layout chain is fitted once as a cubic B-spline. A crease or the region's boundary is fitted through its vertices; a cut of the layout's own, a zigzag of mesh edges, is smoothed and moved onto free fits of the patches beside it, so it lies on the smooth surface, not on the facets. Each patch's four boundary rows of poles are exact pieces of those curves (knot insertion), so neighbours meet exactly (G0) whatever their interiors.
  3. Interiors and G1. The interior poles are fitted by least squares to the patch's vertices, facet centres and edge middles on its unit-square map, more strongly smoothed where little data holds them. Knots are inserted at the worst spans until each patch passes. G1 sweeps then pull each patch's cross-boundary derivative into its neighbours' tangent planes (block Gauss-Seidel, the weight doubling to eight times while the largest angle exceeds freeform_g1_tolerance_deg). A patch a sweep pushes out of the tolerance first gets knots where it misses, as the acceptance step gives it, and keeps its accurate surface only if that still fails.
  4. Extraordinary vertices (extraordinary_vertex). g0 leaves them alone (the G1 measure skips their first span); g1 puts the second pole of every edge curve leaving one, and every corner's twist pole, in a common tangent plane (after Peters, "Patching Catmull-Clark meshes", SIGGRAPH 2000); g1x (the default) also smooths the poles round it; g1xx adds a double knot in the first span towards it (after Loop and Schaefer, ACM TOG 2008). The network of a region with such vertices is also fitted in g0, and a g1 mode is kept only where it does better next to the vertices (the G1 angle with their samples included) and fits as many patches: next to vertices whose patches meet at very unequal angles, the tangent-plane constraint can bend the edge between two of them. On a rounded cube (|x|^4 + |y|^4 + |z|^4 = 1) it did, to angles near 180 degrees, so the network keeps g0 there; the cube cage keeps g1x. A region with extraordinary vertices therefore takes about twice as long in a g1 mode.
  5. Acceptance. A patch is held to the tolerance against the network (a vertex just across a smooth edge may lie on the neighbour): every vertex within half of it and every facet centre within it, no fold (the surface's normal on a grid, denser in the two knot spans next to each side, agrees with the skin's), and the surface's samples within it of its own and its neighbours' triangles. A patch that fails becomes an adaptive face or, failing that, facets with its reason.

With OpenCASCADE each accepted patch is a face with its fitted surface, trimmed, sewn and checked with the rest of the solid: the edge between two network patches is the piece of the shared curve both took their boundary from (no surface intersection, which is slow and unstable where two patches meet tangentially), an edge between a network patch and another B-spline face is approximated on both, and the fillet, blend and vertex-blend stages leave network patches alone. Under auto, an adaptive face the B-rep checks demote climbs one more rung, the network of its region, before it is facets: the cube cage's limit surface, cut into two caps that each fit but fail the skin-to-solid distance, becomes a valid solid of 40 network faces and no facet.

The native STEP writer gives each accepted patch a B_SPLINE_SURFACE_WITH_KNOTS face and writes every layout edge between two network faces once, as the cubic B_SPLINE_CURVE_WITH_KNOTS both faces took their boundary from (its end poles on the edge's vertices), so the file's faces meet on one shared curve and not on a polyline; an edge between a network face and any other face stays a polyline on skin points. The file is reproducible byte for byte.

On the cube cage with one more subdivision level, every patch passes in g0, g1 and g1x (largest G1 angle 1.3 degrees away from the extraordinary vertices, 11.5 degrees with them), and 13 of 24 in g1xx. On the monkey saddle the network is 16 patches whose largest G1 angle is 1.2 degrees. On the 48 × 24 organic torus the eight patches its topology cuts leave hold too few triangles for the curvature they span, its facets sagging about as far as the tolerance, and fall back to adaptive faces; at 72 × 36 the network takes the whole torus (16 patches, no facets). On a double torus (double_torus(20)) two network patches pass and the rest become adaptive faces, leaving 0.039 of the area as facets where adaptive alone leaves 0.094.

The coupled G1 solve ​

freeform_g1_solve="coupled" (C++ FitCadNetworkG1Solve::Coupled, unreleased; "sweeps" is the default and every output as before) replaces the sweeps by one least-squares solve over the whole region per step (the plan, step 7). Its unknowns are every interior pole of every patch and every free pole of the shared edge curves: a curve shared inside the region with no T-junction on it, its end poles and, under g1, g1x and g1xx, the tangent-plane pole at an extraordinary vertex fixed. A patch's boundary rows are linear in its curves' poles (segments, joins and knot refinement keep the knots), and the map is found by building the rows from each free pole alone, so both patches beside a curve still take their rows from the same poles: G0 stays exact. The G1 rows, linearised at the current surfaces in each step, ask both sides for the plane halfway between their normals (each aimed at the other's present plane would only swap them); a free curve is held to where the accurate fit put it, at its vertices' parameters; the weight doubles while the worst angle does not fall, as the sweeps'. A step that pushes a patch out of the tolerance is undone and retried with knots where it misses, else at half the weight, and the sweeps then polish what is left. The region keeps the result unless its accepted patches cover fewer triangles or its largest angle exceeds the sweeps' (num_coupled_regions counts the kept ones); the system is solved by the deterministic conjugate gradients, so the result does not depend on the thread count.

Outside the legacy mode the report also splits the largest G1 angle: max_g1_angle_away_deg away from the extraordinary vertices (their first knot span excluded) and max_g1_angle_at_ev_deg next to them only. Tensor-product bicubics cannot be G1 at a vertex where other than four of them meet, so the second measures how far the construction gets there, not a defect; max_g1_angle_deg keeps its meaning (the angle the network's mode reports, which under g0 skips those spans).

Measured on the KPI fixtures in the network mode, natively and through OpenCASCADE alike (benchmark/fit_cad_kpi_coupled.csv): the hood from 2.87 to 0.28 degrees, the monkey saddle from 1.18 to 0.37, the Gaussian bump from 1.14 to 0.84, the wavy wall of wavy_capped from 26.1 to 3.8, the cube cage of valence 3 from 2.46 to 0.93 away from its extraordinary vertices (18.9 to 6.0 at them) and of valence 6 from 1.62 to 0.57 (16.4 to 2.8 at them); the cage of valence 5, the S band and the loaf keep their sweeps, and a region whose sweeps meet the target or whose patches the data reject skips the coupled steps. No solid loses its validity, closedness or read-back, and natively no patch leaves the tolerance; through OpenCASCADE the hood's faceted share falls (0.141 to 0.132 network, 0.126 to 0.108 auto) but the wavy wall's rises from 0.0047 to 0.047: three coupled patches, within the tolerance by the network's own test, are demoted by the kernel's, whose triangulated faces miss the skin by 1.08 and 1.12 tolerances. Where it runs the solve costs one to four times the sweeps' time.

Hierarchical refinement (experimental) ​

local_refine="thb" refines an adaptive face with truncated hierarchical B-splines (detail/thb_spline, after Giannelli, Jüttler and Speleers, "THB-splines: the truncated basis for hierarchical splines", CAGD 2012) instead of knot lines: level l is the cubic B-spline space with s0 2^l spans a side, each level refines only the cells (and their neighbours) holding the worst samples, and the truncated basis keeps a partition of unity, so the degrees of freedom grow where the misfit is rather than along whole knot lines. freeform_max_control_points caps those degrees of freedom; the face written is the surface flattened exactly into one tensor-product B-spline over the finest level's knots, and its record's num_ctrl counts the hierarchical degrees of freedom. On a narrow bump on a 64 × 64 grid it meets 2e-3 with 153 of them where knot lines need 196 poles. A rung whose hierarchical fit misses its target falls back to knot lines, so "thb" never leaves as facets a patch "knots" fits; the patch network keeps knot lines. The flattened faces can carry more poles than knot-line faces, which a downstream consumer reads as a denser surface.

Provenance ​

The algorithms are reimplemented from the papers cited, in MIT-licensed code; no GPL code (QuadWild, libigl's GPL parts, CGAL's GPL packages) is used or ported, and nothing is vendored. Instant Meshes (BSD-3) and QuadriFlow (MIT) were read as references only.

OpenSubdiv (modified Apache-2.0) and G+Smo (MPL-2.0) are not used; they could only ever be optional bring-your-own backends. The hierarchical refinement follows the THB paper above. No T-spline code is included; if an analysis-suitable T-spline variant is added it will be built from the published papers (Li, Zheng, Sederberg, Hughes and Scott, CAGD 2012; Scott et al., CMAME 2012 and IJNME 2011), not from patent claims. The original T-spline patent, US 7,274,364, expired on 2024-03-26, and the later T-spline and S-spline fitting patents were not used. This is a note on provenance, not legal advice.

Limitations ​

  • Sharp features must be feature edges. The layout cuts along creases sharper than its feature angle (30 degrees) and never asks for G1 across one. A sharp edge the segmentation smoothed over becomes a long, thin patch, or a fit that misses.
  • Noisy scans need smoothing. The noise allowance is bounded: no face is held looser than three times the tolerance. A skin noisier than that keeps facets unless freeform_smoothing or a larger tolerance lets the fit follow the shape rather than the noise.
  • G1 at extraordinary vertices is approximate. The g1 modes share a tangent plane at the vertex and pull the first ring towards it, but the angle across the edges leaving the vertex is not held to freeform_g1_tolerance_deg; max_g1_angle_deg reports it. On the Catmull-Clark fixtures (native network), max_g1_angle_deg is 2.5, 2.5, 2.5 and 2.9 degrees at valence 3 for g0, g1, g1x and g1xx (g0's figure skips the vertices' first spans), 1.4, 3.4, 3.1 and 2.4 at valence 5, and 1.6, 1.6, 1.6 and 1.3 at valence 6. Before the G1 sweeps' patches were given knots where they miss (step 3 of the patch network), the same figures were 5.8, 5.8, 5.7 and 8.0, 1.4, 37, 35 and 1.4, and 14, 14, 23 and 9.8. Accepting the swept surfaces even when they leave the tolerance only made it worse (82 degrees). A construction that holds G1 exactly next to the vertices (Loop and Schaefer's full scheme, or a G-spline) is not implemented, so the angles above are measured, not held to freeform_g1_tolerance_deg.
  • Kernel checks still decide. With OpenCASCADE a face that fits can still fail trimming, sewing or the B-rep check: the car hood's top keeps 0.11 to 0.14 of the area as facets at its corners.
  • Topology and resolution. Regions with handles are laid out after their topology cuts, and the patches those cuts leave often hold too few triangles to fit, so they fall back to adaptive faces. A network patch also needs facets finer than the tolerance: on the 48 × 24 organic torus the facets sag about as far from the surface as the tolerance, no patch passes and the adaptive faces take it; at 72 × 36 the network is 16 patches and at 96 × 48 24 patches, with no facets left (NetworkOnAResolvedTorus).

Fillets, blends and threads ​

Features that no primitive explains are recognised from the patches around them, before the freeform fallback or, for a blend, after it. The fits need no OpenCASCADE (detail/feature_fit); the faces they give are then trimmed, sewn, checked and demoted like any other.

  • Rolling-ball fillets (fillets, type 7). A patch that runs between two analytic faces (the two neighbours sharing the most boundary, together at least 60% of it) is tried as a constant-radius fillet between them: each interior vertex, moved by r against or along its normal, should be a ball centre at r from both primitives. The radius minimises that misfit over a log-spaced scan of [tolerance / 2, diagonal] refined by golden section, for a convex (centres inside) and a concave (centres outside) ball. The face is the pipe of that radius around the spine where the two surfaces, each offset by r towards the centres, meet (GeomFill_Pipe around the GeomAPI_IntSS branch nearest the centres, kept whole and periodic when the centres go most of the way round it). It covers a straight rounded edge, a swept fillet along a curved edge (the foot of a leaning boss, along an ellipse) and a ring. A constant-radius fillet between coaxial surfaces is a torus, which fit_primitives already fits; this stage only sees what it left unexplained.
  • Fillets of varying radius (fillets, type 7, counted in num_variable_fillet). When no one radius explains the patch, each interior vertex gets its own ball radius, and the radii become a law along the rail, the patch's boundary on the first surface: the parameter of a vertex is where its own ball touches that surface, a Chebyshev series (a Fourier series round a closed rail) of the lowest degree up to 8 that explains the radii within a quarter of the tolerance. The face is a B-spline through cross-sections of the ball family: along the rail, the ball touching both surfaces at the law's radius is solved for in the plane through the rail point, and each section is the arc of the ball's characteristic circle from one foot to the other, widened by 15% each way, the sections running a tenth of the rail past each open end so the face trims inside its surface.
  • Blends beside freeform faces (fillets, type 7, counted in num_blend). Once the freeform faces exist, a patch between two fitted faces, at least one of them freeform (plane–B-spline or B-spline–B-spline), is tried as a rolling ball against those surfaces, with the radius found per vertex and fitted as a law exactly as above, constant or varying; a freeform patch can become a blend this way. The neighbours are taken as the freeform stage left them, so the result does not depend on the order the patches are tried in. A ball resting on a nearly flat stretch of a fitted face touches it where its normal happens to point, which wanders far more than the face does, so the balls' centres and radii, not their feet, set the face: smooth laws are fitted through the solved centres (judged across the spine, as a wavering rail stretches the arc length along it) and the arcs ride on them. A blend stays tangent to its fitted neighbours, which lie within half the tolerance of the skin, so a vertex on the blend's own boundary may lie the whole tolerance from it.
  • Helical thread faces (threads, type 8). A patch beside an accepted cylinder or cone is first tried as a straight-flank thread about its axis: the ruled helicoid z = c + k θ + t ρ (k the pitch over 2π, t the flank's slope), one least-squares solve once each vertex's angle is unwrapped over the patch's edges; the face is a B-spline through a grid on it. A patch that is not such a flank, or that has no cylinder or cone beside it, is tried as a helical surface of any profile. Without an axis, the screw comes from the patch itself, as the screw motion whose velocity field is most nearly tangent to it (Pottmann and Randrup, Rotational and helical surface approximation for reverse engineering, Computing 60, 1998): the smallest eigenvector of a normal-weighted 6 × 6 moment, reduced to 3 × 3, refused when a plane, cylinder or sphere leaves more than one screw nearly free, or when the advance vanishes (a surface of revolution). The axis and the advance are then refined together by Levenberg-Marquardt on the residual of the profile: each vertex, with the screw's advance taken off its height, lands in the plane through the axis, and the profile is a Chebyshev series of the lowest degree up to 8, ζ(ρ) or ρ(ζ), within 0.4 of the tolerance. A straight profile is a flank; any other (a rounded root or crest) is counted in num_rounded_thread. A trapezoidal or ISO thread then comes back as cylinders (root and crest) and two helical flanks, and a thread with rounded roots and crests, with no cylinder anywhere, as four helical faces.

Every patch must span at least half a turn to be a thread (less of a helical surface is as well something else). A candidate face must keep every patch vertex within half the tolerance and every facet centre within it, as a freeform face must. Edges beside a fillet, a blend or a thread face skip the exact intersection, which is slow and unstable between tangent or long B-spline surfaces, and go straight to the approximated B-spline. num_fillet and num_helical count the faces, and of them num_variable_fillet, num_blend and num_rounded_thread the new kinds; fillets=False and threads=False leave such patches to the freeform fit.

A boss leaning on a round plate, its foot rounded by a fillet swept along an ellipse: the fillet is one rolling-ball face between the plate's plane and the boss's cylinder

A block whose edge is rounded by a ball shrinking from 0.3 to 0.2 along it: one fillet face of varying radius between two planes

A bar whose wavy top and leaning front are freeform B-spline faces, the edge between them one rolling-ball blend

A rod with a trapezoidal thread: root and crest are cylinders, both flanks helical faces, the shallow end caps facets

A rod whose thread has rounded roots and crests and no cylinder anywhere: four helical faces, found from the screw each patch fits

Chamfers, conic blends, vertex blends and tapered threads ​

Since v17.2.0 (roadmap 6.3) four more kinds of patch get their own faces. Each is tried only where every fit above has failed for that patch, so a skin they do not concern builds the same solid, to the byte, as before; their fits are in detail/feature_fit too.

  • Chamfers (fillets, type 10, num_chamfer) and conic blends (fillets, type 7, num_conic_blend). A patch between two analytic faces (the two neighbours sharing the most boundary, together at least 60% of it) that no rolling ball and no thread explains is tried as a blend of the edge between them with a cross-section other than the rolling ball's circle. Its rails are the patch's boundary edges across from each neighbour; its cross-sections lie in the planes normal to the edge the two surfaces would meet along (n₁ × n₂, through each point of the first rail), from the first rail to where that plane cuts the second. When every interior vertex lies within 0.4 of the tolerance of its section's chord, the patch is a chamfer, of constant or varying width (a chamfer between two planes of varying width is a twisted ruled surface, a constant one a plane, and a chamfer coaxial with a cylinder a cone: those two stay the primitives fit_primitives fits). Otherwise each section is taken as a rational quadratic from rail to rail through the apex where the two surfaces' tangent lines meet, the vertex's weight w = b₁ / (2 √(b₀ b₂)) read off its barycentric coordinates in that triangle, and a weight law of the lowest degree (Chebyshev, Fourier round a closed rail) whose conics pass within 0.4 of the tolerance of every vertex makes it a conic blend: an elliptic, parabolic or hyperbolic section tangent to both faces, of legs that may differ and change along it. The face is a B-spline interpolating the sections, each widened by 15% and carried a tenth of the rail past an open end.
  • Tapered and variable-pitch threads (threads, type 8, num_tapered_thread, num_variable_pitch_thread). A straight flank beside a cone is the same ruled helicoid as a flank of a straight thread (with an apparent pitch), so it is built as before and reported tapered. A flank whose straight helicoid fails is refitted with one more column, z = c + k θ + q (θ − θ₀)² + t ρ, a pitch changing linearly along it, and kept when the pitch changes by more than the tolerance across the patch. A patch no constant screw explains is refitted as a helical surface of any profile on a generalised screw, its advance g(θ) = k θ + q (θ − θ₀)² and its profile moved out by τ g(θ) as it advances, a thread cut on a cone whose radius grows by τ per unit length: τ starts at a neighbouring cone's half-angle and is refined with the axis, the advance and q by the same Levenberg-Marquardt profile fit. A trapezoidal pipe thread then comes back as cones and two tapered flanks, a thread whose pitch grows as cylinders and two variable-pitch flanks, and a rounded one on a taper as four helical faces, the rounded root and crest tapered.
  • Vertex blends (fillets, type 9, num_vertex_blend). After the freeform and blend stages, a patch that is unexplained or freeform, whose boundary is one closed loop around three or more fitted faces (each met along one run) and creased nowhere (no facet across it turns more than 20°), is tried as the corner where blends meet: a plate surface (GeomPlate_BuildPlateSurface) through its vertices, tangent (G1) to each neighbour's surface along the loop, approximated by a B-spline. It is kept when it passes the freeform face's test and its normal stays within 3° of every neighbour's along the loop. This covers a setback corner, three blends of different radii or sections meeting at one vertex; a corner of three equal rolling balls is a sphere, which fit_primitives already fits.

Segmentation is the condition: a conic blend is tangent to both its faces and its curvature varies across it, so no curvature tolerance of segment isolates it alone; label such a skin's patches yourself (segment:patch, from the CAD faces it was tessellated from, say), as the fixtures behind the tests do. A chamfer meets its faces at creases and segments by angle.

A block whose edge is cut by a chamfer of growing width: one chamfer face, a twisted ruled surface, between two planes

A rounded box scaled unequally: twelve conic edge blends and eight vertex blends at its corners, between six planes

A pipe thread: a trapezoidal thread cut on a cone, its root and crest cones and both flanks tapered helical faces

Kinematic surfaces ​

kinematic_surfaces=True (C++ mKinematicSurfaces, unreleased, off, so a default build is unchanged to the byte) first tries every patch no primitive explains as a kinematic surface, the sweep of a planar profile by a motion, before the fillets, threads and freeform faces get it (detail/kinematic_fit, both backends; the plan, step 5):

  • Surface of linear extrusion (type 11, num_extrusion). The patch's area-weighted vertex normals are all perpendicular to one direction, the smallest eigenvector of their second moment Σ a n nᵀ, whose eigenvalue must be under 3·10⁻³ of the trace while the next one is not. The profile is the points projected on the plane normal to it.
  • Surface of revolution (type 12, num_revolution). The normal lines all meet one axis: the linear line complex they best belong to (Pottmann and Randrup) has an advance the tolerance cannot tell from zero over the patch's angles. Because the skin's discretised normals tilt that estimate by about a thousandth of a radian, the axis (two tilts, two offsets) is then refined by Levenberg-Marquardt against the meridian profile, twice. The profile is the points in the meridian half-plane, (ρ, z); a patch reaching the axis, or winding all the way round it, is refused.
  • Helical surface (type 8, num_helical and num_kinematic_helical). helical_fit (an advancing screw, a taper and a linearly varying pitch allowed, any profile) on a patch the thread stage left (OpenCASCADE tries extrusions and revolutions before its fillets, whose chamfer test would otherwise claim the wall between two parallel planes, except on a patch a blend could be: one between two primitives along most of its boundary, other than two parallel planes, which a straight edge blend between two planes also is; what its fillets and threads leave, it then tries as all three kinds).

A profile is a cubic B-spline curve through the points ordered along it (by their angle about their centre, or along their principal direction, whichever path is shorter), averaged into bins and checked against every point by projection (bspline_curve_project) within half the tolerance; a profile that is a line or a circular arc within 0.4 of the tolerance is refused, so planes, cylinders, cones, spheres and tori stay the primitives fit_primitives fits. A patch that is a band, a wall closed round (two boundary loops, Euler characteristic 0), is cut into two discs along two shortest paths (patch_split_to_discs), and both halves must fit: they share the profile and the axis, so a CAD tool sees one surface split at a generator. Every surface runs on past its patch, 5% of its extent along the motion and a tenth of the profile's length past each end, and is accepted by the freeform face's own test (freeform_accept: vertices within half the tolerance, facet centres within it, the surface sampled inside the trim within it).

The extrusion is exact everywhere: natively the face is a SURFACE_OF_LINEAR_EXTRUSION of a B_SPLINE_CURVE_WITH_KNOTS profile, its NURBS form the profile's poles at two heights (degree (p, 1)), and through OpenCASCADE a trimmed Geom_SurfaceOfLinearExtrusion. The revolution is exact too: natively a SURFACE_OF_REVOLUTION about an AXIS1_PLACEMENT, its NURBS form the rational patch the analytic surfaces of revolution use (quadratic arcs of at most 90 degrees in the angle, the profile's own poles and knots along it, step 6), and through OpenCASCADE the same rational B-spline (GeomConvert of the trimmed Geom_SurfaceOfRevolution, within 10⁻¹⁴ of it), its angles turned to run about π so no trim crosses the seam. The helical face is a cubic B-spline within a twentieth of the tolerance of the screw surface, which no polynomial or rational surface is.

The native writer's edges stay polylines through the skin's points and a kinematic face has no p-curves, so a reader computes them, as for the adaptive faces. Measured on the KPI fixtures: the lobed prism (extruded_lobe, 0.615 of its area facets with OpenCASCADE before) and the wavy wall (revolved_wave) become two exact faces each and no facet on either backend, valid, the STEP file read back valid; the native helical sweep falls from 0.60 of its area facets to 0.25 (the threads' own flanks through OpenCASCADE are unchanged, their remaining facets failed edges between the flanks and their cylinders).

Checks and demotion ​

A face is not kept when OpenCASCADE's B-rep check rejects it, when sewing leaves an edge of it free, when its boundary cannot be built, or when it strays: the solid is re-meshed and a face with a point further than tolerance from the skin, or a patch with a skin point further than that from the solid, fails. A failed patch is demoted to facets and the solid is rebuilt. A failure is blamed on the faces the B-rep check names or that a free edge after sewing touches (a face the kernel cannot map back is matched to the patch of its nearest facet), never on every patch at once; after max_demotion_rounds rounds (default 8) each further round demotes the blamed patches together with their neighbours, so the loop ends while the patches nothing blames stay analytic, and an all-facet solid is always valid for a closed skin. A group of coplanar facets whose merged face fails is split back into single facets. A face's distance allowance is tolerance or, when larger, the skin's own chordal sag over its patch (1.05 times the largest distance of a facet centre from the fitted surface), so a coarse tessellation of a small bore is not demoted for its own chords. So a feature the fitter cannot explain, or a face the kernel cannot trim, comes back faceted, never silently wrong, and num_demoted counts the features dropped. MESHIOPLUSPLUS_LOG_LEVEL=debug logs why each patch was demoted.

Edges, sewing and validation options ​

Four options, all off by default so the output is what it was without them (OpenCASCADE backend, v17.11.0):

  • sew_tolerance (0): the tolerance the faces are sewn at; 0 sews at tolerance itself. The edges are shared already, so sewing only closes what the face repair re-made, and a tighter value makes a gap the repair left fail the check instead of being bridged.
  • extend_surfaces: each freeform B-spline surface gets an extended copy, past its patch on each open side by a tenth of the patch's size (GeomLib::ExtendSurfByLength, tangent-continuous). Where the intersection of two faces' surfaces has no branch along their shared chain, the copies are intersected instead, so an edge that runs just outside the fitted area is still an exact curve; the face keeps its own surface, and the edge passes the same checks. num_extended_edges counts the edges found that way. An extended branch is kept only where it stays within tolerance of both faces' own surfaces, since the faces are trimmed on those. It is opt-in for a reason: on the generated threaded rod with freeform_general it finds 9 exact edges but leaves 21 facet faces and 2 demotions against 20 and 1 without it, at two and a half times the time, and swapping the extended surfaces in for the faces themselves (tried first) did worse still.
  • snap_junctions: a B-rep vertex where analytic faces meet is placed by a Gauss-Newton least-squares solve on the surfaces' tangent planes (OpenCASCADE-free, detail::junction_closest): each step minimises the summed squared distances to the tangent planes at the current point's feet, with a small Levenberg damping that leaves a direction no plane constrains where it was. At a transversal corner it lands in a few steps, where the averaged alternating projection creeps. The point is accepted on the same test as before (within tolerance of every surface and of the mesh vertex), and the projection is the fallback; num_snapped_junctions counts the vertices it placed.
  • face_deviation: the two-sided distance between each face and the skin is measured, from the face's re-mesh (vertices and triangle centres) to the skin and from the skin (vertices and facet centres, each charged to the face of the nearest re-mesh triangle) to the solid. The field data fit_cad:face_hausdorff holds per face (in fit_cad:face order) both maxima, an (n, 2) float64 array, and fit_cad:face_rms the root mean square of both sides' distances; the report adds the global hausdorff_max and hausdorff_rms. max_deviation keeps its meaning.

Every run also reports closed: every shell's edges border two faces each (a seam counts for its face). The native backend reports its writer's closed-loop check.

Validation report ​

With validation_report=True (C++ mValidationReport, unreleased; off by default, and the solid is the same either way; both backends) the solid is measured against the skin once it is built, in its NURBS form (detail/brep_deviation), so both backends are held to one measure:

  • CAD to mesh. Each face is sampled on a grid of 25 × 25 nodes over the bounding box of its trims in its own parameters, a node kept when it lies inside the trims (each trimming curve evaluated as a polyline, the even-odd rule across the loops), and each kept node's distance to the skin is measured. This is the side the re-mesh-based face_deviation sees only at its own vertices: a face that bulges between the skin's points, or runs past its patch, shows here.
  • Mesh to CAD. Every skin vertex and facet centre is measured to the face its facet stands for: the face of the nearest triangle of the returned mesh (the skin itself from the native backend, the solid re-meshed from OpenCASCADE), a vertex to each of its facets' faces. The point is projected onto the face's surface by Gauss-Newton from its six nearest sample nodes, a foot kept when it lies inside the trims; otherwise the face's nearest point is on its trim curves, each followed on the surface to a millionth of the skin's size.
  • Normals. At each facet centre's foot point, the angle between the facet's normal and the surface's, unsigned (0 to 90 degrees), so a face's orientation does not enter.
  • The file read back. When a STEP file was written and the build has OpenCASCADE (either backend), the file is read back, checked by BRepCheck_Analyzer, tested for closed shells and its volume compared with the skin's.

The report adds validation_reported, cad_to_mesh_max, cad_to_mesh_p95, cad_to_mesh_p99, mesh_to_cad_max, mesh_to_cad_p95, mesh_to_cad_p99, normal_deviation_max_deg, normal_deviation_p95_deg, step_round_trip_checked, step_round_trip_valid, step_round_trip_volume_ratio and total_freeform_control_points (the control points of every face that is no plane, sphere, cylinder, cone or torus), and the mesh carries the fit_cad:face_deviation field data: per face, in fit_cad:face order, the largest and 95th-percentile CAD-to-mesh distance, the largest mesh-to-CAD distance charged to it, the largest normal deviation and its sample count, an (n, 5) float64 array. The native legacy mode builds the NURBS form for the measure only; its brep stays empty. The measure is of that NURBS form, so it also tests what Kratos CAD JSON receives: on the generated threaded rod with OpenCASCADE, the two multi-turn helical flanks measure 0.10 from the skin (ten tolerances) while the re-meshed solid lies within 0.0045 of it, their trims in the NURBS form covering less than the faces themselves, a limitation of that conversion the report exposes. The measures run serially or on the deterministic distance queries, so they do not depend on the thread count. The KPI table records them for every fixture.

validation_acceptance=True (C++ mValidationAcceptance, unreleased, off) also holds every adaptive, network and general freeform face to these measures before it is accepted: its surface is sampled inside its trim against the skin (as validate_by_surface_sampling does in the freeform modes), and the normal at each facet centre's foot point must lie within 30 degrees (kFitCadValidationNormalDeg) of the facet's, unless the patch shows noise. A face that fails is escalated or demoted with hausdorff_exceeded like any other. The legacy grid faces keep their own test.

Merging. With merge_faces (the default), once the solid is built, faces on one surface are merged and collinear edges joined (ShapeUpgrade_UnifySameDomain); the result is kept only when it stays valid with the same volume (to 1e-9), and the fit_cad:face labels follow the merged faces.

tolerance defaults to three times the largest fit:patch_tolerance of an accepted patch, so it follows the scale fit_primitives worked at; with no accepted patch it is 1e-3 of the bounding-box diagonal. The re-meshing uses a chordal deflection of a quarter of the tolerance unless mesh_deflection says otherwise.

Output and report ​

The return value is the solid re-meshed by OpenCASCADE as one triangle block, with points welded where faces share them exactly, and Int64 cell data fit_cad:face (the B-rep face), fit_cad:type (0 a facet, else the fit:type value: 1 plane, 2 sphere, 3 cylinder, 4 cone, 5 torus; 6 a freeform B-spline, 7 a rolling-ball fillet, blend or conic blend, 8 a helical thread face, 9 a vertex blend, 10 a chamfer, 11 a surface of linear extrusion, 12 a surface of revolution) and fit_cad:patch (the segment:patch label, -1 for a cell with no patch). With return_report=True the report holds:

KeyMeaning
backend"occt" or "native", the engine that built the solid
validthe solid passes OpenCASCADE's B-rep check (native: the writer's closed-shell check)
tolerancethe tolerance applied
volume, skin_volume, volume_ratiothe solid's volume, the skin's enclosed volume and their ratio
max_deviationthe symmetric Hausdorff distance between the skin and the re-meshed solid
num_faces, num_plane … num_torus, num_bspline, num_fillet, num_helical, num_faceted_facesB-rep faces in all, by type (freeform B-splines, fillets and thread flanks included), and planar facets
num_variable_fillet, num_blendof the fillet faces, those whose radius varies along them, and the blends beside a freeform face
num_rounded_threadof the helical faces, those whose profile is not a straight line (a rounded root or crest)
num_vertex_blend, num_chamfervertex blends and chamfers (v17.2.0)
num_conic_blendof the fillet faces, the conic blends (v17.2.0)
num_tapered_thread, num_variable_pitch_threadof the helical faces, those cut on a taper and those whose pitch varies (v17.2.0)
num_split_patchespieces that freeform patches folding over every flattening were split into
num_patches, num_demotedpatches in the fit table, and accepted ones demoted to facets
num_exact_edges, num_approx_edgesedges between analytic faces built as exact intersections and as B-splines
num_solidssolids written, one per piece of the skin
refined, refinement_kept, refine_iterations, num_refine_splits, num_refine_merges, initial_explained_area_fraction, explained_area_fractionwith refine_segmentation only: the refinement, and whether the solid was built from it (v17.11.0)
num_freeform_general, num_freeform_refinements, avg_freeform_poleswith freeform_general only: the general freeform faces (v17.11.0)
closedevery shell is closed: no edge borders only one face (v17.11.0)
num_extended_edgeswith extend_surfaces only: exact edges found on extended surfaces (v17.11.0)
num_snapped_junctionswith snap_junctions only: vertices placed by the least-squares junction solve (v17.11.0)
hausdorff_max, hausdorff_rmswith face_deviation only: the two-sided distance between the solid and the skin over both sides' samples, with the per-face fit_cad:face_hausdorff and fit_cad:face_rms field data (v17.11.0)
validation_reported, cad_to_mesh_*, mesh_to_cad_*, normal_deviation_*, step_round_trip_*, total_freeform_control_pointswith validation_report only: the validation report (unreleased)
num_extrusion, num_revolution, num_kinematic_helicalwith kinematic_surfaces only: the kinematic faces by kind (unreleased; the helical ones are in num_helical too)

The STEP file is AP214 in millimetres. Its header timestamp is pinned and its product is named meshio++ fit_cad, so the same input writes the same bytes; the bytes do depend on the OpenCASCADE version. The work is serial, so nothing depends on the thread count.

The solid as NURBS ​

solid.info["brep"] (C++ FitCadResult::mBrep, a BrepInfo) holds the solid with every face converted to NURBS (the native backend builds it without OpenCASCADE in the freeform modes) (BRepBuilderAPI_NurbsConvert): the surfaces, their trimming loops and the edges with the faces they bound, as a STEP read gives them. Every face of the solid is there, trimmed, and every trimming curve lies in its surface's parameter range. When the exact conversion does not deliver that (OpenCASCADE 7.9 throws on a trimmed cylinder or one wound several turns round, leaves a face that already was a B-spline without a surface, and can stop a converted surface short of its trims), the solid is kept as it is and each surface and edge that is not a B-spline is approximated by one in its own parameters, within 1e-6 of the bounding-box diagonal, so the trimming curves stay valid; planes and lines stay exact. Writing it as Kratos CAD JSON (mp.write("part.cad.json", solid), to-cad --cad-json) makes a scanned part Kratos IGA geometry.

Getting OpenCASCADE ​

fit_cad assumes OpenCASCADE for the best result, and the release CLI binaries include it, and the PyPI wheels get it from the meshioplusplus-occt add-on: pip install "meshioplusplus[occt]" is all it takes (the base wheel alone uses the native backend). Open CASCADE Technology is licensed under the GNU LGPL 2.1 with the additional exception in its OCCT_LGPL_EXCEPTION.txt; the CLI binaries link the pinned OpenCASCADE 7.6.3 statically and the add-on wheel ships it as shared libraries, so they are MIT AND (LGPL-2.1-only WITH OCCT-exception-1.0); the base wheel is MIT, with THIRD_PARTY_NOTICES.md, OpenCASCADE's licence texts and the relink recipe shipped beside them. The meshio++ sources stay MIT. The full WASM artifact links the same commit; the lean one does not.

A build from source turns MESHIOPLUSPLUS_WITH_OCCT on by default and links an OpenCASCADE 7.6 or later when it finds one through its CMake config (OpenCASCADE_ROOT, OpenCASCADE_DIR or CMAKE_PREFIX_PATH for an install outside the default prefixes): a system package, linked dynamically, or the static build build/build-occt.sh PREFIX makes from the pinned commit. -DMESHIOPLUSPLUS_REQUIRE_OCCT=ON makes a missing kernel a configure error; -DMESHIOPLUSPLUS_WITH_OCCT=OFF (build/configure.sh --without-occt) leaves it out.

bash
sudo apt-get install libocct-foundation-dev libocct-modeling-data-dev \
    libocct-modeling-algorithms-dev libocct-data-exchange-dev libtbb-dev   # or:
build/build-occt.sh ~/occt && export OpenCASCADE_ROOT=~/occt
pip install --no-binary meshioplusplus meshioplusplus                       # finds it

Debian's packages export toolkit targets that link TBB, hence libtbb-dev. OpenCASCADE 7.6 or later is supported (7.6 is Ubuntu 24.04's package and the binaries carry 7.6.3); CI runs the fit_cad suites on Ubuntu's 7.6 and on 7.9.3, which MIO_OCCT_PIN=7.9 build/build-occt.sh PREFIX builds from the same recipe. The STEP bytes depend on the kernel's version, so the golden digests that pin fit_cad's output (tests/cpp/test_fit_cad_goldens.cpp) are kept per version; fit_cad_occt_version() in C++ and _core.__occt_version__ in Python name the version a build links ("" without one).

Without the kernel, fit_cad falls back to the native backend and says so once (a warning naming what is lost); backend="occt" raises NotImplementedError (C++ Unsupported) naming -DMESHIOPLUSPLUS_WITH_OCCT=ON. There is no pure-Python fallback of either: without the compiled core fit_cad raises. meshioplusplus._fit_cad.has_occt(), fit_cad_has_occt() in C++, mio_has_occt() in C and the language surfaces below say in advance whether a build has it.

The native backend ​

backend="native" (C++ FitCadBackend::Native), and "auto" (the default) in a build that found no OpenCASCADE, needs no CAD kernel: it segments and fits the skin as above when it has no patches, then writes the step writer's faces="fitted" B-rep. Every accepted plane, sphere, cylinder, cone and torus patch whose type is in types is one analytic face on its fitted surface, bounded by LINE, CIRCLE and polyline edges, its corners moved onto the surfaces they lie on; every other cell is part of a coplanar planar face. A patch with a point further than tolerance from its surface, or whose boundary does not close into loops, is written as planar faces and counted in num_demoted. On a CAD-exported bracket it gives the same twelve planes and four cylinders as the OpenCASCADE backend, which OpenCASCADE reads back as one valid solid of the exact volume.

In the freeform modes it also writes adaptive B-spline faces (B_SPLINE_SURFACE_WITH_KNOTS). With kinematic_surfaces, in any mode, it writes the kinematic faces too: SURFACE_OF_LINEAR_EXTRUSION, SURFACE_OF_REVOLUTION and helical B-splines. What it does not do: legacy freeform, fillet, blend and thread faces (freeform, fillets, threads, exact_edges, mesh_deflection, max_demotion_rounds and merge_faces are ignored), sewing and the B-rep check, and re-meshing. The returned mesh is the input skin with the fit_cad:* cell data, volume and volume_ratio are NaN, max_deviation is the largest distance of a skin point from its analytic face, and valid says the shell was written closed, every edge used once each way. Its STEP bytes do not depend on any library version.

In the freeform modes info["brep"] holds the native solid as trimmed NURBS faces (detail/brep_nurbs, v17.12.0), so Kratos CAD JSON needs no CAD kernel either: a plane is a bilinear patch over its loops, a sphere, cylinder, cone or torus the exact rational surface of revolution over the angles its loops cover (quadratic arcs of at most 90 degrees), and a B-spline face itself. A trim along a parameter line (a circle of latitude, a generator, a network patch's side) is that line and a circle on a plane its exact rational arc; any other is a polyline through the edge's points in the surface's parameters, refined until the surface between them stays within two per cent of the tolerance of the edge's curve when it has one. A loop that winds round a band closes through a seam (an edge of the face alone, its two trims a period apart), a cap round a pole or apex through the pole. A face it cannot express (a loop through a pole, or windings of several turns) leaves info["brep"] empty with a warning naming the face, never a wrong one. On the golden set (a box, a capped cylinder, a turned part, a filleted plate, a threaded rod with 2,503 faces, a monkey saddle network and others) every face comes out and the faces sampled cover the skin's area to within 1.4 per cent. In the legacy mode it stays empty, as before.

CLI ​

sh
meshioplusplus to-cad IN OUT.step [--curvature-tolerance C] [--min-patch-cells N] \
    [--fit-tolerance T] [--tolerance T] [--no-exact-edges] [--types plane,cylinder,...] \
    [--mesh-deflection D] [--max-demotion-rounds N] [--no-freeform] [--freeform-degree P] \
    [--freeform-max-control N] [--no-freeform-split] [--no-fillets] [--no-threads] \
    [--segment-method primitive|angle] [--segment-tolerance T] [--no-merge-faces] \
    [--backend auto|occt|native] [--refine] [--max-refine-iterations N] [--refine-epsilon E] \
    [--normal-weight W] [--no-refine-merge] [--no-refine-split] [--ransac-seed S] \
    [--refine-tolerance T] [--freeform-mode legacy|adaptive|network|auto] \
    [--freeform-parameterization auto|projection|lscm|harmonic] [--g1-tolerance DEG] \
    [--extraordinary-vertex g0|g1|g1x|g1xx] [--local-refine knots|thb] \
    [--freeform-max-control-points N] [--layout-target-patch-size S] \
    [--layout-max-valence-deviation N] [--resegment-rounds N] [--no-layout-snap-to-features] \
    [--no-validate-by-surface-sampling] [--constrain-primitives] [--validation-report] \
    [--validation-acceptance] [--freeform-fit-schedule legacy|continuation] \
    [--freeform-objective default|pdm|tdm|sdm] [--freeform-g1-solve sweeps|coupled] \
    [--kinematic-surfaces] [--mesh-out FILE] \
    [--cad-json FILE] [--json] [--quiet]

A skin without segment:patch is segmented by --segment-method (default primitive, at --segment-tolerance of the diagonal, default 1e-3; angle uses --curvature-tolerance and --min-patch-cells) and fitted, at the segmentation's own tolerance as a length after the primitive method, or with --fit-tolerance (relative, as in fit-primitives) when given, before the solid is built. --backend picks the engine and --no-merge-faces keeps faces on one surface apart; the summary and --json name the backend. --mesh-out also writes the re-meshed solid, --cad-json the solid as Kratos CAD JSON; --no-freeform, --freeform-degree, --freeform-max-control and --no-freeform-split are the freeform options, --no-fillets and --no-threads the feature ones. Both CLIs exit with 2 when the solid fails the B-rep check, as check does for a failed gate.

--refine (v17.11.0) first refines the patches by variational shape approximation (refine_patches, refine_segmentation=True), so more of the skin becomes analytic faces: --max-refine-iterations (default 10) caps the iterations, --refine-epsilon (default 1e-3) stops them when one adds less than that to the area share primitives explain, --normal-weight (default 1) weighs the normal term of a cell's cost, --no-refine-merge and --no-refine-split turn off merging neighbours one primitive explains and splitting a primitive out of a freeform patch, --ransac-seed (default 0x6d657368696f2b2b; the native CLI also takes 0x hexadecimal) seeds the split, and --refine-tolerance (default 1e-3 of the diagonal) is how far a point may lie from its refined patch's primitive. Only with --refine does the summary add a refined: line and --json add refined, refine_iterations, num_refine_splits, num_refine_merges, initial_explained_area_fraction and explained_area_fraction. The refine-patches verb of both CLIs runs the refinement alone (CLI reference).

--freeform-mode and the flags after it are the freeform modes' options (v17.12.0); outside legacy the summary adds a freeform: line with the mode, the faceted area and the adaptive and network faces, and --json adds the mode's report keys and faces. --constrain-primitives fits related primitives together; the summary then adds a constrained: line and --json adds num_constrained_primitives and num_constraint_groups. --validation-report adds the validation report (a validation: line, and its keys in --json), --validation-acceptance holds the freeform faces to it. --freeform-fit-schedule and --freeform-objective are the fit's schedule and objective.

sh
meshioplusplus to-cad bracket.stl bracket.step
meshioplusplus to-cad scan.stl scan.step --segment-method angle --curvature-tolerance 1 --min-patch-cells 20 --fit-tolerance 2e-3
meshioplusplus to-cad scan.stl scan.step --refine --ransac-seed 7 --json

Pipeline ​

json
{"Op": "FitCad", "Path": "part.step", "Tolerance": 0.0, "ExactEdges": true,
 "Types": ["plane", "cylinder"], "MeshDeflection": 0.0, "MaxDemotionRounds": 8,
 "Freeform": true, "FreeformDegree": 3, "FreeformMaxControl": 64,
 "FreeformSplit": true, "Fillets": true, "Threads": true, "MergeFaces": true,
 "Backend": "auto"}

The freeform modes take FreeformMode, FreeformParameterization, FreeformG1ToleranceDeg, FreeformMaxControlPoints, LayoutTargetPatchSize, LayoutMaxValenceDeviation, LayoutSnapToFeatures, ExtraordinaryVertex, ResegmentRounds, LocalRefine and ValidateBySurfaceSampling, and outside legacy the step also reports BrepChecked, FacetAreaFraction, NumFreeformAdaptive, NumNetworkPatches, NumNetworkEdges, NumExtraordinaryVertices, NumResegmented, NumEscalations and MaxG1AngleDeg. ConstrainPrimitives (off) is the constrained primitives option, and with it the step also reports NumConstrainedPrimitives and NumConstraintGroups. FreeformFitSchedule (legacy) and FreeformObjective (default) are the fit's schedule and objective. FreeformG1Solve (sweeps) is the coupled G1 solve's switch, and outside legacy the step also reports MaxG1AngleAwayDeg, MaxG1AngleAtEvDeg and NumCoupledRegions. KinematicSurfaces (off) tries the kinematic surfaces and reports NumExtrusion, NumRevolution and NumKinematicHelical. ValidationReport and ValidationAcceptance (off) are the validation report's options, and with the first the step also reports CadToMeshMax, CadToMeshP95, MeshToCadMax, MeshToCadP95, NormalDeviationMaxDeg, StepRoundTripChecked and StepRoundTripValid.

The step writes the solid to Path when given, and the mesh continues as the re-meshed solid; it reports Native (whether the native backend built it), Valid, VolumeRatio, MaxDeviation, NumFaces, NumBspline, NumFillet, NumHelical, NumVariableFillet, NumBlend, NumRoundedThread, NumVertexBlend, NumChamfer, NumConicBlend, NumTaperedThread, NumVariablePitchThread, NumSplitPatches, NumFacetedFaces and NumDemoted. A Tolerance or MeshDeflection of 0 is automatic; an empty Types facets everything.

Other languages ​

c
mio_fit_cad_opts opts;
mio_fit_cad_opts_init(&opts);
opts.types = (1u << MIO_FIT_PLANE) | (1u << MIO_FIT_CYLINDER);
opts.freeform = 1;             /* the default; freeform_degree, freeform_max_control */
opts.backend = MIO_FIT_CAD_AUTO;  /* or MIO_FIT_CAD_OCCT, MIO_FIT_CAD_NATIVE */
mio_fit_cad_report report;
mio_fit_cad_report_ex report_ex;  /* v17.2.0: num_vertex_blend, ...; backend */
mio_mesh* solid = mio_fit_cad_ex(fitted, "part.step", &opts, &report, &report_ex);
fortran
solid = fit%fit_cad(step_path='part.step', valid=ok, num_demoted=ndropped, used_native=native, stat=ierr)
julia
r = fit_cad(fit; step_path="part.step"); r.valid, r.backend
r
cad <- mio_fit_cad(fit, step_path = "part.step"); cad$backend

The freeform modes are mio_fit_cad3 (v17.12.0) with mio_fit_cad_opts_ex2 (freeform_mode, freeform_parameterization, extraordinary_vertex, local_refine as the MIO_FREEFORM_*, MIO_PARAM_*, MIO_EV_* and MIO_LOCAL_REFINE_* constants, and the layout options; a zero in freeform_g1_tolerance_deg, freeform_max_control_points, layout_target_patch_size or layout_max_valence_deviation reads as its default, the enums' zero is their first value and the flags' zero is off, so mio_fit_cad_opts_ex2_init is the way to get every default) and mio_fit_cad_report_ex3 (the mode's counts and measures, and num_face_records; the records themselves are the fit_cad:face_table field data, demotion_reason as MIO_DEMOTION_*); mio_fit_cad2 forwards to it with the defaults. Fortran's fit_cad takes them as optional arguments (the enums as strings), Julia's and R's as keyword arguments, and WASM's fitCad in camelCase, returning faces outside legacy. The constrained primitives are mio_fit_cad_opts_ex2's constrain_primitives and mio_fit_cad_report_ex3's num_constrained_primitives and num_constraint_groups, taken from the front of their reserved tails (the structs keep their sizes); Fortran's constrain_primitives optional argument, Julia's and R's keyword, and WASM's constrainPrimitives. The validation report is mio_fit_cad4 (unreleased; mio_fit_cad3 forwards to it), whose mio_fit_cad_opts_ex2 takes validation_report and validation_acceptance from its reserved space and whose new mio_fit_cad_report_ex4 (272 bytes, a reserved tail for the later steps of the freeform plan) holds the measures; Fortran's, Julia's, R's and Octave's fit_cad take the two options and return the measures under the Python names, WASM's fitCad as validationReport, validationAcceptance, cadToMeshMax and so on. The fit's schedule and objective are mio_fit_cad_opts_ex2's freeform_fit_schedule and freeform_objective (MIO_FIT_SCHEDULE_*, MIO_OBJECTIVE_*, from its reserved space; zero is the default), and the same names, as strings, in Fortran, Julia, R and Octave, freeformFitSchedule and freeformObjective in WASM.

The C report carries num_bspline, num_fillet, num_helical, num_variable_fillet, num_blend, num_rounded_thread and num_split_patches, and mio_fit_cad_ex's extended report (mio_fit_cad_report_ex, v17.2.0, as mio_fit_cad_report has no room left) num_vertex_blend, num_chamfer, num_conic_blend, num_tapered_thread and num_variable_pitch_thread; Fortran's, Julia's and R's results carry all of them (freeform, freeform_degree, freeform_max_control, freeform_split, fillets, threads, merge_faces and backend are their options; a zero-filled C struct keeps freeform_split, fillets, threads and merge_faces off, mio_fit_cad_opts_init turns them on, and backend 0 is auto), and report_ex.backend (Julia's and R's backend, Fortran's used_native) names the engine. The MCP server's fit_cad tool takes the same options plus segment_method, segment_tolerance, curvature_tolerance, min_patch_cells, fit_tolerance and cad_json_output_path, and reports backend and occt_available. In the browser, fitCad(mesh, {stepPath, mergeFaces, backend, ...}) runs the native backend in the lean artifact, and the full WASM artifact links OpenCASCADE, with the same options and report in camelCase and the solid's B-rep as info; backend: 'occt' throws by name in the lean one.

From sketches instead ​

When a scan is a turned or prismatic part, fitting its faces one by one is the long way round: profile_solid builds the solid from a sketch that fit_curves fitted to a section, by extrusion or revolution and then fillets, chamfers or a shell, through the same OpenCASCADE kernel, and deviation compares it to the scan.

Measured and parked ​

Each of these was tried, or considered and left out, for a reason stated here, and says when it is worth measuring again.

  • A chordal-sag allowance for network patches (roadmap 5.2.4, genus one and more). A network patch's centroid allowance, and its reverse-sampling test, were raised to the patch's own chordal sag from the skin's facet normals, capped at three tolerances. Facet area fractions and patch counts did not move on any of the seven genus fixtures (organic torus 48 by 24: 0.0068 of the area as facets, 72 by 36: none; sphere with a handle 24 and 32: 0.0868 and 0.0628; double torus 20, 24 and 40: 0.0387, 0.1406 and 0.0112), because the vertex test at half the tolerance decides first, not the centroid test. Reverted. Reopen with a vertex test the sag changes.
  • Homology cuts for patches of genus one and more (roadmap 5.2.4). Not attempted: the layout still halves such a patch geometrically until its pieces are discs, because its pieces are groups of triangles, and a cut that runs along both sides of a loop has no representation there. That is a change to the layout's partition, sized large, not a bounded experiment. The baseline is the facet fractions above, network mode with the default extraordinary-vertex mode. Reopen when the layout can carry a piece whose boundary runs along a cut twice, and measure on the same seven fixtures.
  • Parallel but separate axes. Coaxial constraint merges axes that lie on one line only. Two cylinders whose axes are parallel but offset are different surfaces, and merging them would move a face, so they are left apart by design.
  • Angles other than right ones, and symmetric patterns. Planes are made exactly parallel or exactly perpendicular, never at another angle, and equal radii are merged only within the tolerance. A bolt circle or a pattern at a set angle is not constrained, by design: the pass would have to know the pattern.
  • Regularity constraints: 45-degree planes and tangent cylinders (freeform plan, step 8). A prototype extended constrain_primitives with two relations: a plane within its reach of 45 degrees to a reference direction (the axes, then the planes) made exactly so, its offset refitted, and a cylinder whose axis is parallel to a plane and whose radius is within the tolerance of its axis' distance from that plane made tangent to it, each kept only where its patch still passes its fit. Measured on the filleted plate, the rounded box, a 45-degree chamfered block and the turned part, clean and with Gaussian noise of 5·10⁻⁴ of the diagonal, both backends: the relations fire on the noisy filleted plate (four tangencies; volume ratio 0.9988 to 0.9994 through OpenCASCADE, nothing else moves) and the noisy turned part (fifteen relations, among them tangencies to planes far from the cylinders: one more patch demoted through OpenCASCADE, the native volume ratio worse), and nowhere else; no faceted area falls. Parked: worth measuring again with an adjacency test for tangency (the plane must border the cylinder) and on scanned parts whose design angles are known.
  • Optimised rational weights (freeform plan, step 9). A prototype tried every accepted adaptive face again with half, two thirds and four fifths of its poles per direction and weights: its log-weights bounded to [−1, 1] by damped Gauss-Newton, the poles the exact rational least-squares solution at each trial (variable projection), the parameters corrected after each step, the fewest poles passing the face's own test kept; the native writer wrote RATIONAL_B_SPLINE_SURFACE, the NURBS form and OpenCASCADE took the weights. On sampled analytic patches at equal poles the weights cut the largest error to 0.02 to 0.36 of the polynomial fit's (a Gaussian bump, an S band, a hood, a sphere cap and a torus patch; a cubic saddle is exact either way). On the freeform fixtures in the adaptive mode they cut the control points of the monkey saddle from 36 to 16, the Gaussian bump from 173 to 117, the cube cage of valence 5 from 230 to 152 and the sphere with a handle from 2663 to 2052, but the validation report then measured one rational face of the sphere with a handle 2.5 tolerances from its skin (its untrimmed surface holds its points: the trim, or the measure's projection on a strongly weighted face, is at fault, not yet known which) and moved its read-back volume ratio from 1.06 to 1.19; a first version, fitting a few vertices with as many weights, also bulged between them and turned the cage's read-back volume negative. Parked: worth measuring again once a rational face's trim is checked against its edges, with a requirement of more samples than poles and weights.

Not supported ​

  • Blends of a section that is no conic, a chamfer or conic blend beside a freeform face (only analytic neighbours are tried), and a corner patch whose loop meets a neighbour twice or at a crease: they come back freeform or faceted.
  • Threads whose depth varies along them, or whose pitch varies other than linearly, and a tapered or variable-pitch thread with no cylinder or cone beside it that is also too far from one screw for the axis to be found from the patch itself: freeform or faceted, as is a thread patch spanning less than half a turn.
  • A whole thread as one patch: a thread surface whose profile spans the full pitch (one patch over root, flanks and crest) has no single trimmed face to be; segment it at its creases or with a curvature test first.
  • Fitting a STEP or IGES model: those are read as their own NURBS B-rep, not refitted.
  • Feature faces without OpenCASCADE: the native backend writes planes, spheres, cylinders, cones and tori, and, in the freeform modes, adaptive B-spline faces only.

Released under the MIT License.