csgrs

Struct CSG

Source
pub struct CSG<S: Clone> {
    pub polygons: Vec<Polygon<S>>,
}
Expand description

The main CSG solid structure. Contains a list of polygons.

Fields§

§polygons: Vec<Polygon<S>>

Implementations§

Source§

impl<S: Clone> CSG<S>

Source

pub fn new() -> Self

Create an empty CSG

Source

pub fn from_polygons(polygons: Vec<Polygon<S>>) -> Self

Build a CSG from an existing polygon list

Source

pub fn to_polygons(&self) -> &[Polygon<S>]

Return the internal polygons

Source

pub fn union(&self, other: &CSG<S>) -> CSG<S>

CSG union: this ∪ other

Source

pub fn subtract(&self, other: &CSG<S>) -> CSG<S>

CSG subtract: this \ other

Source

pub fn intersect(&self, other: &CSG<S>) -> CSG<S>

CSG intersect: this ∩ other

Source

pub fn inverse(&self) -> CSG<S>

Invert this CSG (flip inside vs. outside)

Source

pub fn cube(options: Option<(&[f64; 3], &[f64; 3])>) -> CSG<S>

Construct an axis-aligned cube, with optional center and radius

Source

pub fn sphere(options: Option<(&[f64; 3], f64, usize, usize)>) -> CSG<S>

Construct a sphere with optional center, radius, slices, stacks

Source

pub fn cylinder(options: Option<(&[f64; 3], &[f64; 3], f64, usize)>) -> CSG<S>

Construct a cylinder with optional start, end, radius, slices

Source

pub fn polyhedron(points: &[[f64; 3]], faces: &[Vec<usize>]) -> CSG<S>

Creates a CSG polyhedron from raw vertex data (points) and face indices.

§Parameters
  • points: a slice of [x,y,z] coordinates.
  • faces: each element is a list of indices into points, describing one face. Each face must have at least 3 indices.
§Example
let pts = &[
    [0.0, 0.0, 0.0], // point0
    [1.0, 0.0, 0.0], // point1
    [1.0, 1.0, 0.0], // point2
    [0.0, 1.0, 0.0], // point3
    [0.5, 0.5, 1.0], // point4 - top
];

// Two faces: bottom square [0,1,2,3], and a pyramid side [0,1,4]
let fcs = vec![
    vec![0, 1, 2, 3],
    vec![0, 1, 4],
    vec![1, 2, 4],
    vec![2, 3, 4],
    vec![3, 0, 4],
];

let csg_poly = CSG::polyhedron(pts, &fcs);
Source

pub fn transform(&self, mat: &Matrix4<f64>) -> CSG<S>

Transform all vertices in this CSG by a given 4×4 matrix.

Source

pub fn translate(&self, v: Vector3<f64>) -> CSG<S>

Source

pub fn rotate(&self, x_deg: f64, y_deg: f64, z_deg: f64) -> CSG<S>

Source

pub fn scale(&self, sx: f64, sy: f64, sz: f64) -> CSG<S>

Source

pub fn mirror(&self, axis: Axis) -> CSG<S>

Mirror across X=0, Y=0, or Z=0 plane

Source

pub fn convex_hull(&self) -> CSG<S>

Compute the convex hull of all vertices in this CSG.

Source

pub fn minkowski_sum(&self, other: &CSG<S>) -> CSG<S>

Compute the Minkowski sum: self ⊕ other

Naive approach: Take every vertex in self, add it to every vertex in other, then compute the convex hull of all resulting points.

Source

pub fn subdivide_triangles(&self, levels: u32) -> CSG<S>

Subdivide all polygons in this CSG ‘levels’ times, returning a new CSG. This results in a triangular mesh with more detail.

Source

pub fn renormalize(&mut self)

Renormalize all polygons in this CSG by re-computing each polygon’s plane and assigning that plane’s normal to all vertices.

Source

pub fn ray_intersections( &self, origin: &Point3<f64>, direction: &Vector3<f64>, ) -> Vec<(Point3<f64>, f64)>

Casts a ray defined by origin + t * direction against all triangles of this CSG and returns a list of (intersection_point, distance), sorted by ascending distance.

§Parameters
  • origin: The ray’s start point.
  • direction: The ray’s direction vector.
§Returns

A Vec of (Point3<f64>, f64) where:

  • Point3<f64> is the intersection coordinate in 3D,
  • f64 is the distance (the ray parameter t) from origin.
Source

pub fn square(params: Option<([f64; 2], bool)>) -> CSG<S>

Creates a 2D square in the XY plane.

§Parameters
  • size: the width and height of the square (default [1.0, 1.0])
  • center: if true, center the square about (0,0); otherwise bottom-left is at (0,0).
§Example

let sq = CSG::square(None); // or with custom params: let sq2 = CSG::square(Some(([2.0, 3.0], true)));

Source

pub fn circle(params: Option<(f64, usize)>) -> CSG<S>

