tins2020/textures.go

97 lines
2.0 KiB
Go
Raw Normal View History

2020-05-08 16:38:26 +00:00
package tins2020
import (
2020-05-09 05:48:02 +00:00
"errors"
"fmt"
2020-05-08 16:38:26 +00:00
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
2020-05-09 05:48:02 +00:00
"opslag.de/schobers/fs/vfs"
2020-05-08 16:38:26 +00:00
)
2020-05-09 05:48:02 +00:00
type Texture struct {
texture *sdl.Texture
rect *sdl.Rect
}
func NewTextureFromSurface(renderer *sdl.Renderer, surface *sdl.Surface) (*Texture, error) {
texture, err := renderer.CreateTextureFromSurface(surface)
if err != nil {
return nil, err
}
return &Texture{texture: texture, rect: &sdl.Rect{X: 0, Y: 0, W: surface.W, H: surface.H}}, nil
}
func (t *Texture) Rect() *sdl.Rect { return t.rect }
func (t *Texture) Copy(renderer *sdl.Renderer, target *sdl.Rect) {
renderer.Copy(t.texture, t.rect, target)
}
// func (t *Texture) CopyF(renderer *sdl.Renderer, target *sdl.FRect) {
// renderer.CopyF(t.texture, t.rect, target) // Depends on SDL >=2.0.10
// }
func (t *Texture) Destroy() { t.texture.Destroy() }
2020-05-08 16:38:26 +00:00
type Textures struct {
2020-05-09 05:48:02 +00:00
dir vfs.CopyDir
2020-05-08 16:38:26 +00:00
renderer *sdl.Renderer
2020-05-09 05:48:02 +00:00
textures map[string]*Texture
2020-05-08 16:38:26 +00:00
}
2020-05-09 05:48:02 +00:00
func (t *Textures) Init(renderer *sdl.Renderer, dir vfs.CopyDir) {
t.dir = dir
2020-05-08 16:38:26 +00:00
t.renderer = renderer
2020-05-09 05:48:02 +00:00
t.textures = map[string]*Texture{}
}
func (t *Textures) Load(name, path string, other ...string) error {
err := t.load(name, path)
if err != nil {
return err
}
if len(other) == 0 {
return nil
}
if len(other)%2 != 0 {
return errors.New("expected name/path pairs")
}
for i := 0; i < len(other); i += 2 {
err = t.load(other[i], other[i+1])
if err != nil {
return fmt.Errorf("error loading '%s'; error: %v", other[i], err)
}
}
return nil
2020-05-08 16:38:26 +00:00
}
2020-05-09 05:48:02 +00:00
func (t *Textures) load(name, path string) error {
texturePath, err := t.dir.Retrieve(path)
if err != nil {
return err
}
surface, err := img.Load(texturePath)
2020-05-08 16:38:26 +00:00
if err != nil {
return err
}
defer surface.Free()
2020-05-09 05:48:02 +00:00
texture, err := NewTextureFromSurface(t.renderer, surface)
if err != nil {
return err
2020-05-08 16:38:26 +00:00
}
t.textures[name] = texture
return nil
}
2020-05-09 05:48:02 +00:00
func (t *Textures) Texture(name string) *Texture { return t.textures[name] }
2020-05-08 16:38:26 +00:00
func (t *Textures) Destroy() {
if t.textures == nil {
return
}
for _, t := range t.textures {
t.Destroy()
}
}