csg

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package csg is experimental: its API may change in a minor release; see https://nsgo.games/docs/stability/.

Package csg provides pure-Go constructive solid geometry (CSG) boolean operations (union, intersection, subtraction) on closed manifold triangle meshes, parametric blockout shape generators (box, sphere, cylinder, cone, capsule, torus, extruded/spun/path-swept polygons, and arbitrary meshes), render3d.Mesh output with normals, UVs, and per-face material IDs, physics3d.TriMeshCollider generation, and deterministic GLB export.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrComplexityLimit is returned when a CSG operation exceeds internal BSP
	// depth or polygon budgets, protecting callers from stack overflow or OOM.
	ErrComplexityLimit = errors.New("csg: complexity limit exceeded")
	// ErrInvalidInput is returned when a shape parameter or mesh input is invalid.
	ErrInvalidInput = errors.New("csg: invalid input")
)

Functions

func ColliderFromMesh

func ColliderFromMesh(m render3d.Mesh, worldTransform math3d.Mat4) *physics3d.TriMeshCollider

ColliderFromMesh builds a physics3d.TriMeshCollider from a render3d.Mesh transformed into world space by worldTransform. When worldTransform has a negative 3x3 determinant, triangle winding is reversed to preserve outward normals. Non-finite or degenerate triangles are skipped safely.

func EncodeGLB

func EncodeGLB(res Result, opts GLBOptions) ([]byte, error)

EncodeGLB encodes res into a deterministic binary glTF 2.0 (.glb) document with one primitive per distinct material ID, POSITION/NORMAL/TEXCOORD_0 attributes, and optional extras.collider metadata.

func ValidatePolygon

func ValidatePolygon(points []math3d.Vec2, mode PolygonMode) error

ValidatePolygon checks that points form an outline Polygon.Build accepts for mode: a simple polygon of 3 to 2048 finite points with non-zero area that does not cross or touch itself, and for PolygonSpin every point at X >= 0 with at least one at X > 0. It does not build the solid, so it does not check the parameters other than the outline. An error about one point is a *PolygonPointError naming it; every error wraps ErrInvalidInput, or ErrComplexityLimit for too many points.

Types

type GLBCollider

type GLBCollider struct {
	Enabled bool
	Tag     string
	Layer   uint32
	Mask    uint32
}

GLBCollider records optional extras.collider metadata on the baked GLB node so physics3d.BuildGLTFColliders recreates a TriMeshCollider after baking.

type GLBMaterial

type GLBMaterial struct {
	Name        string
	BaseColor   math3d.Vec4
	Metallic    float32
	Roughness   float32
	Emissive    math3d.Vec3
	DoubleSided bool
}

GLBMaterial describes one PBR metallic-roughness material written into a baked .glb by EncodeGLB.

type GLBOptions

type GLBOptions struct {
	// Name is the glTF node and mesh name (defaults to "csg").
	Name string
	// Materials maps each Result MaterialID (by slice index) to its PBR surface.
	// Missing entries default to white, non-metallic, roughness 1.
	Materials []GLBMaterial
	// Collider optionally attaches extras.collider metadata for a trimesh collider.
	Collider GLBCollider
}

GLBOptions configures EncodeGLB.

type Op

type Op int

Op identifies a boolean constructive-solid-geometry operation.

const (
	// OpUnion combines the volume of two solids (A ∪ B).
	OpUnion Op = iota
	// OpIntersection keeps only the volume shared by two solids (A ∩ B).
	OpIntersection
	// OpSubtract removes the volume of the second solid from the first (A \ B).
	OpSubtract
)

func ParseOp

func ParseOp(s string) (Op, error)

ParseOp parses a scene-file CSG operation name ("union", "intersection", "subtract").

func (Op) String

func (op Op) String() string

String returns the canonical scene-file spelling of op.

type PathRotation

type PathRotation int

PathRotation controls how a 2D polygon cross-section rotates along a Path.

const (
	// PathRotationPath aligns the cross-section with the curve's smooth
	// Rotation-Minimizing Frame (local +X -> Right, local +Y -> Up, sweep along Tangent).
	PathRotationPath PathRotation = iota
	// PathRotationPolygon keeps the cross-section in its fixed local XY
	// orientation while translating along the path.
	PathRotationPolygon
	// PathRotationPathFollow aligns the cross-section with the curve tangent
	// while keeping local +Y as close to world +Y as possible (ideal for roads).
	PathRotationPathFollow
)

