forked from fogleman/demsphere
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stl.go
61 lines (52 loc) · 1.18 KB
/
stl.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
package demsphere
import (
"bufio"
"encoding/binary"
"io"
"os"
)
func WriteSTLFile(path string, triangles []Triangle) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
defer w.Flush()
return WriteSTL(w, triangles)
}
func WriteSTL(w io.Writer, triangles []Triangle) error {
type STLHeader struct {
_ [80]uint8
Count uint32
}
type STLTriangle struct {
N, V1, V2, V3 [3]float32
_ uint16
}
header := STLHeader{}
header.Count = uint32(len(triangles))
if err := binary.Write(w, binary.LittleEndian, &header); err != nil {
return err
}
for _, triangle := range triangles {
n := triangle.Normal()
d := STLTriangle{}
d.N[0] = float32(n.X)
d.N[1] = float32(n.Y)
d.N[2] = float32(n.Z)
d.V1[0] = float32(triangle.A.X)
d.V1[1] = float32(triangle.A.Y)
d.V1[2] = float32(triangle.A.Z)
d.V2[0] = float32(triangle.B.X)
d.V2[1] = float32(triangle.B.Y)
d.V2[2] = float32(triangle.B.Z)
d.V3[0] = float32(triangle.C.X)
d.V3[1] = float32(triangle.C.Y)
d.V3[2] = float32(triangle.C.Z)
if err := binary.Write(w, binary.LittleEndian, &d); err != nil {
return err
}
}
return nil
}