Chip-8_Go/cmd/web/main.go

99 lines
2.0 KiB
Go
Raw Normal View History

2020-10-11 20:55:31 +01:00
package main
import (
"image/color"
"time"
"sync"
"github.com/llgcode/draw2d/draw2dimg"
"github.com/llgcode/draw2d/draw2dkit"
"github.com/markfarnan/go-canvas/canvas"
"git.jacknet.io/S.D/Chip-8_Go/chip8"
)
var done chan struct{}
var cvs *canvas.Canvas2d
var width, height float64 = 64, 32
var sizeMultiplier = 8
var drawBuf = [64 * 32]byte{}
var graphicsLock sync.Mutex
var sleeptime = 2000
func main() {
println("CHIP8 IS HERE!")
cvs, _ = canvas.NewCanvas2d(false)
cvs.Create(int(width)*sizeMultiplier, int(height)*sizeMultiplier)
height = float64(cvs.Height())
width = float64(cvs.Width())
// load in a rom!!!
resp, err := http.Get("https://github.com/dmatlack/chip8/raw/master/roms/games/Space%20Invaders%20%5BDavid%20Winter%5D.ch8")
if err != nil {
println("FUCK")
panic()
}
content := make([]byte, resp.ContentLength)
n, err := resp.Body.Read(content)
if err != nil {
println("FUCK")
panic()
}
cpu := chip8.NewCHIP8(content)
cvs.Start(60, Render)
i := 0
for {
c := make(chan int)
go timeCycle(c)
cpu.PerformCycle()
if cpu.DrawIsNeeded() {
graphicsLock.Lock()
drawBuf = cpu.GetGraphicsBuffer()
graphicsLock.Unlock()
}
i++
if i > 7 {
cpu.TickTimers()
i = 0
}
<-c
}
}
func timeCycle(c chan int) {
time.Sleep(sleeptime * time.Microsecond)
c <- 0
}
func Render(gc *draw2dimg.GraphicContext) bool {
gc.SetFillColor(color.RGBA{0x00, 0x00, 0x00, 0xff})
gc.Clear()
gc.SetFillColor(color.RGBA{0x00, 0xff, 0x00, 0xff})
//gc.SetStrokeColor(color.RGBA{0x00, 0xff, 0x00, 0xff})
gc.BeginPath()
//gc.ArcTo(gs.laserX, gs.laserY, gs.laserSize, gs.laserSize, 0, math.Pi*2)
graphicsLock.Lock()
defer graphicsLock.Unlock()
for i, val := range drawBuf {
if val != 0 {
x := i % 64
y := i / 64
// println("drawing to ", x, y)
draw2dkit.Rectangle(gc, float64(x*sizeMultiplier), float64(y*sizeMultiplier), float64((x*sizeMultiplier)+sizeMultiplier), float64((y*sizeMultiplier)+sizeMultiplier))
}
}
gc.FillStroke()
gc.Close()
return true
}