9 Commits

11 changed files with 422 additions and 113 deletions

View File

@@ -5,5 +5,5 @@ SET(CMAKE_BUILD_TYPE Debug)
add_subdirectory(submodules/sdl2) add_subdirectory(submodules/sdl2)
SET(CMAKE_EXPORT_COMPILE_COMMANDS ON) SET(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(chocochip8 main.cpp Interpreter.cpp DisplaySDL.cpp BuzzerSDL.cpp) add_executable(chocochip8 main.cpp Interpreter.cpp DisplaySDL.cpp BuzzerSDL.cpp CountdownTimerSDL.cpp KeypadSDL.cpp)
target_link_libraries(chocochip8 SDL2::SDL2-static) target_link_libraries(chocochip8 SDL2::SDL2-static)

18
CountdownTimerSDL.cpp Normal file
View File

@@ -0,0 +1,18 @@
#include "CountdownTimerSDL.hpp"
CountdownTimerSDL::CountdownTimerSDL(unsigned frequency):
mDesiredFrequency{frequency},
mSDLFrequency{SDL_GetPerformanceFrequency()},
mStartTime{0},
mStartValue{0} {}
void CountdownTimerSDL::set(unsigned value) {
mStartTime = SDL_GetPerformanceCounter();
mStartValue = value;
}
unsigned CountdownTimerSDL::get() const {
Uint64 elapsedTime = SDL_GetPerformanceCounter() - mStartTime;
Uint64 elapsedTicks = (elapsedTime * mDesiredFrequency) / mSDLFrequency;
return elapsedTicks >= mStartValue ? 0 : mStartValue - elapsedTicks;
}

17
CountdownTimerSDL.hpp Normal file
View File

@@ -0,0 +1,17 @@
#pragma once
#include <SDL2/SDL_timer.h>
#include "Peripherals.hpp"
class CountdownTimerSDL : public chocochip8::CountdownTimer {
public:
CountdownTimerSDL(unsigned frequency);
void set(unsigned value) override;
unsigned get() const override;
private:
const Uint64 mDesiredFrequency;
const Uint64 mSDLFrequency;
Uint64 mStartTime;
Uint64 mStartValue;
};

View File

@@ -1,8 +1,13 @@
#include "DisplaySDL.hpp" #include "DisplaySDL.hpp"
#include "Peripherals.hpp"
#include <SDL2/SDL_surface.h>
#include <stdexcept> #include <stdexcept>
DisplaySDL::DisplaySDL(int w, int h, uint32_t fgColor, uint32_t bgColor) { DisplaySDL::DisplaySDL(int w, int h, uint32_t fgColor, uint32_t bgColor):
mpFramebuffer{std::make_unique<Framebuffer>()},
mpDisplayState{std::make_unique<Framebuffer>()},
mDoClear{true} {
// Create SDL Window // Create SDL Window
mpWindow = SDL_CreateWindow( mpWindow = SDL_CreateWindow(
"ChocoChip-8", "ChocoChip-8",
@@ -35,43 +40,69 @@ DisplaySDL::~DisplaySDL() {
SDL_DestroyWindow(mpWindow); SDL_DestroyWindow(mpWindow);
} }
void DisplaySDL::updateWindow() const { void DisplaySDL::clear() {
for(auto &scanline : *mpFramebuffer) {
scanline.reset();
}
mDoClear = true;
}
int DisplaySDL::blit(const chocochip8::Scanline &spriteScanline, int y) {
using chocochip8::Scanline;
Scanline &targetScanline = mpFramebuffer->at(y);
bool collision = (spriteScanline & targetScanline).any();
targetScanline ^= spriteScanline;
return collision;
}
void DisplaySDL::updateWindow(bool doWindowUpdate) const {
using chocochip8::Scanline;
SDL_Surface *pSurface = SDL_GetWindowSurface(mpWindow); SDL_Surface *pSurface = SDL_GetWindowSurface(mpWindow);
SDL_LockSurface(pSurface); if(mDoClear) {
for(auto &scanline : *mpDisplayState) {
scanline.reset();
}
SDL_FillRect(pSurface, NULL, mBgColor);
mDoClear = false;
doWindowUpdate = true;
}
int fx, fy; // ChocoChip8 Framebuffer coordinates for(int y = 0; y < mpFramebuffer->size(); y++) {
int sx, sy; // SDL Surface coordinates Scanline &rNewScanline = (*mpFramebuffer)[y];
int lx, ly; // Last-used ChocoChip8 Framebuffer coordinates Scanline &rOldScanline = (*mpDisplayState)[y];
Uint32 lc; // Last-used SDL color if(rNewScanline == rOldScanline) {
// Skip scanlines that haven't changed since the last update
// Fill the entire SDL surface, one pixel at a time continue;
lx = -1; }
ly = -1;
for(sy = 0; sy < pSurface->h; sy++) {
for(sx = 0; sx < pSurface->w; sx++) {
// Map SDL surface coordinates to Chocochip8 Framebuffer coordinates
fx = sx * (double(chocochip8::gcWidth) / pSurface->w);
fy = sy * (double(chocochip8::gcHeight) / pSurface->h);
// Reuse color if this screen pixel maps to the same ChocoChip8 pixel as the last for(int x = 0; x < rNewScanline.size(); x++) {
if(fx != lx || fy != ly) { bool isSet = rNewScanline._Unchecked_test(x);
lx = fx; bool wasSet = rOldScanline._Unchecked_test(x);
ly = ly; if(isSet == wasSet) {
// Read Chocochip8 Framebuffer and choose appropriate color, continue;
// note that the MSB of an scanline's bitset is the leftmost pixel.
lc = (mpFramebuffer->at(fy)[(chocochip8::gcWidth - 1) - fx] ? mFgColor : mBgColor);
} }
// Convert (x, y) indexes into SDL Surface pixel array index // Map framebuffer pixel to SDL surface rectangle,
Uint32 *pPixel = static_cast<Uint32*>(static_cast<void*>( // note that the MSB of an scanline's bitset is the leftmost pixel.
static_cast<char*>(pSurface->pixels) int z = (chocochip8::gcWidth - 1) - x;
+ sy * pSurface->pitch int x1 = ( z * pSurface->w) / chocochip8::gcWidth;
+ sx * pSurface->format->BytesPerPixel int x2 = ((z + 1) * pSurface->w) / chocochip8::gcWidth;
)); int y1 = ( y * pSurface->h) / chocochip8::gcHeight;
*pPixel = lc; int y2 = ((y + 1) * pSurface->h) / chocochip8::gcHeight;
SDL_Rect rect;
rect.x = x1;
rect.y = y1;
rect.w = x2 - x1;
rect.h = y2 - y1;
Uint32 color = (isSet ? mFgColor : mBgColor);
SDL_FillRect(pSurface, &rect, color);
doWindowUpdate = true;
} }
} }
SDL_UnlockSurface(pSurface); if(doWindowUpdate) {
SDL_UpdateWindowSurface(mpWindow); *mpDisplayState = *mpFramebuffer;
SDL_UpdateWindowSurface(mpWindow);
}
} }

View File

@@ -2,17 +2,25 @@
#include "Peripherals.hpp" #include "Peripherals.hpp"
#include <array>
#include <cstdint> #include <cstdint>
#include <memory>
#include <SDL2/SDL_video.h> #include <SDL2/SDL_video.h>
class DisplaySDL : public chocochip8::Display { class DisplaySDL : public chocochip8::Display {
public: public:
DisplaySDL(int w, int h, uint32_t fgCol, uint32_t bgCol); DisplaySDL(int w, int h, uint32_t fgCol = 0xffffff, uint32_t bgCol = 0x000000);
~DisplaySDL() override; ~DisplaySDL() override;
void updateWindow() const; void clear() override;
int blit(const chocochip8::Scanline &scanline, int y) override;
void updateWindow(bool forceWindowUpdate = false) const;
private: private:
using Framebuffer = std::array<chocochip8::Scanline, chocochip8::gcHeight>;
std::unique_ptr<Framebuffer> mpFramebuffer;
mutable std::unique_ptr<Framebuffer> mpDisplayState;
SDL_Window *mpWindow; SDL_Window *mpWindow;
Uint32 mFgColor; Uint32 mFgColor;
Uint32 mBgColor; Uint32 mBgColor;
mutable bool mDoClear;
}; };

View File

@@ -4,15 +4,62 @@
namespace chocochip8 { namespace chocochip8 {
Interpreter::Interpreter(unsigned ticksPerSecond, Display &display, Buzzer &buzzer, Keypad &keypad): // converts any 8-bit sprite row to its high-res 16-bit equivalent
constexpr uint16_t gcvLowResToHighResRowLookupTable[256] = {
0x0000, 0x0003, 0x000C, 0x000F, 0x0030, 0x0033, 0x003C, 0x003F, 0x00C0, 0x00C3, 0x00CC, 0x00CF, 0x00F0, 0x00F3, 0x00FC, 0x00FF,
0x0300, 0x0303, 0x030C, 0x030F, 0x0330, 0x0333, 0x033C, 0x033F, 0x03C0, 0x03C3, 0x03CC, 0x03CF, 0x03F0, 0x03F3, 0x03FC, 0x03FF,
0x0C00, 0x0C03, 0x0C0C, 0x0C0F, 0x0C30, 0x0C33, 0x0C3C, 0x0C3F, 0x0CC0, 0x0CC3, 0x0CCC, 0x0CCF, 0x0CF0, 0x0CF3, 0x0CFC, 0x0CFF,
0x0F00, 0x0F03, 0x0F0C, 0x0F0F, 0x0F30, 0x0F33, 0x0F3C, 0x0F3F, 0x0FC0, 0x0FC3, 0x0FCC, 0x0FCF, 0x0FF0, 0x0FF3, 0x0FFC, 0x0FFF,
0x3000, 0x3003, 0x300C, 0x300F, 0x3030, 0x3033, 0x303C, 0x303F, 0x30C0, 0x30C3, 0x30CC, 0x30CF, 0x30F0, 0x30F3, 0x30FC, 0x30FF,
0x3300, 0x3303, 0x330C, 0x330F, 0x3330, 0x3333, 0x333C, 0x333F, 0x33C0, 0x33C3, 0x33CC, 0x33CF, 0x33F0, 0x33F3, 0x33FC, 0x33FF,
0x3C00, 0x3C03, 0x3C0C, 0x3C0F, 0x3C30, 0x3C33, 0x3C3C, 0x3C3F, 0x3CC0, 0x3CC3, 0x3CCC, 0x3CCF, 0x3CF0, 0x3CF3, 0x3CFC, 0x3CFF,
0x3F00, 0x3F03, 0x3F0C, 0x3F0F, 0x3F30, 0x3F33, 0x3F3C, 0x3F3F, 0x3FC0, 0x3FC3, 0x3FCC, 0x3FCF, 0x3FF0, 0x3FF3, 0x3FFC, 0x3FFF,
0xC000, 0xC003, 0xC00C, 0xC00F, 0xC030, 0xC033, 0xC03C, 0xC03F, 0xC0C0, 0xC0C3, 0xC0CC, 0xC0CF, 0xC0F0, 0xC0F3, 0xC0FC, 0xC0FF,
0xC300, 0xC303, 0xC30C, 0xC30F, 0xC330, 0xC333, 0xC33C, 0xC33F, 0xC3C0, 0xC3C3, 0xC3CC, 0xC3CF, 0xC3F0, 0xC3F3, 0xC3FC, 0xC3FF,
0xCC00, 0xCC03, 0xCC0C, 0xCC0F, 0xCC30, 0xCC33, 0xCC3C, 0xCC3F, 0xCCC0, 0xCCC3, 0xCCCC, 0xCCCF, 0xCCF0, 0xCCF3, 0xCCFC, 0xCCFF,
0xCF00, 0xCF03, 0xCF0C, 0xCF0F, 0xCF30, 0xCF33, 0xCF3C, 0xCF3F, 0xCFC0, 0xCFC3, 0xCFCC, 0xCFCF, 0xCFF0, 0xCFF3, 0xCFFC, 0xCFFF,
0xF000, 0xF003, 0xF00C, 0xF00F, 0xF030, 0xF033, 0xF03C, 0xF03F, 0xF0C0, 0xF0C3, 0xF0CC, 0xF0CF, 0xF0F0, 0xF0F3, 0xF0FC, 0xF0FF,
0xF300, 0xF303, 0xF30C, 0xF30F, 0xF330, 0xF333, 0xF33C, 0xF33F, 0xF3C0, 0xF3C3, 0xF3CC, 0xF3CF, 0xF3F0, 0xF3F3, 0xF3FC, 0xF3FF,
0xFC00, 0xFC03, 0xFC0C, 0xFC0F, 0xFC30, 0xFC33, 0xFC3C, 0xFC3F, 0xFCC0, 0xFCC3, 0xFCCC, 0xFCCF, 0xFCF0, 0xFCF3, 0xFCFC, 0xFCFF,
0xFF00, 0xFF03, 0xFF0C, 0xFF0F, 0xFF30, 0xFF33, 0xFF3C, 0xFF3F, 0xFFC0, 0xFFC3, 0xFFCC, 0xFFCF, 0xFFF0, 0xFFF3, 0xFFFC, 0xFFFF
};
// 4x5 sprites for hex digits 0-F
constexpr uint8_t gcvLowResFontData[80] = {
0xF0, 0x90, 0x90, 0x90, 0xF0,
0x20, 0x60, 0x20, 0x20, 0x70,
0xF0, 0x10, 0xF0, 0x80, 0xF0,
0xF0, 0x10, 0xF0, 0x10, 0xF0,
0x90, 0x90, 0xF0, 0x10, 0x10,
0xF0, 0x80, 0xF0, 0x10, 0xF0,
0xF0, 0x80, 0xF0, 0x90, 0xF0,
0xF0, 0x10, 0x20, 0x40, 0x40,
0xF0, 0x90, 0xF0, 0x90, 0xF0,
0xF0, 0x90, 0xF0, 0x10, 0xF0,
0xF0, 0x90, 0xF0, 0x90, 0x90,
0xE0, 0x90, 0xE0, 0x90, 0xE0,
0xF0, 0x80, 0x80, 0x80, 0xF0,
0xE0, 0x90, 0x90, 0x90, 0xE0,
0xF0, 0x80, 0xF0, 0x80, 0xF0,
0xF0, 0x80, 0xF0, 0x80, 0x80
};
Interpreter::Interpreter(Display &display, Buzzer &buzzer, Keypad &keypad, CountdownTimer &delayTimer, CountdownTimer &soundTimer):
mvMemory(scMemorySize), mvMemory(scMemorySize),
mCallStack{}, mCallStack{},
mrDisplay{display}, mrDisplay{display},
mrBuzzer{buzzer}, mrBuzzer{buzzer},
mrKeypad{keypad}, mrKeypad{keypad},
mcTicksPerSecond{ticksPerSecond}, mrDelayTimer(delayTimer),
mrSoundTimer(soundTimer),
mvSpecialReg{}, mvSpecialReg{},
mvReg{} {} mvReg{},
mIsHighResMode{false} {
// Font sprite data goes into the interpreter reserved memory area
memcpy(mvMemory.data() + scLowRestFontAddr, gcvLowResFontData, sizeof(gcvLowResFontData));
// Initialize any non-zero registers at startup
mvSpecialReg[SR_PC] = scResetVector;
}
void Interpreter::tick() { void Interpreter::tick() {
// decodes all possible machine code arithmetic opcodes // decodes all possible machine code arithmetic opcodes
@@ -24,13 +71,16 @@ void Interpreter::tick() {
}; };
// fetch instruction // fetch instruction
sreg_t pc = mvSpecialReg[SR_PC]; sreg_t iInstAddr = mvSpecialReg[SR_PC];
unsigned inst = (mvMemory[pc] << 8) | mvMemory[pc + 1]; unsigned inst = (mvMemory.at(iInstAddr) << 8) | mvMemory.at(iInstAddr + 1);
// increment program counter
mvSpecialReg[SR_PC] += 2;
// extract fields // extract fields
unsigned regDst = (inst & 0x0F00) >> 8; // destination register index unsigned iRegDst = (inst & 0x0F00) >> 8; // destination register index
unsigned regSrc = (inst & 0x00F0) >> 4; // source register index unsigned iRegSrc = (inst & 0x00F0) >> 4; // source register index
unsigned opcode = (inst & 0x000F); // arithmetic opcode unsigned opcode = (inst & 0x000F); // arithmetic opcode or sprite index
unsigned imm8 = (inst & 0x00FF); // 8-bit immediate unsigned imm8 = (inst & 0x00FF); // 8-bit immediate
unsigned imm12 = (inst & 0x0FFF); // 12-bit immediate unsigned imm12 = (inst & 0x0FFF); // 12-bit immediate
@@ -38,9 +88,7 @@ void Interpreter::tick() {
case 0x0000: // 0NNN - call machine language routine case 0x0000: // 0NNN - call machine language routine
switch(inst) { switch(inst) {
case 0x00E0: // clear display case 0x00E0: // clear display
for(auto &scanline : *mrDisplay.mpFramebuffer) { mrDisplay.clear();
scanline.reset();
}
break; break;
case 0x00EE: // return from subroutine case 0x00EE: // return from subroutine
mvSpecialReg[SR_PC] = mCallStack.top(); mvSpecialReg[SR_PC] = mCallStack.top();
@@ -55,29 +103,29 @@ void Interpreter::tick() {
mvSpecialReg[SR_PC] = imm12; mvSpecialReg[SR_PC] = imm12;
break; break;
case 0x2000: // 2NNN - call subroutine case 0x2000: // 2NNN - call subroutine
mCallStack.push(pc); mCallStack.push(mvSpecialReg[SR_PC]);
mvSpecialReg[SR_PC] = imm12; mvSpecialReg[SR_PC] = imm12;
break; break;
case 0x3000: // 3XNN - skip if equal immediate case 0x3000: // 3XNN - skip if equal immediate
executeArithmetic(Opcode::JEQ, regDst, imm8); executeArithmetic(Opcode::JEQ, iRegDst, imm8);
break; break;
case 0x4000: // 4XNN - skip if nonequal immediate case 0x4000: // 4XNN - skip if nonequal immediate
executeArithmetic(Opcode::JNEQ, regDst, imm8); executeArithmetic(Opcode::JNEQ, iRegDst, imm8);
break; break;
case 0x5000: // 5XY0 - skip if equal case 0x5000: // 5XY0 - skip if equal
executeArithmetic(Opcode::JEQ, regDst, mvReg[regSrc]); executeArithmetic(Opcode::JEQ, iRegDst, mvReg[iRegSrc]);
break; break;
case 0x6000: // 6XNN - load immediate case 0x6000: // 6XNN - load immediate
executeArithmetic(Opcode::SET, regDst, imm8); executeArithmetic(Opcode::SET, iRegDst, imm8);
break; break;
case 0x7000: // 7XNN - increment case 0x7000: // 7XNN - increment
executeArithmetic(Opcode::ADD, regDst, imm8); executeArithmetic(Opcode::ADD, iRegDst, imm8);
break; break;
case 0x8000: // 8XNN - general arithmetic case 0x8000: // 8XNN - general arithmetic
executeArithmetic(opcodeMap[opcode], regDst, mvReg[regSrc]); executeArithmetic(opcodeMap[opcode], iRegDst, mvReg[iRegSrc]);
break; break;
case 0x9000: // 9XY0 - skip if nonequal case 0x9000: // 9XY0 - skip if nonequal
executeArithmetic(Opcode::JNEQ, regDst, mvReg[regSrc]); executeArithmetic(Opcode::JNEQ, iRegDst, mvReg[iRegSrc]);
break; break;
case 0xA000: // ANNN - load I case 0xA000: // ANNN - load I
mvSpecialReg[SR_I] = imm12; mvSpecialReg[SR_I] = imm12;
@@ -86,36 +134,89 @@ void Interpreter::tick() {
mvSpecialReg[SR_I] = mvReg[R_V0] + imm12; mvSpecialReg[SR_I] = mvReg[R_V0] + imm12;
break; break;
case 0xC000: // CXNN - load random case 0xC000: // CXNN - load random
executeArithmetic(Opcode::RAND, regDst, imm8); executeArithmetic(Opcode::RAND, iRegDst, imm8);
break; break;
case 0xD000: // DXYN - draw case 0xD000: // DXYN - draw
executeDraw(mvReg[iRegDst], mvReg[iRegSrc], opcode);
break; break;
case 0xE000: // EX9E, EXA1 - keypad access case 0xE000: // keypad access
switch(inst & 0xF0FF) {
case 0xE09E: // EX9E - skip if key pressed
if(mrKeypad.isKeyPressed(mvReg[iRegDst])) {
mvSpecialReg[SR_PC] += 2;
}
break;
case 0xE0A1: // EXA1 - skip if key not pressed
if(!mrKeypad.isKeyPressed(mvReg[iRegDst])) {
mvSpecialReg[SR_PC] += 2;
}
break;
default:
throw std::invalid_argument("not implemented");
break;
}
break; break;
case 0xF000: // several unique instructions case 0xF000: // several unique instructions
switch(inst & 0xF0FF) {
case 0xF007: // FX07 - read timer register
mvReg[iRegDst] = mrDelayTimer.get();
break;
case 0xF00A: // FX0A - wait for a keypress
mvSpecialReg[SR_PC] -= 2;
for(int i = KEY_0; i < KEY_0 + KEY_COUNT; i++) {
if(mrKeypad.isKeyPressed(i)) {
mvSpecialReg[SR_PC] += 2;
break;
}
}
break;
case 0xF015: // FX15 - set timer register
mrDelayTimer.set(mvReg[iRegDst]);
break;
case 0xF018: // FX18 - set sound timer register
if(mvReg[iRegDst] != 0) {
mrBuzzer.on();
}
mrSoundTimer.set(mvReg[iRegDst]);
break;
case 0xF01E: // FX1E - add to I
mvSpecialReg[SR_I] += mvReg[iRegDst];
break;
case 0xF029: // FX29 - set I to address of font sprite data for digit X
mvSpecialReg[SR_I] = scLowRestFontAddr + 5 * mvReg[iRegDst];
break;
case 0xF033: // FX33 - convert to bcd
mvMemory.at(mvSpecialReg[SR_I]) = (mvReg[iRegDst] / 100) % 10;
mvMemory.at(mvSpecialReg[SR_I] + 1) = (mvReg[iRegDst] / 10) % 10;
mvMemory.at(mvSpecialReg[SR_I] + 2) = mvReg[iRegDst] % 10;
break;
case 0xF055: // FX55 - dump registers
for(int i = 0; i <= iRegDst - R_V0; i++) {
mvMemory.at(mvSpecialReg[SR_I]++) = mvReg[R_V0 + i];
}
break;
case 0xF065: // FX65 - restore registers
for(int i = 0; i <= iRegDst - R_V0; i++) {
mvReg[R_V0 + i] = mvMemory.at(mvSpecialReg[SR_I]++);
}
break;
default:
throw std::invalid_argument("not implemented");
break;
}
break; break;
} }
// increment PC if(mrSoundTimer.get() == 0) {
mvSpecialReg[SR_PC] += 2; mrBuzzer.off();
// decrement timers
if(mvSpecialReg[SR_T1] > 0) {
mvSpecialReg[SR_T1] -= 1;
}
if(mvSpecialReg[SR_T2] > 0) {
mvSpecialReg[SR_T2] -= 1;
if(mvSpecialReg[SR_T2] == 0) {
mrBuzzer.off();
}
} }
} }
void Interpreter::loadProgram(size_t where, char const* data, size_t count) { void Interpreter::loadProgram(char const* data, size_t count, size_t where) {
if(where + count > scMemorySize) { if(where + count > scMemorySize) {
throw std::out_of_range("program exceeds memory bounds or capacity"); throw std::out_of_range("program exceeds memory bounds or capacity");
} }
memcpy(mvMemory.data(), data, count); memcpy(mvMemory.data() + where, data, count);
} }
void Interpreter::executeArithmetic(Opcode opcode, int iReg, reg_t operand) { void Interpreter::executeArithmetic(Opcode opcode, int iReg, reg_t operand) {
@@ -127,27 +228,30 @@ void Interpreter::executeArithmetic(Opcode opcode, int iReg, reg_t operand) {
case Opcode::XOR: mvReg[iReg] ^= operand; break; case Opcode::XOR: mvReg[iReg] ^= operand; break;
case Opcode::RAND: mvReg[iReg] = rand() & operand; break; case Opcode::RAND: mvReg[iReg] = rand() & operand; break;
case Opcode::LSH: case Opcode::LSH:
mvReg[R_VF] = (mvReg[iReg] & 0x80) ? 1 : 0; mvReg[iReg] = operand << 1;
mvReg[iReg] <<= 1; // VF = shifted out bit
mvReg[R_VF] = (operand & 0x80) ? 1 : 0;
break; break;
case Opcode::RSH: case Opcode::RSH:
mvReg[R_VF] = (mvReg[iReg] & 0x01) ? 1 : 0; mvReg[iReg] = operand >> 1;
mvReg[iReg] >>= 1; // VF = shifted out bit
mvReg[R_VF] = (operand & 0x01) ? 1 : 0;
break; break;
case Opcode::ADD: case Opcode::ADD:
tmp = mvReg[iReg] + operand; mvReg[iReg] = mvReg[iReg] + operand;
mvReg[R_VF] = (tmp < mvReg[iReg]) ? 1 : 0; // VF = 1 if carry occurs, VF = 0 if no carry
mvReg[iReg] = tmp; mvReg[R_VF] = (mvReg[iReg] < operand) ? 1 : 0;
break; break;
case Opcode::SUB: case Opcode::SUB:
tmp = mvReg[iReg] - operand; tmp = mvReg[iReg];
mvReg[R_VF] = (tmp > mvReg[iReg]) ? 1 : 0; mvReg[iReg] = mvReg[iReg] - operand;
mvReg[iReg] = tmp; // VF = 0 if borrow occurs, VF = 1 if no borrow
mvReg[R_VF] = (mvReg[iReg] > tmp) ? 0 : 1;
break; break;
case Opcode::SUB2: case Opcode::SUB2:
tmp = operand - mvReg[iReg]; mvReg[iReg] = operand - mvReg[iReg];
mvReg[R_VF] = (tmp > operand) ? 1 : 0; // VF = 0 if borrow occurs, VF = 1 if no borrow
mvReg[iReg] = tmp; mvReg[R_VF] = (mvReg[iReg] > operand) ? 0 : 1;
break; break;
case Opcode::JEQ: case Opcode::JEQ:
if(mvReg[iReg] == operand) { if(mvReg[iReg] == operand) {
@@ -165,4 +269,58 @@ void Interpreter::executeArithmetic(Opcode opcode, int iReg, reg_t operand) {
} }
} }
void Interpreter::executeDraw(uint8_t x, uint8_t y, uint8_t n) {
size_t iMemAddr = mvSpecialReg[SR_I]; // address of the sprite data in memory
int collisionCount = 0; // number of scanlines in which any pixel changes from on to off
// coordinates are doubled in low resolution mode
if(!mIsHighResMode) {
x *= 2;
y *= 2;
}
x %= gcWidth;
y %= gcHeight;
// make x=0 be the right side of the screen instead of the left
x = gcWidth - x;
// draw each row of the sprite
for(int i = 0; i < (mIsHighResMode && n == 0 ? 16 : n); i++) {
uint16_t spriteRowBits;
if(mIsHighResMode) {
// draws an 8xN sprite
spriteRowBits = mvMemory.at(iMemAddr++) << 8;
if(n == 0) {
// draws an 16xN sprite, so fetch another byte from sprite data
spriteRowBits |= mvMemory.at(iMemAddr++);
}
} else {
// in low-res mode, each sprite pixel draws two on-screen pixels
spriteRowBits = gcvLowResToHighResRowLookupTable[mvMemory.at(iMemAddr++)];
}
// convert to bitset and shift into absolute horizontal position on the screen
Scanline spriteScanline(spriteRowBits);
if(x < 16) {
spriteScanline >>= (16 - x);
} else {
spriteScanline <<= (x - 16);
}
// we draw one scanline per sprite row in high-res mode, but twice in low-res mode
for(int j = 0; j < (mIsHighResMode ? 1 : 2); j++) {
// blit the sprite bitset into the screen
if(mrDisplay.blit(spriteScanline, y + i * (mIsHighResMode ? 1 : 2) + j) != 0) {
collisionCount += 1;
}
}
// update state flags
if(mIsHighResMode) {
mvReg[R_VF] = collisionCount;
} else {
mvReg[R_VF] = (collisionCount > 0 ? 1 : 0);
}
}
}
}; // namespace chochochip8 }; // namespace chochochip8

View File

@@ -14,6 +14,7 @@ private:
using sreg_t = unsigned; using sreg_t = unsigned;
public: public:
constexpr static sreg_t scLowRestFontAddr = 0x0000;
constexpr static sreg_t scResetVector = 0x0200; constexpr static sreg_t scResetVector = 0x0200;
constexpr static size_t scMemorySize = 4096; constexpr static size_t scMemorySize = 4096;
@@ -24,7 +25,7 @@ public:
}; };
enum { enum {
SR_PC, SR_I, SR_T1, SR_T2, SR_PC, SR_I, /*SR_T1, SR_T2,*/
SR_COUNT SR_COUNT
}; };
@@ -33,12 +34,13 @@ public:
}; };
public: public:
Interpreter(unsigned ticksPerSecond, Display &display, Buzzer &buzzer, Keypad &keypad); Interpreter(Display &display, Buzzer &buzzer, Keypad &keypad, CountdownTimer &delayTimer, CountdownTimer &soundTimer);
void tick(); void tick();
void loadProgram(size_t where, char const* data, size_t count); void loadProgram(char const* data, size_t count, size_t where = scResetVector);
private: private:
void executeArithmetic(Opcode opcode, int iReg, reg_t operand); void executeArithmetic(Opcode opcode, int iReg, reg_t operand);
void executeDraw(uint8_t x, uint8_t y, uint8_t n);
private: private:
std::vector<uint8_t> mvMemory; std::vector<uint8_t> mvMemory;
@@ -46,9 +48,11 @@ private:
Display &mrDisplay; Display &mrDisplay;
Buzzer &mrBuzzer; Buzzer &mrBuzzer;
Keypad &mrKeypad; Keypad &mrKeypad;
const unsigned mcTicksPerSecond; CountdownTimer &mrDelayTimer;
CountdownTimer &mrSoundTimer;
sreg_t mvSpecialReg[SR_COUNT]; sreg_t mvSpecialReg[SR_COUNT];
reg_t mvReg[R_COUNT]; reg_t mvReg[R_COUNT];
bool mIsHighResMode;
}; // class Interpreter }; // class Interpreter
}; // namespace chocohip8 }; // namespace chocohip8

