Share
Embed
Transcript
146 slides
-
Prerequisite ✅ Go 1.18 (we need generics) ✅ Ebitengine ✅
Legendary tolerance for my English Please ⭐ both Ebitengine and Godot projects :3 2 -
About $username • Compiler engineer during the day • Game
developer during the night • I also stream random indie games from itch io • Played video games since ~2000 I worked with Game Maker, Godot and Ebiten. I also tried Defold and Phaser. 3 -
My published games • Autotanks • Retrowave City • Decipherism
(GameOff 2022 game jam submission) 15 -
Ebitengine vs Godot impressions Cons: • It’s much harder to
become productive 18 -
Ebitengine vs Godot impressions Cons: • It’s much harder to
become productive • Much smaller community 19 -
Ebitengine vs Godot impressions Cons: • It’s much harder to
become productive • Much smaller community • Ebiten provides no “framework” to shape your game 20 -
Ebitengine vs Godot impressions Cons: • It’s much harder to
become productive • Much smaller community • Ebiten provides no “framework” to shape your game • The ecosystem is not mature enough 21 -
Ebitengine vs Godot impressions Pros: • Go as a first-class
language • Full go toolchain benefits: tests, benchmarks, profiling 24 -
Ebitengine vs Godot impressions Pros: • Go as a first-class
language • Full go toolchain benefits: tests, benchmarks, profiling • You can help the ecosystem to get better 25 -
You need more than just Ebitengine Ebitengine Input Nodes/ECS Res.
manager Math utils Collisions Slots/signals UI Layers Camera Tiles Scripting Prem ium content! $$$ 27 -
Some core ideas • Port the code and ideas from
Godot (C++ -> Go) 28 -
Some core ideas • Port the code and ideas from
Godot (C++ -> Go) • Start from the simpler, small games 29 -
Some core ideas • Port the code and ideas from
Godot (C++ -> Go) • Start from the simpler, small games • Browse awesome-ebiten for packages and inspiration 30 -
Why many Go gamedev libs are not mature? In my
opinion: • They’re created to solve a specific task at the moment of the game creation • Most lib authors are interested in creating games, not libraries 31 -
Some other issues • Libraries don’t play well together •
It’s hard to become the #1 library 32 -
Some other issues • Libraries don’t play well together •
It’s hard to become the #1 library 33 -
Vec2 use cases • Velocity, force and other vector-like units
• Simple positions, points in space (X, Y) 36 -
Vec2 use cases • Velocity, force and other vector-like units
• Simple positions, points in space (X, Y) • Normalized (unit) vectors for directions 37 -
Why float64 • Float literals in Go imply float64 type
• Go math library works with float64 • Most ebiten APIs work with float64 Only GPU-related things may require float32 39 -
Why float64 • Float literals in Go imply float64 type
• Go math library works with float64 • Most ebiten APIs work with float64 Only GPU-related things may require float32 40 -
Why float64 • Float literals in Go imply float64 type
• Go math library works with float64 • Most ebiten APIs work with float64 Only GPU-related things may require float32 41 -
Vec2 representation kvartborg/vector uses slices to represent vectors. This is
not efficient because most vectors in 2D game have exactly 2 components. Godot is open-source, you can roll the implementation based on its source code. 42 -
Vec2 representation kvartborg/vector uses slices to represent vectors. This is
not efficient because most vectors in 2D game have exactly 2 components. Godot is open-source, you can roll the implementation based on its source code. 43 -
gmath library github.com/quasilyte/gmath Vec2, radians and other gamedev math helpers.
Inspired by Godot math library. 44 -
type Button struct { Pos Vec2 } type Container struct
{ Pos Vec2 } How about simple vectors for UI elements position? 46 -
type Tank struct { Pos Vec2 } type Turret struct
{ Pos Vec2 } And for the other game objects as well... 48 -
Position requirements • Small size • Can express a position
with offset • Can automatically follow other position (parent) Some positions are still going to be Vec2 50 -
Position requirements • Small size • Can express a position
with offset • Can automatically follow other position (parent) Some positions are still going to be Vec2 51 -
Position requirements • Small size • Can express a position
with offset • Can automatically follow other position (parent) Some positions are still going to be Vec2 52 -
Pointers for the (one-sided) data binding • Data source: a
value owner, read+write • Pointer to data: read-only We can combine both to get a more flexible concept. 53 -
type Pos struct { Base *Vec2 // The position origin
or (0, 0) if nil Offset Vec2 // The offset in relation to the origin } func (p Pos) Resolve() Vec2 { if p.Base == nil { return p.Offset } return p.Base.Add(p.Offset) } 54 -
type Pos struct { Base *Vec2 // The position origin
or (0, 0) if nil Offset Vec2 // The offset in relation to the origin } func (p Pos) Resolve() Vec2 { if p.Base == nil { return p.Offset } return p.Base.Add(p.Offset) } 55 -
type Tank struct { Pos Vec2 } type Turret struct
{ - Pos Vec2 + Pos Pos } 56 -
func (p Pos) WithOffset(ox, oy float64) Pos { ox +=
p.Offset.X oy += p.Offset.Y return Pos{ Base: p.Base, Offset: Vec2{X: ox, Y: oy}, } } 60 -
Why signals & slots? • Reduces objects coupling • An
elegant event listener solution for Go 63 -
Why signals & slots? • Reduces objects coupling • An
elegant event listener solution for Go • Familiar concept (Godot, Phaser, Qt, …) 64 -
In Go terms • Signal = a field inside a
struct 65 -
In Go terms • Signal = a field inside a
struct • Slot = a function bound to a signal 66 -
In Go terms • Signal = a field inside a
struct • Slot = a function bound to a signal • Disconnect = remove bound function 67 -
In Go terms • Signal = a field inside a
struct • Slot = a function bound to a signal • Disconnect = remove bound function • Emit = call all bound functions 68 -
type Event[T any] struct { handlers []eventHandler[T] } type eventHandler[T
any] struct { c connection f func(T) } type connection interface { IsDisposed() bool } 69 -
type Event[T any] struct { handlers []eventHandler[T] } type eventHandler[T
any] struct { c connection f func(T) } type connection interface { IsDisposed() bool } 70 -
type Event[T any] struct { handlers []eventHandler[T] } type eventHandler[T
any] struct { c connection f func(T) } type connection interface { IsDisposed() bool } 71 -
func (e *Event[T]) Connect(conn connection, slot func(T)) { e.handlers =
append(e.handlers, eventHandler[T]{ c: conn, f: slot, }) } 72 -
func (e *Event[T]) Disconnect(conn connection) { for i, h :=
range e.handlers { if h.c == conn { e.handlers[i].c = theRemovedConnection break } } } 73 -
type removedConnection struct{} func (r *removedConnection) IsDisposed() bool { return
true } var theRemovedConnection = &removedConnection{} 74 -
func (e *Event[T]) Emit(arg T) { handlers := e.handlers[:0] for
_, h := range e.handlers { if h.c != nil && h.c.IsDisposed() { continue // effectively removes the handler } h.f(arg) handlers = append(handlers, h) } e.handlers = handlers } 75 -
func (s *state) NewVessel() *Vessel { v := newVessel() v.EventDestroyed.Connect(s.onVesselDestroyed)
return v } func (s *state) onVesselDestroyed(v *Vessel) {} 77 -
EventN vs Event[tuple] With EventN multiple-arg signals are more elegant.
With tuples we get more code reusability. 80 -
func ConnectOneShot[T any](e *Event[T], c connection, f func(T)) { oneshot
:= &oneshotConnector[T]{conn: c} e.Connect(oneshot, func(arg T) { oneshot.fired = true f(arg) }) } 81 -
type oneshotConnector[T any] struct { conn connection fired bool }
func (c *oneshotConnector[T]) IsDisposed() bool { if c.fired { return true } return c.conn != nil && c.conn.IsDisposed() } 82 -
Implementation properties • Tiny overhead and no allocs with 0
connections • Statically typed signatures without interface{} 85 -
Implementation properties • Tiny overhead and no allocs with 0
connections • Statically typed signatures without interface{} • Fast connect+emit 86 -
Implementation properties • Tiny overhead and no allocs with 0
connections • Statically typed signatures without interface{} • Fast connect+emit • Not thread-safe 87 -
Why tuples? • Make things like Event[T] viable • Abstract
away the arity in generic code Go doesn’t have variadic templates, so we need a way to overcome this limitation 89 -
Why tuples? • Make things like Event[T] viable • Abstract
away the arity in generic code Go doesn’t have variadic templates, so we need a way to overcome this limitation 90 -
type Value2[T1 any, T2 any] struct { First T1 Second
T2 } func New2[T1 any, T2 any](a T1, b T2) Value2[T1, T2] { return Value2[T1, T2]{a, b} } 91 -
type Value3[T1 any, T2 any, T3 any] struct { First
T1 Second T2 Third T3 } func New3[T1 any, T2 any, T3 any](...) Value2[T1, T2, T3] { return Value3[T1, T2, T3]{a, b, c} } 92 -
func (v Value2[T1, T2]) Fields() (T1, T2) { return v.First,
v.Second } func (v Value3[T1, T2, T3]) Fields() (T1, T2, T3) { return v.First, v.Second, v.Third } 93 -
// Tuple creation tup := tuple.New2(10, "quasilyte") // Tuple destructuring
id, username := tup.Fields() 94 -
Keymap requirements • Input-device agnostic • Supports N-to-M action-key mapping
• Multi-device support (gamepads, etc.) 98 -
Keymap requirements • Input-device agnostic • Supports N-to-M action-key mapping
• Multi-device support (gamepads, etc.) • Can be conveniently reconfigured at run time 99 -
if inpututil.IsKeyJustPressed(ebiten.KeyW) { obj.moveForward() } if obj.input.IsActionJustPressed(MoveForward) { obj.moveForward() }
The exact key and input method is abstracted away 101 -
if inpututil.IsKeyJustPressed(ebiten.KeyW) { obj.moveForward() } if obj.input.IsActionJustPressed(MoveForward) { obj.moveForward() }
ID-bound input handlers instead of global input system 102 -
Action can be associated with multiple input events Key W
Arrow Up ActionForward D-Pad Up 103 -
Every input handler has its ID (useful for gamepads) Player
2 Gamepad 2 Player 1 Gamepad 1 Handler{ID:1} Handler{ID:0} 104 -
All handlers are connected to some shared “global input system”
InputSystem Handler{ID:1} Handler{ID:0} 105 -
type Handler struct { id int keymap Keymap sys *System
} func (sys *System) NewHandler(id int, k Keymap) *Handler { return &Handler{ id: id, keymap: k, sys: sys, } } 106 -
type Action uint32 type Keymap map[Action][]Key type Key struct {
code int kind keyKind } 107 -
type Action uint32 type Keymap map[Action][]Key type Key struct {
code int kind keyKind } type keyKind uint8 const ( keyKeyboard keyKind = iota keyGamepad keyMouse ) 108 -
var KeyW = Key{ code: int(ebiten.KeyW), kind: keyKeyboard, } var
KeyGamepadUp = Key{ code: int(ebiten.StandardGamepadButtonLeftTop), kind: keyGamepad, } 109 -
var keymap = Keymap{ ActionForward: { KeyW, KeyArrowUp, KeyGamepadUp, },
} inputHandler := isys.NewHandler(0, keymap) 111 -
func (h *Handler) ActionIsJustPressed(action Action) bool { keys, ok :=
h.keymap[action] if !ok { return false } for _, k := range keys { if h.keyIsJustPressed(k) { return true } } return false } 112 -
func (h *Handler) keyIsJustPressed(key Key) bool { switch key.kind {
case keyGamepad: return h.gamepadKeyIsPressed(key) case keyMouse: return h.mouseKeyIsJustPressed(key) default: return h.keyboardKeyIsJustPressed(key) } } 113 -
func (h *Handler) gamepadKeyIsJustPressed(key Key) bool { return inpututil.IsStandardGamepadButtonJustPressed( ebiten.GamepadID(h.id),
ebiten.StandardGamepadButton(key.code), ) } 114 -
Resource loader requirements • Convenient to use to get resources
• Efficient resource lookup and caching 118 -
Resource loader requirements • Convenient to use to get resources
• Efficient resource lookup and caching • API that can prevent some mistyped keys, etc. 119 -
Resource loader requirements • Convenient to use to get resources
• Efficient resource lookup and caching • API that can prevent some mistyped keys, etc. • Can preload resources (+ optionally unload them) 120 -
Typed, integer resource keys type AudioID int type ImageID int
type FontID int 121 -
App enumerates all its resources as enums const ( ImageNone
resource.ImageID = iota ImageTank ImageTurret ) 122 -
...and then associates metadata with them imageResources := map[resource.ImageID]resource.ImageInfo{ ImageTank:
{Path: "sprites/tank.png"}, ImageTurret: {Path: "sprites/turret.png"}, } 123 -
Getting a resource is easy tankImage := loader.GetImage(ImageTank) turretImage :=
loader.GetImage(ImageTurret) 124 -
Resource lookup 1. Find associated metadata a. Return from cache,
if possible 2. Using path info, use asset finder to get raw data 3. Decode data into requested resource 4. Cache the result 5. Return the result 125 -
Asset finder can work with embed data loader.OpenAsset = func(p
string) io.ReadCloser { f, err := gameAssets.Open("_assets/" + p) if err != nil { // handle error } return f } 126 -
Resource preload Just call Get() method on the resource needed
and ignore the results. The next time it’ll be returned from cache. 128 -
Why bother and avoid global state? • Easier to test
your code 130 -
Why bother and avoid global state? • Easier to test
your code • Can substitute dependencies easier 131 -
Why bother and avoid global state? • Easier to test
your code • Can substitute dependencies easier • Scene transitions become trivial 132 -
if inpututil.IsKeyJustPressed(ebiten.KeyW) { obj.moveForward() } if obj.input.IsActionJustPressed(MoveForward) { obj.moveForward() }
Remember this? How obj gets its input handler? 133 -
main() runGame(state) newMenuController(state) newBattleController(state) newPlayerTank(tank, state) Creates the gameState Accepts
gameState as argument All scene controllers hold the gameState On scene change, gameState is passed The scene controller passes it to objects 134 -
type gameState struct { player1input *input.Handler player2input *input.Handler // +
other common game state } 135 -
// This is just a simplified example. func main() {
p1keymap, p2keymap := readKeymaps() state := newGameState() state.player1input = input.NewHandler(0, p1keymap) state.player2input = input.NewHandler(1, p2keymap) runGame(state) } 136 -
Tiled use cases Tiled can be your graphical level editor!
• Object layers to deploy game entities • Tile layers to draw the level landscape • Can also be used to prototype the UI layouts • Tilesets for auto-tiling 139 -
Tiled + modders Non-programmers can use tiled to create levels
for your game. A special triggers tileset can be used to apply visual programming, leveraging the Tiled limitations. 141 -
Things I still try to figure out • Layers and
rendering order abstractions • Viewports and cameras with Ebitengine • Smooth rendering of geometrical shapes • Etc, etc. 143 -
Additional resources • sfxr (or jsfxr) - generate game sound
effects • ccmixter - find CC licensed music for your games I want to try using neural network generated images and music in one of my next games. :) 145