Skip to content

Marching cubes / isosurface extraction ​

What it does ​

Two related entry points sharing one engine:

  • extract_isosurface(values, bmin, bmax, iso, surface, status) — module-level subroutine. Given a 3D scalar field on a regular grid, extract the iso=iso surface as a facet_object array.
  • surface%resample_via_distance_field(resolution, surface_out, status) — TBP. Sample self's signed distance on a regular grid spanning the bbox, then call extract_isosurface at iso=0. Closes the SDF → STL loop: any FOSSIL surface can be re-tessellated through its own distance field.

The marching cubes algorithm itself is well-known (Lorensen & Cline SIGGRAPH 1987); FOSSIL embeds Bourke's canonical 256-entry case-table data. The engineering interest is the second TBP: it turns FOSSIL into a level-set repair tool. Sample SDF, extract iso=0, get a watertight triangulation whose distribution is determined by the grid spacing (not the input's noisy tessellation).

A rounded box decimated to 402 facets, most of them long slivers (the box of the decimation page), resampled at resolution 32: 4192 facets of the grid's size, watertight, volume 1.9710 to 1.9587:

left, the decimated rounded box: its flat faces covered by a few long thin triangles; right, the same box after resample_via_distance_field(32): a regular mesh of small triangles, one pattern per grid cell, the rounded edges and corners kept

Pipeline ​

For each grid cell with corners (i..i+1, j..j+1, k..k+1):

  1. Classify each corner as inside (value < iso) or outside. The 8 corners give an 8-bit case index in [0, 255].
  2. Look up triangulation pattern in Bourke's case table — up to 5 triangles per cell, with edges identified by their endpoint cube-edge index.
  3. Linearly interpolate each triangle vertex along its cube edge: t = (iso - v_a) / (v_b - v_a) is the fractional position between corner a and corner b. Position is bmin + (i, j, k + offsets) * cell_size in world coordinates.
  4. Append the resulting triangles to a flat output buffer.

After extraction, adjacent cubes share edge-vertices that get emitted twice (once per cube). When the result is adopted into a surface_stl_object, analyze runs connect_nearby_vertices which dedupes them via the vertex pool, producing a watertight mesh.

