mirror of
https://codeberg.org/scip/golsky.git
synced 2025-12-16 20:20:57 +01:00
move to codeberg (#10)
This commit is contained in:
BIN
cmd/assets/fonts/NotoSans-Regular.ttf
Normal file
BIN
cmd/assets/fonts/NotoSans-Regular.ttf
Normal file
Binary file not shown.
13
cmd/assets/shaders/row.kg
Normal file
13
cmd/assets/shaders/row.kg
Normal file
@@ -0,0 +1,13 @@
|
||||
//kage:unit pixels
|
||||
|
||||
package main
|
||||
|
||||
var Alife int
|
||||
|
||||
func Fragment(_ vec4, pos vec2, _ vec4) vec4 {
|
||||
if Alife == 1 {
|
||||
return vec4(0.0)
|
||||
}
|
||||
|
||||
return vec4(1.0)
|
||||
}
|
||||
BIN
cmd/assets/sprites/button-9slice1.png
Normal file
BIN
cmd/assets/sprites/button-9slice1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 269 B |
BIN
cmd/assets/sprites/button-9slice2.png
Normal file
BIN
cmd/assets/sprites/button-9slice2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 263 B |
BIN
cmd/assets/sprites/button-9slice3.png
Normal file
BIN
cmd/assets/sprites/button-9slice3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 269 B |
BIN
cmd/assets/sprites/checkbox-9slice1.png
Normal file
BIN
cmd/assets/sprites/checkbox-9slice1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 289 B |
BIN
cmd/assets/sprites/checkbox-9slice2.png
Normal file
BIN
cmd/assets/sprites/checkbox-9slice2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 271 B |
BIN
cmd/assets/src/button-9slice.ase
Normal file
BIN
cmd/assets/src/button-9slice.ase
Normal file
Binary file not shown.
BIN
cmd/assets/src/checkbox-9slice.ase
Normal file
BIN
cmd/assets/src/checkbox-9slice.ase
Normal file
Binary file not shown.
81
cmd/camera.go
Normal file
81
cmd/camera.go
Normal file
@@ -0,0 +1,81 @@
|
||||
// this comes from the camera example but I enhanced it a little bit
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"golang.org/x/image/math/f64"
|
||||
)
|
||||
|
||||
type Camera struct {
|
||||
ViewPort f64.Vec2
|
||||
Position f64.Vec2
|
||||
ZoomFactor int
|
||||
InitialZoomFactor int
|
||||
InitialPosition f64.Vec2
|
||||
ZoomOutFactor int
|
||||
}
|
||||
|
||||
func (c *Camera) String() string {
|
||||
return fmt.Sprintf(
|
||||
"T: %.1f, S: %d",
|
||||
c.Position, c.ZoomFactor,
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Camera) viewportCenter() f64.Vec2 {
|
||||
return f64.Vec2{
|
||||
c.ViewPort[0] * 0.5,
|
||||
c.ViewPort[1] * 0.5,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Camera) worldMatrix() ebiten.GeoM {
|
||||
m := ebiten.GeoM{}
|
||||
m.Translate(-c.Position[0], -c.Position[1])
|
||||
|
||||
viewportCenter := c.viewportCenter()
|
||||
|
||||
// We want to scale and rotate around center of image / screen
|
||||
m.Translate(-viewportCenter[0], -viewportCenter[1])
|
||||
|
||||
m.Scale(
|
||||
math.Pow(1.01, float64(c.ZoomFactor)),
|
||||
math.Pow(1.01, float64(c.ZoomFactor)),
|
||||
)
|
||||
|
||||
m.Translate(viewportCenter[0], viewportCenter[1])
|
||||
return m
|
||||
}
|
||||
|
||||
func (c *Camera) Render(world, screen *ebiten.Image) {
|
||||
screen.DrawImage(world, &ebiten.DrawImageOptions{
|
||||
GeoM: c.worldMatrix(),
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Camera) ScreenToWorld(posX, posY int) (float64, float64) {
|
||||
inverseMatrix := c.worldMatrix()
|
||||
if inverseMatrix.IsInvertible() {
|
||||
inverseMatrix.Invert()
|
||||
return inverseMatrix.Apply(float64(posX), float64(posY))
|
||||
} else {
|
||||
// When scaling it can happened that matrix is not invertable
|
||||
return math.NaN(), math.NaN()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Camera) Setup() {
|
||||
c.Position[0] = c.InitialPosition[0]
|
||||
c.Position[1] = c.InitialPosition[1]
|
||||
c.ZoomFactor = c.InitialZoomFactor
|
||||
}
|
||||
|
||||
func (c *Camera) Reset() {
|
||||
c.Position[0] = c.InitialPosition[0]
|
||||
c.Position[1] = c.InitialPosition[1]
|
||||
c.ZoomFactor = c.ZoomOutFactor
|
||||
}
|
||||
291
cmd/config.go
Normal file
291
cmd/config.go
Normal file
@@ -0,0 +1,291 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"runtime/pprof"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"codeberg.org/scip/golsky/rle"
|
||||
)
|
||||
|
||||
// all the settings comming from commandline, but maybe tweaked later from the UI
|
||||
type Config struct {
|
||||
Width, Height, Cellsize, Density int // measurements
|
||||
ScreenWidth, ScreenHeight int
|
||||
TPG int // ticks per generation/game speed, 1==max
|
||||
Debug, Empty, Paused, Markmode, Drawmode bool // game modi
|
||||
ShowEvolution, ShowGrid, RunOneStep bool // flags
|
||||
Rule *Rule // which rule to use, default: B3/S23
|
||||
RLE *rle.RLE // loaded GOL pattern from RLE file
|
||||
Statefile string // load game state from it if non-nil
|
||||
StateGrid *Grid // a grid from a statefile
|
||||
Wrap bool // wether wraparound mode is in place or not
|
||||
ShowVersion bool
|
||||
UseShader bool // to use a shader to render alife cells
|
||||
Restart, RestartGrid, RestartCache bool
|
||||
StartWithMenu bool
|
||||
Zoomfactor int
|
||||
ZoomOutFactor int
|
||||
InitialCamPos []float64
|
||||
DelayedStart bool // if true game, we wait. like pause but program induced
|
||||
Theme string
|
||||
ThemeManager ThemeManager
|
||||
|
||||
// for internal profiling
|
||||
ProfileFile string
|
||||
ProfileDraw bool
|
||||
ProfileMaxLoops int64
|
||||
}
|
||||
|
||||
const (
|
||||
VERSION = "v0.0.9"
|
||||
Alive = 1
|
||||
Dead = 0
|
||||
|
||||
DEFAULT_GRID_WIDTH = 600
|
||||
DEFAULT_GRID_HEIGHT = 400
|
||||
DEFAULT_CELLSIZE = 4
|
||||
DEFAULT_ZOOMFACTOR = 400
|
||||
DEFAULT_GEOM = "640x384"
|
||||
DEFAULT_THEME = "standard"
|
||||
)
|
||||
|
||||
const KEYBINDINGS string = `
|
||||
- SPACE: pause or resume the game
|
||||
- N: while game is paused: forward one step
|
||||
- PAGE UP: speed up
|
||||
- PAGE DOWN: slow down
|
||||
- MOUSE WHEEL: zoom in or out
|
||||
- LEFT MOUSE BUTTON: use to drag canvas, keep clicked and move mouse
|
||||
- I: enter "insert" (draw) mode: use left mouse to toggle a cells alife state.
|
||||
Leave with insert mode with "space". While in insert mode, use middle mouse
|
||||
button to drag the grid.
|
||||
- R: reset to 1:1 zoom
|
||||
- ESCAPE: open menu, o: open options menu
|
||||
- S: save game state to file (can be loaded with -l)
|
||||
- C: enter mark mode. Mark a rectangle with the mouse, when you
|
||||
release the mouse buttonx it is being saved to an RLE file
|
||||
- D: toggle debug output
|
||||
- Q: quit game
|
||||
`
|
||||
|
||||
func (config *Config) SetupCamera() {
|
||||
config.Zoomfactor = DEFAULT_ZOOMFACTOR / config.Cellsize
|
||||
|
||||
// calculate the initial cam pos. It is negative if the total grid
|
||||
// size is smaller than the screen in a centered position, but
|
||||
// it's zero if it's equal or larger than the screen.
|
||||
config.InitialCamPos = make([]float64, 2)
|
||||
|
||||
config.InitialCamPos[0] = float64(((config.ScreenWidth - (config.Width * config.Cellsize)) / 2) * -1)
|
||||
if config.Width*config.Cellsize >= config.ScreenWidth {
|
||||
// must be positive if world wider than screen
|
||||
config.InitialCamPos[0] = math.Abs(config.InitialCamPos[0])
|
||||
}
|
||||
|
||||
// same for Y
|
||||
config.InitialCamPos[1] = float64(((config.ScreenHeight - (config.Height * config.Cellsize)) / 2) * -1)
|
||||
if config.Height*config.Cellsize > config.ScreenHeight {
|
||||
config.InitialCamPos[1] = math.Abs(config.InitialCamPos[1])
|
||||
}
|
||||
|
||||
// Calculate zoom out factor, which shows 100% of the world. We
|
||||
// need to reverse math.Pow(1.01, $zoomfactor) to get the correct
|
||||
// percentage of the world to show. I.e: with a ScreenHeight of
|
||||
// 384px and a world of 800px the factor to show 100% of the world
|
||||
// is -75: math.Log(384/800) / math.Log(1.01). The 1.01 constant
|
||||
// is being used in camera.go:worldMatrix().
|
||||
|
||||
// FIXME: determine if the diff is larger on width, then calc with
|
||||
// width instead of height
|
||||
config.ZoomOutFactor = int(
|
||||
math.Log(float64(config.ScreenHeight)/(float64(config.Height)*float64(config.Cellsize))) /
|
||||
math.Log(1.01))
|
||||
}
|
||||
|
||||
// parse given window geometry and adjust game settings according to it
|
||||
func (config *Config) ParseGeom(geom string) error {
|
||||
// force a geom
|
||||
geometry := strings.Split(geom, "x")
|
||||
if len(geometry) != 2 {
|
||||
return errors.New("failed to parse -g parameters, expecting WIDTHxHEIGHT")
|
||||
}
|
||||
|
||||
width, err := strconv.Atoi(geometry[0])
|
||||
if err != nil {
|
||||
return errors.New("failed to parse width, expecting integer")
|
||||
}
|
||||
|
||||
height, err := strconv.Atoi(geometry[1])
|
||||
if err != nil {
|
||||
return errors.New("failed to parse height, expecting integer")
|
||||
}
|
||||
|
||||
config.ScreenWidth = width
|
||||
config.ScreenHeight = height
|
||||
|
||||
//config.Cellsize = DEFAULT_CELLSIZE
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// check if we have been given an RLE or LIF file to load, then load
|
||||
// it and adjust game settings accordingly
|
||||
func (config *Config) ParseRLE(rlefile string) error {
|
||||
if rlefile == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var rleobj *rle.RLE
|
||||
|
||||
if strings.HasSuffix(rlefile, ".lif") {
|
||||
lifobj, err := LoadLIF(rlefile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rleobj = lifobj
|
||||
} else {
|
||||
rleobject, err := rle.GetRLE(rlefile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rleobj = rleobject
|
||||
}
|
||||
|
||||
if rleobj == nil {
|
||||
return errors.New("failed to load pattern file (uncatched module error)")
|
||||
}
|
||||
|
||||
config.RLE = rleobj
|
||||
|
||||
// adjust geometry if needed
|
||||
if config.RLE.Width > config.Width || config.RLE.Height > config.Height {
|
||||
config.Width = config.RLE.Width * 2
|
||||
config.Height = config.RLE.Height * 2
|
||||
config.Cellsize = config.ScreenWidth / config.Width
|
||||
}
|
||||
|
||||
fmt.Printf("width: %d, screenwidth: %d, rlewidth: %d, cellsize: %d\n",
|
||||
config.Width, config.ScreenWidth, config.RLE.Width, config.Cellsize)
|
||||
|
||||
// RLE needs an empty grid
|
||||
config.Empty = true
|
||||
|
||||
// it may come with its own rule
|
||||
if config.RLE.Rule != "" {
|
||||
config.Rule = ParseGameRule(config.RLE.Rule)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *Config) EnableCPUProfiling(filename string) error {
|
||||
if filename == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
fd, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pprof.StartCPUProfile(fd)
|
||||
defer pprof.StopCPUProfile()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ParseCommandline() (*Config, error) {
|
||||
config := Config{}
|
||||
|
||||
var (
|
||||
rule, rlefile, geom string
|
||||
)
|
||||
|
||||
// commandline params, most configure directly config flags
|
||||
pflag.IntVarP(&config.Width, "width", "W", DEFAULT_GRID_WIDTH, "grid width in cells")
|
||||
pflag.IntVarP(&config.Height, "height", "H", DEFAULT_GRID_HEIGHT, "grid height in cells")
|
||||
pflag.IntVarP(&config.Cellsize, "cellsize", "c", 8, "cell size in pixels")
|
||||
pflag.StringVarP(&geom, "geom", "G", DEFAULT_GEOM, "window geometry in WxH in pixels, overturns -c")
|
||||
|
||||
pflag.IntVarP(&config.Density, "density", "D", 10, "density of random cells")
|
||||
pflag.IntVarP(&config.TPG, "ticks-per-generation", "t", 10,
|
||||
"game speed: the higher the slower (default: 10)")
|
||||
|
||||
pflag.StringVarP(&rule, "rule", "r", "B3/S23", "game rule")
|
||||
pflag.StringVarP(&rlefile, "pattern-file", "f", "", "RLE or LIF pattern file")
|
||||
|
||||
pflag.BoolVarP(&config.ShowVersion, "version", "v", false, "show version")
|
||||
pflag.BoolVarP(&config.ShowGrid, "show-grid", "g", false, "draw grid lines")
|
||||
pflag.BoolVarP(&config.ShowEvolution, "show-evolution", "s", false, "show evolution traces")
|
||||
|
||||
pflag.BoolVarP(&config.Paused, "paused", "p", false, "do not start simulation (use space to start)")
|
||||
pflag.BoolVarP(&config.Debug, "debug", "d", false, "show debug info")
|
||||
pflag.BoolVarP(&config.Empty, "empty", "e", false, "start with an empty screen")
|
||||
|
||||
// style
|
||||
pflag.StringVarP(&config.Theme, "theme", "T", DEFAULT_THEME, "color theme: standard, dark, light (default: standard)")
|
||||
|
||||
pflag.BoolVarP(&config.Wrap, "wrap-around", "w", false, "wrap around grid mode")
|
||||
pflag.BoolVarP(&config.UseShader, "use-shader", "k", false, "use shader for cell rendering")
|
||||
|
||||
pflag.StringVarP(&config.ProfileFile, "profile-file", "", "", "enable profiling")
|
||||
|
||||
pflag.Parse()
|
||||
|
||||
err := config.ParseGeom(geom)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = config.ParseRLE(rlefile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// load rule from commandline when no rule came from RLE file,
|
||||
// default is B3/S23, aka conways game of life
|
||||
if config.Rule == nil {
|
||||
config.Rule = ParseGameRule(rule)
|
||||
}
|
||||
|
||||
config.SetupCamera()
|
||||
|
||||
config.ThemeManager = NewThemeManager(config.Theme, config.Cellsize)
|
||||
|
||||
//repr.Println(config)
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
func (config *Config) TogglePaused() {
|
||||
config.Paused = !config.Paused
|
||||
}
|
||||
|
||||
func (config *Config) ToggleDebugging() {
|
||||
config.Debug = !config.Debug
|
||||
}
|
||||
|
||||
func (config *Config) SwitchTheme(theme string) {
|
||||
config.ThemeManager.SetCurrentTheme(theme)
|
||||
config.RestartCache = true
|
||||
}
|
||||
|
||||
func (config *Config) ToggleGridlines() {
|
||||
config.ShowGrid = !config.ShowGrid
|
||||
config.RestartCache = true
|
||||
}
|
||||
|
||||
func (config *Config) ToggleEvolution() {
|
||||
config.ShowEvolution = !config.ShowEvolution
|
||||
}
|
||||
|
||||
func (config *Config) ToggleWrap() {
|
||||
config.Wrap = !config.Wrap
|
||||
}
|
||||
82
cmd/game.go
Normal file
82
cmd/game.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
)
|
||||
|
||||
type Game struct {
|
||||
ScreenWidth, ScreenHeight, ReadlWidth, Cellsize int
|
||||
Scenes map[SceneName]Scene
|
||||
CurrentScene SceneName
|
||||
Config *Config
|
||||
Scale float32
|
||||
}
|
||||
|
||||
func NewGame(config *Config, startscene SceneName) *Game {
|
||||
game := &Game{
|
||||
Config: config,
|
||||
Scenes: map[SceneName]Scene{},
|
||||
ScreenWidth: config.ScreenWidth,
|
||||
ScreenHeight: config.ScreenHeight,
|
||||
}
|
||||
|
||||
// setup scene[s]
|
||||
game.CurrentScene = startscene
|
||||
game.Scenes[Play] = NewPlayScene(game, config)
|
||||
game.Scenes[Menu] = NewMenuScene(game, config)
|
||||
game.Scenes[Options] = NewOptionsScene(game, config)
|
||||
game.Scenes[Keybindings] = NewKeybindingsScene(game, config)
|
||||
|
||||
// setup environment
|
||||
ebiten.SetWindowSize(game.ScreenWidth, game.ScreenHeight)
|
||||
ebiten.SetWindowTitle("golsky - conway's game of life")
|
||||
ebiten.SetWindowResizingMode(ebiten.WindowResizingModeEnabled)
|
||||
ebiten.SetScreenClearedEveryFrame(true)
|
||||
|
||||
return game
|
||||
}
|
||||
|
||||
func (game *Game) GetCurrentScene() Scene {
|
||||
return game.Scenes[game.CurrentScene]
|
||||
}
|
||||
|
||||
func (game *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
|
||||
game.ReadlWidth = outsideWidth
|
||||
game.Scale = float32(game.ScreenWidth) / float32(outsideWidth)
|
||||
return game.ScreenWidth, game.ScreenHeight
|
||||
}
|
||||
|
||||
func (game *Game) Update() error {
|
||||
scene := game.GetCurrentScene()
|
||||
|
||||
if quit := scene.Update(); quit != nil {
|
||||
return quit
|
||||
}
|
||||
|
||||
next := scene.GetNext()
|
||||
if next != game.CurrentScene {
|
||||
game.Scenes[next].SetPrevious(game.CurrentScene)
|
||||
scene.ResetNext()
|
||||
game.CurrentScene = next
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (game *Game) Draw(screen *ebiten.Image) {
|
||||
// first draw primary scene[s], although there are only 1
|
||||
for current, scene := range game.Scenes {
|
||||
if scene.IsPrimary() {
|
||||
// primary scenes always draw
|
||||
scene.Draw(screen)
|
||||
|
||||
if current == game.CurrentScene {
|
||||
// avoid to redraw it in the next step
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scene := game.GetCurrentScene()
|
||||
scene.Draw(screen)
|
||||
}
|
||||
19
cmd/generics.go
Normal file
19
cmd/generics.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package cmd
|
||||
|
||||
// find an item in a list, generic variant
|
||||
func Contains[E comparable](s []E, v E) bool {
|
||||
for _, vs := range s {
|
||||
if v == vs {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func Exists[K comparable, V any](m map[K]V, v K) bool {
|
||||
if _, ok := m[v]; ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
383
cmd/grid.go
Normal file
383
cmd/grid.go
Normal file
@@ -0,0 +1,383 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"codeberg.org/scip/golsky/rle"
|
||||
)
|
||||
|
||||
// equals grid height, is being used to access grid elements and must be global
|
||||
var STRIDE int
|
||||
|
||||
type Neighbor struct {
|
||||
X, Y int
|
||||
}
|
||||
|
||||
type Grid struct {
|
||||
Data []uint8
|
||||
NeighborCount []int
|
||||
Neighbors [][]Neighbor
|
||||
Empty bool
|
||||
Config *Config
|
||||
Counter func(x, y int) uint8
|
||||
}
|
||||
|
||||
// Create new empty grid and allocate Data according to provided dimensions
|
||||
func NewGrid(config *Config) *Grid {
|
||||
STRIDE = config.Height
|
||||
if config.Width > config.Height {
|
||||
STRIDE = config.Width
|
||||
}
|
||||
|
||||
size := STRIDE * STRIDE
|
||||
|
||||
grid := &Grid{
|
||||
Data: make([]uint8, size),
|
||||
NeighborCount: make([]int, size),
|
||||
Neighbors: make([][]Neighbor, size),
|
||||
Empty: config.Empty,
|
||||
Config: config,
|
||||
}
|
||||
|
||||
// first setup the cells
|
||||
for y := 0; y < config.Height; y++ {
|
||||
for x := 0; x < config.Width; x++ {
|
||||
grid.Data[y+STRIDE*x] = 0
|
||||
}
|
||||
}
|
||||
|
||||
// in a second pass, collect positions to the neighbors of each cell
|
||||
for y := 0; y < config.Height; y++ {
|
||||
for x := 0; x < config.Width; x++ {
|
||||
grid.SetupNeighbors(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
if grid.Config.Wrap {
|
||||
grid.Counter = grid.CountNeighborsWrap
|
||||
} else {
|
||||
grid.Counter = grid.CountNeighbors
|
||||
}
|
||||
|
||||
return grid
|
||||
}
|
||||
|
||||
func (grid *Grid) SetupNeighbors(x, y int) {
|
||||
idx := 0
|
||||
|
||||
var neighbors []Neighbor
|
||||
|
||||
for nbgY := -1; nbgY < 2; nbgY++ {
|
||||
for nbgX := -1; nbgX < 2; nbgX++ {
|
||||
var col, row int
|
||||
|
||||
if grid.Config.Wrap {
|
||||
// In wrap mode we look at all the 8 neighbors surrounding us.
|
||||
// In case we are on an edge we'll look at the neighbor on the
|
||||
// other side of the grid, thus wrapping lookahead around
|
||||
// using the mod() function.
|
||||
col = (x + nbgX + grid.Config.Width) % grid.Config.Width
|
||||
row = (y + nbgY + grid.Config.Height) % grid.Config.Height
|
||||
|
||||
} else {
|
||||
// In traditional grid mode the edges are deadly
|
||||
if x+nbgX < 0 || x+nbgX >= grid.Config.Width || y+nbgY < 0 || y+nbgY >= grid.Config.Height {
|
||||
continue
|
||||
}
|
||||
|
||||
col = x + nbgX
|
||||
row = y + nbgY
|
||||
}
|
||||
|
||||
if col == x && row == y {
|
||||
continue
|
||||
}
|
||||
|
||||
neighbors = append(neighbors, Neighbor{X: col, Y: row})
|
||||
grid.NeighborCount[y+STRIDE*x]++
|
||||
idx++
|
||||
}
|
||||
}
|
||||
|
||||
grid.Neighbors[y+STRIDE*x] = neighbors
|
||||
}
|
||||
|
||||
func (grid *Grid) CountNeighborsWrap(x, y int) uint8 {
|
||||
var sum uint8
|
||||
|
||||
for nbgX := -1; nbgX < 2; nbgX++ {
|
||||
for nbgY := -1; nbgY < 2; nbgY++ {
|
||||
var col, row int
|
||||
|
||||
// In wrap mode we look at all the 8 neighbors surrounding us.
|
||||
// In case we are on an edge we'll look at the neighbor on the
|
||||
// other side of the grid, thus wrapping lookahead around
|
||||
// using the mod() function.
|
||||
col = (x + nbgX + grid.Config.Width) % grid.Config.Width
|
||||
row = (y + nbgY + grid.Config.Height) % grid.Config.Height
|
||||
|
||||
sum += grid.Data[row+STRIDE*col]
|
||||
}
|
||||
}
|
||||
|
||||
// don't count ourselfes though
|
||||
sum -= grid.Data[y+STRIDE*x]
|
||||
|
||||
return sum
|
||||
}
|
||||
|
||||
func (grid *Grid) CountNeighbors(x, y int) uint8 {
|
||||
var sum uint8
|
||||
|
||||
width := grid.Config.Width
|
||||
height := grid.Config.Height
|
||||
|
||||
for nbgX := -1; nbgX < 2; nbgX++ {
|
||||
for nbgY := -1; nbgY < 2; nbgY++ {
|
||||
var col, row int
|
||||
|
||||
xnbgX := x + nbgX
|
||||
ynbgY := y + nbgY
|
||||
|
||||
// In traditional grid mode the edges are deadly
|
||||
if xnbgX < 0 || xnbgX >= width || ynbgY < 0 || ynbgY >= height {
|
||||
continue
|
||||
}
|
||||
col = xnbgX
|
||||
row = ynbgY
|
||||
|
||||
sum += grid.Data[row+STRIDE*col]
|
||||
}
|
||||
}
|
||||
|
||||
// don't count ourselfes though
|
||||
sum -= grid.Data[y+STRIDE*x]
|
||||
|
||||
return sum
|
||||
}
|
||||
|
||||
// count the living neighbors of a cell
|
||||
func (grid *Grid) _CountNeighbors(x, y int) uint8 {
|
||||
var count uint8
|
||||
|
||||
pos := y + STRIDE*x
|
||||
neighbors := grid.Neighbors[pos]
|
||||
neighborCount := grid.NeighborCount[pos]
|
||||
|
||||
for idx := 0; idx < neighborCount; idx++ {
|
||||
neighbor := neighbors[idx]
|
||||
count += grid.Data[neighbor.Y+STRIDE*neighbor.X]
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
// Create a new 1:1 instance
|
||||
func (grid *Grid) Clone() *Grid {
|
||||
newgrid := &Grid{}
|
||||
|
||||
newgrid.Config = grid.Config
|
||||
newgrid.Data = grid.Data
|
||||
|
||||
return newgrid
|
||||
}
|
||||
|
||||
// copy data
|
||||
// func (grid *Grid) Copy(other *Grid) {
|
||||
// for y := range grid.Data {
|
||||
// for x := range grid.Data[y] {
|
||||
// other.Data[y+STRIDE*x] = grid.Data[y+STRIDE*x]
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// delete all contents
|
||||
// func (grid *Grid) Clear() {
|
||||
// for y := range grid.Data {
|
||||
// for x := range grid.Data[y] {
|
||||
// grid.Data[y+STRIDE*x] = 0
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// initialize with random life cells using the given density
|
||||
func (grid *Grid) FillRandom() {
|
||||
if !grid.Empty {
|
||||
for y := 0; y < grid.Config.Height; y++ {
|
||||
for x := 0; x < grid.Config.Width; x++ {
|
||||
if rand.Intn(grid.Config.Density) == 1 {
|
||||
grid.Data[y+STRIDE*x] = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (grid *Grid) Dump() {
|
||||
for y := 0; y < grid.Config.Height; y++ {
|
||||
for x := 0; x < grid.Config.Width; x++ {
|
||||
if grid.Data[y+STRIDE*x] == 1 {
|
||||
fmt.Print("XX")
|
||||
} else {
|
||||
fmt.Print(" ")
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
// initialize using a given RLE pattern
|
||||
func (grid *Grid) LoadRLE(pattern *rle.RLE) {
|
||||
if pattern != nil {
|
||||
startX := (grid.Config.Width / 2) - (pattern.Width / 2)
|
||||
startY := (grid.Config.Height / 2) - (pattern.Height / 2)
|
||||
var y, x int
|
||||
|
||||
for rowIndex, patternRow := range pattern.Pattern {
|
||||
for colIndex := range patternRow {
|
||||
if pattern.Pattern[rowIndex][colIndex] > 0 {
|
||||
x = colIndex + startX
|
||||
y = rowIndex + startY
|
||||
|
||||
grid.Data[y+STRIDE*x] = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//grid.Dump()
|
||||
}
|
||||
}
|
||||
|
||||
// load a lif file parameters like R and P are not supported yet
|
||||
func LoadLIF(filename string) (*rle.RLE, error) {
|
||||
fd, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(fd)
|
||||
|
||||
scanner.Split(bufio.ScanLines)
|
||||
|
||||
gothead := false
|
||||
|
||||
grid := &rle.RLE{}
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
items := strings.Split(line, "")
|
||||
|
||||
if len(items) < 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.Contains(line, "# r") {
|
||||
parts := strings.Split(line, " ")
|
||||
if len(parts) == 2 {
|
||||
grid.Rule = parts[1]
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if items[0] == "#" {
|
||||
if gothead {
|
||||
break
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
gothead = true
|
||||
|
||||
row := make([]int, len(items))
|
||||
|
||||
for idx, item := range items {
|
||||
switch item {
|
||||
case ".":
|
||||
row[idx] = 0
|
||||
case "o":
|
||||
fallthrough
|
||||
case "*":
|
||||
row[idx] = 1
|
||||
default:
|
||||
return nil, errors.New("cells must be . or o")
|
||||
}
|
||||
}
|
||||
|
||||
grid.Pattern = append(grid.Pattern, row)
|
||||
}
|
||||
|
||||
// sanity check the grid
|
||||
explen := 0
|
||||
rows := 0
|
||||
first := true
|
||||
for _, row := range grid.Pattern {
|
||||
length := len(row)
|
||||
|
||||
if first {
|
||||
explen = length
|
||||
first = false
|
||||
}
|
||||
|
||||
if explen != length {
|
||||
return nil, fmt.Errorf(
|
||||
fmt.Sprintf("all rows must be in the same length, got: %d, expected: %d",
|
||||
length, explen))
|
||||
}
|
||||
|
||||
rows++
|
||||
}
|
||||
|
||||
grid.Width = explen
|
||||
grid.Height = rows
|
||||
|
||||
return grid, nil
|
||||
}
|
||||
|
||||
// save the contents of the whole grid as a simple lif alike
|
||||
// file. One line per row, 0 for dead and 1 for life cell.
|
||||
// file format: https://conwaylife.com/wiki/Life_1.05
|
||||
func (grid *Grid) SaveState(filename, rule string) error {
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open state file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fmt.Fprintf(file, "#Life 1.05\n#R %s\n#D golsky state file\n#P -1 -1\n", rule)
|
||||
|
||||
for y := 0; y < grid.Config.Height; y++ {
|
||||
for x := 0; x < grid.Config.Width; x++ {
|
||||
row := "."
|
||||
if grid.Data[y+STRIDE*x] == 1 {
|
||||
row = "o"
|
||||
}
|
||||
|
||||
_, err := file.WriteString(row)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write to state file: %w", err)
|
||||
}
|
||||
}
|
||||
file.WriteString("\n")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// generate filenames for dumps
|
||||
func GetFilename(generations int64) string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("dump-%s-%d.lif", now.Format("20060102150405"), generations)
|
||||
}
|
||||
|
||||
func GetFilenameRLE(generations int64) string {
|
||||
now := time.Now()
|
||||
return fmt.Sprintf("rect-%s-%d.rle", now.Format("20060102150405"), generations)
|
||||
}
|
||||
98
cmd/keybindings.go
Normal file
98
cmd/keybindings.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
|
||||
"github.com/ebitenui/ebitenui"
|
||||
"github.com/ebitenui/ebitenui/widget"
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
||||
)
|
||||
|
||||
type SceneKeybindings struct {
|
||||
Game *Game
|
||||
Config *Config
|
||||
Next SceneName
|
||||
Prev SceneName
|
||||
Whoami SceneName
|
||||
Ui *ebitenui.UI
|
||||
FontColor color.RGBA
|
||||
First bool
|
||||
}
|
||||
|
||||
func NewKeybindingsScene(game *Game, config *Config) Scene {
|
||||
scene := &SceneKeybindings{
|
||||
Whoami: Keybindings,
|
||||
Game: game,
|
||||
Next: Keybindings,
|
||||
Config: config,
|
||||
FontColor: color.RGBA{255, 30, 30, 0xff},
|
||||
}
|
||||
|
||||
scene.Init()
|
||||
|
||||
return scene
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) GetNext() SceneName {
|
||||
return scene.Next
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) SetPrevious(prev SceneName) {
|
||||
scene.Prev = prev
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) ResetNext() {
|
||||
scene.Next = scene.Whoami
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) SetNext(next SceneName) {
|
||||
scene.Next = next
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) Update() error {
|
||||
scene.Ui.Update()
|
||||
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) || inpututil.IsKeyJustPressed(ebiten.KeyQ) {
|
||||
scene.Config.DelayedStart = false
|
||||
scene.Leave()
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) IsPrimary() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) Draw(screen *ebiten.Image) {
|
||||
scene.Ui.Draw(screen)
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) Leave() {
|
||||
scene.SetNext(Play)
|
||||
}
|
||||
|
||||
func (scene *SceneKeybindings) Init() {
|
||||
rowContainer := NewRowContainer("Key Bindings")
|
||||
|
||||
bindings := widget.NewText(
|
||||
widget.TextOpts.WidgetOpts(widget.WidgetOpts.LayoutData(widget.RowLayoutData{
|
||||
Stretch: true,
|
||||
})),
|
||||
widget.TextOpts.Text(KEYBINDINGS, *FontRenderer.FontSmall, color.NRGBA{0xdf, 0xf4, 0xff, 0xff}))
|
||||
|
||||
cancel := NewMenuButton("Back",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Leave()
|
||||
})
|
||||
|
||||
rowContainer.AddChild(bindings)
|
||||
rowContainer.AddChild(cancel)
|
||||
|
||||
scene.Ui = &ebitenui.UI{
|
||||
Container: rowContainer.Container(),
|
||||
}
|
||||
|
||||
}
|
||||
113
cmd/loader-fonts.go
Normal file
113
cmd/loader-fonts.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/golang/freetype/truetype"
|
||||
"github.com/tinne26/etxt"
|
||||
"golang.org/x/image/font"
|
||||
)
|
||||
|
||||
var FontRenderer = LoadFonts("assets/fonts")
|
||||
|
||||
const (
|
||||
GameFont string = "NotoSans-Regular"
|
||||
GameFontETXT string = "Noto Sans"
|
||||
FontSizeBig int = 48
|
||||
FontSizeNormal int = 24
|
||||
FontSizeSmall int = 12
|
||||
)
|
||||
|
||||
type Texter struct {
|
||||
Renderer *etxt.Renderer
|
||||
FontNormal *font.Face
|
||||
FontBig *font.Face
|
||||
FontSmall *font.Face
|
||||
}
|
||||
|
||||
func LoadFonts(dir string) Texter {
|
||||
// load the font for use with ebitenui
|
||||
fontbytes, err := assetfs.ReadFile(dir + "/" + GameFont + ".ttf")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
gamefont, err := truetype.Parse(fontbytes)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
gameface := truetype.NewFace(gamefont, &truetype.Options{
|
||||
Size: float64(FontSizeNormal),
|
||||
DPI: 72,
|
||||
Hinting: font.HintingFull,
|
||||
})
|
||||
|
||||
biggameface := truetype.NewFace(gamefont, &truetype.Options{
|
||||
Size: float64(FontSizeBig),
|
||||
DPI: 72,
|
||||
Hinting: font.HintingFull,
|
||||
})
|
||||
|
||||
smallgameface := truetype.NewFace(gamefont, &truetype.Options{
|
||||
Size: float64(FontSizeSmall),
|
||||
DPI: 72,
|
||||
Hinting: font.HintingFull,
|
||||
})
|
||||
|
||||
// load the font for use with etxt
|
||||
fontlib := etxt.NewFontLibrary()
|
||||
_, _, err = fontlib.ParseEmbedDirFonts(dir, assetfs)
|
||||
if err != nil {
|
||||
log.Fatalf("Error while loading fonts: %s", err.Error())
|
||||
}
|
||||
|
||||
/*
|
||||
err = fontlib.EachFont(
|
||||
func(fontName string, font *etxt.Font) error {
|
||||
fmt.Printf("font: %s\n", fontName)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
*/
|
||||
|
||||
if !fontlib.HasFont(GameFontETXT) {
|
||||
log.Fatal("missing font: " + GameFontETXT)
|
||||
}
|
||||
|
||||
err = fontlib.EachFont(checkMissingRunes)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
renderer := etxt.NewStdRenderer()
|
||||
|
||||
glyphsCache := etxt.NewDefaultCache(10 * 1024 * 1024) // 10MB
|
||||
renderer.SetCacheHandler(glyphsCache.NewHandler())
|
||||
renderer.SetFont(fontlib.GetFont(GameFontETXT))
|
||||
|
||||
return Texter{
|
||||
Renderer: renderer,
|
||||
FontNormal: &gameface,
|
||||
FontBig: &biggameface,
|
||||
FontSmall: &smallgameface,
|
||||
}
|
||||
}
|
||||
|
||||
// helper function used with FontLibrary.EachFont to make sure
|
||||
// all loaded fonts contain the characters or alphabet we want
|
||||
func checkMissingRunes(name string, font *etxt.Font) error {
|
||||
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
const symbols = "0123456789 .,;:!?-()[]{}_&#@"
|
||||
|
||||
missing, err := etxt.GetMissingRunes(font, letters+symbols)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
log.Fatalf("Font '%s' missing runes: %s", name, string(missing))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
49
cmd/loader-shaders.go
Normal file
49
cmd/loader-shaders.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"log/slog"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
)
|
||||
|
||||
type ShaderRegistry map[string]*ebiten.Shader
|
||||
|
||||
var Shaders = LoadShaders("assets/shaders")
|
||||
|
||||
func LoadShaders(dir string) ShaderRegistry {
|
||||
shaders := ShaderRegistry{}
|
||||
|
||||
entries, err := assetfs.ReadDir(dir)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to read shaders dir %s: %s", dir, err)
|
||||
}
|
||||
|
||||
for _, file := range entries {
|
||||
path := path.Join(dir, file.Name())
|
||||
fd, err := assetfs.Open(path)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to open shader file %s: %s", file.Name(), err)
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
name := strings.TrimSuffix(file.Name(), ".kg")
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(fd)
|
||||
|
||||
shader, err := ebiten.NewShader([]byte(buf.Bytes()))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
shaders[name] = shader
|
||||
|
||||
slog.Debug("loaded shader asset", "path", path)
|
||||
}
|
||||
|
||||
return shaders
|
||||
}
|
||||
69
cmd/loader-sprites.go
Normal file
69
cmd/loader-sprites.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"image"
|
||||
_ "image/png"
|
||||
"io/fs"
|
||||
"log"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
)
|
||||
|
||||
// Maps image name to image data
|
||||
type AssetRegistry map[string]*ebiten.Image
|
||||
|
||||
// A helper to pass the registry easier around
|
||||
type assetData struct {
|
||||
Registry AssetRegistry
|
||||
}
|
||||
|
||||
//go:embed assets/sprites/*.png assets/fonts/*.ttf assets/shaders/*.kg
|
||||
var assetfs embed.FS
|
||||
|
||||
// Called at build time, creates the global asset and animation registries
|
||||
var Assets = LoadImages("assets/sprites")
|
||||
|
||||
// load pngs and json files
|
||||
func LoadImages(dir string) AssetRegistry {
|
||||
Registry := AssetRegistry{}
|
||||
|
||||
// we use embed.FS to iterate over all files in ./assets/
|
||||
entries, err := assetfs.ReadDir(dir)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to read assets dir %s: %s", dir, err)
|
||||
}
|
||||
|
||||
for _, imagefile := range entries {
|
||||
path := path.Join(dir, imagefile.Name())
|
||||
|
||||
fd, err := assetfs.Open(path)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to open file %s: %s", imagefile.Name(), err)
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
switch {
|
||||
case strings.HasSuffix(path, ".png"):
|
||||
name, image := ReadImage(imagefile, fd)
|
||||
Registry[name] = image
|
||||
}
|
||||
}
|
||||
|
||||
return Registry
|
||||
}
|
||||
|
||||
func ReadImage(imagefile fs.DirEntry, fd fs.File) (string, *ebiten.Image) {
|
||||
name := strings.TrimSuffix(imagefile.Name(), ".png")
|
||||
|
||||
img, _, err := image.Decode(fd)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to decode image %s: %s", imagefile.Name(), err)
|
||||
}
|
||||
|
||||
image := ebiten.NewImageFromImage(img)
|
||||
|
||||
return name, image
|
||||
}
|
||||
145
cmd/menu.go
Normal file
145
cmd/menu.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
|
||||
"github.com/ebitenui/ebitenui"
|
||||
"github.com/ebitenui/ebitenui/widget"
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
||||
)
|
||||
|
||||
type SceneMenu struct {
|
||||
Game *Game
|
||||
Config *Config
|
||||
Next SceneName
|
||||
Prev SceneName
|
||||
Whoami SceneName
|
||||
Ui *ebitenui.UI
|
||||
FontColor color.RGBA
|
||||
First bool
|
||||
Exit bool
|
||||
}
|
||||
|
||||
func NewMenuScene(game *Game, config *Config) Scene {
|
||||
scene := &SceneMenu{
|
||||
Whoami: Menu,
|
||||
Game: game,
|
||||
Next: Menu,
|
||||
Config: config,
|
||||
FontColor: color.RGBA{255, 30, 30, 0xff},
|
||||
}
|
||||
|
||||
scene.Init()
|
||||
|
||||
return scene
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) GetNext() SceneName {
|
||||
return scene.Next
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) SetPrevious(prev SceneName) {
|
||||
scene.Prev = prev
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) ResetNext() {
|
||||
scene.Next = scene.Whoami
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) SetNext(next SceneName) {
|
||||
scene.Next = next
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) Update() error {
|
||||
scene.Ui.Update()
|
||||
|
||||
if scene.Exit {
|
||||
return ebiten.Termination
|
||||
}
|
||||
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) || inpututil.IsKeyJustPressed(ebiten.KeyQ) {
|
||||
scene.Config.DelayedStart = false
|
||||
scene.Leave()
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) IsPrimary() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) Draw(screen *ebiten.Image) {
|
||||
scene.Ui.Draw(screen)
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) Leave() {
|
||||
scene.SetNext(Play)
|
||||
}
|
||||
|
||||
func (scene *SceneMenu) Init() {
|
||||
rowContainer := NewRowContainer("Main Menu")
|
||||
|
||||
empty := NewMenuButton("Start with empty grid",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Config.Empty = true
|
||||
scene.Config.Restart = true
|
||||
scene.Leave()
|
||||
})
|
||||
|
||||
random := NewMenuButton("Start with random patterns",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Config.Empty = false
|
||||
scene.Config.Restart = true
|
||||
scene.Leave()
|
||||
})
|
||||
|
||||
copy := NewMenuButton("Save Copy as RLE",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Config.Markmode = true
|
||||
scene.Config.Paused = true
|
||||
scene.Leave()
|
||||
})
|
||||
|
||||
options := NewMenuButton("Options",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.SetNext(Options)
|
||||
})
|
||||
|
||||
bindings := NewMenuButton("Show Key Bindings",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.SetNext(Keybindings)
|
||||
})
|
||||
|
||||
separator1 := NewSeparator(3)
|
||||
separator2 := NewSeparator(3)
|
||||
separator3 := NewSeparator(10)
|
||||
|
||||
cancel := NewMenuButton("Back",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Leave()
|
||||
})
|
||||
|
||||
quit := NewMenuButton("Exit Golsky",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.Exit = true
|
||||
})
|
||||
|
||||
rowContainer.AddChild(empty)
|
||||
rowContainer.AddChild(random)
|
||||
rowContainer.AddChild(separator1)
|
||||
rowContainer.AddChild(options)
|
||||
rowContainer.AddChild(copy)
|
||||
rowContainer.AddChild(bindings)
|
||||
rowContainer.AddChild(separator2)
|
||||
rowContainer.AddChild(cancel)
|
||||
rowContainer.AddChild(separator3)
|
||||
rowContainer.AddChild(quit)
|
||||
|
||||
scene.Ui = &ebitenui.UI{
|
||||
Container: rowContainer.Container(),
|
||||
}
|
||||
|
||||
}
|
||||
157
cmd/options.go
Normal file
157
cmd/options.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
|
||||
"github.com/ebitenui/ebitenui"
|
||||
"github.com/ebitenui/ebitenui/widget"
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
||||
)
|
||||
|
||||
type SceneOptions struct {
|
||||
Game *Game
|
||||
Config *Config
|
||||
Next SceneName
|
||||
Prev SceneName
|
||||
Whoami SceneName
|
||||
Ui *ebitenui.UI
|
||||
FontColor color.RGBA
|
||||
}
|
||||
|
||||
func NewOptionsScene(game *Game, config *Config) Scene {
|
||||
scene := &SceneOptions{
|
||||
Whoami: Options,
|
||||
Game: game,
|
||||
Next: Options,
|
||||
Config: config,
|
||||
FontColor: color.RGBA{255, 30, 30, 0xff},
|
||||
}
|
||||
|
||||
scene.Init()
|
||||
|
||||
return scene
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) GetNext() SceneName {
|
||||
return scene.Next
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) SetPrevious(prev SceneName) {
|
||||
scene.Prev = prev
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) ResetNext() {
|
||||
scene.Next = scene.Whoami
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) SetNext(next SceneName) {
|
||||
scene.Next = next
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) IsPrimary() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) Update() error {
|
||||
scene.Ui.Update()
|
||||
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) || inpututil.IsKeyJustPressed(ebiten.KeyQ) {
|
||||
scene.SetNext(Play)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) Draw(screen *ebiten.Image) {
|
||||
scene.Ui.Draw(screen)
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) SetInitialValue(w *widget.LabeledCheckbox, value bool) {
|
||||
if value {
|
||||
w.SetState(
|
||||
widget.WidgetChecked,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *SceneOptions) Init() {
|
||||
rowContainer := NewRowContainer("Options")
|
||||
|
||||
pause := NewCheckbox("Pause",
|
||||
scene.Config.Paused,
|
||||
func(args *widget.CheckboxChangedEventArgs) {
|
||||
scene.Config.TogglePaused()
|
||||
})
|
||||
|
||||
debugging := NewCheckbox("Debugging",
|
||||
scene.Config.Debug,
|
||||
func(args *widget.CheckboxChangedEventArgs) {
|
||||
scene.Config.ToggleDebugging()
|
||||
})
|
||||
|
||||
gridlines := NewCheckbox("Show grid lines",
|
||||
scene.Config.ShowGrid,
|
||||
func(args *widget.CheckboxChangedEventArgs) {
|
||||
scene.Config.ToggleGridlines()
|
||||
})
|
||||
|
||||
evolution := NewCheckbox("Show evolution traces",
|
||||
scene.Config.ShowEvolution,
|
||||
func(args *widget.CheckboxChangedEventArgs) {
|
||||
scene.Config.ToggleEvolution()
|
||||
})
|
||||
|
||||
wrap := NewCheckbox("Wrap around edges",
|
||||
scene.Config.Wrap,
|
||||
func(args *widget.CheckboxChangedEventArgs) {
|
||||
scene.Config.ToggleWrap()
|
||||
})
|
||||
|
||||
themenames := make([]string, len(THEMES))
|
||||
i := 0
|
||||
for name := range THEMES {
|
||||
themenames[i] = name
|
||||
i++
|
||||
}
|
||||
|
||||
themes := NewCombobox(
|
||||
themenames,
|
||||
scene.Config.Theme,
|
||||
func(args *widget.ListComboButtonEntrySelectedEventArgs) {
|
||||
scene.Config.SwitchTheme(args.Entry.(ListEntry).Name)
|
||||
})
|
||||
|
||||
themelabel := NewLabel("Themes")
|
||||
combocontainer := NewColumnContainer()
|
||||
combocontainer.AddChild(themes)
|
||||
combocontainer.AddChild(themelabel)
|
||||
|
||||
separator := NewSeparator(3)
|
||||
separator2 := NewSeparator(3)
|
||||
|
||||
cancel := NewMenuButton("Close",
|
||||
func(args *widget.ButtonClickedEventArgs) {
|
||||
scene.SetNext(scene.Prev)
|
||||
})
|
||||
|
||||
rowContainer.AddChild(pause)
|
||||
rowContainer.AddChild(debugging)
|
||||
rowContainer.AddChild(gridlines)
|
||||
rowContainer.AddChild(evolution)
|
||||
rowContainer.AddChild(wrap)
|
||||
|
||||
rowContainer.AddChild(separator)
|
||||
|
||||
rowContainer.AddChild(combocontainer)
|
||||
|
||||
rowContainer.AddChild(separator2)
|
||||
|
||||
rowContainer.AddChild(cancel)
|
||||
|
||||
scene.Ui = &ebitenui.UI{
|
||||
Container: rowContainer.Container(),
|
||||
}
|
||||
|
||||
}
|
||||
712
cmd/play.go
Normal file
712
cmd/play.go
Normal file
@@ -0,0 +1,712 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"log"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
||||
"github.com/hajimehoshi/ebiten/v2/vector"
|
||||
"codeberg.org/scip/golsky/rle"
|
||||
"golang.org/x/image/math/f64"
|
||||
)
|
||||
|
||||
type Images struct {
|
||||
Black, White, Age1, Age2, Age3, Age4, Old *ebiten.Image
|
||||
}
|
||||
|
||||
const (
|
||||
DEBUG_FORMAT = "FPS: %0.2f, TPG: %d, M: %0.2fMB, Generations: %d\nScale: %.02f, Zoom: %d, Cam: %.02f,%.02f Cursor: %d,%d %s"
|
||||
)
|
||||
|
||||
type History struct {
|
||||
Age [][]int64
|
||||
}
|
||||
|
||||
func NewHistory(height, width int) History {
|
||||
hist := History{}
|
||||
|
||||
hist.Age = make([][]int64, height)
|
||||
for y := 0; y < height; y++ {
|
||||
hist.Age[y] = make([]int64, width)
|
||||
}
|
||||
|
||||
return hist
|
||||
}
|
||||
|
||||
type ScenePlay struct {
|
||||
Game *Game
|
||||
Config *Config
|
||||
Next SceneName
|
||||
Prev SceneName
|
||||
Whoami SceneName
|
||||
|
||||
Clear bool
|
||||
|
||||
Grids []*Grid // 2 grids: one current, one next
|
||||
History History // holds state of past dead cells for evolution traces
|
||||
Index int // points to current grid
|
||||
Generations int64 // Stats
|
||||
TicksElapsed int // tick counter for game speed
|
||||
Camera Camera // for zoom+move
|
||||
World, Cache *ebiten.Image // actual image we render to
|
||||
WheelTurned bool // when user turns wheel multiple times, zoom faster
|
||||
Dragging bool // middle mouse is pressed, move canvas
|
||||
LastCursorPos []float64 // used to check if the user is dragging
|
||||
MarkTaken bool // true when mouse1 pressed
|
||||
MarkDone bool // true when mouse1 released, copy cells between Mark+Point
|
||||
Mark, Point image.Point // area to marks+save
|
||||
RunOneStep bool // mutable flags from config
|
||||
TPG int // current game speed (ticks per game)
|
||||
Theme Theme
|
||||
RuleCheckFunc func(uint8, uint8) uint8
|
||||
}
|
||||
|
||||
func NewPlayScene(game *Game, config *Config) Scene {
|
||||
scene := &ScenePlay{
|
||||
Whoami: Play,
|
||||
Game: game,
|
||||
Next: Play,
|
||||
Config: config,
|
||||
TPG: config.TPG,
|
||||
RunOneStep: config.RunOneStep,
|
||||
}
|
||||
|
||||
scene.Init()
|
||||
|
||||
return scene
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) IsPrimary() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) GetNext() SceneName {
|
||||
return scene.Next
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) SetPrevious(prev SceneName) {
|
||||
scene.Prev = prev
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) ResetNext() {
|
||||
scene.Next = scene.Whoami
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) SetNext(next SceneName) {
|
||||
scene.Next = next
|
||||
}
|
||||
|
||||
/* The standard Scene of Life is symbolized in rule-string notation
|
||||
* as B3/S23 (23/3 here). A cell is born if it has exactly three
|
||||
* neighbors, survives if it has two or three living neighbors,
|
||||
* and dies otherwise.
|
||||
* we abbreviate the calculation: if state is 0 and 3 neighbors
|
||||
* are a life, check will be just 3. If the cell is alive, 9 will
|
||||
* be added to the life neighbors (to avoid a collision with the
|
||||
* result 3), which will be 11|12 in case of 2|3 life neighbors.
|
||||
*/
|
||||
func (scene *ScenePlay) CheckRuleB3S23(state uint8, neighbors uint8) uint8 {
|
||||
switch (9 * state) + neighbors {
|
||||
case 11:
|
||||
fallthrough
|
||||
case 12:
|
||||
fallthrough
|
||||
case 3:
|
||||
return Alive
|
||||
}
|
||||
|
||||
return Dead
|
||||
}
|
||||
|
||||
/*
|
||||
* The generic rule checker is able to calculate cell state for any
|
||||
* GOL rul, including B3/S23.
|
||||
*/
|
||||
func (scene *ScenePlay) CheckRuleGeneric(state uint8, neighbors uint8) uint8 {
|
||||
var nextstate uint8
|
||||
|
||||
if state != 1 && Contains(scene.Config.Rule.Birth, neighbors) {
|
||||
nextstate = Alive
|
||||
} else if state == 1 && Contains(scene.Config.Rule.Death, neighbors) {
|
||||
nextstate = Alive
|
||||
} else {
|
||||
nextstate = Dead
|
||||
}
|
||||
|
||||
return nextstate
|
||||
}
|
||||
|
||||
// Update all cells according to the current rule
|
||||
func (scene *ScenePlay) UpdateCells() {
|
||||
// count ticks so we know when to actually run
|
||||
scene.TicksElapsed++
|
||||
|
||||
if scene.TPG > scene.TicksElapsed {
|
||||
// need to sleep a little more
|
||||
return
|
||||
}
|
||||
|
||||
// next grid index, we just xor 0|1 to 1|0
|
||||
next := scene.Index ^ 1
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(scene.Config.Height)
|
||||
|
||||
width := scene.Config.Width
|
||||
height := scene.Config.Height
|
||||
|
||||
// compute life status of cells
|
||||
for y := 0; y < height; y++ {
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
for x := 0; x < width; x++ {
|
||||
state := scene.Grids[scene.Index].Data[y+STRIDE*x] // 0|1 == dead or alive
|
||||
neighbors := scene.Grids[scene.Index].Counter(x, y)
|
||||
|
||||
// actually apply the current rules
|
||||
nextstate := scene.RuleCheckFunc(state, neighbors)
|
||||
|
||||
// change state of current cell in next grid
|
||||
scene.Grids[next].Data[y+STRIDE*x] = nextstate
|
||||
|
||||
if scene.Config.ShowEvolution {
|
||||
// set history to current generation so we can infer the
|
||||
// age of the cell's state during rendering and use it to
|
||||
// deduce the color to use if evolution tracing is enabled
|
||||
// 60FPS:
|
||||
if state != nextstate {
|
||||
scene.History.Age[y][x] = scene.Generations
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// switch grid for rendering
|
||||
scene.Index ^= 1
|
||||
|
||||
// global stats counter
|
||||
scene.Generations++
|
||||
|
||||
if scene.Config.RunOneStep {
|
||||
// setp-wise mode, halt the game
|
||||
scene.Config.RunOneStep = false
|
||||
}
|
||||
|
||||
// reset speed counter
|
||||
scene.TicksElapsed = 0
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) Reset() {
|
||||
scene.Config.Paused = true
|
||||
scene.InitGrid()
|
||||
scene.Config.Paused = false
|
||||
}
|
||||
|
||||
// check user input
|
||||
func (scene *ScenePlay) CheckExit() error {
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyQ) {
|
||||
return ebiten.Termination
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) CheckInput() {
|
||||
// primary functions, always available
|
||||
switch {
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyEscape):
|
||||
scene.SetNext(Menu)
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyO):
|
||||
scene.SetNext(Options)
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyC):
|
||||
scene.Config.Markmode = true
|
||||
scene.Config.Drawmode = false
|
||||
scene.Config.Paused = true
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyI):
|
||||
scene.Config.Drawmode = true
|
||||
scene.Config.Paused = true
|
||||
}
|
||||
|
||||
if scene.Config.Markmode {
|
||||
// no need to check any more input in mark mode
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeySpace) || inpututil.IsKeyJustPressed(ebiten.KeyEnter):
|
||||
scene.Config.TogglePaused()
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyPageDown):
|
||||
if scene.TPG < 120 {
|
||||
scene.TPG++
|
||||
}
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyPageUp):
|
||||
if scene.TPG >= 1 {
|
||||
scene.TPG--
|
||||
}
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyS):
|
||||
scene.SaveState()
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyD):
|
||||
scene.Config.Debug = !scene.Config.Debug
|
||||
}
|
||||
|
||||
if scene.Config.Paused {
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyN) {
|
||||
scene.Config.RunOneStep = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) CheckDrawingInput() {
|
||||
if scene.Config.Drawmode {
|
||||
switch {
|
||||
case inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft):
|
||||
scene.ToggleCellOnCursorPos()
|
||||
case inpututil.IsKeyJustPressed(ebiten.KeyEscape):
|
||||
scene.Config.Drawmode = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check dragging input. move the canvas with the mouse while pressing
|
||||
// the middle mouse button, zoom in and out using the wheel.
|
||||
func (scene *ScenePlay) CheckDraggingInput() {
|
||||
if scene.Config.Markmode {
|
||||
return
|
||||
}
|
||||
|
||||
dragbutton := ebiten.MouseButtonLeft
|
||||
|
||||
if scene.Config.Drawmode {
|
||||
dragbutton = ebiten.MouseButtonMiddle
|
||||
}
|
||||
|
||||
// move canvas
|
||||
if scene.Dragging && !ebiten.IsMouseButtonPressed(dragbutton) {
|
||||
// release
|
||||
scene.Dragging = false
|
||||
}
|
||||
|
||||
if !scene.Dragging && ebiten.IsMouseButtonPressed(dragbutton) {
|
||||
// start dragging
|
||||
scene.Dragging = true
|
||||
scene.LastCursorPos[0], scene.LastCursorPos[1] = scene.Camera.ScreenToWorld(ebiten.CursorPosition())
|
||||
}
|
||||
|
||||
if scene.Dragging {
|
||||
x, y := scene.Camera.ScreenToWorld(ebiten.CursorPosition())
|
||||
|
||||
if x != scene.LastCursorPos[0] || y != scene.LastCursorPos[1] {
|
||||
// actually drag by mouse cursor pos diff to last cursor pos
|
||||
scene.Camera.Position[0] -= float64(x - scene.LastCursorPos[0])
|
||||
scene.Camera.Position[1] -= float64(y - scene.LastCursorPos[1])
|
||||
}
|
||||
|
||||
scene.LastCursorPos[0], scene.LastCursorPos[1] = scene.Camera.ScreenToWorld(ebiten.CursorPosition())
|
||||
}
|
||||
|
||||
// also support the arrow keys to move the canvas
|
||||
switch {
|
||||
case ebiten.IsKeyPressed(ebiten.KeyArrowLeft):
|
||||
scene.Camera.Position[0] -= 1
|
||||
case ebiten.IsKeyPressed(ebiten.KeyArrowRight):
|
||||
scene.Camera.Position[0] += 1
|
||||
case ebiten.IsKeyPressed(ebiten.KeyArrowUp):
|
||||
scene.Camera.Position[1] -= 1
|
||||
case ebiten.IsKeyPressed(ebiten.KeyArrowDown):
|
||||
scene.Camera.Position[1] += 1
|
||||
}
|
||||
|
||||
// Zoom
|
||||
_, dy := ebiten.Wheel()
|
||||
|
||||
if dy != 0 {
|
||||
scene.Camera.ZoomFactor += (int(dy) * 5)
|
||||
}
|
||||
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyR) {
|
||||
scene.Camera.Reset()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) GetWorldCursorPos() image.Point {
|
||||
worldX, worldY := scene.Camera.ScreenToWorld(ebiten.CursorPosition())
|
||||
return image.Point{
|
||||
X: int(worldX) / scene.Config.Cellsize,
|
||||
Y: int(worldY) / scene.Config.Cellsize,
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) CheckMarkInput() {
|
||||
if !scene.Config.Markmode {
|
||||
return
|
||||
}
|
||||
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
|
||||
scene.Config.Markmode = false
|
||||
}
|
||||
|
||||
if ebiten.IsMouseButtonPressed(ebiten.MouseButton0) {
|
||||
if !scene.MarkTaken {
|
||||
scene.Mark = scene.GetWorldCursorPos()
|
||||
scene.MarkTaken = true
|
||||
scene.MarkDone = false
|
||||
}
|
||||
|
||||
scene.Point = scene.GetWorldCursorPos()
|
||||
//fmt.Printf("Mark: %v, Point: %v\n", scene.Mark, scene.Point)
|
||||
} else if inpututil.IsMouseButtonJustReleased(ebiten.MouseButton0) {
|
||||
scene.Config.Markmode = false
|
||||
scene.MarkTaken = false
|
||||
scene.MarkDone = true
|
||||
|
||||
scene.SaveRectRLE()
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) SaveState() {
|
||||
filename := GetFilename(scene.Generations)
|
||||
err := scene.Grids[scene.Index].SaveState(filename, scene.Config.Rule.Definition)
|
||||
if err != nil {
|
||||
log.Printf("failed to save game state to %s: %s", filename, err)
|
||||
}
|
||||
log.Printf("saved game state to %s at generation %d\n", filename, scene.Generations)
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) SaveRectRLE() {
|
||||
filename := GetFilenameRLE(scene.Generations)
|
||||
|
||||
if scene.Mark.X == scene.Point.X || scene.Mark.Y == scene.Point.Y {
|
||||
log.Printf("can't save non-rectangle\n")
|
||||
return
|
||||
}
|
||||
|
||||
var width int
|
||||
var height int
|
||||
var startx int
|
||||
var starty int
|
||||
|
||||
if scene.Mark.X < scene.Point.X {
|
||||
// mark left point
|
||||
startx = scene.Mark.X
|
||||
width = scene.Point.X - scene.Mark.X
|
||||
} else {
|
||||
// mark right point
|
||||
startx = scene.Point.X
|
||||
width = scene.Mark.X - scene.Point.X
|
||||
}
|
||||
|
||||
if scene.Mark.Y < scene.Point.Y {
|
||||
// mark above point
|
||||
starty = scene.Mark.Y
|
||||
height = scene.Point.Y - scene.Mark.Y
|
||||
} else {
|
||||
// mark below point
|
||||
starty = scene.Point.Y
|
||||
height = scene.Mark.Y - scene.Point.Y
|
||||
}
|
||||
|
||||
grid := make([][]uint8, height)
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
grid[y] = make([]uint8, width)
|
||||
|
||||
for x := 0; x < width; x++ {
|
||||
grid[y][x] = scene.Grids[scene.Index].Data[(y+starty)+STRIDE*(x+startx)]
|
||||
}
|
||||
}
|
||||
|
||||
err := rle.StoreGridToRLE(grid, filename, scene.Config.Rule.Definition, width, height)
|
||||
if err != nil {
|
||||
log.Printf("failed to save rect to %s: %s\n", filename, err)
|
||||
} else {
|
||||
log.Printf("saved selected rect to %s at generation %d\n", filename, scene.Generations)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) Update() error {
|
||||
if scene.Config.Restart {
|
||||
scene.Config.Restart = false
|
||||
scene.Generations = 0
|
||||
scene.InitGrid()
|
||||
scene.InitCache()
|
||||
return nil
|
||||
}
|
||||
|
||||
if scene.Config.RestartCache {
|
||||
scene.Config.RestartCache = false
|
||||
scene.Theme = scene.Config.ThemeManager.GetCurrentTheme()
|
||||
scene.InitCache()
|
||||
return nil
|
||||
}
|
||||
|
||||
if quit := scene.CheckExit(); quit != nil {
|
||||
return quit
|
||||
}
|
||||
|
||||
scene.CheckInput()
|
||||
scene.CheckDrawingInput()
|
||||
scene.CheckDraggingInput()
|
||||
scene.CheckMarkInput()
|
||||
|
||||
if !scene.Config.Paused || scene.RunOneStep {
|
||||
scene.UpdateCells()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// set a cell to alive or dead
|
||||
func (scene *ScenePlay) ToggleCellOnCursorPos() {
|
||||
// use cursor pos relative to the world
|
||||
worldX, worldY := scene.Camera.ScreenToWorld(ebiten.CursorPosition())
|
||||
x := int(worldX) / scene.Config.Cellsize
|
||||
y := int(worldY) / scene.Config.Cellsize
|
||||
|
||||
if x > -1 && y > -1 && x < scene.Config.Width && y < scene.Config.Height {
|
||||
scene.Grids[scene.Index].Data[y+STRIDE*x] ^= 1
|
||||
scene.History.Age[y][x] = 1
|
||||
}
|
||||
}
|
||||
|
||||
// draw the new grid state
|
||||
func (scene *ScenePlay) Draw(screen *ebiten.Image) {
|
||||
// we fill the whole screen with a background color, the cells
|
||||
// themselfes will be 1px smaller as their nominal size, producing
|
||||
// a nice grey grid with grid lines
|
||||
op := &ebiten.DrawImageOptions{}
|
||||
|
||||
op.GeoM.Translate(0, 0)
|
||||
scene.World.DrawImage(scene.Cache, op)
|
||||
|
||||
for y := 0; y < scene.Config.Height; y++ {
|
||||
for x := 0; x < scene.Config.Width; x++ {
|
||||
op.GeoM.Reset()
|
||||
op.GeoM.Translate(
|
||||
float64(x*scene.Config.Cellsize),
|
||||
float64(y*scene.Config.Cellsize),
|
||||
)
|
||||
|
||||
if scene.Config.ShowEvolution {
|
||||
scene.DrawEvolution(screen, x, y, op)
|
||||
} else {
|
||||
if scene.Grids[scene.Index].Data[y+STRIDE*x] == 1 {
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColLife), op)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scene.DrawMark(scene.World)
|
||||
|
||||
scene.Camera.Render(scene.World, screen)
|
||||
|
||||
scene.DrawDebug(screen)
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) DrawEvolution(screen *ebiten.Image, x, y int, op *ebiten.DrawImageOptions) {
|
||||
age := scene.Generations - scene.History.Age[y][x]
|
||||
|
||||
switch scene.Grids[scene.Index].Data[y+STRIDE*x] {
|
||||
case Alive:
|
||||
if age > 50 && scene.Config.ShowEvolution {
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColOld), op)
|
||||
} else {
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColLife), op)
|
||||
}
|
||||
case Dead:
|
||||
// only draw dead cells in case evolution trace is enabled
|
||||
if scene.History.Age[y][x] > 1 && scene.Config.ShowEvolution {
|
||||
switch {
|
||||
case age < 10:
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColAge1), op)
|
||||
case age < 20:
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColAge2), op)
|
||||
case age < 30:
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColAge3), op)
|
||||
default:
|
||||
scene.World.DrawImage(scene.Theme.Tile(ColAge4), op)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) DrawMark(screen *ebiten.Image) {
|
||||
if scene.Config.Markmode && scene.MarkTaken {
|
||||
x := float32(scene.Mark.X * scene.Config.Cellsize)
|
||||
y := float32(scene.Mark.Y * scene.Config.Cellsize)
|
||||
w := float32((scene.Point.X - scene.Mark.X) * scene.Config.Cellsize)
|
||||
h := float32((scene.Point.Y - scene.Mark.Y) * scene.Config.Cellsize)
|
||||
|
||||
vector.StrokeRect(
|
||||
scene.World,
|
||||
x+1, y+1,
|
||||
w, h,
|
||||
1.0, scene.Theme.Color(ColOld), false,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) DrawDebug(screen *ebiten.Image) {
|
||||
if scene.Config.Debug {
|
||||
paused := ""
|
||||
if scene.Config.Paused {
|
||||
paused = "-- paused --"
|
||||
}
|
||||
|
||||
if scene.Config.Markmode {
|
||||
paused = "-- mark --"
|
||||
}
|
||||
|
||||
if scene.Config.Drawmode {
|
||||
paused = "-- insert --"
|
||||
}
|
||||
|
||||
x, y := ebiten.CursorPosition()
|
||||
debug := fmt.Sprintf(
|
||||
DEBUG_FORMAT,
|
||||
ebiten.ActualTPS(), scene.TPG, GetMem(), scene.Generations,
|
||||
scene.Game.Scale, scene.Camera.ZoomFactor,
|
||||
scene.Camera.Position[0], scene.Camera.Position[1],
|
||||
x, y,
|
||||
paused)
|
||||
|
||||
FontRenderer.Renderer.SetSizePx(10 + int(scene.Game.Scale*10))
|
||||
FontRenderer.Renderer.SetTarget(screen)
|
||||
|
||||
FontRenderer.Renderer.SetColor(scene.Theme.Color(ColLife))
|
||||
FontRenderer.Renderer.Draw(debug, 31, 31)
|
||||
|
||||
FontRenderer.Renderer.SetColor(scene.Theme.Color(ColOld))
|
||||
FontRenderer.Renderer.Draw(debug, 30, 30)
|
||||
|
||||
fmt.Println(debug)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// load a pre-computed pattern from RLE file
|
||||
func (scene *ScenePlay) InitPattern() {
|
||||
scene.Grids[0].LoadRLE(scene.Config.RLE)
|
||||
|
||||
// rule might have changed
|
||||
scene.InitRuleCheckFunc()
|
||||
}
|
||||
|
||||
// pre-render offscreen cache image
|
||||
func (scene *ScenePlay) InitCache() {
|
||||
// setup theme
|
||||
scene.Theme.SetGrid(scene.Config.ShowGrid)
|
||||
|
||||
if !scene.Config.ShowGrid {
|
||||
scene.Cache.Fill(scene.Theme.Color(ColDead))
|
||||
return
|
||||
}
|
||||
|
||||
op := &ebiten.DrawImageOptions{}
|
||||
|
||||
scene.Cache.Fill(scene.Theme.Color(ColGrid))
|
||||
|
||||
for y := 0; y < scene.Config.Height; y++ {
|
||||
for x := 0; x < scene.Config.Width; x++ {
|
||||
op.GeoM.Reset()
|
||||
op.GeoM.Translate(
|
||||
float64(x*scene.Config.Cellsize),
|
||||
float64(y*scene.Config.Cellsize),
|
||||
)
|
||||
|
||||
scene.Cache.DrawImage(scene.Theme.Tile(ColDead), op)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// initialize grid[s], either using pre-computed from state or rle file, or random
|
||||
func (scene *ScenePlay) InitGrid() {
|
||||
grida := NewGrid(scene.Config)
|
||||
gridb := NewGrid(scene.Config)
|
||||
|
||||
// startup is delayed until user has selected options
|
||||
grida.FillRandom()
|
||||
|
||||
scene.Grids = []*Grid{
|
||||
grida,
|
||||
gridb,
|
||||
}
|
||||
|
||||
scene.History = NewHistory(scene.Config.Height, scene.Config.Width)
|
||||
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) Init() {
|
||||
// setup the scene
|
||||
scene.Camera = Camera{
|
||||
ViewPort: f64.Vec2{
|
||||
float64(scene.Config.ScreenWidth),
|
||||
float64(scene.Config.ScreenHeight),
|
||||
},
|
||||
InitialZoomFactor: scene.Config.Zoomfactor,
|
||||
InitialPosition: f64.Vec2{
|
||||
scene.Config.InitialCamPos[0],
|
||||
scene.Config.InitialCamPos[1],
|
||||
},
|
||||
ZoomOutFactor: scene.Config.ZoomOutFactor,
|
||||
}
|
||||
|
||||
scene.World = ebiten.NewImage(
|
||||
scene.Config.Width*scene.Config.Cellsize,
|
||||
scene.Config.Height*scene.Config.Cellsize,
|
||||
)
|
||||
|
||||
scene.Cache = ebiten.NewImage(
|
||||
scene.Config.Width*scene.Config.Cellsize,
|
||||
scene.Config.Height*scene.Config.Cellsize,
|
||||
)
|
||||
|
||||
scene.Theme = scene.Config.ThemeManager.GetCurrentTheme()
|
||||
scene.InitCache()
|
||||
|
||||
if scene.Config.DelayedStart && !scene.Config.Empty {
|
||||
// do not fill the grid when the main menu comes up first, the
|
||||
// user decides interactively what to do
|
||||
scene.Config.Empty = true
|
||||
scene.InitGrid()
|
||||
scene.Config.Empty = false
|
||||
} else {
|
||||
scene.InitGrid()
|
||||
}
|
||||
|
||||
scene.InitPattern()
|
||||
|
||||
scene.Index = 0
|
||||
scene.TicksElapsed = 0
|
||||
|
||||
scene.LastCursorPos = make([]float64, 2)
|
||||
|
||||
if scene.Config.Zoomfactor < 0 || scene.Config.Zoomfactor > 0 {
|
||||
scene.Camera.ZoomFactor = scene.Config.Zoomfactor
|
||||
}
|
||||
|
||||
scene.Camera.Setup()
|
||||
}
|
||||
|
||||
func bool2int(b bool) int {
|
||||
return int(*(*byte)(unsafe.Pointer(&b)))
|
||||
}
|
||||
|
||||
func (scene *ScenePlay) InitRuleCheckFunc() {
|
||||
if scene.Config.Rule.Definition == "B3/S23" {
|
||||
scene.RuleCheckFunc = scene.CheckRuleB3S23
|
||||
} else {
|
||||
scene.RuleCheckFunc = scene.CheckRuleGeneric
|
||||
}
|
||||
}
|
||||
52
cmd/rule.go
Normal file
52
cmd/rule.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// a GOL rule
|
||||
type Rule struct {
|
||||
Definition string
|
||||
Birth []uint8
|
||||
Death []uint8
|
||||
}
|
||||
|
||||
// parse one part of a GOL rule into rule slice
|
||||
func NumbersToList(numbers string) []uint8 {
|
||||
list := []uint8{}
|
||||
|
||||
items := strings.Split(numbers, "")
|
||||
for _, item := range items {
|
||||
num, err := strconv.Atoi(item)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to parse game rule part <%s>: %s", numbers, err)
|
||||
}
|
||||
|
||||
list = append(list, uint8(num))
|
||||
}
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
// parse GOL rule, used in CheckRule()
|
||||
func ParseGameRule(rule string) *Rule {
|
||||
parts := strings.Split(rule, "/")
|
||||
|
||||
if len(parts) < 2 {
|
||||
log.Fatalf("Invalid game rule <%s>", rule)
|
||||
}
|
||||
|
||||
golrule := &Rule{Definition: rule}
|
||||
|
||||
for _, part := range parts {
|
||||
if part[0] == 'B' {
|
||||
golrule.Birth = NumbersToList(part[1:])
|
||||
} else {
|
||||
golrule.Death = NumbersToList(part[1:])
|
||||
}
|
||||
}
|
||||
|
||||
return golrule
|
||||
}
|
||||
28
cmd/scene.go
Normal file
28
cmd/scene.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package cmd
|
||||
|
||||
import "github.com/hajimehoshi/ebiten/v2"
|
||||
|
||||
// Wrapper for different screens to be shown, as Welcome, Options,
|
||||
// About, Menu Level and of course the actual game
|
||||
// Scenes are responsible for screen clearing! That way a scene is able
|
||||
// to render its content onto the running level, e.g. the options scene
|
||||
// etc.
|
||||
|
||||
type SceneName int
|
||||
|
||||
type Scene interface {
|
||||
SetNext(SceneName)
|
||||
GetNext() SceneName
|
||||
SetPrevious(SceneName)
|
||||
ResetNext()
|
||||
Update() error
|
||||
Draw(screen *ebiten.Image)
|
||||
IsPrimary() bool // if true, this scene will be always drawn
|
||||
}
|
||||
|
||||
const (
|
||||
Menu = iota // main top level menu
|
||||
Play // actual playing happens here
|
||||
Options
|
||||
Keybindings
|
||||
)
|
||||
11
cmd/system.go
Normal file
11
cmd/system.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package cmd
|
||||
|
||||
import "runtime"
|
||||
|
||||
// returns current memory usage in MB
|
||||
func GetMem() float64 {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
|
||||
return float64(m.Alloc) / 1024 / 1024
|
||||
}
|
||||
189
cmd/theme.go
Normal file
189
cmd/theme.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image/color"
|
||||
"log"
|
||||
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/vector"
|
||||
)
|
||||
|
||||
// Color definitions. ColLife could be black or white depending on theme
|
||||
const (
|
||||
ColLife = iota
|
||||
ColDead
|
||||
ColOld
|
||||
ColAge1
|
||||
ColAge2
|
||||
ColAge3
|
||||
ColAge4
|
||||
ColGrid
|
||||
)
|
||||
|
||||
// A Theme defines how the grid and the cells are colored. We define
|
||||
// the colors and the actual tile images here, so that they are
|
||||
// readily available from play.go
|
||||
type Theme struct {
|
||||
Tiles map[int]*ebiten.Image
|
||||
GridTiles map[int]*ebiten.Image
|
||||
Colors map[int]color.RGBA
|
||||
Name string
|
||||
ShowGrid bool
|
||||
}
|
||||
|
||||
type ThemeDef struct {
|
||||
life, dead, grid, old, age1, age2, age3, age4 string
|
||||
}
|
||||
|
||||
var THEMES = map[string]ThemeDef{
|
||||
"standard": {
|
||||
life: "e15f0b",
|
||||
dead: "5a5a5a",
|
||||
old: "ff1e1e",
|
||||
grid: "808080",
|
||||
age3: "6c6059",
|
||||
age2: "735f52",
|
||||
age1: "7b5e4b",
|
||||
age4: "635d59",
|
||||
},
|
||||
"dark": {
|
||||
life: "c8c8c8",
|
||||
dead: "000000",
|
||||
old: "ff1e1e",
|
||||
grid: "808080",
|
||||
age1: "522600",
|
||||
age2: "422300",
|
||||
age3: "2b1b00",
|
||||
age4: "191100",
|
||||
},
|
||||
"light": {
|
||||
life: "000000",
|
||||
dead: "c8c8c8",
|
||||
old: "ff1e1e",
|
||||
grid: "808080",
|
||||
age1: "ffc361",
|
||||
age2: "ffd38c",
|
||||
age3: "ffe3b5",
|
||||
age4: "fff0e0",
|
||||
},
|
||||
}
|
||||
|
||||
// create a new theme
|
||||
func NewTheme(def ThemeDef, cellsize int, name string) Theme {
|
||||
theme := Theme{
|
||||
Name: name,
|
||||
Colors: map[int]color.RGBA{
|
||||
ColLife: HexColor2RGBA(def.life),
|
||||
ColDead: HexColor2RGBA(def.dead),
|
||||
ColGrid: HexColor2RGBA(def.grid),
|
||||
ColAge1: HexColor2RGBA(def.age1),
|
||||
ColAge2: HexColor2RGBA(def.age2),
|
||||
ColAge3: HexColor2RGBA(def.age3),
|
||||
ColAge4: HexColor2RGBA(def.age4),
|
||||
ColOld: HexColor2RGBA(def.old),
|
||||
},
|
||||
}
|
||||
|
||||
theme.Tiles = make(map[int]*ebiten.Image, 6)
|
||||
theme.GridTiles = make(map[int]*ebiten.Image, 6)
|
||||
|
||||
for cid, col := range theme.Colors {
|
||||
theme.Tiles[cid] = ebiten.NewImage(cellsize, cellsize)
|
||||
FillCell(theme.Tiles[cid], cellsize, col, 0)
|
||||
|
||||
theme.GridTiles[cid] = ebiten.NewImage(cellsize, cellsize)
|
||||
FillCell(theme.GridTiles[cid], cellsize, col, 1)
|
||||
}
|
||||
|
||||
return theme
|
||||
}
|
||||
|
||||
// return the tile image for the requested color type. panic if
|
||||
// unknown type is being used, which is ok, since the code is the only
|
||||
// user anyway
|
||||
func (theme *Theme) Tile(col int) *ebiten.Image {
|
||||
if theme.ShowGrid {
|
||||
return theme.GridTiles[col]
|
||||
}
|
||||
|
||||
return theme.Tiles[col]
|
||||
}
|
||||
|
||||
func (theme *Theme) Color(col int) color.RGBA {
|
||||
return theme.Colors[col]
|
||||
}
|
||||
|
||||
func (theme *Theme) SetGrid(showgrid bool) {
|
||||
theme.ShowGrid = showgrid
|
||||
}
|
||||
|
||||
type ThemeManager struct {
|
||||
Theme string
|
||||
Themes map[string]Theme
|
||||
}
|
||||
|
||||
// Manager is used to easily switch themes from cli or menu
|
||||
func NewThemeManager(initial string, cellsize int) ThemeManager {
|
||||
manager := ThemeManager{
|
||||
Theme: initial,
|
||||
}
|
||||
|
||||
manager.Themes = make(map[string]Theme, len(THEMES))
|
||||
|
||||
for name, def := range THEMES {
|
||||
manager.Themes[name] = NewTheme(def, cellsize, name)
|
||||
}
|
||||
|
||||
return manager
|
||||
}
|
||||
|
||||
func (manager *ThemeManager) GetCurrentTheme() Theme {
|
||||
return manager.Themes[manager.Theme]
|
||||
}
|
||||
|
||||
func (manager *ThemeManager) GetCurrentThemeName() string {
|
||||
return manager.Theme
|
||||
}
|
||||
|
||||
func (manager *ThemeManager) SetCurrentTheme(theme string) {
|
||||
if Exists(manager.Themes, theme) {
|
||||
manager.Theme = theme
|
||||
}
|
||||
}
|
||||
|
||||
// Fill a cell with the given color.
|
||||
//
|
||||
// We do not draw the cell at 0,0 of it's position but at 1,1. This
|
||||
// creates a top and lef transparent. By using a different background
|
||||
// for the whole grid we can then decide wether to show grid lines or
|
||||
// not.
|
||||
//
|
||||
// If no gridlines are selected the background will just be filled
|
||||
// with the DEAD color. However, IF we are to show the gridlines, we
|
||||
// fill it with a lighter color. The transparent edges of all tiles
|
||||
// then create the grid.
|
||||
//
|
||||
// So we don't draw a grid, we just left a grid behind, which saves us
|
||||
// from a lot of drawing operations.
|
||||
func FillCell(tile *ebiten.Image, cellsize int, col color.RGBA, x int) {
|
||||
vector.DrawFilledRect(
|
||||
tile,
|
||||
float32(x),
|
||||
float32(x),
|
||||
float32(cellsize),
|
||||
float32(cellsize),
|
||||
col, false,
|
||||
)
|
||||
}
|
||||
|
||||
func HexColor2RGBA(hex string) color.RGBA {
|
||||
var r, g, b uint8
|
||||
|
||||
_, err := fmt.Sscanf(hex, "%02x%02x%02x", &r, &g, &b)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to parse hex color: %s", err)
|
||||
}
|
||||
|
||||
return color.RGBA{r, g, b, 255}
|
||||
}
|
||||
305
cmd/widgets.go
Normal file
305
cmd/widgets.go
Normal file
@@ -0,0 +1,305 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
|
||||
"github.com/ebitenui/ebitenui/image"
|
||||
"github.com/ebitenui/ebitenui/widget"
|
||||
)
|
||||
|
||||
func NewMenuButton(
|
||||
text string,
|
||||
action func(args *widget.ButtonClickedEventArgs)) *widget.Button {
|
||||
|
||||
buttonImage, _ := LoadButtonImage()
|
||||
|
||||
return widget.NewButton(
|
||||
widget.ButtonOpts.WidgetOpts(
|
||||
widget.WidgetOpts.LayoutData(widget.RowLayoutData{
|
||||
Position: widget.RowLayoutPositionCenter,
|
||||
Stretch: true,
|
||||
MaxWidth: 200,
|
||||
MaxHeight: 100,
|
||||
}),
|
||||
),
|
||||
|
||||
widget.ButtonOpts.Image(buttonImage),
|
||||
|
||||
widget.ButtonOpts.Text(text, *FontRenderer.FontSmall, &widget.ButtonTextColor{
|
||||
Idle: color.NRGBA{0xdf, 0xf4, 0xff, 0xff},
|
||||
}),
|
||||
|
||||
widget.ButtonOpts.TextPadding(widget.Insets{
|
||||
Left: 5,
|
||||
Right: 5,
|
||||
Top: 5,
|
||||
Bottom: 5,
|
||||
}),
|
||||
|
||||
widget.ButtonOpts.ClickedHandler(action),
|
||||
)
|
||||
}
|
||||
|
||||
func NewCheckbox(
|
||||
text string,
|
||||
initialvalue bool,
|
||||
action func(args *widget.CheckboxChangedEventArgs)) *widget.LabeledCheckbox {
|
||||
|
||||
checkboxImage, _ := LoadCheckboxImage()
|
||||
buttonImage, _ := LoadButtonImage()
|
||||
|
||||
var state widget.WidgetState
|
||||
if initialvalue {
|
||||
state = widget.WidgetChecked
|
||||
}
|
||||
|
||||
return widget.NewLabeledCheckbox(
|
||||
widget.LabeledCheckboxOpts.CheckboxOpts(
|
||||
widget.CheckboxOpts.ButtonOpts(
|
||||
widget.ButtonOpts.Image(buttonImage),
|
||||
),
|
||||
widget.CheckboxOpts.Image(checkboxImage),
|
||||
widget.CheckboxOpts.StateChangedHandler(action),
|
||||
widget.CheckboxOpts.InitialState(state),
|
||||
),
|
||||
widget.LabeledCheckboxOpts.LabelOpts(
|
||||
widget.LabelOpts.Text(text, *FontRenderer.FontSmall,
|
||||
&widget.LabelColor{
|
||||
Idle: color.NRGBA{0xdf, 0xf4, 0xff, 0xff},
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func NewSeparator(padding int) widget.PreferredSizeLocateableWidget {
|
||||
c := widget.NewContainer(
|
||||
widget.ContainerOpts.Layout(widget.NewRowLayout(
|
||||
widget.RowLayoutOpts.Direction(widget.DirectionVertical),
|
||||
widget.RowLayoutOpts.Padding(widget.Insets{
|
||||
Top: padding,
|
||||
Bottom: 0,
|
||||
}))),
|
||||
widget.ContainerOpts.WidgetOpts(
|
||||
widget.WidgetOpts.LayoutData(
|
||||
widget.RowLayoutData{Stretch: true})))
|
||||
return c
|
||||
}
|
||||
|
||||
type ListEntry struct {
|
||||
id int
|
||||
Name string
|
||||
}
|
||||
|
||||
func NewCombobox(items []string, selected string,
|
||||
action func(args *widget.ListComboButtonEntrySelectedEventArgs)) *widget.ListComboButton {
|
||||
buttonImage, _ := LoadButtonImage()
|
||||
|
||||
entries := make([]any, 0, len(items))
|
||||
idxselected := 0
|
||||
for i, item := range items {
|
||||
entries = append(entries, ListEntry{i, item})
|
||||
if items[i] == selected {
|
||||
idxselected = i
|
||||
}
|
||||
}
|
||||
|
||||
comboBox := widget.NewListComboButton(
|
||||
widget.ListComboButtonOpts.SelectComboButtonOpts(
|
||||
widget.SelectComboButtonOpts.ComboButtonOpts(
|
||||
//Set the max height of the dropdown list
|
||||
widget.ComboButtonOpts.MaxContentHeight(150),
|
||||
//Set the parameters for the primary displayed button
|
||||
widget.ComboButtonOpts.ButtonOpts(
|
||||
widget.ButtonOpts.Image(buttonImage),
|
||||
widget.ButtonOpts.TextPadding(widget.NewInsetsSimple(5)),
|
||||
widget.ButtonOpts.Text("", *FontRenderer.FontSmall, &widget.ButtonTextColor{
|
||||
Idle: color.White,
|
||||
Disabled: color.White,
|
||||
}),
|
||||
widget.ButtonOpts.WidgetOpts(
|
||||
//Set how wide the button should be
|
||||
widget.WidgetOpts.MinSize(50, 0),
|
||||
//Set the combobox's position
|
||||
widget.WidgetOpts.LayoutData(widget.AnchorLayoutData{
|
||||
HorizontalPosition: widget.AnchorLayoutPositionCenter,
|
||||
VerticalPosition: widget.AnchorLayoutPositionCenter,
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
widget.ListComboButtonOpts.ListOpts(
|
||||
//Set how wide the dropdown list should be
|
||||
widget.ListOpts.ContainerOpts(
|
||||
widget.ContainerOpts.WidgetOpts(widget.WidgetOpts.MinSize(50, 0)),
|
||||
),
|
||||
//Set the entries in the list
|
||||
widget.ListOpts.Entries(entries),
|
||||
widget.ListOpts.ScrollContainerOpts(
|
||||
//Set the background images/color for the dropdown list
|
||||
widget.ScrollContainerOpts.Image(&widget.ScrollContainerImage{
|
||||
Idle: image.NewNineSliceColor(color.NRGBA{100, 100, 100, 255}),
|
||||
Disabled: image.NewNineSliceColor(color.NRGBA{100, 100, 100, 255}),
|
||||
Mask: image.NewNineSliceColor(color.NRGBA{100, 100, 100, 255}),
|
||||
}),
|
||||
),
|
||||
widget.ListOpts.SliderOpts(
|
||||
//Set the background images/color for the background of the slider track
|
||||
widget.SliderOpts.Images(&widget.SliderTrackImage{
|
||||
Idle: image.NewNineSliceColor(color.NRGBA{100, 100, 100, 255}),
|
||||
Hover: image.NewNineSliceColor(color.NRGBA{100, 100, 100, 255}),
|
||||
}, buttonImage),
|
||||
widget.SliderOpts.MinHandleSize(5),
|
||||
//Set how wide the track should be
|
||||
widget.SliderOpts.TrackPadding(widget.NewInsetsSimple(2))),
|
||||
//Set the font for the list options
|
||||
widget.ListOpts.EntryFontFace(*FontRenderer.FontSmall),
|
||||
//Set the colors for the list
|
||||
widget.ListOpts.EntryColor(&widget.ListEntryColor{
|
||||
Selected: color.NRGBA{254, 255, 255, 255},
|
||||
Unselected: color.NRGBA{254, 255, 255, 255},
|
||||
SelectedBackground: HexColor2RGBA(THEMES["standard"].life),
|
||||
SelectedFocusedBackground: HexColor2RGBA(THEMES["standard"].old),
|
||||
FocusedBackground: HexColor2RGBA(THEMES["standard"].old),
|
||||
DisabledUnselected: HexColor2RGBA(THEMES["standard"].grid),
|
||||
DisabledSelected: HexColor2RGBA(THEMES["standard"].grid),
|
||||
DisabledSelectedBackground: HexColor2RGBA(THEMES["standard"].grid),
|
||||
}),
|
||||
//Padding for each entry
|
||||
widget.ListOpts.EntryTextPadding(widget.NewInsetsSimple(5)),
|
||||
),
|
||||
//Define how the entry is displayed
|
||||
widget.ListComboButtonOpts.EntryLabelFunc(
|
||||
func(e any) string {
|
||||
//Button Label function, visible if not open
|
||||
return e.(ListEntry).Name
|
||||
},
|
||||
func(e any) string {
|
||||
//List Label function, visible items if open
|
||||
return e.(ListEntry).Name
|
||||
}),
|
||||
//Callback when a new entry is selected
|
||||
widget.ListComboButtonOpts.EntrySelectedHandler(action),
|
||||
)
|
||||
|
||||
//Select the middle entry -- optional
|
||||
comboBox.SetSelectedEntry(entries[idxselected])
|
||||
|
||||
return comboBox
|
||||
}
|
||||
|
||||
func NewLabel(text string) *widget.Text {
|
||||
return widget.NewText(
|
||||
widget.TextOpts.Text(text, *FontRenderer.FontSmall, color.White),
|
||||
widget.TextOpts.Position(widget.TextPositionCenter, widget.TextPositionCenter),
|
||||
widget.TextOpts.WidgetOpts(
|
||||
widget.WidgetOpts.LayoutData(widget.RowLayoutData{
|
||||
Position: widget.RowLayoutPositionCenter,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
/////////////// containers
|
||||
|
||||
type RowContainer struct {
|
||||
Root *widget.Container
|
||||
Row *widget.Container
|
||||
}
|
||||
|
||||
func (container *RowContainer) AddChild(child widget.PreferredSizeLocateableWidget) {
|
||||
container.Row.AddChild(child)
|
||||
}
|
||||
|
||||
func (container *RowContainer) Container() *widget.Container {
|
||||
return container.Root
|
||||
}
|
||||
|
||||
// set arg to false if no background needed
|
||||
func NewRowContainer(title string) *RowContainer {
|
||||
buttonImageHover := image.NewNineSlice(Assets["button-9slice3"], [3]int{3, 3, 3}, [3]int{3, 3, 3})
|
||||
|
||||
uiContainer := widget.NewContainer(
|
||||
widget.ContainerOpts.Layout(widget.NewAnchorLayout()),
|
||||
)
|
||||
|
||||
titleLabel := widget.NewText(
|
||||
widget.TextOpts.WidgetOpts(widget.WidgetOpts.LayoutData(widget.RowLayoutData{
|
||||
Stretch: true,
|
||||
})),
|
||||
widget.TextOpts.Text(title, *FontRenderer.FontNormal, color.NRGBA{0xdf, 0xf4, 0xff, 0xff}))
|
||||
|
||||
rowContainer := widget.NewContainer(
|
||||
widget.ContainerOpts.WidgetOpts(
|
||||
widget.WidgetOpts.LayoutData(widget.AnchorLayoutData{
|
||||
HorizontalPosition: widget.AnchorLayoutPositionCenter,
|
||||
VerticalPosition: widget.AnchorLayoutPositionCenter,
|
||||
}),
|
||||
),
|
||||
widget.ContainerOpts.Layout(widget.NewRowLayout(
|
||||
widget.RowLayoutOpts.Direction(widget.DirectionVertical),
|
||||
widget.RowLayoutOpts.Padding(widget.NewInsetsSimple(8)),
|
||||
widget.RowLayoutOpts.Spacing(0),
|
||||
)),
|
||||
widget.ContainerOpts.BackgroundImage(buttonImageHover),
|
||||
)
|
||||
|
||||
rowContainer.AddChild(titleLabel)
|
||||
|
||||
uiContainer.AddChild(rowContainer)
|
||||
|
||||
return &RowContainer{
|
||||
Root: uiContainer,
|
||||
Row: rowContainer,
|
||||
}
|
||||
}
|
||||
|
||||
func NewColumnContainer() *widget.Container {
|
||||
colcontainer := widget.NewContainer(
|
||||
widget.ContainerOpts.Layout(
|
||||
widget.NewGridLayout(
|
||||
widget.GridLayoutOpts.Columns(2),
|
||||
widget.GridLayoutOpts.Spacing(5, 0),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
return colcontainer
|
||||
}
|
||||
|
||||
func LoadButtonImage() (*widget.ButtonImage, error) {
|
||||
idle := image.NewNineSlice(Assets["button-9slice2"], [3]int{3, 3, 3}, [3]int{3, 3, 3})
|
||||
hover := image.NewNineSlice(Assets["button-9slice3"], [3]int{3, 3, 3}, [3]int{3, 3, 3})
|
||||
pressed := image.NewNineSlice(Assets["button-9slice1"], [3]int{3, 3, 3}, [3]int{3, 3, 3})
|
||||
|
||||
return &widget.ButtonImage{
|
||||
Idle: idle,
|
||||
Hover: hover,
|
||||
Pressed: pressed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadComboLabelImage() *widget.ButtonImageImage {
|
||||
return &widget.ButtonImageImage{
|
||||
Idle: Assets["checkbox-9slice2"],
|
||||
Disabled: Assets["checkbox-9slice2"],
|
||||
}
|
||||
}
|
||||
|
||||
func LoadCheckboxImage() (*widget.CheckboxGraphicImage, error) {
|
||||
unchecked := &widget.ButtonImageImage{
|
||||
Idle: Assets["checkbox-9slice2"],
|
||||
Disabled: Assets["checkbox-9slice2"],
|
||||
}
|
||||
|
||||
checked := &widget.ButtonImageImage{
|
||||
Idle: Assets["checkbox-9slice1"],
|
||||
Disabled: Assets["checkbox-9slice1"],
|
||||
}
|
||||
|
||||
return &widget.CheckboxGraphicImage{
|
||||
Checked: checked,
|
||||
Unchecked: unchecked,
|
||||
Greyed: unchecked,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user