aboutsummaryrefslogtreecommitdiff
path: root/go/ui/spinner.go
blob: 083ec292cd4aa1e0096d4244cd05131e60a86210 (plain)
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
package ui

import (
	"image/color"
	"math"

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

var (
	SPINNER_DEFAULT_FOREGROUND = color.White
	SPINNER_DEFAULT_STROKE     = 5
)

type Spinner struct {
	WidgetBase
	fg    color.Color
	alpha uint64
}

func NewSpinner(x, y int, diameter int) *Spinner {
	s := &Spinner{
		WidgetBase: NewWidgetBase(x, y, diameter, diameter),
		fg:         SPINNER_DEFAULT_FOREGROUND,
	}
	s.renderImpl = func() *ebiten.Image { return s.render() }
	s.EventHandlersMap["update"] = func() error {
		s.alpha = s.alpha + 3
		s.ForceRedraw()
		return nil
	}
	return s
}

func (s *Spinner) Fg(fg color.Color) *Spinner {
	s.fg = fg
	return s
}

func (s *Spinner) render() *ebiten.Image {
	img := ebiten.NewImage(s.Width, s.Height)
	var path vector.Path

	r := float64((s.Width - 2*SPINNER_DEFAULT_STROKE) / 2)
	cx := s.Width/2 + SPINNER_DEFAULT_STROKE
	cy := cx
	a1 := float64(s.alpha%360) * math.Pi / 180
	a2 := float64((s.alpha+90)%360) * math.Pi / 180

	path.Arc(float32(cx), float32(cy), float32(r), float32(a2), float32(a1), vector.Clockwise)

	strokeOp := &vector.StrokeOptions{}
	strokeOp.Width = float32(SPINNER_DEFAULT_STROKE)
	vertices := []ebiten.Vertex{}
	indices := []uint16{}
	vertices, indices = path.AppendVerticesAndIndicesForStroke(vertices, indices, strokeOp)

	{
		r, g, b, a := s.fg.RGBA()
		for i := range vertices {
			vertices[i].SrcX = 1
			vertices[i].SrcY = 1
			vertices[i].ColorR = float32(r)
			vertices[i].ColorG = float32(g)
			vertices[i].ColorB = float32(b)
			vertices[i].ColorA = float32(a)
		}
	}

	op := &ebiten.DrawTrianglesOptions{}
	op.AntiAlias = true
	op.FillRule = ebiten.FillRuleNonZero
	op.ColorScaleMode = ebiten.ColorScaleModePremultipliedAlpha
	img.DrawTriangles(vertices, indices, whiteSubImage, op)
	return img
}