From 35c01939a00f338dadf1dff01da3240f140f9738 Mon Sep 17 00:00:00 2001 From: "S.D" Date: Tue, 13 Oct 2020 20:46:48 +0100 Subject: [PATCH] separate out running chip8 to goroutine --- cmd/web/main.go | 74 ++++++++++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 28 deletions(-) diff --git a/cmd/web/main.go b/cmd/web/main.go index 9ac43af..c5cbb0a 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -24,6 +24,7 @@ var graphicsLock sync.Mutex var keysLock sync.Mutex var window js.Value var keys [16]byte +var gameRunning = true var keyMap = map[int]int{ 88: 0, // x @@ -59,6 +60,48 @@ func keyEventHandle(event js.Value) { } } +func cpuCycle(cpu *chip8.Chip8, c chan int, i int) { + cpu.PerformCycle() + if cpu.DrawIsNeeded() { + drawNeeded = true + graphicsLock.Lock() + drawBuf = cpu.GetGraphicsBuffer() + graphicsLock.Unlock() + keysLock.Lock() + cpu.UpdateKeys(keys) + keysLock.Unlock() + } + if i > 7 { + cpu.TickTimers() + //println("here!") + } + c <- 1 +} + +func timeCycle(c chan int) { + time.Sleep(2000 * time.Microsecond) + c <- 0 +} + +func runGame(game []byte) { + cpu := chip8.NewCHIP8(game) + i := 0 + for gameRunning { + c := make(chan int) + go timeCycle(c) + i ++ + go cpuCycle(cpu, c, i) + if i > 7 { + i = 0 + } + + x, y := <-c, <-c + if x == 0 { + println("CPU RUNNING SLOW") + println(x, y) + } + } +} func main() { println("CHIP8 IS HERE!") window = js.Global() @@ -79,36 +122,11 @@ func main() { height = float64(cvs.Height()) width = float64(cvs.Width()) - cpu := chip8.NewCHIP8(getSpaceInvaders()) - cvs.Start(60, Render) - i := 0 - for { - c := make(chan int) - go timeCycle(c) - cpu.PerformCycle() - if cpu.DrawIsNeeded() { - drawNeeded = true - graphicsLock.Lock() - drawBuf = cpu.GetGraphicsBuffer() - graphicsLock.Unlock() - keysLock.Lock() - cpu.UpdateKeys(keys) - keysLock.Unlock() - } - i++ - if i > 7 { - cpu.TickTimers() - i = 0 - //println("here!") - } - <-c - } -} -func timeCycle(c chan int) { - time.Sleep(2000 * time.Microsecond) - c <- 0 + go runGame(getPong()) + never_returns := make(chan int) + <-never_returns } func Render(gc *draw2dimg.GraphicContext) bool {