func ParsePathRotation

func ParsePathRotation(s string) (PathRotation, error)

ParsePathRotation parses a scene-file polygon path rotation mode ("polygon", "path", "pathFollow"). An empty string defaults to PathRotationPath.

type Polygon

type Polygon struct {
	// Points are the 2D XY vertices of a simple closed polygon (at least 3 points).
	Points []math3d.Vec2
	// Mode selects Depth, Spin, or Path extrusion (default PolygonDepth).
	Mode PolygonMode
	// Depth is the extrusion distance along Z for PolygonDepth.
	Depth float32
	// SpinDegrees is the revolution angle in degrees for PolygonSpin, in (0, 360] (0 defaults to 360).
	SpinDegrees float32
	// SpinSides is the number of revolution steps for PolygonSpin (0 defaults to 16).
	SpinSides int
	// Path is the 3D curve for PolygonPath.
	Path math3d.Curve3D
	// Interval is the arc-length spacing between cross-sections for PolygonPath (<= 0 picks a default).
	Interval float32
	// Rotation controls cross-section orientation along Path (default PathRotationPath).
	Rotation PathRotation
	// Joined connects the last cross-section back to the first without end caps for PolygonPath.
	Joined bool
}

Polygon describes a 2D cross-section polygon extruded by depth, spun around Y, or swept along a 3D curve into a closed Solid.

func (Polygon) Build

func (p Polygon) Build() (*Solid, error)

Build constructs a closed Solid from p.

type PolygonMode

type PolygonMode int

PolygonMode selects how a 2D polygon is extruded into a 3D Solid.

const (
	// PolygonDepth extrudes the 2D polygon straight along Z from -Depth/2 to +Depth/2.
	PolygonDepth PolygonMode = iota
	// PolygonSpin revolves the 2D polygon around the Y axis by SpinDegrees in SpinSides steps.
	PolygonSpin
	// PolygonPath sweeps the 2D polygon along Path at Interval arc-length spacing.
	PolygonPath
)

func ParsePolygonMode

func ParsePolygonMode(s string) (PolygonMode, error)

ParsePolygonMode parses a scene-file polygon extrusion mode ("depth", "spin", "path"). An empty string defaults to PolygonDepth.

type PolygonPointError

type PolygonPointError struct {
	// Index is the point's index in Polygon.Points.
	Index int
	// Reason describes the broken rule.
	Reason string
}

PolygonPointError reports the outline point at Index that breaks a Polygon rule. It wraps ErrInvalidInput.

func (*PolygonPointError) Error

func (e *PolygonPointError) Error() string

Error returns the error's message.

func (*PolygonPointError) Unwrap

func (e *PolygonPointError) Unwrap() error

Unwrap returns ErrInvalidInput.

type Result

type Result struct {
	// Mesh is the combined indexed render3d.Mesh with Positions, Normals, UVs, and Indices.
	Mesh render3d.Mesh
	// MaterialIDs holds one material ID per triangle in Mesh (len(MaterialIDs) == len(Mesh.Indices)/3).
	MaterialIDs []int
}

Result holds the triangulated mesh and per-triangle material IDs produced by Solid.ToMesh.

func (Result) SubMeshes

func (r Result) SubMeshes() []SubMesh

SubMeshes partitions r into one SubMesh per distinct material ID, ordered by ascending MaterialID.

func (Result) Volume

func (r Result) Volume() float64

Volume returns the signed volume of r's mesh (positive for closed outward-wound meshes).

type Solid

type Solid struct {
	// contains filtered or unexported fields
}

Solid is an immutable closed 3D geometry built from polygons carrying normals, UVs, and per-face material IDs.

func Apply

func Apply(op Op, a, b *Solid) (*Solid, error)

Apply evaluates the boolean operation op on solids a and b.

func Box

func Box(size math3d.Vec3) (*Solid, error)

Box returns an axis-aligned box centered at the origin with dimensions size.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/math3d"
	"github.com/nsgo-dev/game/pkg/world3d/csg"
)

