Skip to content

Usage ​

All examples use use fossil which re-exports surface_stl_object and facet_object, plus the constants for sign algorithms (SIGN_PSEUDO_NORMAL, SIGN_RAY_INTERSECTIONS, SIGN_SOLID_ANGLE, SIGN_FAST_WINDING_NUMBER), tree kinds (AABB_TREE_SAH_BVH, AABB_TREE_OCTREE), and status codes (STATUS_OK, STATUS_INVALID_INPUT, …).

Numeric kinds (I4P, R8P) come from PENF; 3D vectors and unit versors (ex_R8P, ey_R8P, ez_R8P) come from VecFor.

Every block on this page is a region of a program in docs/examples/src/ (ref_usage_*.f90), compiled and run when the site is built; the outputs shown are those runs. The bodies are the test fixtures dragon.stl (6588 facets, not watertight), cube-01.stl (the unit cube) and naca0012-ascii.stl.

Loading an STL file ​

Auto-detect format ​

Pass guess_format=.true. to let FOSSIL determine whether the file is ASCII or binary automatically.

f90
use fossil, only : surface_stl_object, STATUS_OK, STATUS_INVALID_INPUT
use penf,   only : I4P, R8P
use vecfor, only : vector_R8P

implicit none
type(surface_stl_object) :: surface, wing, copy, head
type(vector_R8P)         :: bmin, bmax
integer(I4P)             :: stat, u

call surface%load_from_file(file_name='dragon.stl', guess_format=.true.)  ! ASCII or binary, from the file size
print '(A,I0)', 'dragon.stl             facets ', surface%get_facets_number()

load_from_file runs analyze internally — bounding box, connectivity, volume, centroid, AABB tree, and pseudo-normals are all populated before it returns. You typically call sanitize next to repair common STL defects.

the dragon as loaded, inside its bounding box with the corners bmin and bmax labelled, its centroid marked, and in red the edges without a single neighbouring facet (fcon_edge = 0) at the jaws, the horns and the tail: on the dragon as loaded these are its 61 non-manifold edges, not open boundaries (see Validity predicates)

Explicit format ​

f90
call wing%load_from_file(file_name='naca0012-ascii.stl', is_ascii=.true.)     ! explicitly ASCII
call copy%load_from_file(file_name='dragon-out-binary.stl', is_ascii=.false.)  ! explicitly binary
print '(A,I0)', 'naca0012-ascii.stl     facets ', wing%get_facets_number()
print '(A,I0)', 'dragon-out-binary.stl  facets ', copy%get_facets_number()

is_ascii defaults to .true. when guess_format is absent or .false..

Load with on-the-fly clipping ​

Only the facets that overlap the box are loaded, without a separate clip pass; a facet crossing the box is kept whole, so the loaded surface can reach out of it:

f90
bmin%x = -15._R8P ; bmin%y = -5._R8P ; bmin%z =  0._R8P
bmax%x =   0._R8P ; bmax%y =  5._R8P ; bmax%z = 20._R8P
call head%load_from_file(file_name='dragon.stl', guess_format=.true., clip_min=bmin, clip_max=bmax)
print '(A,I0)', 'clipped load           facets ', head%get_facets_number()
bmin = head%get_bmin() ; bmax = head%get_bmax()
print '(A,F9.4,A,F9.4,A)', 'clipped load           x in [', bmin%x, ',', bmax%x, ']'

Rejecting bad input ​

If any vertex coordinate is NaN or Inf, load_from_file refuses the file via the optional status argument rather than letting the bad value propagate:

f90
open(newunit=u, file='maybe_bad.stl', action='write')  ! one facet with a NaN coordinate
write(u, '(A)') 'solid bad', ' facet normal 0 0 1', '  outer loop', '   vertex 0 0 0', '   vertex 1 0 0', &
                '   vertex NaN 1 0', '  endloop', ' endfacet', 'endsolid bad'
close(u)
call surface%load_from_file(file_name='maybe_bad.stl', guess_format=.true., status=stat)
if (stat == STATUS_INVALID_INPUT) then
   write(*, '(A)') 'STL contains non-finite coordinates; aborting.'
   stop