Nodes on the level. A node whose value equals iso counts as outside, and every crossing on its edges is the node itself, bit for bit: the triangles that collapse there have coincident vertices and are not emitted. A node within round-off of iso is treated the same way (issue #87): if every crossing on its grid edges lies within 1e-12 of a cell side of it, it takes the value iso. A sphere sampled on a grid with nodes on it is the common case: norm2(p) - 1 at (0, −0.6, −0.8) on a grid of spacing 0.1 is −1.1e-16, not 0, and the crossings 1e-16 from the node made slivers of area 1e-32 that the curvature and smoothing routines report as degenerate (status 2). Fields with no node that close to the level give the same triangles, bit for bit.

The four stages on 3³ cells of side 1, the field the signed distance to a sphere of radius 2.3 about (3.4, −0.4, 3.4): 7 corners inside, 57 outside, 13 triangles. Every triangle vertex lies on a cell edge between an inside and an outside corner:

a 3 by 3 by 3 grid of cells drawn as grey lines, its corners as points, teal inside the sphere and ember outside; the 13 triangles marching cubes emits in the cells near the front corner, where the sphere cuts the grid, with their vertices as gold points on the cell edges

API ​

extract_isosurface (module function) ​

fortran
use fossil, only : extract_isosurface

call extract_isosurface(values, bmin, bmax, iso, surface, status)
   real(R8P),                       intent(in)            :: values(:, :, :)
   type(vector_R8P),                intent(in)            :: bmin, bmax
   real(R8P),                       intent(in)            :: iso
   type(facet_object), allocatable, intent(out)           :: surface(:)
   integer(I4P),                    intent(out), optional :: status

surface is a flat array of triangles; pass it to surface_stl_object%adopt_facets to turn it into a queryable surface.

resample_via_distance_field (TBP) ​

fortran
call self%resample_via_distance_field(resolution, surface_out, status)
   class(surface_stl_object), intent(in)            :: self
   integer(I4P),              intent(in)            :: resolution
   type(surface_stl_object),  intent(out)           :: surface_out
   integer(I4P),              intent(out), optional :: status
  • resolution is the grid-corner count along the longest bbox axis; the other two scale proportionally so cells stay cubic.
  • A 5 % bbox-diagonal margin is added around the source to make sure the geometry doesn't touch the grid boundary.
  • surface_out must be distinct from self — aliasing them would consume self%facet mid-loop.

Example ​

extract_isosurface on the signed distance of the unit sphere, sampled on [-1.5, 1.5]³ with the spacing h halved twice, measured against the exact volume 4π/3:

f90
previous = 0._R8P
do m = 0, 2
   n = 16 * 2**m + 1                                           ! 17, 33, 65 samples per side of [-1.5, 1.5]^3
   h = 3._R8P / (n - 1)
   allocate(phi(n, n, n))
   do k = 1, n ; do j = 1, n ; do i = 1, n
      phi(i, j, k) = norm2(-1.5_R8P + h * ([i, j, k] - 1)) - 1._R8P   ! signed distance to the unit sphere
   enddo ; enddo ; enddo
   call extract_isosurface(values=phi, bmin=vector_R8P(-1.5_R8P, -1.5_R8P, -1.5_R8P), &
                           bmax=vector_R8P(1.5_R8P, 1.5_R8P, 1.5_R8P), iso=0._R8P, surface=facets, status=status)
   if (status /= MC_STATUS_OK) error stop 'marching cubes failed'
   call sphere%adopt_facets(facets=facets)                     ! analyze merges the vertices shared by cells
   error = EXACT - sphere%get_volume()
   print '(A,F7.5,A,I5,A,L1,A,ES8.2)', 'sphere, h ', h, ': ', sphere%get_facets_number(), ' facets, watertight ', &
         sphere%is_watertight(), ', volume error ', error
   if (m > 0) print '(A,F4.2)', '                    error ratio to the previous h ', previous / error
   previous = error ; deallocate(phi)
enddo

resample_via_distance_field on cube-01.stl, at three resolutions:

f90
call body%load_from_file(file_name='cube-01.stl', guess_format=.true.)  ! the unit cube, 48 facets
do m = 0, 2
   n = 12 * 2**m                                                ! grid points along the longest side
   call body%resample_via_distance_field(resolution=n, surface_out=resampled, status=status)
   if (status /= MC_STATUS_OK) error stop 'resample failed'
   print '(A,I2,A,I5,A,L1,A,F7.5,A,ES8.2)', 'cube at ', n, ': ', resampled%get_facets_number(), ' facets, watertight ', &
         resampled%is_watertight(), ', volume ', resampled%get_volume(), ', deficit ', 1._R8P - resampled%get_volume()
enddo
$ ref_marching_cubes
sphere, h 0.18750:  1064 facets, watertight T, volume error 8.72E-02
sphere, h 0.09375:  4280 facets, watertight T, volume error 2.20E-02
                    error ratio to the previous h 3.97
sphere, h 0.04688: 17192 facets, watertight T, volume error 5.47E-03
                    error ratio to the previous h 4.02
cube at 12:  1196 facets, watertight T, volume 0.98567, deficit 1.43E-02
cube at 24:  4796 facets, watertight T, volume 0.98800, deficit 1.20E-02
cube at 48: 21164 facets, watertight T, volume 0.99759, deficit 2.41E-03
  • Watertight. Every extraction is closed once adopt_facets has merged the vertices that neighbouring cells emit twice: no sanitize is needed on these smooth fields.
  • Second order. The sphere's volume error falls by 3.97 and 4.02 when h halves: the linear interpolation along the cell edges puts the vertices on the sphere to O(h²), and the chords between them cut inside it by O(h²). The facet count grows as 1/h2 (1064, 4280, 17192).
  • Corners and edges. On the cube, the distance is linear across every face, so the faces come out flat and exact; the deficit comes from the cells across the 12 edges and 8 corners, where the chords cut them. How much depends on where the faces fall inside the cells (the grid spans the box plus a 5 % margin), so it does not fall smoothly with the resolution: 1.43e-2, 1.20e-2, 2.41e-3.
  • Count. 1196 to 21164 facets for a body of 48: decimate brings the count back down when it matters.

Visual reference ​

Sphere extracted from analytic SDF at 64³ grid resolution (9452 facets, volume 4.179 vs analytic 4.189):

the unit sphere extract_isosurface draws from its analytic signed distance on a 64^3 grid over [-2, 2]^3: 9452 facets, volume 4.179

Cube resampled through its own SDF at resolution=64 (40 364 facets, volume 0.99997: close, not bit-exact, the deficit is 3.4e-5); a corner, zoomed (the whole surface is too heavy to draw):

a corner of the unit cube re-tessellated by resample_via_distance_field at resolution 64, one regular pattern of triangles per grid cell; the whole surface has 40364 facets, volume 0.99997

The resampled cube has far more triangles than the input (12 → 40 k) because MC tessellates by grid cell, not by silhouette. Run decimate afterwards if the count matters.

Known limitations ​

  • Lorensen-Cline ambiguity on cases 105 / 150. The standard 256- entry MC table doesn't disambiguate the diagonally-opposite- corners-inside cases — the same case index can produce surfaces with topologically-different connectivity at adjacent cubes, occasionally leaving small holes. MC33 (Chernyaev 1995) is the documented upgrade path; for typical AMR-CFD use cases (smooth SDF, well-resolved grid), the ambiguity rarely fires.
  • resample_via_distance_field's surface_out cannot alias self. Passing the same surface for both consumes self%facet mid-loop and produces an empty output. Always use a distinct destination surface.
  • Output triangle count grows as resolution² (surface area / cell-face area). 32³ resolution typically gives a few thousand facets; 128³ gives hundreds of thousands. Plan for decimate after if downstream cares about count.
  • The output isn't exactly watertight by construction — MC's per-cell triangulation can create tiny T-junctions at refinement transitions of the input SDF. adopt_facets's connect_nearby_vertices filters most of these; the rest are closed by sanitize if needed.

See also ​

  • surface%distance — the signed-distance query that resample_via_distance_field samples internally.
  • decimate — the natural follow-up if the MC output is denser than the downstream pipeline can handle.
  • alpha_wrap — the heavyweight alternative for inputs too dirty for SDF resampling to repair.

References ​

  • Lorensen & Cline, Marching Cubes: A High Resolution 3D Surface Construction Algorithm, SIGGRAPH 1987. The reference algorithm.
  • Bourke, Polygonising a scalar field, 1994 (online article). The canonical 256-entry case table FOSSIL embeds.
  • Chernyaev, Marching Cubes 33: Construction of Topologically Correct Isosurfaces, GVG technical report 1995. The topology-correct upgrade path (MC33) that closes the ambiguity gap.