-
Notifications
You must be signed in to change notification settings - Fork 4
/
texture.go
103 lines (88 loc) · 1.93 KB
/
texture.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
package main
import (
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"os"
)
type TextureType int
const (
TextureTypeSolidColor TextureType = iota
TextureTypeImage
TextureTypeImageFast
)
type Texture struct {
width, height int
widthF, heightF float32
scale float32
color color.RGBA
pixels []color.RGBA
typ TextureType
}
func NewColorTexture(c color.RGBA) *Texture {
return &Texture{
typ: TextureTypeSolidColor,
color: c,
}
}
func NewImageTexture(img image.Image) (*Texture, error) {
bounds := img.Bounds()
width := bounds.Dx()
height := bounds.Dy()
typ := TextureTypeImage
if isPowerOfTwo(width) && isPowerOfTwo(height) {
typ = TextureTypeImageFast
}
t := &Texture{
width: width,
height: height,
widthF: float32(width),
heightF: float32(height),
pixels: make([]color.RGBA, bounds.Dx()*bounds.Dy()),
typ: typ,
scale: 1.0,
}
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
c := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA)
t.pixels[y*width+x] = c
}
}
return t, nil
}
func (t *Texture) SetScale(scale float32) {
t.scale = scale
}
func (t *Texture) Sample(u, v float32) color.RGBA {
switch t.typ {
case TextureTypeSolidColor:
return t.color
case TextureTypeImageFast:
// Fast path for mod operation with power of two sizes
x := int((1-u)*t.scale*t.widthF) & (t.width - 1)
y := int(v*t.scale*t.heightF) & (t.height - 1)
return t.pixels[y*t.width+x]
case TextureTypeImage:
x := int((1-u)*t.scale*t.widthF) % t.width
y := int(v*t.scale*t.heightF) % t.height
idx := y*t.width + x
if idx < 0 {
idx = 0
}
return t.pixels[idx]
default:
return color.RGBA{255, 0, 255, 255}
}
}
func LoadTextureFile(filename string) (*Texture, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return NewImageTexture(img)
}