func main() {
	outer, err := csg.Box(math3d.Vec3{X: 4, Y: 4, Z: 4})
	if err != nil {
		panic(err)
	}
	cut, err := csg.Box(math3d.Vec3{X: 2, Y: 2, Z: 6})
	if err != nil {
		panic(err)
	}
	result, err := outer.Subtract(cut.WithMaterial(1))
	if err != nil {
		panic(err)
	}
	mesh := result.ToMesh()
	fmt.Printf("volume=%.0f materials=%d\n", mesh.Volume(), len(mesh.SubMeshes()))
}
Output:
volume=48 materials=2

func Capsule

func Capsule(radius, height float32, segments, rings int) (*Solid, error)

Capsule returns a vertical capsule centered at the origin along Y with the given radius and total height. When height <= 2*radius, it degenerates cleanly to a sphere of the given radius.

func Cone

func Cone(radius, height float32, segments int) (*Solid, error)

Cone returns a vertical cone centered at the origin along Y, apex at +height/2 and base at -height/2. Non-positive segments uses the default (24).

func Cylinder

func Cylinder(radius, height float32, segments int) (*Solid, error)

Cylinder returns a vertical cylinder centered at the origin along Y with flat caps. Non-positive segments uses the default (24).

func CylinderCone

func CylinderCone(bottomRadius, topRadius, height float32, segments int) (*Solid, error)

CylinderCone returns a vertical tapered cylinder, frustum, or cone centered at the origin along Y, with bottomRadius at -height/2 and topRadius at +height/2. At least one radius must be positive; both must be finite and non-negative.

func Empty

func Empty() *Solid

Empty returns an empty Solid containing no faces.

func FromMesh

func FromMesh(m render3d.Mesh, matID int) (*Solid, error)

FromMesh builds a Solid from an arbitrary render3d.Mesh, assigning matID to all triangles. Degenerate zero-area triangles are skipped; missing normals are computed from triangle winding and missing UVs default to planar projections.

func Sphere

func Sphere(radius float32, segments, rings int) (*Solid, error)

Sphere returns a UV sphere centered at the origin with the given radius. Non-positive segments or rings use defaults (24 and 12).

func Torus

func Torus(majorRadius, minorRadius float32, majorSegments, minorSegments int) (*Solid, error)

Torus returns a torus centered at the origin lying in the XZ plane around the Y axis, with majorRadius (distance from center to tube center) and minorRadius (tube radius). Requires 0 < minorRadius < majorRadius.

func (*Solid) Clone

func (s *Solid) Clone() *Solid

Clone returns a deep copy of s.

func (*Solid) Collider

func (s *Solid) Collider() *physics3d.TriMeshCollider

Collider builds a static physics3d.TriMeshCollider from s's triangulated mesh.

func (*Solid) Intersect

func (s *Solid) Intersect(other *Solid) (*Solid, error)

Intersect returns a new Solid representing s ∩ other.

func (*Solid) IsEmpty

func (s *Solid) IsEmpty() bool

IsEmpty reports whether s contains no geometry.

func (*Solid) Subtract

func (s *Solid) Subtract(other *Solid) (*Solid, error)

Subtract returns a new Solid representing s \ other.

func (*Solid) ToMesh

func (s *Solid) ToMesh() Result

ToMesh triangulates s, heals T-junctions for watertight boundaries, and returns a deterministic Result with valid finite Positions, Normals, UVs, Indices, and per-triangle MaterialIDs.

func (*Solid) Transform

func (s *Solid) Transform(m math3d.Mat4) *Solid

Transform returns a copy of s transformed by the 4x4 affine matrix m. Normals are transformed by the cofactor matrix of m's upper 3x3 block and re-normalized; if m has a negative 3x3 determinant (mirroring), face winding is reversed so outward normals are preserved.

func (*Solid) Union

func (s *Solid) Union(other *Solid) (*Solid, error)

Union returns a new Solid representing a ∪ b.

func (*Solid) Volume

func (s *Solid) Volume() float64

Volume returns the signed volume of s (positive for closed outward-wound solids).

func (*Solid) WithMaterial

func (s *Solid) WithMaterial(matID int) *Solid

WithMaterial returns a copy of s with every face assigned material ID matID.

type SubMesh

type SubMesh struct {
	MaterialID int
	Mesh       render3d.Mesh
}

SubMesh is the slice of a Result belonging to a single material ID.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL