aboutsummaryrefslogtreecommitdiff
path: root/selection/selection.go
blob: 275511017e2bed6ace416c549d99345f51d22085 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

package selection

import (
	"age_of_empires/ecs"
	"age_of_empires/physics"
	"math"

	"github.com/hajimehoshi/ebiten/v2"
)

const HALO_WIDTH = 10

type Priority int

const (
	Unit Priority = iota
	Building
)

type GlobalSelection struct {
	IsActive bool
	Start    physics.Point
}

type Selection struct {
	IsSelected bool
	Halo       *ebiten.Image
	Priority   Priority
}

type Multiple struct {
	Bounds      physics.Rectangle
	Preselected []*ecs.Component[Selection]
}

func NewMultiple(start physics.Point, end physics.Point) Multiple {
	return Multiple{
		Bounds:      physics.Rectangle{Min: start, Max: end}.Canon(),
		Preselected: []*ecs.Component[Selection]{},
	}
}

func (m *Multiple) Preselect(position ecs.Component[physics.Point], bounds physics.Rectangle, selection *ecs.Component[Selection]) {
	if !selection.IsEnabled {
		return
	}
	selection.Value.IsSelected = false
	if m.Bounds.Overlaps(bounds) {
		m.Preselected = append(m.Preselected, selection)
	}
}

func (m *Multiple) Select() {
	if len(m.Preselected) == 0 {
		return
	}
	highestPriority := Priority(math.MaxInt)
	for _, selection := range m.Preselected {
		if selection.Value.Priority < highestPriority {
			highestPriority = selection.Value.Priority
		}
	}
	for _, selection := range m.Preselected {
		if selection.Value.Priority == highestPriority {
			selection.Value.IsSelected = true
		}
	}
}

type Single struct {
	Cursor      physics.Point
	HasSelected bool
}

func NewSingle(cursor physics.Point) Single {
	return Single{
		Cursor:      cursor,
		HasSelected: false,
	}
}

func (s *Single) Select(position ecs.Component[physics.Point], bounds physics.Rectangle, selection *ecs.Component[Selection]) {
	if !selection.IsEnabled {
		return
	}
	selection.Value.IsSelected = false
	if s.HasSelected || !s.Cursor.In(bounds) {
		return
	}
	selection.Value.IsSelected = true
}