Lazy loading with ref

This commit is contained in:
Josh Deprez 2021-07-31 16:38:54 +10:00 committed by Josh Deprez
parent acaa279e05
commit ec8daf7b79
3 changed files with 41 additions and 18 deletions

View file

@ -1,6 +1,18 @@
package engine
import "github.com/hajimehoshi/ebiten/v2"
import (
"fmt"
"image"
"io/fs"
"github.com/hajimehoshi/ebiten/v2"
)
var (
AssetFS fs.FS
imageCache = make(map[string]*ebiten.Image)
)
type ImageRef struct {
Path string
@ -8,9 +20,24 @@ type ImageRef struct {
image *ebiten.Image
}
func (r *ImageRef) Image() *ebiten.Image {
if r.image == nil {
// TODO
func (r *ImageRef) Image() (*ebiten.Image, error) {
if r.image != nil {
return r.image, nil
}
return r.image
r.image = imageCache[r.Path]
if r.image != nil {
return r.image, nil
}
f, err := AssetFS.Open(r.Path)
if err != nil {
return nil, fmt.Errorf("open asset: %w", err)
}
defer f.Close()
i, _, err := image.Decode(f)
if err != nil {
return nil, fmt.Errorf("decode asset: %w", err)
}
r.image = ebiten.NewImageFromImage(i)
imageCache[r.Path] = r.image
return r.image, nil
}

View file

@ -3,6 +3,7 @@ package engine
import (
"encoding/gob"
"image"
"log"
"github.com/hajimehoshi/ebiten/v2"
)
@ -15,7 +16,7 @@ func init() {
type Tilemap struct {
Map [][]Tile
Src *ebiten.Image // must be a horizontal tile set
Src ImageRef // must be a horizontal tile set
TileSize int
Transform ebiten.GeoM
ZPos
@ -30,7 +31,11 @@ func (t *Tilemap) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
op.GeoM.Concat(geom)
sx := tile.TileIndex() * t.TileSize
src := t.Src.SubImage(image.Rect(sx, 0, sx+t.TileSize, t.TileSize)).(*ebiten.Image)
im, err := t.Src.Image()
if err != nil {
log.Fatalf("Loading image from reference: %v", err)
}
src := im.SubImage(image.Rect(sx, 0, sx+t.TileSize, t.TileSize)).(*ebiten.Image)
screen.DrawImage(src, &op)
}
}

13
main.go
View file

@ -2,7 +2,6 @@ package main
import (
"embed"
"image"
_ "image/png"
"log"
@ -19,15 +18,7 @@ func main() {
ebiten.SetWindowSize(screenWidth*2, screenHeight*2)
ebiten.SetWindowTitle("TODO")
boxesFile, err := assets.Open("assets/boxes.png")
if err != nil {
log.Fatalf("Couldn't open asset: %v", err)
}
boxesPNG, _, err := image.Decode(boxesFile)
if err != nil {
log.Fatalf("Couldn't decode asset: %v", err)
}
boxesFile.Close()
engine.AssetFS = assets
staticTiles := [][]engine.StaticTile{
{0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1},
@ -73,7 +64,7 @@ func main() {
tilemap := &engine.Tilemap{
Map: tiles,
Src: ebiten.NewImageFromImage(boxesPNG),
Src: engine.ImageRef{Path: "assets/boxes.png"},
TileSize: 16,
}