STL to STEP: How It Works

An STL file is only a pile of flat triangles. A STEP file for CAD needs faces: a plane, a cylinder of a given radius, a spline surface, each bounded by edges shared with its neighbours. The app works out which triangles belong to which real surface, fits that surface, and writes the result as a STEP solid. It is all plain JavaScript running in your browser, so no file is uploaded.

The pipeline

Page STL, session or drop three.js viewer Web Worker (stl2step-core.js) parse → weld → half-edge adjacency flat facets → cylinders → cones / tori fragments → spline surfaces your edits → refit those triangles faces, kinds, edges → page STEP writer (on Export) Face list colors, info, selection Downloads .step and .stl2stp

Why a worker. A 900,000-triangle file takes a few seconds to analyze, so the whole engine runs in a Web Worker and the page stays responsive. The page keeps only the triangle positions for drawing, plus a face number per triangle. Clicking a face, hiding objects and coloring all happen on the page; anything that needs the geometry (fitting, double-click growth, auto-merge, export) is a message to the worker.

Re-using work. The worker keeps the automatic analysis. An edit doesn’t redo it: it re-runs only the last stage, which builds the faces and then refits the triangles you edited. That is why a merge on a large model takes a fraction of a second while the first load takes seconds.

Reading the mesh

Binary or ASCII. A binary STL has an 80-byte header, a triangle count, then 50 bytes per triangle. If the file size matches that count it is read as binary; otherwise, if it starts with solid and contains facet, it is read as ASCII. The ASCII reader scans bytes for vertex and parses the numbers itself rather than splitting strings, so a 269 MB ASCII file reads in a couple of seconds.

Welding. STL repeats every corner for each triangle that uses it. Corners are snapped to a grid of size diagonal × 10−6 and hashed, so copies of one point become one vertex. Triangles that collapse (two corners the same, or no area) are dropped. Each triangle gets its unit normal and area.

Adjacency. Every triangle edge is a half-edge running from one corner to the next. The half-edge running the other way along the same edge is its twin, found by looking up the far vertex. Twins tell the engine which triangles touch, which is all the later stages need. Edges with no twin are open edges; the status line reports them, because a mesh with holes can’t become a closed solid.

Finding the surfaces

Recognition works on small groups of triangles rather than single ones, and goes from the simplest surface to the hardest. The fit tolerance is how far any vertex may sit from a fitted surface; left blank it is 0.02 % of the model’s diagonal (0.029 mm on a 145 mm part).

StageWhat it does
1. Flat facetsStarting from the largest triangle, grow a group across neighbours whose normal is within the coplanar angle (1°) and whose far corner is within the tolerance of the seed’s plane. Each group is a candidate plane or one strip of a curved surface. Groups whose normals differ by less than the smooth edge angle (32°) are recorded as smoothly joined.
2. CylindersSeeds are three smoothly joined groups whose normals all lie in one plane (the axis is perpendicular to every normal of a cylinder). The axis is the direction least represented in the normals: the eigenvector with the smallest eigenvalue of Σ n·nᵀ. Projected along the axis, the vertices lie on a circle, found with an algebraic least-squares circle fit. The cylinder then grows into neighbouring groups whose vertices are all within tolerance and whose normals face the right way (within 15°), and is refitted once grown.
3. Cones, tori, spheresFour groups whose normal tips lie on one plane seed a cone (a cone’s normals make a fixed angle with its axis). The radius at each height comes from a 5-parameter least-squares fit, x² + y² = a·x + b·y + c + d·z + e·z². A cone band whose rims blend smoothly into its neighbours is put aside as one ring of a doughnut or ball. Rings sharing an axis are grouped, and their cross-section is fitted with a circle: a torus, or a sphere when the circle is centred on the axis.
4. Clean-upLeftover small groups next to a fitted surface are added to it if all their vertices fit.
5. FragmentsLong chains of narrow arcs and loose strips (a wavy wall tessellated as hundreds of slivers) are stitched into spline surfaces; see below.
6. FacesEvery fitted surface becomes a face. Each remaining flat group becomes a plane, unless it is a small piece surrounded by other small pieces: those are joined into a freeform face that is exported as its triangles.

Merging fragments into spline surfaces

A curved wall that is not a cylinder (an S-shaped rib, a drafted or twisted wall) has no single analytic surface. Stage 2 then finds many slim cylinders that each fit two or three strips, and the result is hundreds of faces. With Merge fragments into spline surfaces on, two passes replace them:

  • Bands. A strip of triangles running between two rails (top and bottom edge of a wall) is walked from end to end. Each rail is turned into a smooth curve with local (Bessel) tangents, its handles capped so it cannot overshoot, and the band becomes one ruled B-spline surface between the two rails.
  • Grids. Regions tiled by four-sided strips (swept rounds) are arranged into a grid and stitched into one bicubic B-spline patch.

