Skip to content

Load STL and CAD geometry ​

Every SHORE command reads its body through one Geometry interface, whether the file is a triangulated STL or a STEP, IGES or BREP model. These recipes load both, list what a CAD model contains, and show when the exact CAD projection matters.

The code is examples/cookbook/load_geometry.py (about 4 s). CAD input needs the cad extra: pip install "shore-mesh[cad]" (build123d and OCP); STL needs nothing extra.

Load a file and list its entities ​

The CAD test model is a half wing–body built with build123d and written in the three CAD formats:

python
# A half wing-body (fuselage + NACA 0012 wing, cut at the symmetry plane z = 0),
# written as STEP, BREP and IGES. Any CAD tool's export works the same way.
radius, length, span = 0.5, 5.0, 3.0
fuselage = bd.Cylinder(radius, length, rotation=(0, 90, 0))
fuselage += bd.Pos(-length / 2, 0, 0) * bd.Sphere(radius) + bd.Pos(length / 2, 0, 0) * bd.Sphere(
    radius
)
sec = naca("0012", 40, closed_te=False)
le = int(np.argmin(sec[:, 0]))
upper = [(float(x), float(y), 0.0) for x, y in sec[: le + 1]]
lower = [(float(x), float(y), 0.0) for x, y in sec[le:]]
wire = bd.Wire([bd.Spline(*upper), bd.Spline(*lower), bd.Line(lower[-1], upper[0])])
wing = bd.extrude(bd.make_face(wire), amount=span)
model = (fuselage + wing) & (bd.Pos(0, 0, 10) * bd.Box(40, 40, 20))
bd.export_step(model, "wing_body.step")
bd.export_brep(model, "wing_body.brep")
writer = IGESControl_Writer()
writer.AddShape(model.wrapped)
writer.ComputeModel()
writer.Write("wing_body.igs")

load_geometry picks the backend from the suffix: .stl gives an StlGeometry, .step/.stp, .iges/.igs and .brep/.brp give an OcctGeometry.

python
for path in ("wing_body.step", "wing_body.brep", "wing_body.igs"):
    geo = load_geometry(path)  # backend chosen by suffix
    counts = {kind.value: len(geo.entities(kind)) for kind in EntityKind}
    print(f"{path:15s} {counts}")
geo = load_geometry("wing_body.step")
print("bounds", np.round(geo.bounds, 3).tolist())
display = geo.display()  # what the GUI draws: triangles per face, edge polylines
print(f"tessellation: {len(display.triangles)} triangles over {len(geo.faces)} faces")
text
wing_body.step  {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
wing_body.brep  {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
wing_body.igs   {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
bounds [[-3.0, -0.5, -0.0], [3.0, 0.5, 3.0]]
tessellation: 5078 triangles over 8 faces
The CAD wing–body: faces coloured per face, edges as dark curves.The CAD wing–body: faces coloured per face, edges as dark curves.
The CAD wing–body: faces coloured per face, edges as dark curves.
  • Entities have four kinds: BODY (always one), SURFACE (CAD faces), CURVE (CAD edges) and POINT (CAD vertices). An EntityRef(kind, index) names one; the index is what Project.associate(..., indices=...) and the GUI's Association dock use.
  • An STL has one BODY and no faces. Its CURVE and POINT entities are the feature curves found at load time: see Feature curves of an STL.
  • IGES stores faces as independent trimmed surfaces; the loader sews them (tolerance 1e-6) so adjacent faces share their edges, which association needs. The counts above match the STEP file after sewing.
  • A CAD file without the cad extra raises MeshInputError with the pip install hint; an unknown suffix raises too.

Choose between tessellated and exact projection ​

A CAD geometry answers project from a tessellation by default (tier 1) and from the exact B-rep with exact=True (tier 2). The recipe projects 200 points onto a unit sphere three ways:

python
# A STEP sphere of radius 1 and the same sphere as a 1280-triangle STL.
bd.export_step(bd.Sphere(1.0), "sphere.step")
shapes.sphere(radius=1.0, subdivisions=3).export("sphere.stl")
points = np.random.default_rng(0).normal(size=(200, 3))
points *= 1.3 / np.linalg.norm(points, axis=1, keepdims=True)  # on a sphere of radius 1.3

cad = load_geometry("sphere.step")
stl = load_geometry("sphere.stl")
for label, geom, exact in (
    ("STL", stl, False),
    ("CAD tier 1", cad, False),
    ("CAD exact", cad, True),
):
    proj = geom.project(points, exact=exact)  # closest point on the whole body
    err = np.abs(np.linalg.norm(proj.points, axis=1) - 1.0).max()
    print(f"{label:10s} max |r - 1| = {err:.1e}")
face = EntityRef(EntityKind.SURFACE, 0)
on_face = cad.project(points, face, exact=True)
print("(u, v) of the first point on face 0:", np.round(on_face.params[0], 4))
text
STL        max |r - 1| = 4.3e-03
CAD tier 1 max |r - 1| = 2.6e-03
CAD exact  max |r - 1| = 1.1e-16
(u, v) of the first point on face 0: [5.4731 1.2934]
  • The tier-1 tessellation has a linear deflection of 1e-3 times the bounding-box diagonal (OcctGeometry(rel_deflection=...) or deflection= changes it). Its error is the same order as a fine STL's.
  • Use the exact tier when the wall spacing is near the faceting error: a first cell of 1e-5 on a body of unit size cannot sit on a surface that is wrong by 1e-3. Project.snap(exact=True) and Project.premesh(exact=True) put the nodes on the exact surface.
  • Projecting onto one SURFACE returns its (u, v) parameters in Projection.params; projecting onto a CURVE returns the curve parameter. An STL has no parametrisation (params is None).
  • On a trimmed face, when the foot point on the underlying surface falls outside the trim, the exact projection returns the closest point of the face itself, which lies on its boundary.

Name geometries in a project ​

A project holds several geometries under names; the commands refer to them by name (geometry="wing_body"). Body.from_file is the single-body entry point the marching topologies use.

python
p = Project()
p.load_geometry("wing_body.step", name="wing_body")
p.load_geometry("sphere.stl", name="ball")
for name, body in p.geometries.items():
    print(f"{name}: {type(body.geometry).__name__}, CAD={body.is_cad}")
body = Body.from_file("sphere.step")  # what the marching topologies take
print("anchor", np.round(body.anchor, 6), "CAD", body.is_cad)
text
wing_body: OcctGeometry, CAD=True
ball: StlGeometry, CAD=False
anchor [0. 0. 0.] CAD True
  • Project.load_geometry(path, name=...) defaults to the name "body". Loading a second file under the same name replaces the first and discards the meshes of the components built on it (undo restores them).

  • Body.from_file also resolves the anchor, the interior point from which the cubed-sphere and O-grid topologies cast rays. On CAD the anchor is found on the merged tessellation. A body without a valid anchor (an open half model) still loads; the error is raised only when something needs the ray caster.

  • The CLI takes CAD wherever it takes STL; for example a cubed sphere on the STEP sphere:

    bash
    shore mesh sphere.step --ni 33 --nj 64 --nk 21 --theta-cap-deg 35 -o sphere_cad

See also ​

Released under the MIT License.