ichigo/engine/game.go

414 lines
9.7 KiB
Go
Raw Normal View History

2021-07-23 13:12:54 +10:00
package engine
2021-08-01 16:10:30 +10:00
import (
"encoding/gob"
2021-08-30 16:25:50 +10:00
"errors"
2021-08-27 14:30:39 +10:00
"fmt"
2021-08-22 20:27:08 +10:00
"io/fs"
2021-08-31 17:03:43 +10:00
"math"
2021-08-27 15:39:10 +10:00
"reflect"
2021-08-31 17:03:43 +10:00
"sort"
2021-08-25 16:46:30 +10:00
"sync"
2021-08-01 16:10:30 +10:00
"github.com/hajimehoshi/ebiten/v2"
)
2021-08-28 18:14:37 +10:00
var _ interface {
Disabler
Hider
Identifier
Updater
Scanner
} = &Game{}
2021-08-30 16:25:50 +10:00
var (
errNilComponent = errors.New("nil component")
errNilParent = errors.New("nil parent")
)
2021-08-01 16:10:30 +10:00
func init() {
2021-08-25 15:04:38 +10:00
gob.Register(&Game{})
2021-08-01 16:10:30 +10:00
}
2021-08-27 16:48:09 +10:00
// Game implements the ebiten methods using a collection of components. One
// component must be the designated root component - usually a scene of some
// kind.
2021-07-23 13:12:54 +10:00
type Game struct {
2021-08-25 16:46:30 +10:00
Disabled
Hidden
2021-07-23 13:13:50 +10:00
ScreenWidth int
ScreenHeight int
2021-09-01 09:17:08 +10:00
Root interface{} // typically a *Scene or SceneRef though
2021-08-01 16:10:30 +10:00
2021-08-31 17:03:43 +10:00
dbmu sync.RWMutex
byID map[string]Identifier // Named components by ID
byAB map[abKey]map[interface{}]struct{} // Ancestor/behaviour index
2021-09-01 09:17:08 +10:00
drawList drawList // draw list :|
2021-08-31 17:03:43 +10:00
par map[interface{}]interface{} // par[x] is parent of x
2021-08-27 15:39:10 +10:00
}
2021-09-01 09:17:08 +10:00
// Draw draws everything.
2021-07-23 13:12:54 +10:00
func (g *Game) Draw(screen *ebiten.Image) {
2021-08-25 16:46:30 +10:00
if g.Hidden {
return
}
2021-08-31 22:05:21 +10:00
2021-09-01 09:17:08 +10:00
// Hiding a parent component should hide the child objects, and the
// transform applied to a child should be the cumulative transform of all
// parents as well.
// accum memoises the results for each component.
type state struct {
hidden bool
opts ebiten.DrawImageOptions
}
accum := map[interface{}]state{
g: {hidden: false},
}
// Draw everything in g.drawList, where not hidden (itself or any parent)
for _, d := range g.drawList {
// Is d hidden itself?
if h, ok := d.(Hider); ok && h.IsHidden() {
accum[d] = state{hidden: true}
continue // skip drawing
2021-08-31 18:19:14 +10:00
}
2021-09-01 09:17:08 +10:00
// Walk up g.par to find the nearest state in accum.
var st state
stack := []interface{}{d}
for p := g.par[d]; ; p = g.par[p] {
if s, found := accum[p]; found {
st = s
break
2021-08-31 18:19:14 +10:00
}
2021-09-01 09:17:08 +10:00
stack = append(stack, p)
}
// Unwind the stack, accumulating state along the way.
for len(stack) > 0 {
l1 := len(stack) - 1
p := stack[l1]
stack = stack[:l1]
if h, ok := p.(Hider); ok {
st.hidden = st.hidden || h.IsHidden()
2021-08-31 18:19:14 +10:00
}
2021-08-31 22:05:21 +10:00
if st.hidden {
2021-09-01 09:17:08 +10:00
accum[p] = state{hidden: true}
2021-08-31 18:19:14 +10:00
continue
}
2021-09-01 09:17:08 +10:00
// p is not hidden, so compute its cumulative transform.
if t, ok := p.(Transformer); ok {
st.opts = concatOpts(t.Transform(), st.opts)
}
accum[p] = st
2021-08-31 17:03:43 +10:00
}
2021-09-01 09:17:08 +10:00
// Skip drawing if hidden.
if st.hidden {
continue
}
d.Draw(screen, &st.opts)
2021-08-31 17:03:43 +10:00
}
2021-07-23 13:12:54 +10:00
}
// Layout returns the configured screen width/height.
func (g *Game) Layout(outsideWidth, outsideHeight int) (w, h int) {
return g.ScreenWidth, g.ScreenHeight
}
2021-07-23 13:46:19 +10:00
2021-09-01 09:17:08 +10:00
// Update updates everything.
2021-08-25 16:46:30 +10:00
func (g *Game) Update() error {
if g.Disabled {
return nil
}
2021-08-31 17:03:43 +10:00
2021-09-01 09:17:08 +10:00
// Need to do a similar trick for Draw: disabling a parent object should
// disable the child objects.
// accum memoises the disabled state for each component.
accum := map[interface{}]bool{
g: false,
2021-08-31 17:03:43 +10:00
}
2021-09-01 09:17:08 +10:00
// Update everything that is not disabled.
for u := range g.Query(g.Ident(), UpdaterType) {
// Skip g (note g satisfies Updater, so this would infinitely recurse)
if u == g {
continue
}
// Is u disabled itself?
if d, ok := u.(Disabler); ok && d.IsDisabled() {
accum[u] = true
continue
}
// Walk up g.par to find the nearest state in accum.
var st bool
stack := []interface{}{u}
for p := g.par[u]; ; p = g.par[p] {
if s, found := accum[p]; found {
st = s
break
2021-08-31 18:19:14 +10:00
}
2021-09-01 09:17:08 +10:00
stack = append(stack, p)
}
// Unwind the stack, accumulating state along the way.
for len(stack) > 0 {
l1 := len(stack) - 1
p := stack[l1]
stack = stack[:l1]
if d, ok := p.(Disabler); ok {
st = st || d.IsDisabled()
}
accum[p] = st
}
// Skip updating if disabled.
if st {
continue
}
if err := u.(Updater).Update(); err != nil {
return err
}
}
// Sort the draw list (on every frame - this isn't as bad as it sounds)
sort.Stable(g.drawList)
// Truncate tombstones from the end.
for i := len(g.drawList) - 1; i >= 0; i-- {
if g.drawList[i] == (tombstone{}) {
g.drawList = g.drawList[:i]
2021-08-31 17:03:43 +10:00
}
}
return nil
2021-08-25 16:46:30 +10:00
}
2021-08-20 16:46:26 +10:00
2021-08-28 18:14:37 +10:00
// Ident returns "__GAME__".
func (g *Game) Ident() string { return "__GAME__" }
2021-08-01 17:14:57 +10:00
// Component returns the component with a given ID, or nil if there is none.
2021-08-30 15:49:51 +10:00
// This only returns sensible values for registered components (e.g. after
// LoadAndPrepare).
2021-08-27 14:43:37 +10:00
func (g *Game) Component(id string) Identifier {
2021-08-25 16:46:30 +10:00
g.dbmu.RLock()
defer g.dbmu.RUnlock()
2021-08-30 13:33:01 +10:00
return g.byID[id]
2021-08-25 16:46:30 +10:00
}
2021-08-01 16:10:30 +10:00
2021-08-30 15:49:51 +10:00
// Parent returns the parent of a given component, or nil if there is none.
// This only returns sensible values for registered components (e.g. after
// LoadAndPrepare).
func (g *Game) Parent(c interface{}) interface{} {
g.dbmu.RLock()
defer g.dbmu.RUnlock()
return g.par[c]
}
2021-08-27 15:39:10 +10:00
// Query looks for components having both a given ancestor and implementing
// a given behaviour (see Behaviors in interface.go). This only returns sensible
// values after LoadAndPrepare. Note that every component is its own ancestor.
2021-08-30 15:03:22 +10:00
func (g *Game) Query(ancestorID string, behaviour reflect.Type) map[interface{}]struct{} {
2021-08-27 15:39:10 +10:00
g.dbmu.RLock()
defer g.dbmu.RUnlock()
2021-08-30 13:33:01 +10:00
return g.byAB[abKey{ancestorID, behaviour}]
2021-08-27 15:39:10 +10:00
}
2021-08-04 12:40:51 +10:00
// Scan implements Scanner.
2021-08-20 16:46:26 +10:00
func (g *Game) Scan() []interface{} { return []interface{}{g.Root} }
2021-08-01 16:41:10 +10:00
2021-08-30 16:25:50 +10:00
// Walk calls visit with every component and its parent, reachable from the
// given component via Scan, for as long as visit returns nil. The parent of
// the first component (as passed to visit) will be nil.
func Walk(component interface{}, visit func(component, parent interface{}) error) error {
return walk(component, nil, visit)
2021-08-27 13:56:50 +10:00
}
2021-08-30 16:25:50 +10:00
func walk(component, parent interface{}, visit func(component, parent interface{}) error) error {
if err := visit(component, parent); err != nil {
2021-08-20 15:01:31 +10:00
return err
2021-08-01 16:41:10 +10:00
}
2021-08-30 16:25:50 +10:00
sc, ok := component.(Scanner)
2021-08-15 17:11:26 +10:00
if !ok {
2021-08-20 15:01:31 +10:00
return nil
2021-08-15 17:11:26 +10:00
}
for _, c := range sc.Scan() {
2021-08-30 16:25:50 +10:00
if err := walk(c, component, visit); err != nil {
2021-08-20 15:01:31 +10:00
return err
2021-08-01 16:10:30 +10:00
}
}
2021-08-20 15:01:31 +10:00
return nil
2021-08-01 16:10:30 +10:00
}
2021-08-27 15:39:10 +10:00
// LoadAndPrepare first calls Load on all Loaders. Once loading is complete, it
// builds the component databases and then calls Prepare on every Preparer.
// LoadAndPrepare must be called before any calls to Component or Query.
2021-08-27 13:56:50 +10:00
func (g *Game) LoadAndPrepare(assets fs.FS) error {
2021-08-27 16:46:04 +10:00
// Load all the Loaders.
2021-08-30 16:25:50 +10:00
if err := Walk(g, func(c, _ interface{}) error {
2021-08-20 16:31:06 +10:00
l, ok := c.(Loader)
if !ok {
return nil
}
2021-08-23 10:09:49 +10:00
return l.Load(assets)
2021-08-27 13:56:50 +10:00
}); err != nil {
return err
}
2021-08-27 14:43:37 +10:00
// Build the component databases
2021-08-25 16:46:30 +10:00
g.dbmu.Lock()
2021-08-30 13:33:01 +10:00
g.byID = make(map[string]Identifier)
2021-08-30 15:03:22 +10:00
g.byAB = make(map[abKey]map[interface{}]struct{})
2021-08-30 15:49:51 +10:00
g.par = make(map[interface{}]interface{})
2021-08-30 16:27:12 +10:00
if err := Walk(g, g.register); err != nil {
2021-08-27 14:43:37 +10:00
return err
}
2021-08-25 16:46:30 +10:00
g.dbmu.Unlock()
2021-08-27 13:56:50 +10:00
2021-08-27 14:43:37 +10:00
// Prepare all the Preppers
2021-08-30 15:03:22 +10:00
for p := range g.Query(g.Ident(), PrepperType) {
2021-08-27 16:46:04 +10:00
if err := p.(Prepper).Prepare(g); err != nil {
return err
2021-08-05 12:26:41 +10:00
}
2021-08-27 16:46:04 +10:00
}
return nil
2021-08-01 16:10:30 +10:00
}
2021-08-27 16:59:20 +10:00
2021-08-30 16:27:12 +10:00
// Register registers a component into the component database (as the
2021-08-30 16:25:50 +10:00
// child of a given parent). Passing a nil component or parent is an error.
// Registering multiple components with the same ID is also an error.
2021-08-30 16:27:12 +10:00
func (g *Game) Register(component, parent interface{}) error {
2021-08-30 16:25:50 +10:00
if component == nil {
return errNilComponent
}
if parent == nil && component != g {
return errNilParent
}
g.dbmu.Lock()
defer g.dbmu.Unlock()
2021-08-30 16:27:12 +10:00
return g.register(component, parent)
2021-08-30 16:25:50 +10:00
}
2021-08-30 16:27:12 +10:00
func (g *Game) register(component, parent interface{}) error {
2021-08-30 15:49:51 +10:00
// register in g.par
2021-08-30 16:25:50 +10:00
if parent != nil {
g.par[component] = parent
2021-08-30 15:49:51 +10:00
}
2021-08-31 17:03:43 +10:00
// register in g.drawList
if d, ok := component.(Drawer); ok {
g.drawList = append(g.drawList, d)
}
2021-08-30 15:08:22 +10:00
// register in g.byAB
2021-08-30 16:25:50 +10:00
ct := reflect.TypeOf(component)
2021-08-27 16:59:20 +10:00
for _, b := range Behaviours {
if !ct.Implements(b) {
continue
}
2021-08-30 16:25:50 +10:00
// TODO: better than O(len(path)^2) time and memory?
for p := component; p != nil; p = g.par[p] {
2021-08-28 18:14:37 +10:00
i, ok := p.(Identifier)
2021-08-30 15:49:51 +10:00
if !ok {
2021-08-28 18:14:37 +10:00
continue
}
2021-08-30 13:33:01 +10:00
k := abKey{i.Ident(), b}
2021-08-30 15:03:22 +10:00
if g.byAB[k] == nil {
g.byAB[k] = make(map[interface{}]struct{})
}
2021-08-30 16:25:50 +10:00
g.byAB[k][component] = struct{}{}
2021-08-27 16:59:20 +10:00
}
}
2021-08-30 15:49:51 +10:00
// register in g.byID if needed
2021-08-30 16:25:50 +10:00
i, ok := component.(Identifier)
2021-08-30 15:49:51 +10:00
if !ok {
2021-08-27 16:59:20 +10:00
return nil
}
id := i.Ident()
2021-08-30 13:33:01 +10:00
if _, exists := g.byID[id]; exists {
2021-08-27 16:59:20 +10:00
return fmt.Errorf("duplicate id %q", id)
}
2021-08-30 13:33:01 +10:00
g.byID[id] = i
2021-08-27 16:59:20 +10:00
return nil
}
2021-08-30 15:07:57 +10:00
2021-08-30 16:27:12 +10:00
// Unregister removes the component from the component database.
2021-08-30 16:25:50 +10:00
// Passing a nil component has no effect.
2021-08-30 16:27:12 +10:00
func (g *Game) Unregister(component interface{}) {
2021-08-30 16:25:50 +10:00
if component == nil {
return
}
2021-08-30 15:49:51 +10:00
g.dbmu.Lock()
2021-08-30 16:27:12 +10:00
g.unregister(component)
2021-08-30 15:49:51 +10:00
g.dbmu.Unlock()
}
2021-08-30 16:27:12 +10:00
func (g *Game) unregister(component interface{}) {
2021-08-30 15:49:51 +10:00
// unregister from g.byAB, using g.par to trace the path
2021-08-30 16:25:50 +10:00
ct := reflect.TypeOf(component)
2021-08-30 15:07:57 +10:00
for _, b := range Behaviours {
if !ct.Implements(b) {
continue
}
2021-08-30 16:25:50 +10:00
for p := component; p != nil; p = g.par[p] {
2021-08-30 15:07:57 +10:00
i, ok := p.(Identifier)
2021-08-30 15:49:51 +10:00
if !ok {
2021-08-30 15:07:57 +10:00
continue
}
k := abKey{i.Ident(), b}
if g.byAB[k] == nil {
continue
}
2021-08-30 16:25:50 +10:00
delete(g.byAB[k], component)
2021-08-30 15:07:57 +10:00
}
}
2021-08-30 15:49:51 +10:00
// unregister from g.par
2021-08-30 16:25:50 +10:00
delete(g.par, component)
2021-08-30 15:49:51 +10:00
2021-08-31 17:03:43 +10:00
// unregister from g.drawList
for i, d := range g.drawList {
if d == component {
g.drawList[i] = tombstone{}
}
}
2021-08-30 15:49:51 +10:00
// unregister from g.byID if needed
2021-08-30 16:25:50 +10:00
i, ok := component.(Identifier)
2021-08-30 15:49:51 +10:00
if !ok {
2021-08-30 15:07:57 +10:00
return
}
delete(g.byID, i.Ident())
}
2021-09-01 09:17:08 +10:00
// --------- Helper types ---------
type abKey struct {
ancestor string
behaviour reflect.Type
}
var _ Drawer = tombstone{}
type tombstone struct{}
func (tombstone) Draw(*ebiten.Image, *ebiten.DrawImageOptions) {}
2021-09-01 09:17:08 +10:00
func (tombstone) DrawOrder() float64 { return math.Inf(1) }
type drawList []Drawer
func (d drawList) Less(i, j int) bool { return d[i].DrawOrder() < d[j].DrawOrder() }
func (d drawList) Len() int { return len(d) }
func (d drawList) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func concatOpts(a, b ebiten.DrawImageOptions) ebiten.DrawImageOptions {
a.ColorM.Concat(b.ColorM)
a.GeoM.Concat(b.GeoM)
if b.CompositeMode != 0 {
a.CompositeMode = b.CompositeMode
}
if b.Filter != 0 {
a.Filter = b.Filter
}
return a
}