A fast, optionally multithreaded Constructive Solid Geometry (CSG) library in Rust, built around Boolean operations (union, difference, intersection) on sets of polygons stored in BSP trees. csgrs helps you construct 2D and 3D geometry with an OpenSCAD-like syntax, and to transform, interrogate, and simulate those shapes without leaving Rust.
This library aims to integrate cleanly with the Dimforge ecosystem (e.g., nalgebra
, Parry
, and Rapier
), leverage earclip
/earcut
and cavalier_contours
for robust processing of convex and non-convex polygons and polygons with holes, be light weight and full featured, and provide an extensible type-safe API.
The BSP tree works with shapes made of lines. In 3D, csgrs interpolates all curves so that they can be processed by the BSP. csgrs has limited support for recovering curves from interpolated lines into 2D, and for offsetting curves in 2D. Recovering curves should work even on models imported as a mesh, allowing them to be "upgraded" to real arcs for offsetting, booleans, toolpathing, etc.
Install the Rust language tools from rustup.rs.
cargo new my_cad_project
cd my_cad_project
cargo add csgrs
// Alias the library’s generic CSG type with empty metadata:
type CSG = csgrs::csg::CSG<()>;
// Create two shapes:
let cube = CSG::cube(2.0, 2.0, 2.0, None); // 2×2×2 cube at origin, no metadata
let sphere = CSG::sphere(1.0, 16, 8, None); // sphere of radius=1 at origin, no metadata
// Difference one from the other:
let difference_result = cube.difference(&sphere);
// Write the result as an ASCII STL:
let stl = difference_result.to_stl_ascii("cube_minus_sphere");
std::fs::write("cube_sphere_difference.stl", stl).unwrap();
CSG<S>
is the main type. It stores:- a
Vec<Polygon<S>>
polygons, describing 3D shapes, eachPolygon<S>
holds:- a
Vec<Vertex>
(positions + normals), - a
Plane
describing the polygon’s orientation in 3D. - an optional metadata field (
Option<S>
)
- a
- a
cavalier_contours
Shape<Real>
polylines, describing 2D shapes:Vec<IndexedPolyline<Real>>
ccw_plines, which contains indexed positive shapes, 0 - many allowed.Vec<IndexedPolyline<Real>>
cw_plines, which contains indexed negative shapes (i.e. holes), 0 - many allowed.StaticAABB2DIndex<Real>
plines_index, a spatial index of all the polyline area bounding boxes, positions correspond to all the counter clockwise polylines followed by all the clockwise polylines
- an optional metadata field (
Option<S>
)
- a
CSG<S>
provides methods for working with 2D and 3D shapes. You can build a CSG<S>
from polygons with CSG::from_polygons(...)
or from polylines with CSG::from_polylines(...)
. Polygons must be closed, planar, have 3 or more vertices. Polylines can be open or closed, have holes, but must be planar in the XY. Operations work on both 2D and 3D shapes though they generally do not interact except where one is explicitly transformed into the other as in extrude or slice. Polygons and polylines are triangulated with earclip
/earcut
when being exported as an STL, or when a polyline is converted into polygons using CSG::to_polygons(...)
.
CSG::square(width: Real, length: Real, metadata: Option<S>)
CSG::circle(radius: Real, segments: usize, metadata: Option<S>)
CSG::polygon(&[[x1,y1],[x2,y2],...], metadata: Option<S>)
CSG::rounded_rectangle(width: Real, height: Real, corner_radius: Real, corner_segments: usize, metadata: Option<S>)
CSG::ellipse(width: Real, height: Real, segments: usize, metadata: Option<S>)
CSG::regular_ngon(sides: usize, radius: Real, metadata: Option<S>)
CSG::right_triangle(width: Real, height: Real, metadata: Option<S>)
CSG::trapezoid(top_width: Real, bottom_width: Real, height: Real, top_offset: Real, metadata: Option<S>)
CSG::star(num_points: usize, outer_radius: Real, inner_radius: Real, metadata: Option<S>)
CSG::teardrop(width: Real, height: Real, segments: usize, metadata: Option<S>)
CSG::egg_outline(width: Real, length: Real, segments: usize, metadata: Option<S>)
CSG::squircle(width: Real, height: Real, segments: usize, metadata: Option<S>)
CSG::keyhole(circle_radius: Real, handle_width: Real, handle_height: Real, segments: usize, metadata: Option<S>)
CSG::reuleaux_polygon(sides: usize, radius: Real, arc_segments_per_side: usize, metadata: Option<S>)
CSG::ring(id: Real, thickness: Real, segments: usize, metadata: Option<S>)
CSG::pie_slice(radius: Real, start_angle_deg: Real, end_angle_deg: Real, segments: usize, metadata: Option<S>)
CSG::metaball_2d(balls: &[(nalgebra::Point2<Real>, Real)], resolution: (usize, usize), iso_value: Real, padding: Real, metadata: Option<S>)
CSG::supershape(a: Real, b: Real, m: Real, n1: Real, n2: Real, n3: Real, segments: usize, metadata: Option<S>)
CSG::circle_with_keyway(radius: Real, segments: usize, key_width: Real, key_depth: Real, metadata: Option<S>)
CSG::circle_with_flat(radius: Real, segments: usize, flat_dist: Real, metadata: Option<S>)
CSG::circle_with_two_flats(radius: Real, segments: usize, flat_dist: Real, metadata: Option<S>)
CSG::from_polylines(polylines: &[Polyline], metadata: Option<S>)
— create a new CSG fromcavalier_contours
polylinesCSG::from_image(img: &GrayImage, threshold: u8, closepaths: bool, metadata: Option<S>)
- Builds a new CSG from the “on” pixels of a grayscale imageCSG::text(text: &str, font_data: &[u8], size: Real, metadata: Option<S>)
- generate 2D text geometry in the XY plane from TTF fonts viameshtext
let square = CSG::square(1.0, 1.0, None); // 1×1 at origin
let rect = CSG::square(2.0, 4.0, None);
let circle = CSG::circle(1.0, 32, None); // radius=1, 32 segments
let circle2 = CSG::circle(2.0, 64, None);
let font_data = include_bytes!("../fonts/MyFont.ttf");
let csg_text = CSG::text("Hello!", font_data, 20.0, None);
// Then extrude the text to make it 3D:
let text_3d = csg_text.extrude(1.0);
CSG::extrude(height: Real)
- Simple extrude in Z+CSG::extrude_vector(direction: Vector3)
- Extrude along Vector3 directionCSG::linear_extrude(direction: Vector3, twist: Real, segments: usize, scale: Real)
- Extrude along Vector3 direction with twist, segments, and scaleCSG::extrude_between(&polygon_bottom.polygons[0], &polygon_top.polygons[0], false)
- Extrude Between Two PolygonsCSG::rotate_extrude(angle_degs, segments)
- Extrude while rotating around the Y axisCSG::sweep(shape_2d: &Polygon<S>, path_2d: &Polygon<S>)
- Extrude along a pathCSG::extrude_polyline(poly: &Polyline, direction: Vector3, metadata: Option<S>)
- Extrude a polyline to create a surface
let square = CSG::square(2.0, 2.0, None);
let prism = square.extrude(5.0);
let revolve_shape = square.rotate_extrude(360.0, 16);
let polygon_bottom = CSG::circle(2.0, 64, None);
let polygon_top = polygon_bottom.translate(0.0, 0.0, 5.0);
let lofted = CSG::extrude_between(&polygon_bottom.polygons[0], &polygon_top.polygons[0], false);
CSG::cube(width: Real, length: Real, height: Real, metadata: Option<S>)
CSG::sphere(radius: Real, segments: usize, stacks: usize, metadata: Option<S>)
CSG::cylinder(radius: Real, height: Real, segments: usize, metadata: Option<S>)
CSG::frustrum(radius1: Real, radius2: Real, height: Real, segments: usize, metadata: Option<S>)
- Construct a frustum at origin with height andradius1
andradius2
CSG::frustrum_ptp(start: Point3, end: Point3, radius1: Real, radius2: Real, segments: usize, metadata: Option<S>)
- Construct a frustum fromstart
toend
withradius1
andradius2
CSG::polyhedron(points: &[[Real; 3]], faces: &[Vec<usize>], metadata: Option<S>)
CSG::egg(width: Real, length: Real, revolve_segments: usize, outline_segments: usize, metadata: Option<S>)
CSG::teardrop(width: Real, height: Real, revolve_segments: usize, shape_segments: usize, metadata: Option<S>)
CSG::teardrop_cylinder(width: Real, length: Real, height: Real, shape_segments: usize, metadata: Option<S>)
CSG::ellipsoid(rx: Real, ry: Real, rz: Real, segments: usize, stacks: usize, metadata: Option<S>)
CSG::metaballs(balls: &[MetaBall], resolution: (usize, usize, usize), iso_value: Real, padding: Real, metadata: Option<S>)
CSG::sdf<F>(sdf: F, resolution: (usize, usize, usize), min_pt: Point3, max_pt: Point3, iso_value: Real, metadata: Option<S>)
- Return a CSG created by meshing a signed distance field within a bounding boxCSG::gyroid(resolution: usize, period: Real, iso_value: Real, metadata: Option<S>)
- Generate a Triply Periodic Minimal Surface (Gyroid) inside the volume ofself
// Unit cube at origin, no metadata
let cube = CSG::cube(1.0, 1.0, 1.0, None);
// Sphere of radius=2 at origin with 32 segments and 16 stacks
let sphere = CSG::sphere(2.0, 32, 16, None);
// Cylinder from radius=1, height=2, 16 segments, and no metadata
let cyl = CSG::cylinder(1.0, 2.0, 16, None);
// Create a custom polyhedron from points and face indices:
let points = &[
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.5, 0.5, 1.0],
];
let faces = vec![
vec![0, 1, 2, 3], // base rectangle
vec![0, 1, 4], // triangular side
vec![1, 2, 4],
vec![2, 3, 4],
vec![3, 0, 4],
];
let pyramid = CSG::polyhedron(points, &faces, None);
// Metaballs https://en.wikipedia.org/wiki/Metaballs
use csgrs::csg::MetaBall;
let balls = vec![
MetaBall::new(Point3::origin(), 1.0),
MetaBall::new(Point3::new(1.5, 0.0, 0.0), 1.0),
];
let resolution = (60, 60, 60);
let iso_value = 1.0;
let padding = 1.0;
let metaball_csg = CSG::from_metaballs(
&balls,
resolution,
iso_value,
padding,
None,
);
// Example Signed Distance Field for a sphere of radius 1.5 centered at (0,0,0)
let my_sdf = |p: &Point3<Real>| p.coords.norm() - 1.5;
let resolution = (60, 60, 60);
let min_pt = Point3::new(-2.0, -2.0, -2.0);
let max_pt = Point3::new( 2.0, 2.0, 2.0);
let iso_value = 0.0; // Typically zero for SDF-based surfaces
let csg_shape = CSG::from_sdf(my_sdf, resolution, min_pt, max_pt, iso_value, None);
let union_result = cube.union(&sphere);
let difference_result = cube.difference(&sphere);
let intersection_result = cylinder.intersection(&sphere);
They all return a new CSG<S>
CSG::translate(x: Real, y: Real, z: Real)
- Returns the CSG translated by x, y, and zCSG::translate_vector(vector: Vector3)
- Returns the CSG translated by vectorCSG::rotate(x_deg, y_deg, z_deg)
- Returns the CSG rotated in x, y, and zCSG::scale(scale_x, scale_y, scale_z)
- Returns the CSG scaled in x, y, and zCSG::mirror(plane: Plane)
- Returns the CSG mirrored across planeCSG::center()
- Returns the CSG centered at the originCSG::float()
- Returns the CSG translated so that its bottommost point(s) sit exactly at z=0CSG::transform(&Matrix4)
- Returns the CSG after applying arbitrary affine transformsCSG::distribute_arc(count: usize, radius: Real, start_angle_deg: Real, end_angle_deg: Real)
CSG::distribute_linear(count: usize, dir: nalgebra::Vector3, spacing: Real)
CSG::distribute_grid(rows: usize, cols: usize, dx: Real, dy: Real)
use nalgebra::Vector3;
use csgrs::plane::Plane;
let moved = cube.translate(3.0, 0.0, 0.0);
let moved2 = cube.translate_vector(Vector3::new(3.0, 0.0, 0.0));
let rotated = sphere.rotate(0.0, 45.0, 90.0);
let scaled = cylinder.scale(2.0, 1.0, 1.0);
let plane_x = Plane { normal: Vector3::x(), w: 0.0 }; // x=0 plane
let plane_y = Plane { normal: Vector3::y(), w: 0.0 }; // y=0 plane
let plane_z = Plane { normal: Vector3::z(), w: 0.0 }; // z=0 plane
let mirrored = cube.mirror(plane_x);
CSG::vertices()
— collect all vertices from the CSGCSG::inverse()
— flips the inside/outside orientation.CSG::convex_hull()
— useschull
to generate a 3D convex hull.CSG::minkowski_sum(&other)
— naive Minkowski sum, then takes the hull.CSG::ray_intersections(origin, direction)
— returns all intersection points and distances.CSG::flatten()
— flattens a 3D shape into 2D (on the XY plane), unions the outlines.CSG::slice(plane)
— slices the CSG by a plane and returns the cross-section polygons.CSG::offset_2d(distance)
— outward (or inward) offset in 2D usingcavalier_contours
.CSG::subdivide_triangles(subdivisions)
— subdivides each polygon’s triangles, increasing mesh density.CSG::renormalize()
— re-computes each polygon’s plane from its vertices, resetting all normals.CSG::reconstruct_polyline_3d(polylines: &[Polygon<S>])
— reconstructs a 3d polyline from 2d polylines with matching start/end pointsCSG::bounding_box()
— computes the bounding box of the shapeCSG::triangulate()
— triangulates all polygons returning a CSG containing trianglesCSG::triangulate_earclip()
— triangulates all polygons withearclip
returning a CSG containing trianglesCSG::from_polygons(polygons: &[Polygon<S>])
- create a new CSG from PolygonsCSG::from_earclip(polys: &[Vec<Vec<Real>>], metadata: Option<S>)
— create a new CSG fromearclip
polysCSG::from_earcut(polys: &[Vec<Vec<Real>>], metadata: Option<S>)
- create a new CSG fromearcut
polys
- Export ASCII STL:
csg.to_stl_ascii("solid_name") -> String
- Export Binary STL:
csg.to_stl_binary("solid_name") -> io::Result<Vec<u8>>
- Import STL:
CSG::from_stl(&stl_data) -> io::Result<CSG<S>>
// Save to ASCII STL
let stl_text = csg_union.to_stl_ascii("union_solid");
std::fs::write("union_ascii.stl", stl_text).unwrap();
// Save to binary STL
let stl_bytes = csg_union.to_stl_binary("union_solid").unwrap();
std::fs::write("union_bin.stl", stl_bytes).unwrap();
// Load from an STL file on disk
let file_data = std::fs::read("some_file.stl")?;
let imported_csg = CSG::from_stl(&file_data)?;
- Export:
csg.to_dxf() -> Result<Vec<u8>, Box<dyn Error>>
- Import:
CSG::from_dxf(&dxf_data) -> Result<CSG<S>, Box<dyn Error>>
// Export DXF
let dxf_bytes = csg_obj.to_dxf()?;
std::fs::write("output.dxf", dxf_bytes)?;
// Import DXF
let dxf_data = std::fs::read("some_file.dxf")?;
let csg_dxf = CSG::from_dxf(&dxf_data)?;
Hershey fonts are single stroke fonts which produce open ended polylines in the XY plane via hershey
:
let font_data = include_bytes("../fonts/myfont.jhf");
let csg_text = CSG::from_hershey("Hello!", font_data, 20.0, None);
// Then extrude the text to make it 3D:
let mut text_3d = CSG::new();
for polygon in csg_text.polygons {
text_3d.union(&CSG::extrude_polyline(polygon.to_polyline(), Vector3::z(), None));
}
csg.to_trimesh()
returns a SharedShape
containing a TriMesh<Real>
.
use csgrs::csg::CSG;
use csgrs::float_types::rapier3d::prelude::*; // re-exported for f32/f64 support
let trimesh_shape = csg_obj.to_trimesh(); // SharedShape with a TriMesh
csg.to_rigid_body(rb_set, co_set, translation, rotation, density)
helps build and insert both a rigid body and a collider:
use nalgebra::Vector3;
use csgrs::float_types::rapier3d::prelude::*; // re-exported for f32/f64 support
use csgrs::float_types::FRAC_PI_2;
use csgrs::csg::CSG;
let mut rb_set = RigidBodySet::new();
let mut co_set = ColliderSet::new();
let axis_angle = Vector3::z() * FRAC_PI_2; // 90° around Z
let rb_handle = csg_obj.to_rigid_body(
&mut rb_set,
&mut co_set,
Vector3::new(0.0, 0.0, 0.0), // translation
axis_angle, // axis-angle
1.0, // density
);
let density = 1.0;
let (mass, com, inertia_frame) = csg_obj.mass_properties(density);
println!("Mass: {}", mass);
println!("Center of Mass: {:?}", com);
println!("Inertia local frame: {:?}", inertia_frame);
csg.is_manifold()
triangulates the CSG, builds a HashMap of all edges (pairs of vertices), and checks that each is used exactly twice. Returns true
if manifold, false
if not.
if (csg_obj.is_manifold()){
println!("CSG is manifold!");
} else {
println!("Not manifold.");
}
Although CSG typically focuses on three‐dimensional Boolean operations, this library also provides a robust 2D subsystem built on top of cavalier_contours. Each Polygon<S>
in 3D can be projected into 2D (its own local XY plane) for 2D boolean operations such as union, difference, intersection, and xor. These are especially handy if you’re offsetting shapes, working with complex polygons, or just want 2D output.
Polygon::translate(x: Real, y: Real, z: Real)
- Returns a new Polygon translated by x, y, and zPolygon::translate_vector(vector: Vector3)
- Returns a new Polygon translated by vectorPolygon::transform(&Matrix4)
for arbitrary affine transformsPolygon::flip()
- Reverses winding order, flips vertices normals, and flips the plane normal, i.e. flips the polygon
Polygon::subdivide_triangles()
- Subdivide this polygon into smaller trianglesPolygon::calculate_new_normal()
- return a normal calculated from all polygon verticesPolygon::set_new_normal()
- recalculate and set polygon normalPolygon::triangulate()
- Triangulate this polygon into a list of triangles, each triangle is [v0, v1, v2]Polygon::check_coordinates_finite()
- Returns an error if any coordinate is not finite (NaN or ±∞)Polygon::check_repeated_points()
- Check for repeated adjacent points. Return the first repeated coordinate if foundPolygon::check_ring_closed()
- Check ring closure: first and last vertex must coincide if polygon is meant to be closedPolygon::check_minimum_ring_size()
- Check that the ring has at least 3 distinct pointsPolygon::check_ring_self_intersection()
- Very basic ring self‐intersection check by naive line–line intersection
The polyline_area
function computes the signed area of a closed Polyline
:
- Positive if the points are in counterclockwise (CCW) order.
- Negative if the points are in clockwise (CW) order.
- Near‐zero for degenerate or collinear loops.
CSG<S>
is generic over S: Clone
. Each polygon has an optional metadata: Option<S>
.
Use cases include storing color, ID, or layer info.
use csgrs::polygon::Polygon;
use csgrs::vertex::Vertex;
use nalgebra::{Point3, Vector3};
#[derive(Clone)]
struct MyMetadata {
color: (u8, u8, u8),
label: String,
}
type CSG = csgrs::CSG<MyMetadata>;
// For a single polygon:
let mut poly = Polygon::new(
vec![
Vertex::new(Point3::origin(), Vector3::z()),
Vertex::new(Point3::new(1.0, 0.0, 0.0), Vector3::z()),
Vertex::new(Point3::new(0.0, 1.0, 0.0), Vector3::z()),
],
Some(MyMetadata {
color: (255, 0, 0),
label: "Triangle".into(),
}),
);
// Retrieve metadata
if let Some(data) = poly.metadata() {
println!("This polygon is labeled {}", data.label);
}
// Mutate metadata
if let Some(data_mut) = poly.metadata_mut() {
data_mut.label.push_str("_extended");
}
- transition all extrudes over to CCShape native / polygon secondary, disengage chulls
- transition text to CCShape, which can then be extruded / tessellated through the normal means
- check flatten() works on polygons and flattens to polylines, same for slice
- fix shape of reuleaux
- fix metaballs_2d
- fix intersect_cube_sphere, subtract_cube_sphere
- make improved use of the bounding box index in CCShape to speed operations
- fix up error handling with result types
- ray intersection (singular)
- expose cavalier_contour Polyline traits on 2D shapes
- https://www.nalgebra.org/docs/user_guide/projections/ for 2d and 3d
- convert more for loops to iterators - csg::transform
- polygons_by_metadata public function of a CSG
- draft implementation done, pending API discussion
- document coordinate system / coordinate transformations / compounded transformations
- determine why flattened_cube.stl produces invalid output with to_stl_binary but not to_stl_ascii
- determine why square_2d_shrink.stl produces invalid output with to_stl_binary but not to_stl_ascii
- determine why square_2d produces invalid output with to_stl_binary but not to_stl_ascii
- 2d functionality tests
- bending
- gears
- lead-ins, lead-outs
- gpu accelleration?
- reduce dependency feature sets
- space filling curves, hilbert sort polygons / points
- identify more candidates for par_iter: minkowski, polygon_from_slice, is_manifold
- svg import/export
- http://www.ofitselfso.com/MiscNotes/CAMBamStickFonts.php
- screw threads
- attachment points / rapier integration
- implement 2d offsetting with these for testing against cavalier_contours
- support scale and translation along a vector in rotate extrude
- reimplement 3D offsetting with voxelcsgrs or https://docs.rs/parry3d/latest/parry3d/transformation/vhacd/struct.VHACD.html
- reimplement convex hull with https://docs.rs/parry3d-f64/latest/parry3d_f64/transformation/fn.convex_hull.html
- implement 2d/3d convex decomposition with https://docs.rs/parry3d-f64/latest/parry3d_f64/transformation/vhacd/struct.VHACD.html
- reimplement transformations and shapes with https://docs.rs/parry3d/latest/parry3d/transformation/utils/index.html
- std::io::Cursor, std::error::Error - core2 no_std transition
- identify opportunities to use parry2d_f64 and parry3d_f64 modules and functions to simplify and enhance our own
MIT License
Copyright (c) 2025 Timothy Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This library initially based on a translation of CSG.js © 2011 Evan Wallace, under the MIT license.
If you find issues, please file an issue or submit a pull request. Feedback and contributions are welcome!
Have fun building geometry in Rust!