Both passes check every piece against the mesh. Where the surface strays more than 1.5 × the tolerance (or 8–12 % of the strip size), the band or patch is split there instead of accepted. Arcs at least as wide as Keep arcs wider than (default 30°) are real rounds and are never folded into a spline; raise it to 360 if you do want arc-built walls merged.

Feature names

The face list groups faces by what they look like, using each face’s coverage (the angle it sweeps round its axis, found from the largest gap in its vertices’ angles) and how its border meets its neighbours. The names are only labels: the STEP surface type is the same whatever the label says.

LabelRuleSTEP surface
Hole / Cylinder (full)Cylinder covering the full 360°, facing inward / outwardCYLINDRICAL_SURFACE
Cylinder (partial)Any other cylinder piece, rounded corners includedCYLINDRICAL_SURFACE
Chamfer (conical)Cone whose slant length is at most its larger radiusCONICAL_SURFACE
Chamfer (flat)Plane mostly bordered by two larger faces, meeting both at 8–82° on the same side, at most 0.6 × the smaller one’s areaPLANE
Fillet (toroidal)Torus piece whose profile spans ≤ 185° and whose border is mostly smoothTOROIDAL_SURFACE
Cone, Torus, SphereThe rest of those surfacesCONICAL / TOROIDAL / SPHERICAL_SURFACE
Spline surfaceMerged fragments or a spline you fittedB_SPLINE_SURFACE_WITH_KNOTS
Freeform (faceted)Small pieces that fit nothingone PLANE per facet

Editing by hand

Selecting. A click casts a ray from the camera and takes the face of the first triangle it hits. Shift- or Ctrl-click adds or removes. Grow smooth (G) adds every neighbour whose shared border has an average angle under the smooth edge angle.

Double-click picks up the faces that belong with the one you hit:

  • On a plane, cylinder, cone, sphere or torus it adds neighbours whose every vertex lies on that same surface (within 1.5 × tolerance), and keeps going from them. Split pieces of one cylinder come together; a different surface stops it.
  • On a spline or faceted face, or on a lone partial cylinder (usually a scrap of a wavy wall), it spreads across borders flatter than Double-click: join edges under (15°), and stops at planes.

Edits are triangle lists. Merging stores the selected triangles and the type you chose, not face numbers, because face numbers change every time the model is re-analyzed. A later edit takes triangles away from an earlier one, an edit left with none disappears, and Revert removes your selection’s triangles from all edits. On every run, the automatic faces are built first and each edit then claims its triangles and refits them as one face.

Fitting a chosen type. Each fit starts from a closed-form guess and is refined by Levenberg–Marquardt least squares on up to 4,000 of the region’s vertices:

TypeStarting guessRefined parameters
PlaneSmallest eigenvector of the vertex covariance (exact, no refinement needed)—
CylinderAxis from the triangle normals (area-weighted Σ n·nᵀ), circle fit across itcentre, axis, radius
ConeAxis from the spread of the normals, circle fit, then radius vs height by a straight-line fitcentre, axis, radius, slope
SphereLinear fit of x² + y² + z² = 2c·x + dcentre, radius

Merge (auto) tries plane, cylinder, sphere and cone in that order and keeps the first whose largest vertex deviation is within the tolerance; if none is, it fits one spline. A forced type is always fitted, whatever the error, and the info box shows the maximum and RMS deviation (orange when over the tolerance).

Fitting one spline through a selection

A B-spline surface is a sheet S(u, v) over a rectangle of parameters. To fit one, every vertex first needs a (u, v): the selection has to be laid out flat, like peeling a label off a bottle.

Flattening. Several layouts are tried and the least distorted one wins. Distortion is measured per triangle from how its flat copy is stretched and squashed compared with the original (2.0 is perfect up to scale):

  • Projection onto the selection’s average plane (only if no triangle flips over).
  • Unrolling around the best cylinder axis: u = angle × radius, v = height. A selection that goes all the way round has no seam to unroll from, so it is cut into two halves, each fitted as its own face.
  • Rectangle (for a selection with one boundary loop): the four sharpest boundary corners go to the corners of a rectangle whose sides match the boundary lengths, and the inside vertices settle where every vertex is the weighted average of its neighbours (Tutte’s method, solved by conjugate gradients).
  • Circle: the same, with the boundary spread round a circle.
  • Conformal (least-squares conformal map): keeps the shape of every triangle as well as possible, with two far-apart vertices pinned. Usually the best for long strips.

If no layout works (overlaps or flipped triangles), the selection is cut in half along its longest direction and each half is tried again, up to six levels deep.