endif

The run of the loading blocks (and of the save block below, which writes dragon-out-binary.stl): the clipped load keeps 3811 of the 6588 facets, and its x range ends at 1.2261, past the box face x = 0, because the facets crossing that face are kept whole.

$ ref_usage_io
dragon.stl             facets 6588
naca0012-ascii.stl     facets 188
dragon-out-binary.stl  facets 6588
clipped load           facets 3811
clipped load           x in [ -10.8287,   1.2261]
STL contains non-finite coordinates; aborting.

Printing statistics ​

f90
call surface%load_from_file(file_name='cube-01.stl', guess_format=.true.)
call surface%sanitize
print '(A)', surface%statistics()

The output for the cube fixture, post-sanitize:

$ ref_usage_analysis statistics
X extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
Y extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
Z extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
volume: +0.99999999999999956E+000
centroid: [+0.50000000000000000E+000, +0.50000000000000000E+000, +0.50000000000000000E+000]
number of facets: +48
number of facets with 1 edges disconnected: +0
number of facets with 2 edges disconnected: +0
number of facets with 3 edges disconnected: +0
number of non-manifold edges (3+ incident facets): +0
degenerate facets removed (last pass): +0
duplicate facets removed (last pass): +0
number of AABB refinement levels: -1

The last line is the depth of the octree; the default SAH BVH has no levels and reports AABB_AUTO_REFINEMENT (-1).

The same cube drawn with what the statistics describe: the box of the extents, the centroid, and the 48 facet normals, all pointing out, which is why the divergence-theorem volume is +1.0000:

the cube fixture after sanitize drawn translucent inside its bounding box, the extents [0, 1] labelled, its centroid (0.5, 0.5, 0.5) marked, and the normal of each of its 48 facets drawn from the facet centroid, every one pointing outwards

TIP

Volume is positive for a closed body with outward-pointing normals (the standard divergence-theorem convention; sanitize produces this state). If you see a negative volume after sanitize, the mesh is probably non-watertight — check the non-manifold-edge and disconnected-edge counts.


Saving an STL file ​

f90
call surface%save_into_file(file_name='dragon-out-ascii.stl')                    ! ASCII (the default)
call surface%save_into_file(file_name='dragon-out-binary.stl', is_ascii=.false.) ! binary

