Compare commits

...

9 Commits

Author SHA1 Message Date
e90bea4513 ebiten: convert view-map 2019-12-30 00:51:20 +00:00
c54ead71f3 ebiten: convert view-menu 2019-12-29 23:47:22 +00:00
7475bdf0e7 ebiten: convert view-set 2019-12-29 20:41:41 +00:00
77202d9fab ui: Add fps, tps display 2019-12-29 20:34:07 +00:00
32b722ae88 ebiten: Convert view-minimap 2019-12-29 19:44:36 +00:00
1403580167 build: use a $(GOBUILD) 2019-12-29 19:44:26 +00:00
51e066ade1 ui: run in background 2019-12-29 19:41:20 +00:00
d1a1c50afc ui: event handlers 2019-12-29 17:30:21 +00:00
6f605aa502 ebiten: convert view-obj 2019-12-29 15:38:49 +00:00
12 changed files with 638 additions and 812 deletions

View File

@@ -1,30 +1,32 @@
srcfiles = $(shell find . -iname *.go)
srcfiles = Makefile $(shell find . -iname *.go)
GOBUILD ?= go build
all: loader palette-idx view-obj view-map view-menu view-minimap view-set wh40k
loader: $(srcfiles)
go build -o loader ur.gs/ordoor/cmd/loader
$(GOBUILD) -o loader ur.gs/ordoor/cmd/loader
palette-idx: $(srcfiles)
go build -o palette-idx ur.gs/ordoor/cmd/palette-idx
$(GOBUILD) -o palette-idx ur.gs/ordoor/cmd/palette-idx
view-obj: $(srcfiles)
go build -o view-obj ur.gs/ordoor/cmd/view-obj
$(GOBUILD) -o view-obj ur.gs/ordoor/cmd/view-obj
view-map: $(srcfiles)
go build -o view-map ur.gs/ordoor/cmd/view-map
$(GOBUILD) -o view-map ur.gs/ordoor/cmd/view-map
view-menu: $(srcfiles)
go build -o view-menu ur.gs/ordoor/cmd/view-menu
$(GOBUILD) -o view-menu ur.gs/ordoor/cmd/view-menu
view-minimap: $(srcfiles)
go build -o view-minimap ur.gs/ordoor/cmd/view-minimap
$(GOBUILD) -o view-minimap ur.gs/ordoor/cmd/view-minimap
view-set: $(srcfiles)
go build -o view-set ur.gs/ordoor/cmd/view-set
$(GOBUILD) -o view-set ur.gs/ordoor/cmd/view-set
wh40k: $(srcfiles)
go build -o wh40k ur.gs/ordoor/cmd/wh40k
$(GOBUILD) -o wh40k ur.gs/ordoor/cmd/wh40k
clean:
rm -f loader view-obj view-map view-minimap view-set wh40k

View File

