2021-08-26 13:54:22 +10:00
|
|
|
package engine
|
|
|
|
|
|
|
|
import (
|
|
|
|
"image"
|
|
|
|
|
|
|
|
"github.com/hajimehoshi/ebiten/v2"
|
|
|
|
)
|
|
|
|
|
2021-08-27 11:49:11 +10:00
|
|
|
var _ interface {
|
|
|
|
Prepper
|
|
|
|
Scanner
|
|
|
|
} = &Sheet{}
|
2021-08-26 13:54:22 +10:00
|
|
|
|
|
|
|
// Sheet handles images that consist of a grid of equally sized regions
|
|
|
|
// (cells) and can produce subimages for the cell at an index. This is useful
|
2021-09-02 11:53:04 +10:00
|
|
|
// for various applications such as sprite animation and tile maps. Additionally
|
|
|
|
// each sheet carries a collection of animations that use the sheet.
|
2021-08-26 13:54:22 +10:00
|
|
|
type Sheet struct {
|
2021-09-02 11:53:04 +10:00
|
|
|
AnimDefs map[string]*AnimDef
|
2021-08-26 13:54:22 +10:00
|
|
|
CellSize image.Point
|
|
|
|
Src ImageRef
|
|
|
|
|
|
|
|
w int // width as measured in number of cells
|
|
|
|
}
|
|
|
|
|
2021-09-02 11:53:04 +10:00
|
|
|
// NewAnim returns a new Anim for the given key, or nil if not found in
|
|
|
|
// AnimDefs.
|
|
|
|
func (s *Sheet) NewAnim(key string) *Anim {
|
|
|
|
return s.AnimDefs[key].NewAnim()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare computes the width of the image (in cells).
|
2021-08-27 14:52:24 +10:00
|
|
|
func (s *Sheet) Prepare(*Game) error {
|
2021-08-26 13:54:22 +10:00
|
|
|
s.w, _ = s.Src.Image().Size()
|
|
|
|
s.w /= s.CellSize.X
|
2021-08-27 14:52:24 +10:00
|
|
|
return nil
|
2021-08-26 13:54:22 +10:00
|
|
|
}
|
|
|
|
|
2021-09-02 11:53:04 +10:00
|
|
|
// Scan returns the Src.
|
2021-08-26 13:54:22 +10:00
|
|
|
func (s *Sheet) Scan() []interface{} { return []interface{}{&s.Src} }
|
|
|
|
|
2021-09-02 11:53:04 +10:00
|
|
|
// SubImage returns an *ebiten.Image corresponding to the given cell index.
|
2021-08-26 13:54:22 +10:00
|
|
|
func (s *Sheet) SubImage(i int) *ebiten.Image {
|
2021-09-01 17:24:43 +10:00
|
|
|
p := pmul(image.Pt(i%s.w, i/s.w), s.CellSize)
|
2021-08-26 13:54:22 +10:00
|
|
|
r := image.Rectangle{p, p.Add(s.CellSize)}
|
|
|
|
return s.Src.Image().SubImage(r).(*ebiten.Image)
|
|
|
|
}
|