ichigo/engine/scene.go

97 lines
2 KiB
Go
Raw Normal View History

package engine
import (
2021-07-30 17:26:23 +10:00
"encoding/gob"
"math"
"sort"
"github.com/hajimehoshi/ebiten/v2"
)
2021-08-18 16:34:51 +10:00
// Ensure Scene satisfies interfaces.
var (
_ Identifier = &Scene{}
_ Drawer = &Scene{}
_ DrawOrderer = &Scene{}
_ Prepper = &Scene{}
_ Scanner = &Scene{}
_ Updater = &Scene{}
)
2021-07-30 17:26:23 +10:00
func init() {
gob.Register(Scene{})
}
2021-07-30 14:25:32 +10:00
// Scene manages drawing and updating a bunch of components.
type Scene struct {
Components []interface{}
2021-08-02 14:38:48 +10:00
Disabled bool
2021-08-18 16:34:51 +10:00
ZOrder
2021-08-18 15:23:02 +10:00
Hidden bool
ID
}
2021-07-30 14:25:32 +10:00
// Draw draws all components in order.
2021-08-12 14:06:01 +10:00
func (s *Scene) Draw(screen *ebiten.Image, opts ebiten.DrawImageOptions) {
2021-08-01 17:08:26 +10:00
if s.Hidden {
return
}
2021-08-18 15:23:02 +10:00
// Draw everything.
2021-07-30 14:36:11 +10:00
for _, i := range s.Components {
if d, ok := i.(Drawer); ok {
2021-08-12 14:06:01 +10:00
d.Draw(screen, opts)
}
}
}
// Prepare does an initial Z-order sort.
2021-08-18 15:23:02 +10:00
func (s *Scene) Prepare(game *Game) { s.sortByDrawOrder() }
2021-08-18 14:02:15 +10:00
// sortByDrawOrder sorts the components by Z position.
// Everything without a Z sorts first. Stable sort is used to avoid Z-fighting
// (among layers without a Z, or those with equal Z).
2021-08-18 14:02:15 +10:00
func (s *Scene) sortByDrawOrder() {
2021-07-30 14:36:11 +10:00
sort.SliceStable(s.Components, func(i, j int) bool {
2021-08-18 14:02:15 +10:00
a, aok := s.Components[i].(DrawOrderer)
b, bok := s.Components[j].(DrawOrderer)
if aok && bok {
2021-08-18 14:02:15 +10:00
return a.DrawOrder() < b.DrawOrder()
}
return !aok && bok
})
}
2021-08-02 12:21:24 +10:00
// Scan returns all immediate subcomponents.
2021-08-02 12:16:10 +10:00
func (s *Scene) Scan() []interface{} { return s.Components }
2021-08-01 16:10:30 +10:00
// Update calls Update on all Updater components.
2021-07-30 14:36:11 +10:00
func (s *Scene) Update() error {
2021-08-02 14:38:48 +10:00
if s.Disabled {
return nil
}
2021-07-30 14:36:11 +10:00
for _, c := range s.Components {
// Update each updater in turn
if u, ok := c.(Updater); ok {
if err := u.Update(); err != nil {
return err
}
}
}
// Check if the updates put the components out of order; if so, sort
2021-08-18 14:02:15 +10:00
cz := -math.MaxFloat64 // fun fact: this is min float64
for _, c := range s.Components {
2021-08-18 14:02:15 +10:00
z, ok := c.(DrawOrderer)
if !ok {
continue
}
2021-08-18 14:02:15 +10:00
if t := z.DrawOrder(); t > cz {
cz = t
continue
}
2021-08-18 14:02:15 +10:00
s.sortByDrawOrder()
return nil
}
return nil
}