is_ascii defaults to .true.: pass is_ascii=.false. for a binary file. A surface with several patches is written as one solid block per patch in ASCII. An existing file is replaced: a binary file is 84 + 50 n bytes for n facets whatever was there before (issue #80).

An STL file has no shared vertices: each facet is written on its own, its normal and its three vertices. The cube fixture saved this way holds 144 vertex records for its 26 distinct vertices; load_from_file welds them back (analyze builds the vertex pool), and the file loaded back has the same 48 facets and volume 1.0000:

the cube fixture exploded, every facet facing the camera shrunk towards its centroid and pushed out along its normal, each with its own three vertices as gold points; one facet's normal is drawn and labelled, one of its vertices labelled

The Named patches page shows a multi-patch file read back.


Sanitize (the full repair pipeline) ​

sanitize is the orchestrator. It runs every repair pass in the right order and prints one stderr warning per defect class detected.

f90
call surface%load_from_file(file_name='dragon.stl', guess_format=.true.)
call surface%sanitize
print '(A)', surface%statistics()

On the dragon it removes 62 duplicate facets and reports what it cannot repair: facets with disconnected edges and 54 non-manifold edges remain. A disconnected edge is a facet edge without a single neighbour: a boundary edge of the holes the duplicates leave (128 of them, which sanitize(fill_holes=.true.) closes), or a facet edge on a non-manifold edge, which is not a hole.

$ ref_usage_repair sanitize
WARNING: sanitize: 62 duplicate facet(s) removed
WARNING: sanitize: 129 facet(s) with 1 disconnected edge remain
WARNING: sanitize: 14 facet(s) with 2 disconnected edges remain
WARNING: sanitize: 49 facet(s) with 3 disconnected edges remain
WARNING: sanitize: 54 non-manifold edge(s) (3+ incident facets) detected
X extents: [-0.10828700065612793E+002, +0.96460599899291992E+001]
Y extents: [-0.41883192062377930E+001, +0.49512038230895996E+001]
Z extents: [+0.52821402549743652E+001, +0.19741262435913086E+002]
volume: +0.46588084411411188E+003
centroid: [-0.12166249553566366E+001, +0.80652024443980008E+000, +0.10307739535120760E+002]
number of facets: +6526
number of facets with 1 edges disconnected: +129
number of facets with 2 edges disconnected: +14
number of facets with 3 edges disconnected: +49
number of non-manifold edges (3+ incident facets): +54
degenerate facets removed (last pass): +0
duplicate facets removed (last pass): +62
number of AABB refinement levels: -1

The passes that run inside sanitize:

  1. remove_degenerate_facets — drop zero-area / sliver triangles before their NaN normals contaminate downstream queries.
  2. connect_nearby_vertices (if disconnected edges were detected) — union-find vertex deduplication on a tolerance.
  3. analyze — rebuild metrix, connectivity, vertex occurrences.
  4. remove_duplicate_facets — drop literal duplicates, including reversed-orientation ones.
  5. analyze — rebuild after duplicate removal (only if any duplicates were dropped).
  6. sanitize_normals — BFS-propagate winding consistency, then global flip so volume > 0.
  7. fill_holes — only with sanitize(fill_holes=.true.): close the boundary loops with minimum-weight patches (refine_holes and fair_holes refine and fair the patches; see Hole filling).

Each individual pass is also callable directly if you want fine-grained control. Called one by one, in this order, on the unit cube with one defect of each kind (a degenerate facet, a facet shifted by 1e-4, a duplicate facet, two facets wound inwards and a missing facet), each pass removes its own defect:

an animation of the unit cube with five defects labelled (a degenerate facet as three gold points on the top front edge, a crack along a shifted facet in red, a duplicate facet in brown, two facets wound inwards in ember, a hole), then one frame per pass: remove_degenerate_facets removes 1 facet, connect_nearby_vertices closes the crack, remove_duplicate_facets removes 1 and leaves the 3 boundary edges of the hole, sanitize_normals flips 2 facets, fill_holes closes the hole: watertight, volume 1.0000

On the dragon the passes show a less obvious effect: as loaded it has no open boundary at all, only 61 non-manifold edges, several of them made by duplicate facets; removing the 62 duplicates turns those edges into 128 boundary edges (see the next section).


Validity predicates ​

After sanitize, three named predicates summarise the mesh state:

f90
if (.not. surface%is_watertight()) print '(A)', 'surface has boundary or non-manifold edges'
if (.not. surface%is_manifold())   print '(A)', 'surface has non-manifold edges (3+ incidences)'
if (.not. surface%is_volume()) then
   print '(A)', 'volume is not physically meaningful: do not trust get_volume()/get_centroid()'
endif
PredicateTrue iff
is_watertightEvery edge has exactly 2 incident facets
is_manifoldNo non-manifold edges (boundary edges allowed)
is_volumewatertight AND volume > 0 AND finite centroid

The block run on the dragon as loaded, then on the cube after sanitize:

$ ref_usage_analysis validity
dragon.stl as loaded:
surface has boundary or non-manifold edges
surface has non-manifold edges (3+ incidences)
volume is not physically meaningful: do not trust get_volume()/get_centroid()
  is_watertight F  is_manifold F  is_volume F
cube-01.stl after sanitize:
  is_watertight T  is_manifold T  is_volume T

What the predicates see on the dragon, from feature_edges (boundary edges have one facet, non-manifold edges three or more): as loaded, 0 boundary and 61 non-manifold edges; after sanitize, 128 boundary and 54 non-manifold edges. All three predicates stay false in both states:

an animation of the dragon drawn translucent in two frames: as loaded, with its 61 non-manifold edges in gold and no boundary edge; after sanitize, with 128 boundary edges in red, where duplicate facets were removed, and 54 non-manifold edges in gold


Call analyze after transforming

translate, rotate, mirror and resize move the vertices only. The centroid, volume, bounding box, AABB tree and pseudo-normals stay as they were until call surface%analyze, so getters and distance queries return stale values until then. One analyze after the last transform of a batch is enough. See After a transform.

The blocks below start each operation from a copy of the dragon as loaded (surface = dragon), declared as:

f90
use fossil, only : surface_stl_object
use penf,   only : I4P, R8P
use vecfor, only : vector_R8P, ex_R8P, ey_R8P, ez_R8P, rotation_matrix_R8P, mirror_matrix_R8P

implicit none
real(R8P), parameter     :: pi = 4._R8P * atan(1._R8P)
type(surface_stl_object) :: dragon, surface, remainder, surface_1, surface_2
type(vector_R8P)         :: delta, axis, normal, factor, bmin, bmax
real(R8P)                :: angle, matrix(3,3)

call dragon%load_from_file(file_name='dragon.stl', guess_format=.true.)

Translate ​

Move the surface by a vectorial delta or by individual axis components (delta and x/y/z together are ambiguous: status = STATUS_AMBIGUOUS_ARGS, or an error stop without status):

f90
surface = dragon
delta%x = 1._R8P ; delta%y = 0._R8P ; delta%z = 0._R8P
call surface%translate(delta=delta)                       ! by a 3-D vector
call surface%translate(x=2._R8P)                          ! by scalar components, any combination
call surface%translate(y=1.5_R8P)
call surface%translate(x=1._R8P, y=2._R8P, z=0.5_R8P)
call surface%analyze                                      ! box, volume, tree of the moved surface

the dragon as loaded as a translucent ghost and, solid, the dragon translated by (4, 3.5, 0.5), the segment between the two centroids marked


Rotate ​

Rotate around an arbitrary axis by an angle in radians; the pivot is the origin:

f90
surface = dragon
axis  = ex_R8P                                            ! about the x axis
angle = pi / 2._R8P                                       ! a quarter turn, in radians
call surface%rotate(axis=axis, angle=angle)               ! about the origin
call surface%analyze

Alternatively, provide a pre-built rotation matrix:

f90
surface = dragon
matrix = rotation_matrix_R8P(axis=ex_R8P, angle=pi / 2._R8P)
call surface%rotate(matrix=matrix)                        ! the same quarter turn
call surface%analyze

Both forms take an optional center, the pivot of the rotation:

f90
surface = dragon
call surface%rotate(axis=ex_R8P, angle=pi / 2._R8P, center=surface%get_centroid())  ! about the centroid
call surface%analyze

the dragon as loaded as a ghost above the x axis, and the dragon after a quarter turn about the x axis through the origin, lying below the axis


Mirror ​

Mirror with respect to a plane through the origin, defined by its normal (normalised inside):

f90
surface = dragon
normal = ex_R8P                                           ! through the yz plane (normal = x axis)
call surface%mirror(normal=normal)
call surface%analyze
f90
surface = dragon
normal = ex_R8P + ey_R8P                                  ! through an oblique plane (normalised inside)
call surface%mirror(normal=normal)
call surface%analyze

Or by a pre-built mirror matrix:

f90
surface = dragon
matrix = mirror_matrix_R8P(normal=ex_R8P)
call surface%mirror(matrix=matrix)                        ! the same as normal=ex_R8P
call surface%analyze

the dragon seen from above: the original as a ghost lying along x, and its reflection through the plane x + y = 0, drawn as a line, lying along y

The facet winding is reversed together with the reflection, so an outward surface stays outward (the same holds for resize with an odd number of negative factors): the volumes of the mirrored dragons in the run below stay +465.929. As for every transform, call surface%analyze before queries.


Resize (scale) ​

Scale all facets by a uniform or per-axis factor (factor and x/y/z together are ambiguous, as for translate). The default pivot is the origin:

f90
surface = dragon
factor = 2._R8P * ex_R8P + 2._R8P * ey_R8P + 2._R8P * ez_R8P
call surface%resize(factor=factor)                        ! uniform, about the origin
call surface%analyze
f90
surface = dragon
call surface%resize(x=0.5_R8P, z=1.2_R8P)                 ! per axis; y keeps its size
call surface%analyze

Pass respect_centroid=.true. to scale about the surface centroid instead (the centroid of the last analyze):

f90
surface = dragon
call surface%resize(factor=factor, respect_centroid=.true.)  ! about the centroid of the last analyze
call surface%analyze

the dragon as loaded as a ghost and, solid, the dragon scaled by 2 about the origin, marked below: twice as large and moved away from the origin


Clip ​

Keep only the facets that overlap a given axis-aligned bounding box (a facet crossing the box is kept whole). The removed facets can be captured as a separate surface:

f90
surface = dragon
bmin%x = -15._R8P ; bmin%y = -5._R8P ; bmin%z =  0._R8P
bmax%x =   0._R8P ; bmax%y =  5._R8P ; bmax%z = 20._R8P
call surface%clip(bmin=bmin, bmax=bmax, remainder=remainder)  ! clip re-runs analyze on both
print '(A,I0,A,I0,A,I0)', 'clip           kept ', surface%get_facets_number(), ', remainder ', &
                          remainder%get_facets_number(), ', of ', dragon%get_facets_number()

the clip box around the head half of the dragon: the 3811 kept facets solid, reaching out of the box where they cross its face, and the 2777 facets of the remainder as a ghost


Merge ​

Combine two surfaces into one. The result is stored in the first surface; here the two parts are the clip and its remainder, saved and loaded back:

f90
call surface%save_into_file(file_name='dragon_part_1.stl')
call remainder%save_into_file(file_name='dragon_part_2.stl')
call surface_1%load_from_file(file_name='dragon_part_1.stl', guess_format=.true.)
call surface_2%load_from_file(file_name='dragon_part_2.stl', guess_format=.true.)
call surface_1%merge_solids(other=surface_2)              ! merge_solids re-runs analyze
call surface_1%save_into_file(file_name='dragon_merged.stl')
print '(A,I0,A)', 'merge          ', surface_1%get_facets_number(), ' facets'

the merged surface: the facets of dragon_part_1 in stone and those of dragon_part_2 in ember, together the whole dragon again

The run of every block of the manipulation sections: the box and the volume that analyze computes after each operation. Rotations, mirrors and translations keep the volume 465.929; the uniform factor 2 multiplies it by 8 (3727.429), the factors (0.5, 1, 1.2) by 0.6 (279.557). The merge gives back the 6588 facets and the box of the dragon.

$ ref_usage_manipulation
as loaded      box   -10.829   -4.188    5.282 ..    9.646    4.951   19.741  volume   465.929
translate      box    -6.829   -0.688    5.782 ..   13.646    8.451   20.241  volume   465.929
rotate         box   -10.829  -19.741   -4.188 ..    9.646   -5.282    4.951  volume   465.929
rotate matrix  box   -10.829  -19.741   -4.188 ..    9.646   -5.282    4.951  volume   465.929
rotate centre  box   -10.829   -8.626    5.314 ..    9.646    5.833   14.453  volume   465.929
mirror x       box    -9.646   -4.188    5.282 ..   10.829    4.951   19.741  volume   465.929
mirror x+y     box    -4.951   -9.646    5.282 ..    4.188   10.829   19.741  volume   465.929
mirror matrix  box    -9.646   -4.188    5.282 ..   10.829    4.951   19.741  volume   465.929
resize x2      box   -21.657   -8.377   10.564 ..   19.292    9.902   39.483  volume  3727.429
resize x,z     box    -5.414   -4.188    6.339 ..    4.823    4.951   23.690  volume   279.557
resize centre  box   -20.441   -9.183    0.256 ..   20.508    9.096   29.174  volume  3727.429
clip           kept 3811, remainder 2777, of 6588
clip           box   -10.829   -4.188    5.283 ..    1.226    4.242   19.741  volume   288.640
merge          6588 facets
merge          box   -10.829   -4.188    5.282 ..    9.646    4.951   19.741  volume   465.929

Distance queries ​

The first blocks query the unit cube cube-01.stl:

f90
use fossil, only : surface_stl_object, SIGN_RAY_INTERSECTIONS, AABB_TREE_OCTREE, STATUS_OK
use penf,   only : I4P, R8P
use vecfor, only : vector_R8P, ex_R8P, ey_R8P, ez_R8P

implicit none
type(surface_stl_object) :: surface, dragon, dragon_octree
type(vector_R8P)         :: p, closest, normal
type(vector_R8P)         :: points(21)
real(R8P)                :: d2, d, sd, sd_ray, dist, d_bvh(21), d_oct(21)
logical                  :: inside, same
integer(I4P)             :: facet, edge, vertex, i, status
type(vector_R8P), allocatable :: bmin(:), bmax(:)
integer(I4P),     allocatable :: depth(:)
logical,          allocatable :: leaf(:)

call surface%load_from_file(file_name='cube-01.stl', guess_format=.true.)  ! the unit cube [0, 1]^3

Unsigned distance (squared, default) ​

f90
d2 = surface%distance(point=2._R8P * ex_R8P + 0._R8P * ey_R8P + 0._R8P * ez_R8P)  ! squared (the default)
print '(A,F10.6)', 'squared distance of (2, 0, 0)         ', d2

Euclidean (non-squared) distance ​

f90
p = 2._R8P * ex_R8P + 2._R8P * ey_R8P + 0.5_R8P * ez_R8P
d = surface%distance(point=p, is_square_root=.true.)
print '(A,F10.6)', 'distance of (2, 2, 0.5)               ', d

Signed distance ​

Negative inside, positive outside. Default sign algorithm is SIGN_PSEUDO_NORMAL (Bærentzen–Aanæs); pass sign_algorithm= to override.

f90
p = 0.5_R8P * ex_R8P + 0.5_R8P * ey_R8P + 0.25_R8P * ez_R8P
sd = surface%distance(point=p, is_signed=.true., is_square_root=.true.)
! Override the sign algorithm for benchmarking or for meshes whose orientation
! cannot be sanitised (e.g. open shells where outward is ill-defined).
sd_ray = surface%distance(point=p, is_signed=.true., is_square_root=.true., sign_algorithm=SIGN_RAY_INTERSECTIONS)
print '(A,F10.6,A,F10.6)', 'signed distance of (0.5, 0.5, 0.25)   ', sd, ', by ray intersections ', sd_ray

Point-in-polyhedron test ​

f90
inside = surface%is_point_inside(point=0.5_R8P * ex_R8P + 0.5_R8P * ey_R8P + 0.5_R8P * ez_R8P)
if (inside) print '(A)', 'point (0.5, 0.5, 0.5) is inside the surface'

Closest point and normal ​

compute_distance returns the distance together with the closest facet, the local edge (0 if the closest point is not on an edge) and the local vertex (0 if it is not on a vertex) of that facet, the closest point and the pseudo-normal there:

f90
call dragon%load_from_file(file_name='dragon.stl', guess_format=.true.)
p = 0._R8P * ex_R8P + 0._R8P * ey_R8P + 25._R8P * ez_R8P
call dragon%compute_distance(point=p, distance=dist, is_square_root=.true., facet_index=facet, edge_index=edge, &
                             vertex_index=vertex, closest_point=closest, normal=normal)
print '(A,F9.4)',   'dragon, (0, 0, 25): distance ', dist
print '(A,3F9.4)',  '  closest point ', closest%x, closest%y, closest%z
print '(A,3F9.4)',  '  normal        ', normal%x, normal%y, normal%z
print '(A,I0,A,I0,A,I0)', '  facet ', facet, ', local edge ', edge, ', local vertex ', vertex

probe points around the dragon, each joined to its closest point on the surface, with the pseudo-normal drawn as a short segment from the closest point; where the closest point lies on an edge or a vertex the normal is not the facet normal

Batched distances ​

distance_many is a loop of distance over a point array, OpenMP-parallel, with the same options for every point; distances is allocated by the caller, and a size mismatch returns STATUS_INVALID_INPUT:

f90
do i = 1, size(points)                                     ! 21 points on a line through the dragon
   points(i) = (-12._R8P + 1.1_R8P * (i - 1)) * ex_R8P + 0.5_R8P * ey_R8P + 12._R8P * ez_R8P
enddo
call dragon%distance_many(points=points, distances=d_bvh, is_signed=.true., is_square_root=.true., status=status)
if (status /= STATUS_OK) error stop 'distance_many: points and distances differ in size'
same = .true.
do i = 1, size(points)
   same = same .and. (d_bvh(i) == dragon%distance(point=points(i), is_signed=.true., is_square_root=.true.))
enddo
print '(A,I0,A,L1)', 'distance_many: ', size(points), ' points, equal to distance bit for bit ', same
print '(A,I0)', '  inside ', count(d_bvh < 0._R8P)

Choosing the AABB tree kind ​

The default AABB_TREE_SAH_BVH is faster on every measured mesh (see AABB tree and tutorial 5). The legacy octree is still selectable:

f90
call dragon_octree%load_from_file(file_name='dragon.stl', guess_format=.true., aabb_tree_kind=AABB_TREE_OCTREE)
call dragon_octree%distance_many(points=points, distances=d_oct, is_signed=.true., is_square_root=.true.)
print '(A,L1)', 'octree and SAH BVH: equal bit for bit ', all(d_bvh == d_oct)

Both kinds produce bit-exact distance results — the difference is purely query speed.

Reading the tree ​

The tree itself is private, but tree_boxes returns its boxes, read only (issue #89): every node down to max_depth (default: all), breadth first from the root, with the optional depth, leaf flag, parent and the facets of each leaf (CSR: facet_ids(facet_start(i):facet_start(i+1)-1), every facet in exactly one leaf). For the BVH the boxes bound their facets and overlap; for the octree they are the cells of its partition, empty cells left out, and a leaf holds the facets whose centroid it contains. save_aabb_into_file writes one STL per leaf through it, for either kind; curve%tree_boxes is the 2-D twin over the segment BVH:

f90
call dragon%tree_boxes(bmin=bmin, bmax=bmax, depth=depth, leaf=leaf)                ! the whole SAH BVH
print '(A,I0,A,I0,A,I0)', 'BVH boxes ', size(bmin), ', leaves ', count(leaf), ', depth ', maxval(depth)
call dragon_octree%tree_boxes(bmin=bmin, bmax=bmax, depth=depth, leaf=leaf)
print '(A,I0,A,I0,A,I0)', 'octree boxes ', size(bmin), ', leaves ', count(leaf), ', depth ', maxval(depth)

The run of the distance blocks:

$ ref_usage_distance
squared distance of (2, 0, 0)           1.000000
distance of (2, 2, 0.5)                 1.414214
signed distance of (0.5, 0.5, 0.25)    -0.250000, by ray intersections  -0.250000
point (0.5, 0.5, 0.5) is inside the surface
dragon, (0, 0, 25): distance    6.2099
  closest point   -0.3929   2.7780  19.4600
  normal           0.0968  -0.5028   0.8590
  facet 6302, local edge 2, local vertex 0
distance_many: 21 points, equal to distance bit for bit T
  inside 8
octree and SAH BVH: equal bit for bit T
BVH boxes 313, leaves 157, depth 10
octree boxes 59, leaves 50, depth 2

Connect nearby vertices (repair) ​

sanitize calls this internally when needed; you only invoke it directly if you want to repair a surface without running the full pipeline. The surface here is the cube with its first facet shifted by 1e-4 along x, which disconnects its three edges from the neighbours:

f90
allocate(facets(surface%get_facets_number()))
do i = 1, size(facets)
   f => surface%facet_at(i) ; facets(i) = f
enddo
do i = 1, 3                                                  ! shift the first facet: its edges disconnect
   facets(1)%vertex(i) = facets(1)%vertex(i) + 1.e-4_R8P * ex_R8P
enddo
call surface%adopt_facets(facets=facets)                     ! adopt_facets runs analyze
f90
print '(A)', surface%statistics(prefix='before ')   ! shows disconnected edge counts
call surface%connect_nearby_vertices
call surface%analyze
print '(A)', surface%statistics(prefix='after  ')   ! disconnected edges should be reduced

Each group of nearby vertices is replaced by its centroid, so the crack closes (no disconnected edges after) but the merged vertices sit between the old positions: the volume moves from 0.9999958 to 0.9999948.

$ ref_usage_repair connect
before X extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
before Y extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
before Z extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
before volume: +0.99999583333333364E+000
before centroid: [+0.50000312470051955E+000, +0.49999895832899305E+000, +0.50000104167100701E+000]
before number of facets: +48
before number of facets with 1 edges disconnected: +3
before number of facets with 2 edges disconnected: +0
before number of facets with 3 edges disconnected: +1
before number of non-manifold edges (3+ incident facets): +0
before degenerate facets removed (last pass): +0
before duplicate facets removed (last pass): +0
before number of AABB refinement levels: -1
after  X extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
after  Y extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
after  Z extents: [+0.00000000000000000E+000, +0.10000000000000000E+001]
after  volume: +0.99999479166666694E+000
after  centroid: [+0.50000260414189079E+000, +0.49999874131288879E+000, +0.50000125868711121E+000]
after  number of facets: +48
after  number of facets with 1 edges disconnected: +0
after  number of facets with 2 edges disconnected: +0
after  number of facets with 3 edges disconnected: +0
after  number of non-manifold edges (3+ incident facets): +0
after  degenerate facets removed (last pass): +0
after  duplicate facets removed (last pass): +0
after  number of AABB refinement levels: -1

Zoomed on one corner of the shifted facet, at the point (0, 0.5, 0), 4e-4 across:

an animation of two frames zoomed on a corner of the cube, 4e-4 across: before, the shifted facet's vertex and the neighbours' vertex as two gold points 1e-4 apart, with the disconnected edges in red; after connect_nearby_vertices, one vertex at the centroid of the group and no red edge


Full workflow example ​

f90
!< Usage reference, full workflow: load, repair, centre the centroid at the origin, rescale the longest side to 1, save.
program ref_usage_workflow
use fossil, only : surface_stl_object
use penf,   only : R8P
use vecfor, only : vector_R8P, ex_R8P, ey_R8P, ez_R8P

implicit none
type(surface_stl_object) :: surface
type(vector_R8P)         :: bmin, bmax, c

! 1. Load (analyze runs internally).
call surface%load_from_file(file_name='dragon.stl', guess_format=.true.)

! 2. Run the full repair pipeline.
call surface%sanitize

! 3. Centre at the origin and rescale to fit in a unit box.
c = surface%get_centroid() ; bmin = surface%get_bmin() ; bmax = surface%get_bmax()
call surface%translate(delta=-c)
call surface%resize(factor=(1._R8P / maxval([bmax%x - bmin%x, bmax%y - bmin%y, bmax%z - bmin%z])) * &
                           (ex_R8P + ey_R8P + ez_R8P))
call surface%analyze
bmin = surface%get_bmin() ; bmax = surface%get_bmax() ; c = surface%get_centroid()
print '(A,3F9.4)', 'box min      ', bmin%x, bmin%y, bmin%z
print '(A,3F9.4)', 'box max      ', bmax%x, bmax%y, bmax%z
print '(A,L1)',    'centroid within 1e-12 of the origin ', max(abs(c%x), abs(c%y), abs(c%z)) < 1.e-12_R8P

! 4. Save.
call surface%save_into_file(file_name='dragon-normalized.stl')
endprogram ref_usage_workflow
$ ref_usage_workflow
WARNING: sanitize: 62 duplicate facet(s) removed
WARNING: sanitize: 129 facet(s) with 1 disconnected edge remain
WARNING: sanitize: 14 facet(s) with 2 disconnected edges remain
WARNING: sanitize: 49 facet(s) with 3 disconnected edges remain
WARNING: sanitize: 54 non-manifold edge(s) (3+ incident facets) detected
box min        -0.4695  -0.2440  -0.2455
box max         0.5305   0.2024   0.4607
centroid within 1e-12 of the origin T

the dragon after the workflow: its centroid at the origin, marked, with the x, y and z axes drawn from it, inside its bounding box, whose longest side (along x) is 1 and whose corner bmin is (-0.4695, -0.2440, -0.2455)