forked from quasilyte/ge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_cache.go
51 lines (41 loc) · 1.12 KB
/
image_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
package ge
import (
"image"
"github.com/hajimehoshi/ebiten/v2"
)
type imageCacheKey struct {
imageWidth int
imageHeight int
}
type imageCache struct {
m map[imageCacheKey]*ebiten.Image
tmp unsafeImage
}
func (cache *imageCache) UnsafeSubImage(i *ebiten.Image, bounds image.Rectangle) *ebiten.Image {
// Basically, we're doing this:
// > subImage = i.SubImage(bounds)
// But without redundant allocation.
unsafeImg := toUnsafeImage(i)
unsafeSubImage := cache.UnsafeImageForSubImage()
unsafeSubImage.original = unsafeImg
unsafeSubImage.bounds = bounds
unsafeSubImage.image = unsafeImg.image
return toEbitenImage(unsafeSubImage)
}
func (cache *imageCache) UnsafeImageForSubImage() *unsafeImage {
return &cache.tmp
}
func (cache *imageCache) Init() {
cache.m = make(map[imageCacheKey]*ebiten.Image)
cache.tmp.addr = &cache.tmp
}
func (cache *imageCache) NewTempImage(width, height int) *ebiten.Image {
key := imageCacheKey{imageWidth: width, imageHeight: height}
if cachedImage, ok := cache.m[key]; ok {
cachedImage.Clear()
return cachedImage
}
img := ebiten.NewImage(width, height)
cache.m[key] = img
return img
}