Creates a 2D circle in the XY plane.

Source

pub fn polygon_2d(points: &[[f64; 2]]) -> CSG<S>

Creates a 2D polygon in the XY plane from a list of [x, y] points.

§Parameters
  • points: a sequence of 2D points (e.g. [[0.0,0.0], [1.0,0.0], [0.5,1.0]]) describing the polygon boundary in order.

Note: This simple version ignores ‘paths’ and holes. For more complex polygons, we’ll have to handle multiple paths, winding order, holes, etc.

§Example

let pts = vec![[0.0, 0.0], [2.0, 0.0], [1.0, 1.5]]; let poly2d = CSG::polygon_2d(&pts);

Source

pub fn extrude(&self, height: f64) -> CSG<S>

Linearly extrude this (2D) shape in the +Z direction by height.

This is similar to OpenSCAD’s linear_extrude(height=...) assuming the base 2D shape is in the XY plane with a +Z normal.

  • If your shape is centered around Z=0, the resulting extrusion will go from Z=0 to Z=height.
  • The top polygons will be created at Z=height.
  • The bottom polygons remain at Z=0 (the original).
  • Side polygons will be formed around the perimeter.
Source

pub fn rotate_extrude(&self, angle_degs: f64, segments: usize) -> CSG<S>

Rotate-extrude (revolve) this 2D shape around the Z-axis from 0..angle_degs.

  • segments determines how many steps to sample around the axis.
  • For a full revolve, pass angle_degs = 360.0.

This is similar to OpenSCAD’s rotate_extrude(angle=..., segments=...).

Source

pub fn bounding_box(&self) -> Aabb

Returns a parry3d::bounding_volume::Aabb.

Source

pub fn vertices(&self) -> Vec<Vertex>

Helper to collect all vertices from the CSG.

Source

pub fn grow(&self, distance: f64) -> CSG<S>

Approximate growing (outward offset) of the shape by a given distance (3D). This method unions translated copies of the shape along a sphere.

Source

pub fn shrink(&self, distance: f64) -> CSG<S>

Approximate shrinking (inward offset) of the shape by a given distance (3D). This method unions translated copies of the complement of the shape along a sphere, then inverts the result.

Source

pub fn grow_2d(&self, distance: f64) -> CSG<S>

Approximate 2D growing (outward offset) of the shape by a given distance.

Source

pub fn shrink_2d(&self, distance: f64) -> CSG<S>

Approximate 2D shrinking (inward offset) of the shape by a given distance.

Source

pub fn text_mesh(text_str: &str, font_data: &[u8], size: Option<f64>) -> CSG<S>

Creates 2D text in the XY plane using the meshtext crate to generate glyph meshes.

  • text_str: the text to render
  • font_data: TTF font file bytes (e.g. include_bytes!("../assets/FiraMono-Regular.ttf"))
  • size: optional scaling factor (e.g., a rough “font size”).

Note: This is a basic example that:

  • does not handle kerning or multi-line text,
  • simply advances the cursor by each glyph’s width,
  • places all characters along the X axis.
Source

pub fn to_trimesh(&self) -> SharedShape

Convert the polygons in this CSG to a Parry TriMesh. Useful for collision detection or physics simulations.

Source

pub fn mass_properties( &self, density: f64, ) -> (f64, Point3<f64>, Unit<Quaternion<f64>>)

Approximate mass properties using Rapier.

Source

pub fn to_rigid_body( &self, rb_set: &mut RigidBodySet, co_set: &mut ColliderSet, translation: Vector3<f64>, rotation: Vector3<f64>, density: f64, ) -> RigidBodyHandle

Create a Rapier rigid body + collider from this CSG, using an axis-angle rotation in 3D (the vector’s length is the rotation in radians, and its direction is the axis).

Source

pub fn to_stl(&self, name: &str) -> String

Convert this CSG to an ASCII STL string with the given name.

let csg = CSG::cube(None);
let stl_text = csg.to_stl("my_solid");
println!("{}", stl_text);
Source

pub fn to_stl_file(&self, file_path: &str) -> Result<(), Error>

Export the CSG object to a binary STL file using stl_io.

Source

pub fn from_stl_file(file_path: &str) -> Result<CSG<S>, Error>

Import a CSG object from a binary STL file using stl_io.

Trait Implementations§

Source§

impl<S: Clone + Clone> Clone for CSG<S>

Source§

fn clone(&self) -> CSG<S>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S: Debug + Clone> Debug for CSG<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S> Freeze for CSG<S>

§

impl<S> RefUnwindSafe for CSG<S>
where S: RefUnwindSafe,

§

impl<S> Send for CSG<S>
where S: Send,

§

impl<S> Sync for CSG<S>
where S: Sync,

§

impl<S> Unpin for CSG<S>
where S: Unpin,

§

impl<S> UnwindSafe for CSG<S>
where S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.