-
Notifications
You must be signed in to change notification settings - Fork 0
/
solid.go
108 lines (102 loc) · 2.79 KB
/
solid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package csg
// Solid holds a binary space partition tree representing a 3D solid.
// Two solids can be combined using the `Union()`, `Subtract()` and
// `Intersect()` methods.
type Solid struct {
Polygons Polygons
}
// SolidFromPolygons constructs a CSG solid from a list of `csg.Polygon`
// instances.
func SolidFromPolygons(polygons Polygons) *Solid {
return &Solid{Polygons: polygons}
}
// Union returns a new CSG solid representing space in either this solid or
// in the solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.Union(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +----+
// +----+--+ | +----+ |
// | B | | |
// | | | |
// +-------+ +-------+
//
func (s *Solid) Union(other *Solid) *Solid {
a, b := &BSP{}, &BSP{}
a.AddPolygons(s.Polygons.Clone())
b.AddPolygons(other.Polygons.Clone())
a.ClipTo(b)
b.ClipTo(a)
b.Invert()
b.ClipTo(a)
b.Invert()
a.AddPolygons(b.AllPolygons())
return SolidFromPolygons(a.AllPolygons())
}
// Subtract returns a new CSG solid representing space in this solid but not
// in the solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.Subtract(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +--+
// +----+--+ | +----+
// | B |
// | |
// +-------+
//
func (s *Solid) Subtract(other *Solid) *Solid {
a, b := &BSP{}, &BSP{}
a.AddPolygons(s.Polygons.Clone())
b.AddPolygons(other.Polygons.Clone())
a.Invert()
a.ClipTo(b)
b.ClipTo(a)
b.Invert()
b.ClipTo(a)
b.Invert()
a.AddPolygons(b.AllPolygons())
a.Invert()
return SolidFromPolygons(a.AllPolygons())
}
// Intersect returns a new CSG solid representing space both this solid and in
// the solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.intersect(B)
//
// +-------+
// | |
// | A |
// | +--+----+ = +--+
// +----+--+ | +--+
// | B |
// | |
// +-------+
//
func (s *Solid) Intersect(other *Solid) *Solid {
a, b := &BSP{}, &BSP{}
a.AddPolygons(s.Polygons.Clone())
b.AddPolygons(other.Polygons.Clone())
a.Invert()
b.ClipTo(a)
b.Invert()
a.ClipTo(b)
b.ClipTo(a)
a.AddPolygons(b.AllPolygons())
a.Invert()
return SolidFromPolygons(a.AllPolygons())
}
// Inverse returns a new CSG solid with solid and empty space switched.
// This solid is not modified.
func (s *Solid) Inverse() *Solid {
polygons := s.Polygons.Clone()
for i := range polygons {
polygons[i].Flip()
}
return SolidFromPolygons(polygons)
}