blooblib/run.go

114 lines
2.3 KiB
Go

package bloob
import (
_ "embed"
"fmt"
"github.com/veandco/go-sdl2/sdl"
"time"
)
type Runnable interface {
Init(settings *Settings)
Render(screen *Image)
Update(bloob *Bloob)
}
type Settings struct {
WindowSize Vec2i
Scale int
TargetFps int
Title string
}
type Bloob struct {
MousePos Vec2i
Cursor *Image
}
var DefaultCursor *Image
//go:embed "cursor.png"
var defaultCursorBytes []byte
func Run(game Runnable) {
_ = sdl.Init(sdl.INIT_EVERYTHING)
defer sdl.Quit()
settings := Settings{
WindowSize: Vec2i{X: 640, Y: 360},
Scale: 3,
TargetFps: 60,
Title: "Blooblib",
}
if DefaultCursor == nil {
DefaultCursor = LoadImageBytes(defaultCursorBytes)
}
bloob := Bloob{
Cursor: DefaultCursor,
}
game.Init(&settings)
window, _ := sdl.CreateWindow(
settings.Title,
sdl.WINDOWPOS_CENTERED,
sdl.WINDOWPOS_CENTERED,
int32(settings.WindowSize.X*settings.Scale),
int32(settings.WindowSize.Y*settings.Scale),
sdl.WINDOW_SHOWN,
)
surface, _ := window.GetSurface()
windowImage := NewImageFromPointer(surface.Data(), MulScalar(settings.WindowSize, settings.Scale))
screen := NewImage(settings.WindowSize)
screen.Alpha = false
sdl.ShowCursor(sdl.DISABLE)
_ = window.UpdateSurface()
lastSecond := time.Now()
framesSinceLastSecond := 0
targetFPS := 60
frameDuration := time.Second / time.Duration(targetFPS)
lastFrame := lastSecond
running := true
for running {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event := event.(type) {
case sdl.QuitEvent:
running = false
break
case sdl.MouseMotionEvent:
bloob.MousePos.X = int(event.X) / settings.Scale
bloob.MousePos.Y = int(event.Y) / settings.Scale
break
}
}
now := time.Now()
delta := now.Sub(lastSecond)
if delta.Seconds() >= 1.0 {
fmt.Printf("FPS: %5d | mspf: %f\n", framesSinceLastSecond, 1000.0/float32(framesSinceLastSecond))
framesSinceLastSecond = 0
lastSecond = lastSecond.Add(time.Second)
}
delta2 := now.Sub(lastFrame)
if delta2 >= frameDuration {
game.Update(&bloob)
game.Render(screen)
if bloob.Cursor != nil {
screen.Draw(bloob.Cursor, bloob.MousePos)
}
windowImage.DrawUpscale(screen)
framesSinceLastSecond += 1
lastFrame = lastFrame.Add(frameDuration)
}
_ = window.UpdateSurface()
}
}