main.swift: fix clock delay

This commit is contained in:
Andrew Glaze 2024-08-18 16:33:25 -04:00
parent 5f770589c8
commit 9c5cb22223
2 changed files with 12 additions and 8 deletions

View File

@ -124,14 +124,16 @@ class CPU {
func run(onCycle: @escaping () -> (), onComplete: @escaping () -> ()) {
let opcodes = OPCODES_MAP
_ = Timer.scheduledTimer(withTimeInterval: 0.00007, repeats: true) { [self] timer in
processOpcodes(onCycle: onCycle, opcodes: opcodes, timer: timer) {
//_ = Timer.scheduledTimer(withTimeInterval: 0.00007, repeats: true) { [self] timer in
while true {
processOpcodes(onCycle: onCycle, opcodes: opcodes) {
onComplete()
}
}
//}
}
func processOpcodes(onCycle: () -> (), opcodes: [UInt8: OpCode], timer: Timer, onComplete: () -> ()) {
func processOpcodes(onCycle: () -> (), opcodes: [UInt8: OpCode], onComplete: () -> ()) {
onCycle()
let code = memRead(programCounter)
programCounter += 1
@ -295,7 +297,7 @@ class CPU {
inx()
/// BRK
case 0x00:
timer.invalidate()
//timer.invalidate()
onComplete()
/// NOP Read
case 0x04, 0x44, 0x64, 0x14, 0x34, 0x54, 0x74, 0xd4, 0xf4, 0x0c, 0x1c, 0x3c, 0x5c, 0x7c, 0xdc, 0xfc:

View File

@ -94,7 +94,7 @@ func readScreenState(_ cpu: CPU, frame: inout [UInt8]) -> Bool {
return update
}
guard let rom = NSData(contentsOfFile: "nestest.nes") else { fatalError("Rom not found") }
guard let rom = NSData(contentsOfFile: "snake.nes") else { fatalError("Rom not found") }
var gameCode = [UInt8](repeating: 0, count: rom.length)
rom.getBytes(&gameCode, length: rom.length)
@ -103,20 +103,22 @@ let bus = Bus(try! Rom(gameCode))
var cpu = CPU(bus: bus)
//cpu.load(gameCode)
cpu.reset()
cpu.programCounter = 0xC000
//cpu.programCounter = 0xC000
var screenState = [UInt8](repeating: 0, count: 32 * 3 * 32)
var rng = SystemRandomNumberGenerator()
cpu.run(onCycle: {
print(dumpCpuState(cpu))
//print(dumpCpuState(cpu))
handleUserInput(cpu, event: &event)
//cpu.memWrite(0xfe, data: UInt8.random(in: 1...16, using: &rng))
cpu.memWrite(0xfe, data: UInt8.random(in: 1...16, using: &rng))
if readScreenState(cpu, frame: &screenState) {
SDL_UpdateTexture(texture, nil, screenState, 32 * 3)
SDL_RenderCopy(canvas, texture, nil, nil)
SDL_RenderPresent(canvas)
}
usleep(70)
}, onComplete: {
SDL_DestroyWindow(window)
SDL_Quit()