36
KeypadSDL.cpp Normal file
View File

@@ -0,0 +1,36 @@
#include "KeypadSDL.hpp"
bool KeypadSDL::isKeyPressed(int key) const {
return mvKeyDown.at(key);
}
void KeypadSDL::processEvent(SDL_Event &e) {
auto keymap = [](int sdlKeyCode) -> int {
switch(sdlKeyCode) {
case SDLK_1: return chocochip8::KEY_1;
case SDLK_2: return chocochip8::KEY_2;
case SDLK_3: return chocochip8::KEY_3;
case SDLK_4: return chocochip8::KEY_C;
case SDLK_q: return chocochip8::KEY_4;
case SDLK_w: return chocochip8::KEY_5;
case SDLK_e: return chocochip8::KEY_6;
case SDLK_r: return chocochip8::KEY_D;
case SDLK_a: return chocochip8::KEY_7;
case SDLK_s: return chocochip8::KEY_8;
case SDLK_d: return chocochip8::KEY_9;
case SDLK_f: return chocochip8::KEY_E;
case SDLK_z: return chocochip8::KEY_A;
case SDLK_x: return chocochip8::KEY_0;
case SDLK_c: return chocochip8::KEY_B;
case SDLK_v: return chocochip8::KEY_F;
default : return -1;
}
};
if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN) {
int k = keymap(e.key.keysym.sym);
if(k != -1) {
mvKeyDown[k] = (e.type == SDL_KEYDOWN);
}
}
}

