/
cache.go
89 lines (74 loc) · 2.19 KB
/
cache.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
package render
import (
"image"
"sync"
"github.com/golang/freetype/truetype"
"github.com/oakmound/oak/v4/alg/intgeom"
)
// DefaultCache is the receiver for package level sprites, sheets, and font loading operations.
var DefaultCache = NewCache()
// Cache is a simple image data cache
type Cache struct {
imageLock sync.RWMutex
loadedImages map[string]*image.RGBA
sheetLock sync.RWMutex
loadedSheets map[string]*Sheet
fontLock sync.RWMutex
loadedFonts map[string]*truetype.Font
}
// NewCache returns an empty Cache
func NewCache() *Cache {
return &Cache{
loadedImages: make(map[string]*image.RGBA),
loadedSheets: make(map[string]*Sheet),
loadedFonts: make(map[string]*truetype.Font),
}
}
// ClearAll will remove all elements from a Cache
func (c *Cache) ClearAll() {
c.imageLock.Lock()
c.sheetLock.Lock()
c.fontLock.Lock()
c.loadedImages = make(map[string]*image.RGBA)
c.loadedSheets = make(map[string]*Sheet)
c.loadedFonts = make(map[string]*truetype.Font)
c.fontLock.Unlock()
c.sheetLock.Unlock()
c.imageLock.Unlock()
}
// Clear will remove elements matching the given key from the Cache.
func (c *Cache) Clear(key string) {
c.imageLock.Lock()
c.sheetLock.Lock()
c.fontLock.Lock()
delete(c.loadedImages, key)
delete(c.loadedSheets, key)
delete(c.loadedFonts, key)
c.fontLock.Unlock()
c.sheetLock.Unlock()
c.imageLock.Unlock()
}
// GetSprite calls GetSprite on the Default Cache.
func GetSprite(file string) (*Sprite, error) {
return DefaultCache.GetSprite(file)
}
// LoadSprite calls LoadSprite on the Default Cache.
func LoadSprite(file string) (*Sprite, error) {
return DefaultCache.LoadSprite(file)
}
// GetSheet calls GetSheet on the Default Cache.
func GetSheet(file string) (*Sheet, error) {
return DefaultCache.GetSheet(file)
}
// LoadSheet calls LoadSheet on the Default Cache.
func LoadSheet(file string, cellSize intgeom.Point2) (*Sheet, error) {
return DefaultCache.LoadSheet(file, cellSize)
}
// GetFont calls GetFont on the Default Cache.
func GetFont(file string) (*truetype.Font, error) {
return DefaultCache.GetFont(file)
}
// LoadFont calls LoadFont on the Default Cache.
func LoadFont(file string) (*truetype.Font, error) {
return DefaultCache.LoadFont(file)
}