forked from dskinner/htm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
130 lines (112 loc) · 2.48 KB
/
image.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package htm
import (
"errors"
"fmt"
"image"
"image/draw"
"image/png"
"math"
"os"
"sort"
"azul3d.org/lmath.v1"
)
// max returns largest value contained in vertices.
func max(h *HTM) float64 {
var n float64
for _, v0 := range h.Vertices {
if n < v0.X {
n = v0.X
}
if n < v0.Y {
n = v0.Y
}
if n < v0.Z {
n = v0.Z
}
}
return n
}
// min returns smallest value contained in vertices.
func min(h *HTM) float64 {
var n float64
for _, v0 := range h.Vertices {
if n > v0.X {
n = v0.X
}
if n > v0.Y {
n = v0.Y
}
if n > v0.Z {
n = v0.Z
}
}
return n
}
func maxAbs(h *HTM) float64 {
a, b := math.Abs(min(h)), max(h)
if a > b {
return a
}
return b
}
func norm(x float64, max float64) float64 {
return (x + max) / (max * 2)
}
type vec3Slice []lmath.Vec3
func (p vec3Slice) Len() int { return len(p) }
func (p vec3Slice) Less(i, j int) bool { return p[i].Z < p[j].Z }
func (p vec3Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// sortVec3s sorts by Z back to front.
func sortVec3s(p vec3Slice) { sort.Sort(p) }
type ColorSet func(m *image.RGBA, x, y int, z float64)
func Image(h *HTM, size image.Point, cset ColorSet) *image.RGBA {
r := image.Rect(0, 0, size.X, size.Y)
m := image.NewRGBA(r)
max := maxAbs(h)
p := append([]lmath.Vec3(nil), h.VerticesNotEmpty()...)
sortVec3s(p)
for _, v0 := range p {
x := int(norm(v0.X, max) * float64(size.X))
y := int(norm(v0.Y, max) * float64(size.Y))
z := norm(v0.Z, max)
cset(m, x, y, z)
}
return m
}
func ImageConstraint(h *HTM, cn Tester, size image.Point, cset ColorSet) *image.RGBA {
r := image.Rect(0, 0, size.X, size.Y)
m := image.NewRGBA(r)
max := maxAbs(h)
var p []lmath.Vec3
for idx := range Iter(h, h.Intersections(cn)...) {
v0, v1, v2 := h.VerticesAt(idx)
p = append(p, v0, v1, v2)
}
sortVec3s(p)
for _, v0 := range p {
x := int(norm(v0.X, max) * float64(size.X))
y := int(norm(v0.Y, max) * float64(size.Y))
z := norm(v0.Z, max)
cset(m, x, y, z)
}
return m
}
func MergeImages(dst *image.RGBA, srcs ...*image.RGBA) {
for _, src := range srcs {
draw.Draw(dst, src.Bounds(), src, image.ZP, draw.Over)
}
}
func WriteImage(fn string, m *image.RGBA) error {
if m == nil {
return errors.New("received nil image")
}
out, err := os.Create(fn)
if err != nil {
return fmt.Errorf("Failed to create new file %s: %s", fn, err)
}
defer out.Close()
if err := png.Encode(out, m); err != nil {
return fmt.Errorf("Failed to encode %s: %s", fn, err)
}
return nil
}