Least squares. The surface is a cubic B-spline. Its control points are found by least squares: the vertices pull the surface towards them (boundary vertices four times harder, because neighbouring faces share those edges), and each triangle’s centre pulls at a quarter strength so the surface cannot ripple between vertices. A small “thin plate” penalty on the second differences of the control net keeps empty parts of the parameter rectangle smooth. The equations form a banded matrix, solved by banded Cholesky factorization, which stays fast even with thousands of control points.

Refining. After each fit, every vertex’s (u, v) is moved to the nearest point on the new surface (Gauss–Newton) and the surface is fitted again. Then knots are added only in the parameter spans that still have vertices further than the tolerance away, and the loop repeats, up to 14 rounds or 6,000 control points. A smooth wall ends up with few control points and a tight bend gets many, where it needs them. Finally the surface is flipped if needed so its normal points out of the solid.

Auto-merge

Auto-merge everything visible is the double-click and Merge (auto) done for you, for every face, largest first. Faces you already edited and hidden faces are skipped. For each face still free:

  1. Grow a group from it exactly as a double-click would, leaving out faces already claimed.
  2. Measure how far the group turns: if any triangle’s normal is more than 80° from the group’s average, only plane, cylinder, sphere and cone are tried. Splines that wrap round corners fit well but some CAD importers fail to draw them.
  3. Fit. Keep the merge only if every resulting face is within the tolerance; otherwise leave the faces as they were.

All accepted merges are added as one batch, so one Undo removes them together. On the 22-object fidget model this turns 1,329 faces into 134, with every tapered band one exact cone.

Writing the STEP file

The file is ISO 10303-21 text using the AP214 schema, in millimetres, with the fit tolerance as the model’s accuracy. It describes a boundary representation: faces, each with a surface and loops of edges, the edges shared by the two faces either side.

Edges come from the mesh. A half-edge is on a boundary when the triangle across it belongs to another face. Boundary half-edges are followed round each face into loops, and every loop is cut into edges at its corners, the vertices where the pair of faces on either side changes. Each edge’s shape is chosen in this order:

EdgeWhenSTEP curve
StraightAll points within half the tolerance of the chordLINE
Rim of a spline wall or patchThe edge follows the wall’s profile or the patch’s boundary rowB_SPLINE_CURVE
CircleAll points at one height and one radius of a neighbouring cylinder, cone, torus or sphereCIRCLE
Edge of a fitted splineThe 3D polyline, plus its exact (u, v) on each spline face so CAD doesn’t have to project itSURFACE_CURVE + PCURVE
Anything elseDegree-1 B-spline through the mesh verticesB_SPLINE_CURVE

Solids. Faces joined by shared edges form one shell. If every edge of a shell is used by exactly two faces, the shell is closed and written as a solid (MANIFOLD_SOLID_BREP); a mesh with holes gives an open shell instead. A face with no boundary at all (a whole sphere) is written as its triangles, since a face needs at least one loop.

Checked against a CAD kernel. During development every change was exported and read back with OpenCascade (the kernel behind FreeCAD), comparing the solid count and surface area with the mesh. The test models come back as closed solids with area within about 0.1 % of the STL.

Objects, hiding and sessions

Objects are the separate pieces in the file: groups of triangles that share no vertex with any other group, found with a union–find pass over the triangles’ corners. Hiding works per object or per selected face; the viewer simply leaves those triangles out of what it draws and what a click can hit, and double-click and auto-merge skip them.

Saved in the browser. Edits are stored in the browser’s local storage under the file name and triangle count, so reopening the same STL on the same computer brings them back.

Session files (.stl2stp) carry everything to another computer: a short header, the settings, edits, hidden parts and camera as JSON, then the welded triangles as 32-bit floats, all gzip-compressed with the browser’s own CompressionStream. Opening one rebuilds a binary STL from those triangles, so the mesh welds into exactly the same triangle order and the edits land on the right triangles (the page checks the count and warns if not). The sponge holder’s session is 0.2 MB.

Libraries and limits

LibraryVersionUsed for
three.js (jsDelivr)0.160.03D view, orbit controls, picking
stl2step-core.js (this site)—everything else: parsing, recognition, fitting, STEP writing

Limits.

  • The result can only be as good as the mesh. A coarse STL gives coarse arcs; fitted radii come from the facet corners, so they are close but not exact.
  • Edges follow the mesh’s triangle edges, so a boundary between two faces is a polyline (or a fitted line or circle), not a recomputed intersection curve.
  • Spline surfaces use many control points, so files with many splines are large (a few MB to tens of MB); merging and auto-merge shrink them a lot.
  • Large spline surfaces that wrap around corners fit the mesh but may not draw in every CAD program; auto-merge avoids them.
  • Everything runs in one browser tab, so very large meshes (millions of triangles) are limited by its memory.