/
images.go
66 lines (52 loc) · 1.33 KB
/
images.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
package sources
import (
"bytes"
"embed"
"fmt"
"image"
_ "image/png"
"path/filepath"
"regexp"
"sync"
"github.com/hajimehoshi/ebiten/v2"
"github.com/sirupsen/logrus"
)
type Images struct {
sync.Mutex
Collection map[string]*ebiten.Image
}
func (i *Images) loadFile(fs embed.FS, path string) {
if reg := regexp.MustCompile(`\.png*$`); reg.MatchString(path) {
file, err := fs.ReadFile(path)
if err != nil {
logrus.Fatal("error happened opening image file from embedded fs", err)
}
image, _, err := image.Decode(bytes.NewReader(file))
if err != nil {
logrus.Fatal("error happened decoding image file from embedded fs to ebiten image", err)
}
img := ebiten.NewImageFromImage(image)
i.Lock()
i.Collection[reg.Split(path, -1)[0]] = img
i.Unlock()
}
}
func (i *Images) Load(fs embed.FS, path string, s, wg *sync.WaitGroup) {
NewParser(fs, path, i.loadFile).Parse()
wg.Done()
s.Done()
}
func (i *Images) GetImage(path string) *ebiten.Image {
path = filepath.Join("dist/images", path)
image, ok := i.Collection[path]
if !ok {
logrus.Fatal(fmt.Sprintf("image with path '%s' not found", path))
}
return image
}
func (i *Images) GetCopyOfImage(path string) *ebiten.Image {
return ebiten.NewImageFromImage(i.GetImage(path))
}
func NewImages() *Images {
return &Images{Collection: make(map[string]*ebiten.Image)}
}