@@ -3,15 +3,13 @@ package main
import (
"flag"
"fmt"
"image"
"log"
"math"
"os"
"path/filepath"
"time"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/conv"
"ur.gs/ordoor/internal/data"
@@ -30,23 +28,16 @@ type env struct {
gameMap *maps.GameMap
set *sets.MapSet
objects map[string]*conv.Object
sprites map[string][]*pixel.Sprite
batch *pixel.Batch
step int
state state
lastState state
}
type state struct {
env *env
step int
fpsTicker <-chan time.Time
cam pixel.Matrix
camPos pixel.Vec
zoom float64
rot float64
zIdx int
zoom float64
origin image.Point
zIdx int
}
func main() {
@@ -69,69 +60,67 @@ func main() {
log.Fatalf("Couldn't load set file %s: %v", setFile, err)
}
rawObjs := []*data.Object{}
objects := make([]*conv.Object, 0, len(mapSet.Palette))
for _, name := range mapSet.Palette {
objFile := filepath.Join(*gamePath, "Obj", name+".obj")
obj, err := data.LoadObject(objFile)
rawObj, err := data.LoadObject(objFile)
if err != nil {
log.Fatalf("Failed to load %s: %v", name, err)
}
obj.Name = name
rawObjs = append(rawObjs, obj)
rawObj.Name = name
obj, err := conv.ConvertObject(rawObj, name)
if err != nil {
log.Fatal(err)
}
objects = append(objects, obj)
}
objects, spritesheet := conv.ConvertObjects(rawObjs)
batch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
state := state{
zoom: 1.0,
origin: image.Point{0, -3000}, // FIXME: haxxx
}
env := &env{
gameMap: gameMap,
set: mapSet,
objects: conv.MapByName(objects),
batch: batch,
gameMap: gameMap,
set: mapSet,
objects: conv.MapByName(objects),
state: state,
lastState: state,
}
// The main thread now belongs to pixelgl
pixelgl.Run(env.run)
}
func (e *env) run() {
title := "View Map " + *mapFile
win, err := ui.NewWindow(title + " | FPS: ?")
win, err := ui.NewWindow("View Map " + *mapFile)
if err != nil {
log.Fatal("Couldn't create window: %v", err)
}
pWin := win.PixelWindow
state := &state{
env: e,
// camPos: pixel.V(0, float64(-pWin.Bounds().Size().Y)),
// camPos: pixel.V(float64(3700), float64(0)),
zoom: 1.0,
rot: 0.785,
step: -1,
fpsTicker: time.Tick(time.Second),
// TODO: click to view cell data
win.OnKeyUp(ebiten.KeyLeft, env.changeOrigin(+64, +0))
win.OnKeyUp(ebiten.KeyRight, env.changeOrigin(-64, +0))
win.OnKeyUp(ebiten.KeyUp, env.changeOrigin(+0, +64))
win.OnKeyUp(ebiten.KeyDown, env.changeOrigin(+0, -64))
win.OnMouseWheel(env.changeZoom)
for i := 0; i <= 6; i++ {
win.OnKeyUp(ebiten.Key1+ebiten.Key(i), env.setZIdx(i))
}
pWin.SetSmooth(true)
win.Run(func() {
oldState := *state
state = state.runStep(pWin)
if err := win.Run(env.Update, env.Draw); err != nil {
log.Fatal(err)
}
}
if oldState != *state || oldState.step == -1 {
log.Printf("zoom=%.2f rot=%.4f zIdx=%v camPos=%#v", state.zoom, state.rot, state.zIdx, state.camPos)
state.present(pWin)
}
func (e *env) Update() error {
if e.step == 0 || e.lastState != e.state {
log.Printf("zoom=%.2f zIdx=%v camPos=%#v", e.state.zoom, e.state.zIdx, e.state.origin)
}
state.step += 1
select {
case <-state.fpsTicker:
pWin.SetTitle(fmt.Sprintf("%s | FPS: %d", title, state.step))
state.step = 0
default:
}
e.lastState = e.state
e.step += 1
})
return nil
}
func (e *env) getSprite(palette []string, ref maps.ObjRef) (*conv.Sprite, error) {
@@ -158,63 +147,52 @@ func (e *env) getSprite(palette []string, ref maps.ObjRef) (*conv.Sprite, error)
return obj.Sprites[ref.Sprite()], nil
}
func (s *state) present(pWin *pixelgl.Window) {
pWin.Clear(colornames.Black)
s.env.batch.Clear()
center := pWin.Bounds().Center()
cam := pixel.IM
cam = cam.ScaledXY(center, pixel.Vec{1.0, -1.0}) // invert the Y axis
cam = cam.Scaled(center, s.zoom) // apply current zoom factor
cam = cam.Moved(center.Sub(s.camPos)) // Make it central
s.cam = cam
pWin.SetMatrix(cam)
func (e *env) Draw(screen *ebiten.Image) error {
// TODO: we should be able to perform bounds clipping on these
minX := int(s.env.gameMap.MinWidth)
maxX := int(s.env.gameMap.MaxWidth)
minY := int(s.env.gameMap.MinLength)
maxY := int(s.env.gameMap.MaxLength)
minX := int(e.gameMap.MinWidth)
maxX := int(e.gameMap.MaxWidth)
minY := int(e.gameMap.MinLength)
maxY := int(e.gameMap.MaxLength)
minZ := 0
maxZ := int(s.zIdx) + 1
maxZ := int(e.state.zIdx) + 1
for z := minZ; z < maxZ; z++ {
for y := minY; y < maxY; y++ {
for x := minX; x < maxX; x++ {
s.renderCell(x, y, z, s.env.batch)
if err := e.renderCell(x, y, z, screen); err != nil {
return err
}
}
}
}
s.env.batch.Draw(pWin)
pWin.Update()
return nil
}
func (s *state) renderCell(x, y, z int, target pixel.Target) {
func (e *env) renderCell(x, y, z int, screen *ebiten.Image) error {
var sprites []*conv.Sprite
cell := s.env.gameMap.Cells.At(x, y, z)
cell := e.gameMap.Cells.At(x, y, z)
if spr, err := s.env.getSprite(s.env.set.Palette, cell.Surface); err != nil {
if spr, err := e.getSprite(e.set.Palette, cell.Surface); err != nil {
log.Printf("%v %v %v surface: %v", x, y, z, err)
} else if spr != nil {
sprites = append(sprites, spr)
}
if spr, err := s.env.getSprite(s.env.set.Palette, cell.Center); err != nil {
if spr, err := e.getSprite(e.set.Palette, cell.Center); err != nil {
log.Printf("%v %v %v center: %v", x, y, z, err)
} else if spr != nil {
sprites = append(sprites, spr)
}
if spr, err := s.env.getSprite(s.env.set.Palette, cell.Left); err != nil {
if spr, err := e.getSprite(e.set.Palette, cell.Left); err != nil {
log.Printf("%v %v %v left: %v", x, y, z, err)
} else if spr != nil {
sprites = append(sprites, spr)
}
if spr, err := s.env.getSprite(s.env.set.Palette, cell.Right); err != nil {
if spr, err := e.getSprite(e.set.Palette, cell.Right); err != nil {
log.Printf("%v %v %v right: %v", x, y, z, err)
} else if spr != nil {
sprites = append(sprites, spr)
@@ -222,14 +200,39 @@ func (s *state) renderCell(x, y, z int, target pixel.Target) {
// Taking the Z index away *seems* to draw the object in the correct place.
// FIXME: There are some artifacts, investigate more
fX := float64(x)
fY := float64(y)
fx, fy := cellToPix(float64(x), float64(y))
fx += float64(e.state.origin.X)
fy += float64(e.state.origin.Y)
iso := s.cellToPix(pixel.V(fX, fY))
iso = iso.Add(pixel.Vec{0.0, -float64(z * 48.0)})
iso := ebiten.GeoM{}
iso.Translate(fx, fy)
iso.Translate(0.0, -float64(z*48.0)) // offset for Z index
iso.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor
for _, sprite := range sprites {
sprite.Spr.Draw(target, pixel.IM.Moved(iso))
if err := screen.DrawImage(sprite.Image, &ebiten.DrawImageOptions{GeoM: iso}); err != nil {
return err
}
}
return nil
}
func (e *env) changeOrigin(byX, byY int) func() {
return func() {
e.state.origin.X += byX
e.state.origin.Y += byY
}
}
func (e *env) changeZoom(_, y float64) {
// Zoom in and out with the mouse wheel
e.state.zoom *= math.Pow(1.2, y)
}
func (e *env) setZIdx(to int) func() {
return func() {
e.state.zIdx = to
}
}
@@ -239,76 +242,11 @@ var (
)
// Doesn't take the camera or Z level into account
func (s *state) cellToPix(cell pixel.Vec) pixel.Vec {
return pixel.V(
(cell.X-cell.Y)*cellWidth,
(cell.X+cell.Y)*cellHeight/2.0,
)
func cellToPix(x, y float64) (float64, float64) {
return (x - y) * cellWidth, (x + y) * cellHeight / 2.0
}
// Doesn't take the camera or Z level into account
func (s *state) pixToCell(pix pixel.Vec) pixel.Vec {
return pixel.V(
pix.Y/cellHeight+pix.X/(cellWidth*2.0),
pix.Y/cellHeight-pix.X/(cellWidth*2.0),
)
}
func (s *state) runStep(pWin *pixelgl.Window) *state {
newState := *s
newState.handleKeys(pWin)
return &newState
}
func (s *state) handleKeys(pWin *pixelgl.Window) {
// Do this first to avoid taking the below mutations into account
// FIXME: this suggests we should pass the next state into here and
// modify it instead
if pWin.JustPressed(pixelgl.MouseButton1) {
if s.zIdx != 0 {
log.Printf("WARNING: z-index not yet taken into account")
}
log.Printf("cam: %#v", s.cam)
pos := s.pixToCell(s.cam.Unproject(pWin.MousePosition()))
log.Printf("X=%v Y=%v, zIdx=%v", pos.X, pos.Y, s.zIdx)
cell := s.env.gameMap.Cells.At(int(pos.X), int(pos.Y), s.zIdx)
log.Printf("Cell=%#v", cell)
}
if pWin.Pressed(pixelgl.KeyLeft) {
s.camPos.X -= 64
}
if pWin.Pressed(pixelgl.KeyRight) {
s.camPos.X += 64
}
if pWin.Pressed(pixelgl.KeyDown) {
s.camPos.Y -= 64
}
if pWin.Pressed(pixelgl.KeyUp) {
s.camPos.Y += 64
}
for i := 1; i <= 7; i++ {
if pWin.JustPressed(pixelgl.Key0 + pixelgl.Button(i)) {
s.zIdx = i - 1
}
}
if pWin.Pressed(pixelgl.KeyMinus) {
s.rot -= 0.001
}
if pWin.Pressed(pixelgl.KeyEqual) {
s.rot += 0.001
}
// Zoom in and out with the mouse wheel
s.zoom *= math.Pow(1.2, pWin.MouseScroll().Y)
func pixToCell(x, y float64) (float64, float64) {
return y/cellHeight + x/(cellWidth*2.0), y/cellHeight - x/(cellWidth*2.0)
}

View File

@@ -3,13 +3,12 @@ package main
import (
"flag"
"fmt"
"image"
"log"
"os"
"path/filepath"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/conv"
"ur.gs/ordoor/internal/data"
@@ -26,41 +25,53 @@ var (
type env struct {
menu *menus.Menu
objects []*conv.Object
batch *pixel.Batch
fonts []*conv.Font
fontObjs []*conv.Object
fontBatch *pixel.Batch
fonts []*conv.Font
fontObjs []*conv.Object
step int
state state
lastState state
}
type state struct {
env *env
cam pixel.Matrix
step int
// Redraw the window if these change
winPos pixel.Vec
winBounds pixel.Rect
winBounds image.Rectangle
}
func loadObjects(names ...string) ([]*conv.Object, *pixel.Batch) {
var raw []*data.Object
func loadObjects(names ...string) ([]*conv.Object, error) {
objs := make([]*conv.Object, 0, len(names))
for _, name := range names {
objFile := filepath.Join(filepath.Dir(*menuFile), name)
obj, err := data.LoadObject(objFile)
rawObj, err := data.LoadObject(objFile)
if err != nil {
log.Fatalf("Failed to load %s: %v", name, err)
}
obj.Name = name
raw = append(raw, obj)
obj, err := conv.ConvertObject(rawObj, name)
if err != nil {
return nil, err
}
objs = append(objs, obj)
}
objects, spritesheet := conv.ConvertObjects(raw)
batch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
return objs, nil
}
return objects, batch
func loadFonts(names ...string) ([]*conv.Font, error) {
var out []*conv.Font
for _, name := range names {
fnt, err := fonts.LoadFont(filepath.Join(*gamePath, "Fonts", name+".fnt"))
if err != nil {
return nil, fmt.Errorf("%v: %v", name, err)
}
out = append(out, conv.ConvertFont(fnt))
}
return out, nil
}
func main() {
@@ -87,61 +98,36 @@ func main() {
log.Fatalf("Failed to load font: %v", err)
}
menuObjs, menuBatch := loadObjects(menu.ObjectFiles...)
menuObjs, err := loadObjects(menu.ObjectFiles...)
if err != nil {
log.Fatalf("Failed to load objects: %v", err)
}
state := state{}
env := &env{
menu: menu, objects: menuObjs, batch: menuBatch,
fonts: loadedFonts,
menu: menu,
objects: menuObjs,
fonts: loadedFonts,
state: state,
lastState: state,
}
// The main thread now belongs to pixelgl
pixelgl.Run(env.run)
}
func loadFonts(names ...string) ([]*conv.Font, error) {
var out []*conv.Font
for _, name := range names {
fnt, err := fonts.LoadFont(filepath.Join(*gamePath, "Fonts", name+".fnt"))
if err != nil {
return nil, fmt.Errorf("%v: %v", name, err)
}
out = append(out, conv.ConvertFont(fnt))
}
return out, nil
}
func (e *env) run() {
win, err := ui.NewWindow("View Menu: " + *menuFile)
if err != nil {
log.Fatal("Couldn't create window: %v", err)
}
pWin := win.PixelWindow
state := &state{env: e}
// For now, just try to display the various objects
// left + right to change object, up + down to change frame
win.Run(func() {
oldState := *state
state = state.runStep(pWin)
if oldState != *state || oldState.step == 0 {
state.present(pWin)
}
state.step += 1
})
if err := win.Run(env.Update, env.Draw); err != nil {
log.Fatal(err)
}
}
func (s *state) runStep(pWin *pixelgl.Window) *state {
newState := *s
newState.winPos = pWin.GetPos()
newState.winBounds = pWin.Bounds()
newState.handleKeys(pWin)
func (e *env) Update() error {
// No behaviour yet
return &newState
e.step += 1
e.lastState = e.state
return nil
}
const (
@@ -149,35 +135,29 @@ const (
origY = 480.0
)
func (s *state) present(pWin *pixelgl.Window) {
pWin.Clear(colornames.Black)
s.env.batch.Clear()
func (e *env) Draw(screen *ebiten.Image) error {
// The menus expect to be drawn to a 640x480 screen. We need to scale and
// project that so it fills the window appropriately. This is a combination
// of translate + zoom
winSize := pWin.Bounds().Max
scaleFactor := pixel.Vec{winSize.X / origX, winSize.Y / origY}
winSize := screen.Bounds().Max
scaleX := float64(winSize.X) / float64(origX)
scaleY := float64(winSize.Y) / float64(origY)
cam := pixel.IM
cam = cam.ScaledXY(pixel.ZV, pixel.Vec{1.0, -1.0}) // invert the Y axis
cam = cam.Moved(pixel.Vec{origX / 2, origY / 2})
cam = cam.ScaledXY(pixel.ZV, scaleFactor)
s.cam = cam
s.env.batch.SetMatrix(cam)
cam := ebiten.GeoM{}
cam.Scale(scaleX, scaleY)
textCanvas := pixelgl.NewCanvas(pWin.Bounds())
textCanvas.SetMatrix(pixel.IM.ScaledXY(pixel.ZV, scaleFactor))
for _, record := range s.env.menu.Records {
s.drawRecord(record, s.env.batch, textCanvas)
for _, record := range e.menu.Records {
if err := e.drawRecord(record, screen, cam); err != nil {
return err
}
}
s.env.batch.Draw(pWin)
textCanvas.Draw(pWin, pixel.IM)
return nil
}
func (s *state) drawRecord(record *menus.Record, target, textTarget pixel.Target) {
func (e *env) drawRecord(record *menus.Record, screen *ebiten.Image, offset ebiten.GeoM) error {
origOffset := offset
// Draw this record if it's valid to do so. FIXME: lots to learn
if len(record.SpriteId) >= 0 {
spriteId := record.SpriteId[0]
@@ -210,59 +190,25 @@ func (s *state) drawRecord(record *menus.Record, target, textTarget pixel.Target
)
// FIXME: Need to handle multiple objects
offset := pixel.V(x, y)
obj := s.env.objects[0]
obj := e.objects[0]
sprite := obj.Sprites[spriteId]
sprite.Spr.Draw(target, pixel.IM.Moved(offset))
offset.Translate(x, y)
screen.DrawImage(sprite.Image, &ebiten.DrawImageOptions{GeoM: offset})
// FIXME: we probably shouldn't draw everything?
// FIXME: handle multiple fonts
if len(s.env.fonts) > 0 && record.Desc != "" {
s.env.fonts[0].Output(textTarget, pixel.IM.Moved(offset), record.Desc)
if len(e.fonts) > 0 && record.Desc != "" {
e.fonts[0].Output(screen, origOffset, record.Desc)
}
}
out:
// Draw all children of this record
for _, child := range record.Children {
s.drawRecord(child, target, textTarget)
}
}
func (s *state) handleKeys(pWin *pixelgl.Window) {
if pWin.JustPressed(pixelgl.MouseButton1) {
log.Printf("cam: %#v", s.cam)
pos := s.cam.Unproject(pWin.MousePosition())
log.Printf("X=%v Y=%v", pos.X, pos.Y)
if err := e.drawRecord(child, screen, offset); err != nil {
return err
}
}
/*
if pWin.JustPressed(pixelgl.KeyLeft) {
if s.objIdx > 0 {
s.objIdx -= 1
s.spriteIdx = 0
}
}
if pWin.JustPressed(pixelgl.KeyRight) {
if s.objIdx < s.env.set.Count()-1 {
s.objIdx += 1
s.spriteIdx = 0
}
}
if pWin.JustPressed(pixelgl.KeyDown) {
if s.spriteIdx > 0 {
s.spriteIdx -= 1
}
}
if pWin.JustPressed(pixelgl.KeyUp) {
if s.spriteIdx < len(s.curObject().Sprites)-1 {
s.spriteIdx += 1
}
}
// Zoom in and out with the mouse wheel
s.zoom *= math.Pow(1.2, pWin.MouseScroll().Y)
*/
return nil
}

View File

@@ -2,16 +2,15 @@ package main
import (
"flag"
"image"
"image/color"
"log"
"math"
"os"
"path/filepath"
"time"
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/maps"
"ur.gs/ordoor/internal/sets"
@@ -27,16 +26,18 @@ var (
type env struct {
gameMap *maps.GameMap
set *sets.MapSet
state state
lastState state
step int
}
type runState struct {
env *env
type state struct {
autoUpdate bool
started time.Time
cam pixel.Matrix
camPos pixel.Vec
origin image.Point
zoom float64
@@ -64,41 +65,141 @@ func main() {
log.Fatalf("Couldn't load set file %s: %v", setFile, err)
}
env := &env{gameMap: gameMap, set: mapSet}
state := state{
autoUpdate: true,
zoom: 8.0,
}
env := &env{gameMap: gameMap, set: mapSet, state: state, lastState: state}
// The main thread now belongs to pixelgl
pixelgl.Run(env.run)
}
func (e *env) run() {
win, err := ui.NewWindow("View Map " + *mapFile)
if err != nil {
log.Fatal("Couldn't create window: %v", err)
}
pWin := win.PixelWindow
state := &runState{
env: e,
autoUpdate: true,
camPos: pixel.V(0, float64(-pWin.Bounds().Size().Y)),
zoom: 8.0,
win.OnKeyUp(ebiten.KeyEnter, env.toggleAutoUpdate)
win.OnKeyUp(ebiten.KeyLeft, env.changeOrigin(+4, +0))
win.OnKeyUp(ebiten.KeyRight, env.changeOrigin(-4, +0))
win.OnKeyUp(ebiten.KeyUp, env.changeOrigin(+0, +4))
win.OnKeyUp(ebiten.KeyDown, env.changeOrigin(+0, -4))
win.OnKeyUp(ebiten.KeyMinus, env.changeCellIdx(-1))
win.OnKeyUp(ebiten.KeyEqual, env.changeCellIdx(+1))
for i := 0; i <= 6; i++ {
win.OnKeyUp(ebiten.Key1+ebiten.Key(i), env.setZIdx(i))
}
win.Run(func() {
oldState := *state
state = runStep(pWin, state)
win.OnMouseWheel(env.changeZoom)
if oldState != *state {
log.Printf("z=%d cellIdx=%d", state.zIdx, state.cellIdx)
present(pWin, state)
if err := win.Run(env.Update, env.Draw); err != nil {
log.Fatal(err)
}
}
func (e *env) setZIdx(to int) func() {
return func() {
e.state.zIdx = to
}
}
// Enable / disable auto-update
func (e *env) toggleAutoUpdate() {
e.state.autoUpdate = !e.state.autoUpdate
if e.state.autoUpdate {
e.state.started = time.Now()
}
}
func (e *env) changeOrigin(byX, byY int) func() {
return func() {
e.state.origin.X += byX
e.state.origin.Y += byY
}
}
func (e *env) changeCellIdx(by int) func() {
return func() {
e.state.cellIdx += by
if e.state.cellIdx < 0 {
e.state.cellIdx = 0
}
})
if e.state.cellIdx > maps.CellSize-1 {
e.state.cellIdx = maps.CellSize - 1
}
}
}
func (e *env) changeZoom(_, y float64) {
// Zoom in and out with the mouse wheel
e.state.zoom *= math.Pow(1.2, y)
}
func (e *env) Update() error {
// TODO: show details of clicked-on cell in terminal
// Automatically cycle every 500ms when auto-update is on
if e.state.autoUpdate && time.Now().Sub(e.state.started) > 500*time.Millisecond {
e.state.cellIdx += 1
// bounds checking
if e.state.cellIdx >= maps.CellSize {
e.state.cellIdx = 0
e.state.zIdx += 1
}
if e.state.zIdx >= maps.MaxHeight {
e.state.zIdx = 0
}
e.state.started = time.Now()
}
if e.step == 0 || e.lastState != e.state {
log.Printf("z=%d cellIdx=%d origin=%#v", e.state.zIdx, e.state.cellIdx, e.state.origin)
}
e.step += 1
e.lastState = e.state
return nil
}
func (e *env) Draw(screen *ebiten.Image) error {
gameMap := e.gameMap
imd, err := ebiten.NewImage(
int(gameMap.MaxWidth),
int(gameMap.MaxLength),
ebiten.FilterDefault,
)
if err != nil {
return err
}
for y := int(gameMap.MinLength); y < int(gameMap.MaxLength); y++ {
for x := int(gameMap.MinWidth); x < int(gameMap.MaxWidth); x++ {
cell := gameMap.Cells.At(x, y, int(e.state.zIdx))
imd.Set(x, y, makeColour(&cell, e.state.cellIdx))
}
}
// TODO: draw a boundary around the minimap
cam := ebiten.GeoM{}
cam.Translate(float64(e.state.origin.X), float64(e.state.origin.Y)) // Move to origin
cam.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor
cam.Rotate(0.785) // Apply isometric angle
return screen.DrawImage(imd, &ebiten.DrawImageOptions{GeoM: cam})
}
// Converts pixel coordinates to cell coordinates
func vecToCell(vec pixel.Vec) (int, int) {
x := int(vec.X)
y := int(vec.Y)
func vecToCell(p image.Point) (int, int) {
x := int(p.X)
y := int(p.Y)
if x < 0 {
x = 0
@@ -119,56 +220,13 @@ func vecToCell(vec pixel.Vec) (int, int) {
return x, y
}
func cellToVec(x, y int) pixel.Rect {
min := pixel.Vec{X: float64(x), Y: float64(y)}
max := pixel.Vec{X: min.X + 1, Y: min.Y + 1}
return pixel.Rect{Min: min, Max: max}
func cellToVec(x, y int) image.Rectangle {
min := image.Point{X: x, Y: y}
max := image.Point{X: min.X + 1, Y: min.Y + 1}
return image.Rect(min.X, min.Y, max.X, max.Y)
}
func present(win *pixelgl.Window, state *runState) {
gameMap := state.env.gameMap
imd := imdraw.New(nil)
for y := gameMap.MinLength; y < gameMap.MaxLength; y++ {
for x := gameMap.MinWidth; x < gameMap.MaxWidth; x++ {
rect := cellToVec(int(x), int(y))
cell := gameMap.Cells.At(int(x), int(y), int(state.zIdx))
// TODO: represent the state of the cell *sensibly*, using colour.
// Need to understand the contents better first, so for now optimize
// for exploration
imd.Color = makeColour(&cell, state.cellIdx)
imd.Push(rect.Min, rect.Max)
imd.Rectangle(0.0)
}
}
// Draw the boundary
rect := pixel.R(
float64(gameMap.MinWidth)-0.5, float64(gameMap.MinLength)-0.5,
float64(gameMap.MaxWidth)+0.5, float64(gameMap.MaxLength)+0.5,
)
imd.Color = pixel.RGB(255, 0, 0)
imd.EndShape = imdraw.SharpEndShape
imd.Push(rect.Min, rect.Max)
imd.Rectangle(1.0)
center := win.Bounds().Center()
cam := pixel.IM
cam = cam.ScaledXY(pixel.ZV, pixel.Vec{1.0, -1.0}) // invert the Y axis
cam = cam.Scaled(pixel.ZV, state.zoom) // apply current zoom factor
cam = cam.Moved(center.Sub(state.camPos)) // Make it central
cam = cam.Rotated(center.Sub(state.camPos), -0.785) // Apply isometric angle
state.cam = cam
win.SetMatrix(state.cam)
win.Clear(colornames.Black)
imd.Draw(win)
}
func makeColour(cell *maps.Cell, colIdx int) pixel.RGBA {
func makeColour(cell *maps.Cell, colIdx int) color.RGBA {
var scale func(float64) float64
mult := func(factor float64) func(float64) float64 {
@@ -176,6 +234,7 @@ func makeColour(cell *maps.Cell, colIdx int) pixel.RGBA {
}
// Different columns do better with different levels of greyscale.
// FIXME: this may not be translated correctly from pixel
switch colIdx {
case 0:
@@ -202,94 +261,6 @@ func makeColour(cell *maps.Cell, colIdx int) pixel.RGBA {
scale = mult(0.01) // close to maximum resolution, low-value fields will be lost
}
col := scale(float64(cell.At(colIdx)))
return pixel.RGB(col, col, col)
}
func runStep(win *pixelgl.Window, state *runState) *runState {
nextState := *state
// Enable / disable auto-update with the enter key
if win.JustPressed(pixelgl.KeyEnter) {
nextState.autoUpdate = !state.autoUpdate
log.Printf("autoUpdate=%v", nextState.autoUpdate)
if nextState.autoUpdate {
nextState.started = time.Now()
}
}
// Automatically cycle every second when auto-update is on
if nextState.autoUpdate && time.Now().Sub(state.started) > 500*time.Millisecond {
nextState.cellIdx = nextState.cellIdx + 1
if nextState.cellIdx >= maps.CellSize {
nextState.cellIdx = 0
nextState.zIdx = nextState.zIdx + 1
}
if nextState.zIdx >= maps.MaxHeight {
nextState.zIdx = 0
}
nextState.started = time.Now()
}
if win.Pressed(pixelgl.KeyLeft) {
nextState.camPos.X -= 4
}
if win.Pressed(pixelgl.KeyRight) {
nextState.camPos.X += 4
}
if win.Pressed(pixelgl.KeyDown) {
nextState.camPos.Y -= 4
}
if win.Pressed(pixelgl.KeyUp) {
nextState.camPos.Y += 4
}
for i := 0; i <= 6; i++ {
if win.JustPressed(pixelgl.Key1 + pixelgl.Button(i)) {
nextState.zIdx = i
}
}
// Decrease the cell index
if win.JustPressed(pixelgl.KeyMinus) {
if nextState.cellIdx > 0 {
nextState.cellIdx -= 1
}
}
// Increase the cell index
if win.JustPressed(pixelgl.KeyEqual) {
if nextState.cellIdx < maps.CellSize-1 {
nextState.cellIdx += 1
}
}
// Show details of clicked-on cell in termal
if win.JustPressed(pixelgl.MouseButtonLeft) {
vec := state.cam.Unproject(win.MousePosition())
x, y := vecToCell(vec)
log.Printf("%#v -> %d,%d", vec, x, y)
cell := state.env.gameMap.Cells.At(x, y, state.zIdx)
log.Printf(
"x=%d y=%d z=%d SurfaceTile=%d (%s) SurfaceSprite=%d SquadRelated=%d",
x, y, state.zIdx,
cell.Surface.Index(), state.env.set.SurfacePalette[int(cell.Surface.Index())], cell.Surface.Sprite(),
cell.SquadRelated,
)
log.Printf("CellIdx%d=%d. Full cell data: %#v", state.cellIdx, cell.At(state.cellIdx), cell)
}
// Zoom in and out with the mouse wheel
nextState.zoom *= math.Pow(1.2, win.MouseScroll().Y)
if nextState.zoom != state.zoom {
log.Printf("zoom=%.2f", nextState.zoom)
}
return &nextState
col := uint8(scale(float64(cell.At(colIdx))))
return color.RGBA{col, col, col, 255}
}

View File

@@ -2,14 +2,13 @@ package main
import (
"flag"
"image"
"log"
"math"
"os"
"path/filepath"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/conv"
"ur.gs/ordoor/internal/data"
@@ -22,19 +21,18 @@ var (
)
type env struct {
obj *conv.Object
obj *conv.Object
step int
state state
lastState state
}
type state struct {
env *env
step int
spriteIdx int
zoom float64
cam pixel.Matrix
camPos pixel.Vec
zoom float64
origin image.Point
}
func main() {
@@ -49,86 +47,92 @@ func main() {
if err != nil {
log.Fatalf("Failed to load %s: %v", *objFile, err)
}
obj := conv.ConvertObject(rawObj, filepath.Base(*objFile))
env := &env{obj: obj}
obj, err := conv.ConvertObject(rawObj, filepath.Base(*objFile))
if err != nil {
log.Fatalf("Failed to convert %s: %v", *objFile, err)
}
// The main thread now belongs to pixelgl
pixelgl.Run(env.run)
}
state := state{
zoom: 6.0,
origin: image.Point{0, 0},
}
env := &env{
obj: obj,
state: state,
lastState: state,
}
func (e *env) run() {
win, err := ui.NewWindow("View Object: " + *objFile)
if err != nil {
log.Fatal("Couldn't create window: %v", err)
log.Fatal(err)
}
pWin := win.PixelWindow
state := &state{
env: e,
camPos: pixel.V(0, float64(-pWin.Bounds().Size().Y)),
zoom: 8.0,
win.OnKeyUp(ebiten.KeyMinus, env.changeSprite(-1))
win.OnKeyUp(ebiten.KeyEqual, env.changeSprite(+1))
win.OnKeyUp(ebiten.KeyLeft, env.changeOrigin(+4, +0))
win.OnKeyUp(ebiten.KeyRight, env.changeOrigin(-4, +0))
win.OnKeyUp(ebiten.KeyUp, env.changeOrigin(+0, +4))
win.OnKeyUp(ebiten.KeyDown, env.changeOrigin(+0, -4))
win.OnMouseWheel(env.changeZoom)
// The main thread now belongs to ebiten
if err := win.Run(env.Update, env.Draw); err != nil {
log.Fatal(err)
}
// For now, just try to display the various objects
// left + right to change object, up + down to change frame
win.Run(func() {
oldState := *state
state = state.runStep(pWin)
if oldState != *state || oldState.step == 0 {
log.Printf(
"new state: numSprites=%d sprite=%d zoom=%.2f",
len(state.env.obj.Sprites),
state.spriteIdx,
state.zoom,
)
state.present(pWin)
}
state.step += 1
})
}
func (s *state) runStep(pWin *pixelgl.Window) *state {
newState := *s
newState.handleKeys(pWin)
return &newState
}
func (s *state) present(pWin *pixelgl.Window) {
obj := s.env.obj
sprite := obj.Sprites[s.spriteIdx]
center := pWin.Bounds().Center()
cam := pixel.IM
cam = cam.ScaledXY(center, pixel.Vec{1.0, -1.0}) // invert the Y axis
cam = cam.Scaled(center, s.zoom) // apply current zoom factor
//cam = cam.Moved(center.Sub(s.camPos)) // Make it central
//cam = cam.Rotated(center, -0.785) // Apply isometric angle
s.cam = cam
pWin.SetMatrix(s.cam)
pWin.Clear(colornames.Black)
pixel.NewSprite(sprite.Pic, sprite.Pic.Bounds()).Draw(pWin, pixel.IM.Moved(center))
}
func (s *state) handleKeys(pWin *pixelgl.Window) {
if pWin.JustPressed(pixelgl.KeyMinus) {
if s.spriteIdx > 0 {
s.spriteIdx -= 1
}
func (e *env) Update() error {
if e.step == 0 || e.lastState != e.state {
log.Printf(
"new state: numSprites=%d sprite=%d zoom=%.2f, origin=%+v",
len(e.obj.Sprites),
e.state.spriteIdx,
e.state.zoom,
e.state.origin,
)
}
if pWin.JustPressed(pixelgl.KeyEqual) {
if s.spriteIdx < len(s.env.obj.Sprites)-1 {
s.spriteIdx += 1
// This should be the final action
e.step += 1
e.lastState = e.state
return nil
}
func (e *env) Draw(screen *ebiten.Image) error {
sprite := e.obj.Sprites[e.state.spriteIdx]
cam := ebiten.GeoM{}
cam.Translate(float64(e.state.origin.X), float64(e.state.origin.Y)) // Move to origin
cam.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor
return screen.DrawImage(sprite.Image, &ebiten.DrawImageOptions{GeoM: cam})
}
func (e *env) changeSprite(by int) func() {
return func() {
e.state.spriteIdx += by
if e.state.spriteIdx < 0 {
e.state.spriteIdx = 0
}
if e.state.spriteIdx > len(e.obj.Sprites)-1 {
e.state.spriteIdx = len(e.obj.Sprites) - 1
}
}
}
func (e *env) changeOrigin(byX, byY int) func() {
return func() {
e.state.origin.X += byX
e.state.origin.Y += byY
}
}
func (e *env) changeZoom(_, y float64) {
// Zoom in and out with the mouse wheel
s.zoom *= math.Pow(1.2, pWin.MouseScroll().Y)
e.state.zoom *= math.Pow(1.2, y)
}

View File

@@ -2,14 +2,13 @@ package main
import (
"flag"
"image"
"log"
"math"
"os"
"path/filepath"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"golang.org/x/image/colornames"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/conv"
"ur.gs/ordoor/internal/data"
@@ -25,20 +24,18 @@ var (
type env struct {
set *sets.MapSet
objects map[string]*conv.Object
batch *pixel.Batch
step int
state state
lastState state
}
type state struct {
env *env
step int
objIdx int
spriteIdx int
zoom float64
cam pixel.Matrix
camPos pixel.Vec
zoom float64
origin image.Point
}
func main() {
@@ -54,7 +51,7 @@ func main() {
log.Fatalf("Couldn't load set file %s: %v", *setFile, err)
}
rawObjs := []*data.Object{}
rawObjs := make([]*data.Object, 0, len(mapSet.Palette))
for _, name := range mapSet.Palette {
objFile := filepath.Join(*gamePath, "Obj", name+".obj")
obj, err := data.LoadObject(objFile)
@@ -66,109 +63,115 @@ func main() {
rawObjs = append(rawObjs, obj)
}
objects, spritesheet := conv.ConvertObjects(rawObjs)
batch := pixel.NewBatch(&pixel.TrianglesData{}, spritesheet)
objs := make([]*conv.Object, 0, len(rawObjs))
for _, rawObj := range rawObjs {
obj, err := conv.ConvertObject(rawObj, rawObj.Name)
if err != nil {
log.Fatal(err)
}
env := &env{objects: conv.MapByName(objects), set: mapSet, batch: batch}
objs = append(objs, obj)
}
// The main thread now belongs to pixelgl
pixelgl.Run(env.run)
}
func (e *env) run() {
win, err := ui.NewWindow("View Set: " + *setFile)
if err != nil {
log.Fatal("Couldn't create window: %v", err)
}
pWin := win.PixelWindow
state := &state{
env: e,
camPos: pixel.V(0, float64(-pWin.Bounds().Size().Y)),
zoom: 8.0,
state := state{zoom: 8.0}
env := &env{
set: mapSet,
objects: conv.MapByName(objs),
state: state,
lastState: state,
}
// For now, just try to display the various objects
// left + right to change object, up + down to change frame
win.Run(func() {
oldState := *state
state = state.runStep(pWin)
win.OnKeyUp(ebiten.KeyLeft, env.changeObjIdx(-1))
win.OnKeyUp(ebiten.KeyRight, env.changeObjIdx(+1))
if oldState != *state || oldState.step == 0 {
log.Printf(
"new state: numObj=%d object=%d (%s) numFrames=%d sprite=%d zoom=%.2f",
state.env.set.Count(),
state.objIdx,
state.env.set.Palette[state.objIdx], // FIXME: palette is a confusing name
len(state.curObject().Sprites),
state.spriteIdx,
state.zoom,
)
state.present(pWin)
}
win.OnKeyUp(ebiten.KeyUp, env.changeSpriteIdx(+1))
win.OnKeyUp(ebiten.KeyDown, env.changeSpriteIdx(-1))
state.step += 1
})
win.OnMouseWheel(env.changeZoom)
// Main thread now belongs to ebiten
if err := win.Run(env.Update, env.Draw); err != nil {
log.Fatal(err)
}
}
func (s *state) runStep(pWin *pixelgl.Window) *state {
newState := *s
newState.handleKeys(pWin)
func (e *env) Update() error {
if e.step == 0 || e.lastState != e.state {
log.Printf(
"new state: numObj=%d object=%d (%s) numFrames=%d sprite=%d zoom=%.2f",
e.set.Count(),
e.state.objIdx,
e.set.Palette[e.state.objIdx], // FIXME: palette is a confusing name
len(e.curObject().Sprites),
e.state.spriteIdx,
e.state.zoom,
)
}
return &newState
e.step += 1
e.lastState = e.state
return nil
}
func (s *state) present(pWin *pixelgl.Window) {
obj := s.curObject()
sprite := obj.Sprites[s.spriteIdx]
func (e *env) Draw(screen *ebiten.Image) error {
obj := e.curObject()
sprite := obj.Sprites[e.state.spriteIdx]
pWin.Clear(colornames.Black)
s.env.batch.Clear()
cam := ebiten.GeoM{}
cam.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor
center := pWin.Bounds().Center()
// TODO: centre the image
cam := pixel.IM
cam = cam.ScaledXY(center, pixel.Vec{1.0, -1.0}) // invert the Y axis
cam = cam.Scaled(center, s.zoom) // apply current zoom factor
s.cam = cam
pWin.SetMatrix(s.cam)
sprite.Spr.Draw(s.env.batch, pixel.IM.Moved(center))
s.env.batch.Draw(pWin)
return screen.DrawImage(sprite.Image, &ebiten.DrawImageOptions{GeoM: cam})
}
func (s *state) handleKeys(pWin *pixelgl.Window) {
if pWin.JustPressed(pixelgl.KeyLeft) {
if s.objIdx > 0 {
s.objIdx -= 1
s.spriteIdx = 0
func (e *env) changeObjIdx(by int) func() {
return func() {
old := e.state.objIdx
e.state.objIdx += by
if e.state.objIdx < 0 {
e.state.objIdx = 0
}
if e.state.objIdx > e.set.Count()-1 {
e.state.objIdx = e.set.Count() - 1
}
// reset sprite index when object changes
if old != e.state.objIdx {
e.state.spriteIdx = 0
}
}
}
if pWin.JustPressed(pixelgl.KeyRight) {
if s.objIdx < s.env.set.Count()-1 {
s.objIdx += 1
s.spriteIdx = 0
}
}
if pWin.JustPressed(pixelgl.KeyDown) {
if s.spriteIdx > 0 {
s.spriteIdx -= 1
}
}
if pWin.JustPressed(pixelgl.KeyUp) {
if s.spriteIdx < len(s.curObject().Sprites)-1 {
s.spriteIdx += 1
func (e *env) changeSpriteIdx(by int) func() {
return func() {
e.state.spriteIdx += by
if e.state.spriteIdx < 0 {
e.state.spriteIdx = 0
}
count := len(e.curObject().Sprites)
if e.state.spriteIdx > count-1 {
e.state.spriteIdx = count - 1
}
}
}
func (e *env) changeZoom(_, y float64) {
// Zoom in and out with the mouse wheel
s.zoom *= math.Pow(1.2, pWin.MouseScroll().Y)
e.state.zoom *= math.Pow(1.2, y)
}
func (s *state) curObject() *conv.Object {
name := s.env.set.Palette[s.objIdx]
return s.env.objects[name]
func (e *env) curObject() *conv.Object {
name := e.set.Palette[e.state.objIdx]
return e.objects[name]
}

4
go.mod
View File

@@ -8,8 +8,8 @@ require (
github.com/faiface/mainthread v0.0.0-20171120011319-8b78f0a41ae3 // indirect
github.com/faiface/pixel v0.8.0
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7 // indirect
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1 // indirect
github.com/go-gl/mathgl v0.0.0-20190713194549-592312d8590a // indirect
github.com/hajimehoshi/ebiten v1.10.2
github.com/pkg/errors v0.8.1 // indirect
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8
)

43
go.sum
View File

@@ -1,5 +1,6 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/faiface/glhf v0.0.0-20181018222622-82a6317ac380 h1:FvZ0mIGh6b3kOITxUnxS3tLZMh7yEoHo75v3/AgUqg0=
github.com/faiface/glhf v0.0.0-20181018222622-82a6317ac380/go.mod h1:zqnPFFIuYFFxl7uH2gYByJwIVKG7fRqlqQCbzAnHs9g=
github.com/faiface/mainthread v0.0.0-20171120011319-8b78f0a41ae3 h1:baVdMKlASEHrj19iqjARrPbaRisD7EuZEVJj6ZMLl1Q=
@@ -12,9 +13,51 @@ github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1 h1:QbL/5oDUmRBzO9/Z7Seo
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/mathgl v0.0.0-20190713194549-592312d8590a h1:yoAEv7yeWqfL/l9A/J5QOndXIJCldv+uuQB1DSNQbS0=
github.com/go-gl/mathgl v0.0.0-20190713194549-592312d8590a/go.mod h1:yhpkQzEiH9yPyxDUGzkmgScbaBVlhC06qodikEM0ZwQ=
github.com/gofrs/flock v0.7.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/hajimehoshi/bitmapfont v1.2.0/go.mod h1:h9QrPk6Ktb2neObTlAbma6Ini1xgMjbJ3w7ysmD7IOU=
github.com/hajimehoshi/ebiten v1.10.2 h1:PiJBY4Q4udip675T+Zqvb3NKMp1eyLWBelp660ZMrkQ=
github.com/hajimehoshi/ebiten v1.10.2/go.mod h1:i9dIEUf5/MuPtbK1/wHR0PB7ZtqhjOxxg+U1xfxapcY=
github.com/hajimehoshi/go-mp3 v0.2.1/go.mod h1:Rr+2P46iH6PwTPVgSsEwBkon0CK5DxCAeX/Rp65DCTE=
github.com/hajimehoshi/oto v0.3.4/go.mod h1:PgjqsBJff0efqL2nlMJidJgVJywLn6M4y8PI4TfeWfA=
github.com/hajimehoshi/oto v0.5.4/go.mod h1:0QXGEkbuJRohbJaxr7ZQSxnju7hEhseiPx2hrh6raOI=
github.com/jakecoffman/cp v0.1.0/go.mod h1:a3xPx9N8RyFAACD644t2dj/nK4SuLg1v+jL61m2yVo4=
github.com/jfreymuth/oggvorbis v1.0.0/go.mod h1:abe6F9QRjuU9l+2jek3gj46lu40N4qlYxh2grqkLEDM=
github.com/jfreymuth/vorbis v1.0.0/go.mod h1:8zy3lUAm9K/rJJk223RKy6vjCZTWC61NA2QD06bfOE0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190321063152-3fc05d484e9f/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190703141733-d6a02ce849c9/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a h1:gHevYm0pO4QUbwy8Dmdr01R5r1BuKtfYqRqF0h/Cbh0=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190415191353-3e0bab5405d6/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mobile v0.0.0-20191025110607-73ccc5ba0426/go.mod h1:p895TfNkDgPEmEQrNiOtIl3j98d/tGU95djDj7NfyjQ=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190429190828-d89cdac9e872/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190909214602-067311248421/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191026034945-b2104f82a97d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -3,35 +3,21 @@ package conv
import (
"fmt"
"github.com/faiface/pixel"
"github.com/faiface/pixel/text"
"golang.org/x/image/colornames"
"golang.org/x/image/font/basicfont"
"ur.gs/ordoor/internal/fonts"
)
type Font struct {
Name string
Atlas *text.Atlas
Text *text.Text
}
func (f *Font) Output(to pixel.Target, m pixel.Matrix, format string, args ...interface{}) {
text := text.New(pixel.V(0.0, 0.0), f.Atlas)
text.Color = colornames.White
func (f *Font) Output(to interface{}, m interface{}, format string, args ...interface{}) {
fmt.Fprintf(text, format, args...)
// FIXME: actually output some text onto screen
text.Draw(to, m)
fmt.Printf(format+"\n", args...)
}
func ConvertFont(font *fonts.Font) *Font {
// FIXME: actually use the pixel data in font
atlas := text.NewAtlas(basicfont.Face7x13, text.ASCII)
return &Font{
Name: font.Name,
Atlas: atlas,
}
return &Font{Name: font.Name}
}

View File

@@ -1,23 +1,11 @@
package conv
import (
"fmt"
"image/color"
"log"
"github.com/faiface/pixel"
"github.com/hajimehoshi/ebiten"
"ur.gs/ordoor/internal/data"
)
const (
// Textures can be this size at most. So putting every sprite onto the same
// sheet is a fraught business. With effective packing, it may be fine.
// If not, I'll have to come up with another idea
maxTextureX = 8192
maxTextureY = 8192
)
// Important conversions:
//
// * Width & height now stored using int
@@ -26,8 +14,7 @@ type Sprite struct {
Width int
Height int
Pic *pixel.PictureData
Spr *pixel.Sprite
Image *ebiten.Image
}
type Object struct {
@@ -45,140 +32,38 @@ func MapByName(objects []*Object) map[string]*Object {
return out
}
func ConvertObjects(objects []*data.Object) ([]*Object, *pixel.PictureData) {
// FIXME: this is rather inefficient. It would be better to determine the
// maximum size we need for the objects at hand.
spritesheet := pixel.MakePictureData(
pixel.R(0.0, 0.0, float64(maxTextureX), float64(maxTextureY)),
)
// These are updated each time a sprite is added to the sheet
xOffset := 0
yOffset := 0
rowMaxY := 0
out := make([]*Object, 0, len(objects))
for _, rawObj := range objects {
sprites := make([]*Sprite, 0, len(rawObj.Sprites))
for i, rawSpr := range rawObj.Sprites {
width := int(rawSpr.Width)
height := int(rawSpr.Height)
// CR+LF if needed
if xOffset+width > maxTextureX {
xOffset = 0
yOffset += rowMaxY
}
if xOffset+width > maxTextureX || yOffset+height > maxTextureY {
panic("Sprite does not fit in spritesheet")
}
spr := spriteToPic(rawObj.Name, i, rawSpr, spritesheet, xOffset, yOffset)
sprites = append(sprites, &Sprite{width, height, spritesheet, spr})
xOffset = xOffset + width
if height > rowMaxY {
rowMaxY = height
}
}
out = append(out, &Object{Name: rawObj.Name, Sprites: sprites})
}
return out, spritesheet
}
func ConvertObjectWithSpritesheet(rawObj *data.Object, name string, pic *pixel.PictureData, xOffset int) *Object {
// We store the sprites vertically in the provided pic
yOffset := 0
func ConvertObject(rawObj *data.Object, name string) (*Object, error) {
out := &Object{
Name: name,
Sprites: make([]*Sprite, len(rawObj.Sprites)),
}
for i, rawSpr := range rawObj.Sprites {
spr := spriteToPic(name, i, rawSpr, pic, xOffset, yOffset)
out.Sprites[i] = &Sprite{
Width: int(rawSpr.Width),
Height: int(rawSpr.Height),
Pic: pic,
Spr: spr,
}
w := int(rawSpr.Width)
h := int(rawSpr.Height)
data := spriteToData(name, i, rawSpr)
yOffset = yOffset + int(rawSpr.Height)
image, err := ebiten.NewImage(w, h, ebiten.FilterDefault)
if err != nil {
return nil, err
}
_ = image.ReplacePixels(data)
out.Sprites[i] = &Sprite{Width: w, Height: h, Image: image}
}
return out
return out, nil
}
func ConvertObject(rawObj *data.Object, name string) *Object {
out := &Object{
Name: name,
Sprites: make([]*Sprite, len(rawObj.Sprites)),
}
for i, rawSpr := range rawObj.Sprites {
pic := pixel.MakePictureData(
pixel.R(
float64(0),
float64(0),
float64(rawSpr.Width),
float64(rawSpr.Height),
),
)
spr := spriteToPic(name, i, rawSpr, pic, 0, 0)
out.Sprites[i] = &Sprite{
Width: int(rawSpr.Width),
Height: int(rawSpr.Height),
Pic: pic,
Spr: spr,
}
}
return out
}
func spriteToPic(name string, idx int, sprite *data.Sprite, pic *pixel.PictureData, xOffset, yOffset int) *pixel.Sprite {
func spriteToData(name string, idx int, sprite *data.Sprite) []byte {
width := int(sprite.Width)
height := int(sprite.Height)
out := make([]byte, 0, 4*width*height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
b := sprite.Data[y*width+x]
// Update the picture
if err := setPaletteColor(pic, x+xOffset, y+yOffset, b); err != nil {
log.Printf("%s %d: %d,%d: %v", name, idx, x, y, err)
}
}
for _, palette := range sprite.Data {
color := data.ColorPalette[int(palette)]
out = append(out, color.R, color.G, color.B, color.A)
}
bounds := pixel.R(
float64(xOffset),
float64(yOffset),
float64(xOffset+width),
float64(yOffset+height),
)
return pixel.NewSprite(pic, bounds)
}
func setPaletteColor(pic *pixel.PictureData, x int, y int, colorIdx byte) error {
vec := pixel.V(float64(x), float64(y))
idx := pic.Index(vec)
if idx > len(pic.Pix)-1 {
return fmt.Errorf("Got index %v which exceeds bounds", idx)
}
r, g, b, a := data.ColorPalette[int(colorIdx)].RGBA()
color := color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}
pic.Pix[idx] = color
return nil
return out
}

View File

@@ -5,7 +5,7 @@ import "image/color"
var (
Transparent = color.RGBA{R: 0, G: 0, B: 0, A: 0}
ColorPalette = color.Palette{
ColorPalette = []color.RGBA{
Transparent,
color.RGBA{R: 128, G: 0, B: 0, A: 255},
color.RGBA{R: 0, G: 128, B: 0, A: 255},

View File

@@ -2,9 +2,11 @@ package ui
import (
"flag"
"fmt"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/ebitenutil"
"github.com/hajimehoshi/ebiten/inpututil"
)
var (
@@ -13,35 +15,81 @@ var (
)
type Window struct {
PixelWindow *pixelgl.Window
ButtonEventHandlers map[pixelgl.Button][]func()
Title string
KeyUpHandlers map[ebiten.Key]func()
MouseWheelHandler func(float64, float64)
// User-provided update actions
updateFn func() error
drawFn func(*ebiten.Image) error
debug bool
}
// WARE! 0,0 is the *bottom left* of the window
// 0,0 is the *top left* of the window
//
// To invert things so 0,0 is the *top left*, apply the InvertY` matrix
// ebiten assumes a single window, so only call this once...
func NewWindow(title string) (*Window, error) {
cfg := pixelgl.WindowConfig{
Title: title,
Bounds: pixel.R(0, 0, float64(*winX), float64(*winY)),
VSync: true,
Resizable: true,
}
pixelWindow, err := pixelgl.NewWindow(cfg)
if err != nil {
return nil, err
}
ebiten.SetRunnableInBackground(true)
return &Window{
PixelWindow: pixelWindow,
Title: title,
KeyUpHandlers: make(map[ebiten.Key]func()),
debug: true,
}, nil
}
// TODO: a stop or other cancellation mechanism
func (w *Window) Run(f func()) {
for !w.PixelWindow.Closed() {
f()
w.PixelWindow.Update()
}
// TODO: multiple handlers for the same key?
func (w *Window) OnKeyUp(key ebiten.Key, f func()) {
w.KeyUpHandlers[key] = f
}
func (w *Window) OnMouseWheel(f func(x, y float64)) {
w.MouseWheelHandler = f
}
func (w *Window) run(screen *ebiten.Image) error {
if err := w.updateFn(); err != nil {
return err
}
// Process keys
// TODO: efficient set operations
for key, cb := range w.KeyUpHandlers {
if inpututil.IsKeyJustReleased(key) {
cb()
}
}
if w.MouseWheelHandler != nil {
x, y := ebiten.Wheel()
if x != 0 || y != 0 {
w.MouseWheelHandler(x, y)
}
}
if !ebiten.IsDrawingSkipped() {
if err := w.drawFn(screen); err != nil {
return err
}
if w.debug {
// Draw FPS, etc, to the screen
msg := fmt.Sprintf("tps=%0.2f fps=%0.2f", ebiten.CurrentTPS(), ebiten.CurrentFPS())
ebitenutil.DebugPrint(screen, msg)
}
}
return nil
}
// TODO: a stop or other cancellation mechanism
//
// Note that this must be called on the main OS thread
func (w *Window) Run(updateFn func() error, drawFn func(*ebiten.Image) error) error {
w.updateFn = updateFn
w.drawFn = drawFn
return ebiten.Run(w.run, *winX, *winY, 1, w.Title)
}