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 ¶
- Variables
- func ColliderFromMesh(m render3d.Mesh, worldTransform math3d.Mat4) *physics3d.TriMeshCollider
- func EncodeGLB(res Result, opts GLBOptions) ([]byte, error)
- func ValidatePolygon(points []math3d.Vec2, mode PolygonMode) error
- type GLBCollider
- type GLBMaterial
- type GLBOptions
- type Op
- type PathRotation
- type Polygon
- type PolygonMode
- type PolygonPointError
- type Result
- type Solid
- func Apply(op Op, a, b *Solid) (*Solid, error)
- func Box(size math3d.Vec3) (*Solid, error)
- func Capsule(radius, height float32, segments, rings int) (*Solid, error)
- func Cone(radius, height float32, segments int) (*Solid, error)
- func Cylinder(radius, height float32, segments int) (*Solid, error)
- func CylinderCone(bottomRadius, topRadius, height float32, segments int) (*Solid, error)
- func Empty() *Solid
- func FromMesh(m render3d.Mesh, matID int) (*Solid, error)
- func Sphere(radius float32, segments, rings int) (*Solid, error)
- func Torus(majorRadius, minorRadius float32, majorSegments, minorSegments int) (*Solid, error)
- func (s *Solid) Clone() *Solid
- func (s *Solid) Collider() *physics3d.TriMeshCollider
- func (s *Solid) Intersect(other *Solid) (*Solid, error)
- func (s *Solid) IsEmpty() bool
- func (s *Solid) Subtract(other *Solid) (*Solid, error)
- func (s *Solid) ToMesh() Result
- func (s *Solid) Transform(m math3d.Mat4) *Solid
- func (s *Solid) Union(other *Solid) (*Solid, error)
- func (s *Solid) Volume() float64
- func (s *Solid) WithMaterial(matID int) *Solid
- type SubMesh
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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.
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.
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.
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 Box ¶
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 ¶
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 ¶
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 ¶
Cylinder returns a vertical cylinder centered at the origin along Y with flat caps. Non-positive segments uses the default (24).
func CylinderCone ¶
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 FromMesh ¶
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 ¶
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 ¶
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) Collider ¶
func (s *Solid) Collider() *physics3d.TriMeshCollider
Collider builds a static physics3d.TriMeshCollider from s's triangulated mesh.
func (*Solid) ToMesh ¶
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 ¶
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) Volume ¶
Volume returns the signed volume of s (positive for closed outward-wound solids).
func (*Solid) WithMaterial ¶
WithMaterial returns a copy of s with every face assigned material ID matID.