-
Notifications
You must be signed in to change notification settings - Fork 4
/
objloader.go
70 lines (66 loc) · 1.31 KB
/
objloader.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
package primitive
import (
"bufio"
"bytes"
"fmt"
"strconv"
"strings"
)
// LoadOBJ will load and OBJ and return vertices and deduplicated edges.
func LoadOBJ(b []byte) (verts P3Ds, edges [][2]int) {
scanner := bufio.NewScanner(bytes.NewBuffer(b))
known := make(map[uint64]struct{})
addLine := func(a, b uint64) {
if a == b {
return
}
if b < a {
a, b = b, a
}
v := a | (b << 32)
if _, ok := known[v]; ok {
return
}
known[v] = struct{}{}
edges = append(edges, [2]int{int(a), int(b)})
}
for scanner.Scan() {
t := scanner.Text()
if strings.HasPrefix(t, "v ") {
var c Point3D
n, err := fmt.Sscanf(t, "v %f %f %f", &c.X, &c.Y, &c.Z)
if err != nil {
panic(err)
}
if n != 3 {
panic("not 3")
}
verts = append(verts, c)
continue
}
if strings.HasPrefix(t, "f ") {
t := strings.TrimPrefix(t, "f ")
faces := strings.Fields(t)
indices := make([]uint64, len(faces))
for i, v := range faces {
s, err := strconv.ParseUint(v, 10, 32)
if err != nil {
panic(err)
}
if s == 0 {
panic("index 0 face found, should start with 1")
}
indices[i] = s - 1
}
for i, v := range indices {
if i == 0 {
// add first to last
addLine(v, indices[len(indices)-1])
continue
}
addLine(v, indices[i-1])
}
}
}
return
}