12
KeypadSDL.hpp Normal file
View File

@@ -0,0 +1,12 @@
#include "Peripherals.hpp"
#include <SDL2/SDL_events.h>
#include <array>
class KeypadSDL : public chocochip8::Keypad {
public:
bool isKeyPressed(int key) const override;
void processEvent(SDL_Event &e);
private:
std::array<bool, chocochip8::KEY_COUNT> mvKeyDown;
};

View File

@@ -1,30 +1,26 @@
#pragma once #pragma once
#include <array>
#include <bitset> #include <bitset>
#include <memory>
namespace chocochip8 { namespace chocochip8 {
constexpr size_t gcWidth = 128; constexpr size_t gcWidth = 128;
constexpr size_t gcHeight = 64; constexpr size_t gcHeight = 64;
using Scanline = std::bitset<gcWidth>; using Scanline = std::bitset<gcWidth>;
using Framebuffer = std::array<Scanline, gcHeight>;
enum class Key { enum {
KEY_0, KEY_1, KEY_2, KEY_3, KEY_0, KEY_1, KEY_2, KEY_3,
KEY_4, KEY_5, KEY_6, KEY_7, KEY_4, KEY_5, KEY_6, KEY_7,
KEY_8, KEY_9, KEY_A, KEY_B, KEY_8, KEY_9, KEY_A, KEY_B,
KEY_C, KEY_D, KEY_E, KEY_F KEY_C, KEY_D, KEY_E, KEY_F,
KEY_COUNT
}; };
class Display { class Display {
public: public:
friend class Interpreter;
Display(): mpFramebuffer{std::make_unique<Framebuffer>()} {}
virtual ~Display() = default; virtual ~Display() = default;
protected: virtual int blit(const Scanline& spriteScanline, int y) = 0;
std::unique_ptr<Framebuffer> mpFramebuffer; virtual void clear() = 0;
}; };
class Buzzer { class Buzzer {
@@ -37,7 +33,14 @@ namespace chocochip8 {
class Keypad { class Keypad {
public: public:
virtual ~Keypad() = default; virtual ~Keypad() = default;
virtual void isKeyPressed(Key key) = 0; virtual bool isKeyPressed(int key) const = 0;
};
class CountdownTimer {
public:
virtual ~CountdownTimer() = default;
virtual void set(unsigned value) = 0;
virtual unsigned get() const = 0;
}; };
}; // namespace chocochip8 }; // namespace chocochip8

View File

@@ -1,36 +1,58 @@
#include <iostream> #include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "BuzzerSDL.hpp" #include "BuzzerSDL.hpp"
#include "CountdownTimerSDL.hpp"
#include "DisplaySDL.hpp" #include "DisplaySDL.hpp"
#include "Peripherals.hpp" #include "KeypadSDL.hpp"
#include "Interpreter.hpp"
int main(int argc, char* args[]) { int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << '\n'; std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << '\n';
return 1; return 1;
} }
class DisplayTest : public DisplaySDL {
public:
DisplayTest() : DisplaySDL(1280, 640, 0xff0000, 0x00ff00) {
for(int i = 0; i < chocochip8::gcHeight; i+=2) {
mpFramebuffer->at(i).set();
}
}
};
BuzzerSDL buzzer(440); BuzzerSDL buzzer(440);
//buzzer.on(); int N = 4;
DisplayTest display; DisplaySDL display(128*N, 64*N);
KeypadSDL keypad;
CountdownTimerSDL delayTimer(60);
CountdownTimerSDL soundTimer(60);
CountdownTimerSDL displayTimer(60);
chocochip8::Interpreter chip8(display, buzzer, keypad, delayTimer, soundTimer);
auto rom = std::vector<char>();
auto romfile = std::ifstream(argv[1] != NULL ? argv[1] : "/dev/stdin", std::ios_base::in | std::ios_base::binary);
std::copy(
std::istreambuf_iterator<char>(romfile),
std::istreambuf_iterator<char>(),
std::back_insert_iterator(rom)
);
chip8.loadProgram(rom.data(), rom.size());
SDL_Event event; SDL_Event event;
while(SDL_WaitEvent(&event) && event.type != SDL_QUIT) { bool done = false;
display.updateWindow(); while(!done) {
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
done = true;
} else {
keypad.processEvent(event);
}
}
chip8.tick();
if(displayTimer.get() == 0) {
display.updateWindow();
displayTimer.set(1);
}
} }
buzzer.off(); buzzer.off();
SDL_Quit(); SDL_Quit();
return 0; return 0;
} }