port this code to C using SDL3 main.py: from screen import SSLib from cpu import Chip8…
- User
port this code to C using SDL3 main.py: from screen import SSLib from cpu import Chip8 import time
class Emulator: def init(self): self.cpu = Chip8() self.sslib = SSLib((64, 32), 29) self.font = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, # 0 0x20, 0x60, 0x20, 0x20, 0x70, # 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, # 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, # 3 0x90, 0x90, 0xF0, 0x10, 0x10, # 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, # 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, # 6 0xF0, 0x10, 0x20, 0x40, 0x40, # 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, # 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, # 9 0xF0, 0x90, 0xF0, 0x90, 0x90, # A 0xE0, 0x90, 0xE0, 0x90, 0xE0, # B 0xF0, 0x80, 0x80, 0x80, 0xF0, # C 0xE0, 0x90, 0x90, 0x90, 0xE0, # D 0xF0, 0x80, 0xF0, 0x80, 0xF0, # E 0xF0, 0x80, 0xF0, 0x80, 0x80 # F ]
self.key_dict = { '': 0xFF, '[1]': 1, '[2]': 2, '[3]': 3, '[4]': 4, '[5]': 5, '[6]': 6, '[7]': 7, '[8]': 8, '[9]': 9, '[/]': 0xA, '[*]': 0xB, '[-]': 0xC, '[+]': 0xD, 'enter': 0xE, '[.]': 0xF, } def run(self, program): # load font for i, v in enumerate(self.font): self.cpu.memory[0x50 + i] = v # load program for i, v in enumerate(program): self.cpu.memory[0x200 + i] = v # run while True: data = self.sslib.update() if data[0]: self.sslib.terminate(); break self.cpu.key_down = data[1] try: self.cpu.key = self.key_dict[data[2]] except KeyError: pass if data[2] == 'd': # dump cpu state print('CPU STATE') for i, v, in enumerate(self.cpu.V): print(' - V{:01X} = 0x{:04x}'.format(i, v)) print(' - PC = 0x{:04x}'.format(self.cpu.pc)) print(' - I = 0x{:04x}'.format(self.cpu.I)) print(' - DT = 0x{:04x}'.format(self.cpu.delay_timer)) print(' - ST = 0x{:04x}'.format(self.cpu.sound_timer)) self.cpu.execute(self.cpu.decode(self.cpu.fetch())) clock = time.perf_counter() * 700 sleep = int(clock) + 1 - clock time.sleep(sleep/700) self.sslib.draw(self.cpu.display)if name == 'main': with open('3-corax+.ch8', 'rb') as f: program = f.read()
e = Emulator() e.run(program)cpu.py: from dataclasses import dataclass, field import random import array
class OverflowArray(array.array): def setitem(self, index, value): max_value = (1 << (self.itemsize * 8)) - 1 value = value & max_value super().setitem(index, value)
class Instruction: def init(self, value): self.value = value self.opcode = (self.value & 0b1111000000000000) >> 12 self.X = (self.value & 0b0000111100000000) >> 8 self.Y = (self.value & 0b0000000011110000) >> 4 self.N = (self.value & 0b0000000000001111) >> 0 self.NN = (self.value & 0b0000000011111111) >> 0 self.NNN = (self.value & 0b0000111111111111) >> 0
class Chip8: def init(self):
self.memory = OverflowArray('B', [0] * 4096) self.display = OverflowArray('B', [0] * (64 * 32)) self.stack = OverflowArray('H', [0] * 32) # 32 stack entries self.V = OverflowArray('B', [0] * 16) self.I = 0 self.pc = 0x200 self.delay_timer = 0 self.sound_timer = 0 self.key = 0 self.key_down = False self.quirks = { 'COSMAC_SHIFT': True, 'COSMAC_JUMP_TABLE': True, 'AMIGA_FX1E_VF': True, 'STORE_TEMP_VAR': True, }def fetch(self): instruction = (self.memory[self.pc] << 8) | self.memory[self.pc + 1] self.pc += 2 return instruction def decode(self, value): x = Instruction(value) return x def execute(self, instruction): if self.delay_timer > 0: self.delay_timer -= 1 if self.sound_timer > 0: print('beeeep') self.sound_timer -= 1 u16mask = (1 << 16) - 1 match instruction.opcode: case 0x0: # 0 - misc operations match instruction.NNN: case 0x0E0: # 00E0 - clear screen self.display = OverflowArray('B', [0] * (64 * 32)) case 0x0EE: # 00EE - return from subroutine self.pc = self.stack.pop() case _: pass case 0x1: # 1NNN - jump self.pc = instruction.NNN case 0x2: # 2NNN - call subroutine self.stack.append(self.pc) self.pc = instruction.NNN case 0x3: # 3XNN - skip if vx == nn if self.V[instruction.X] == instruction.NN: self.pc += 2 case 0x4: # 4XNN - skip if vx != nn if self.V[instruction.X] != instruction.NN: self.pc += 2 case 0x5: # 5XY0 - skip if vx == vy if self.V[instruction.X] == self.V[instruction.Y]: self.pc += 2 case 0x6: # 6XNN - set VX self.V[instruction.X] = instruction.NN case 0x7: # 7XNN - add to VX self.V[instruction.X] += instruction.NN case 0x8: # 8XYN - logic and arithmetic group match instruction.N: case 0x0: # 8XY0 - set vx = vy self.V[instruction.X] = self.V[instruction.Y] case 0x1: # 8XY1 - vx = vx | vy self.V[instruction.X] = self.V[instruction.X] | self.V[instruction.Y] case 0x2: # 8XY2 - vx = vx & vy self.V[instruction.X] = self.V[instruction.X] & self.V[instruction.Y] case 0x3: # 8XY3 - vx = vx ^ vy self.V[instruction.X] = self.V[instruction.X] ^ self.V[instruction.Y] case 0x4: # 8XY4 - vx = vx + vy, vf = carry op = self.V[instruction.X] + self.V[instruction.Y] self.V[0xF] = 1 if op > 255 else 0 self.V[instruction.X] = op case 0x5: # 8XY5 - vx = vx - vy op = self.V[instruction.X] - self.V[instruction.Y] self.V[0xF] = 0 if op > 255 else 1 self.V[instruction.X] = op case 0x6: # 8XY6 - vx = vx >> 1 if self.quirks['COSMAC_SHIFT']: self.V[instruction.X] = self.V[instruction.Y] self.V[instruction.X] = (self.V[instruction.X] >> 1) & u16mask self.V[0xF] = 1 if self.V[instruction.X] & 1 == 1 else 0 case 0x7: # 8XY7 - vx = vy - vx op = self.V[instruction.Y] - self.V[instruction.X] self.V[0xF] = 0 if op > 255 else 1 self.V[instruction.X] = op case 0xE: # 8XYE - vx = vx << 1 if self.quirks['COSMAC_SHIFT']: self.V[instruction.X] = self.V[instruction.Y] self.V[instruction.X] = (self.V[instruction.X] << 1) & u16mask self.V[0xF] = 1 if (self.V[instruction.X] & 0b10) >> 1 == 1 else 0 case 0x9: # 9XY0 - skip if vx != vy if self.V[instruction.X] != self.V[instruction.Y]: self.pc += 2 case 0xA: # ANNN - set I self.I = instruction.NNN case 0xB: # BNNN/BXNN - pc = nnn + v0 / pc = nnn + vx if self.quirks['COSMAC_JUMP_TABLE']: self.pc = instruction.NNN + self.V[0] else: self.pc = instruction.NNN + self.V[instruction.X] case 0xC: # CXNN - vx = random & nn self.V[instruction.X] = random.randint(0x00, 0xFF) & instruction.NN case 0xD: # DXYN - display self.draw(instruction.X, instruction.Y, instruction.N) case 0xE: # EXNN - key group match instruction.NN: case 0x9E: # EX9E - skip if key in vx is pressed if self.key_down and self.key == self.V[instruction.X]: self.pc += 2 case 0xA1: # EX9E - skip if key in vx is not pressed if self.key != self.V[instruction.X]: self.pc += 2 case 0xF: # FXNN - misc instructions match instruction.NN: case 0x07: # FX07 - vx = delay timer self.V[instruction.X] = self.delay_timer case 0x15: # FX15 - delay timer = vx self.delay_timer = self.V[instruction.X] case 0x18: # FX18 - sound timer = vx self.sound_timer = self.V[instruction.X] case 0x1E: # FX1E - i = i + vx self.I += self.V[instruction.X] if self.quirks['AMIGA_FX1E_VF']: self.V[0xF] = self.I > 0x0FFF case 0x0A: # FX0A - wait for key if not self.key_down: self.pc -= 2 else: self.V[instruction.X] = self.key case 0x29: # FX29 - i = font character self.I = 0x50 + (self.V[instruction.X] * 5) case 0x33: # FX33 - BCD for i, c in enumerate(str(self.V[instruction.X])): self.memory[self.I + i] = int(c) case 0x55: # FX55 - store v0 - vx into memory[i] for i in range(instruction.X): self.memory[self.I + i] = self.V[i] if not self.quirks['STORE_TEMP_VAR']: self.I = self.I + instruction.X + 1 case 0x65: # FX65 - load v0 - vx from memory[i] for i in range(instruction.X): self.V[i] = self.memory[self.I + i] if not self.quirks['STORE_TEMP_VAR']: self.I = self.I + instruction.X + 1 case _: print(f'UNRECOGNIZED INSTRUCTION\n - V = {hex(instruction.value)}\n - O = {hex(instruction.opcode)}\n - X = {hex(instruction.X)}\n - Y = {hex(instruction.Y)}\n - N = {hex(instruction.N)}\n - NN = {hex(instruction.NN)}\n - NNN = {hex(instruction.NNN)}\n') def draw(self, X, Y, N): self.V[0xF] = 0 y_pos = self.V[Y] % 32 for row in range(N): x_pos = self.V[X] % 64 sprite_byte = self.memory[self.I + row] bits = bin(sprite_byte)[2:].zfill(8) for bit in bits: if bit == '1': index = x_pos + 64 * y_pos self.display[index] ^= 1 self.V[0xF] = self.display[index] x_pos += 1 if x_pos > 63: break y_pos += 1 if y_pos > 31: breakscreen.py: import pygame
class SSLib: def init(self, reso, scalar): self.reso = reso self.scalar = scalar self.scaled = (reso[0] * scalar, reso[1] * scalar) self.screen = pygame.display.set_mode(self.scaled) self.pixel = pygame.Surface(reso) self.key_down = False
def update(self): key = '' for event in pygame.event.get(): if event.type == pygame.QUIT: return (True, False, '') if event.type == pygame.KEYDOWN: self.key_down = True key = pygame.key.name(event.key) if event.type == pygame.KEYUP: self.key_down = False return (False, self.key_down, key) def draw(self, arr): self.screen.fill((255, 255, 255)) for i, v in enumerate(arr): x = i % self.reso[0] y = i // self.reso[0] self.pixel.set_at((x, y), (255, 204, 1) if v else (153, 102, 1)) pygame.transform.scale(self.pixel, self.scaled, self.screen) pygame.display.flip() def terminate(self): pygame.quit() - Assistant
Porting your CHIP-8 emulator from Python to C using SDL3 involves translating the Python classes and logic into C structures and functions while leveraging SDL3 for graphics and input handling. Below is a structured approach with separate C files mirroring your Python modules:
main.c,cpu.h,cpu.c,screen.h, andscreen.c.Project Structure
chip8_emulator/ ├── main.c ├── cpu.c ├── cpu.h ├── screen.c ├── screen.h ├── Makefile └── fonts.cCompilation Instructions
Ensure you have SDL3 installed on your system. You can compile the project using the provided
Makefileor manually usinggcc.Using Makefile:
Create a
Makefilewith the following content:CC = gcc CFLAGS = -Wall -Wextra -O2 `sdl3-config --cflags` LDFLAGS = `sdl3-config --libs` SRCS = main.c cpu.c screen.c fonts.c OBJS = $(SRCS:.c=.o) TARGET = chip8_emulator all: $(TARGET) $(TARGET): $(OBJS) $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) %.o: %.c $(CC) $(CFLAGS) -c $< -o $@ clean: rm -f $(OBJS) $(TARGET)Run
makein the project directory to build the emulator.Using GCC Directly:
gcc -Wall -Wextra -O2 main.c cpu.c screen.c fonts.c -o chip8_emulator `sdl3-config --cflags --libs`1.
cpu.hDefines the structures and functions related to the CHIP-8 CPU.
// cpu.h #ifndef CPU_H #define CPU_H #include <stdint.h> #include <stdbool.h> // Define display size #define DISPLAY_WIDTH 64 #define DISPLAY_HEIGHT 32 typedef struct { uint8_t memory[4096]; uint8_t V[16]; // General-purpose registers V0 to VF uint16_t I; // Index register uint16_t pc; // Program counter uint16_t stack[32]; uint16_t sp; // Stack pointer uint8_t delay_timer; uint8_t sound_timer; uint8_t key; bool key_down; bool quirks[4]; // COSMAC_SHIFT, COSMAC_JUMP_TABLE, AMIGA_FX1E_VF, STORE_TEMP_VAR uint8_t display[DISPLAY_WIDTH * DISPLAY_HEIGHT]; } Chip8; // Initialize the CHIP-8 CPU void chip8_init(Chip8 *chip); // Load font set into memory void chip8_load_fonts(Chip8 *chip); // Load program into memory starting at 0x200 bool chip8_load_program(Chip8 *chip, const uint8_t *program, size_t size); // Fetch the next opcode uint16_t chip8_fetch_opcode(Chip8 *chip); // Decode and execute the opcode void chip8_execute_opcode(Chip8 *chip, uint16_t opcode); // Update timers void chip8_update_timers(Chip8 *chip); // Utility functions uint8_t chip8_random_byte(); #endif // CPU_H2.
cpu.cImplements the CHIP-8 CPU logic, including opcode execution.
// cpu.c #include "cpu.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> // CHIP-8 font set extern const uint8_t chip8_fontset[80]; void chip8_init(Chip8 *chip) { memset(chip, 0, sizeof(Chip8)); chip8_load_fonts(chip); chip->pc = 0x200; // Programs start at memory location 0x200 // Initialize quirks chip->quirks[0] = true; // COSMAC_SHIFT chip->quirks[1] = true; // COSMAC_JUMP_TABLE chip->quirks[2] = true; // AMIGA_FX1E_VF chip->quirks[3] = true; // STORE_TEMP_VAR srand(time(NULL)); } void chip8_load_fonts(Chip8 *chip) { memcpy(&chip->memory[0x50], chip8_fontset, sizeof(chip8_fontset)); } bool chip8_load_program(Chip8 *chip, const uint8_t *program, size_t size) { if (size > (4096 - 0x200)) { fprintf(stderr, "Program size exceeds available memory.\n"); return false; } memcpy(&chip->memory[0x200], program, size); return true; } uint16_t chip8_fetch_opcode(Chip8 *chip) { return (chip->memory[chip->pc] << 8) | chip->memory[chip->pc + 1]; } uint8_t chip8_random_byte() { return rand() % 256; } void chip8_execute_opcode(Chip8 *chip, uint16_t opcode) { // Decode the opcode uint8_t nibbles[4]; nibbles[0] = (opcode & 0xF000) >> 12; nibbles[1] = (opcode & 0x0F00) >> 8; nibbles[2] = (opcode & 0x00F0) >> 4; nibbles[3] = (opcode & 0x000F); uint16_t NNN = opcode & 0x0FFF; uint8_t NN = opcode & 0x00FF; uint8_t N = opcode & 0x000F; uint8_t X = nibbles[1]; uint8_t Y = nibbles[2]; switch (nibbles[0]) { case 0x0: switch (NNN) { case 0x00E0: // Clear the display memset(chip->display, 0, sizeof(chip->display)); chip->pc += 2; break; case 0x00EE: // Return from subroutine if (chip->sp == 0) { fprintf(stderr, "Stack underflow!\n"); exit(EXIT_FAILURE); } chip->sp--; chip->pc = chip->stack[chip->sp]; chip->pc += 2; break; default: // SYS addr - ignored chip->pc += 2; break; } break; case 0x1: // Jump to address NNN chip->pc = NNN; break; case 0x2: // Call subroutine at NNN if (chip->sp >= 32) { fprintf(stderr, "Stack overflow!\n"); exit(EXIT_FAILURE); } chip->stack[chip->sp++] = chip->pc; chip->pc = NNN; break; case 0x3: // Skip next instruction if Vx == NN if (chip->V[X] == NN) chip->pc += 4; else chip->pc += 2; break; case 0x4: // Skip next instruction if Vx != NN if (chip->V[X] != NN) chip->pc += 4; else chip->pc += 2; break; case 0x5: // Skip next instruction if Vx == Vy if (chip->V[X] == chip->V[Y]) chip->pc += 4; else chip->pc += 2; break; case 0x6: // Set Vx = NN chip->V[X] = NN; chip->pc += 2; break; case 0x7: // Set Vx = Vx + NN chip->V[X] += NN; chip->pc += 2; break; case 0x8: switch (N) { case 0x0: // Set Vx = Vy chip->V[X] = chip->V[Y]; break; case 0x1: // Set Vx = Vx OR Vy chip->V[X] |= chip->V[Y]; break; case 0x2: // Set Vx = Vx AND Vy chip->V[X] &= chip->V[Y]; break; case 0x3: // Set Vx = Vx XOR Vy chip->V[X] ^= chip->V[Y]; break; case 0x4: { // Set Vx = Vx + Vy, set VF = carry uint16_t sum = chip->V[X] + chip->V[Y]; chip->V[0xF] = (sum > 255) ? 1 : 0; chip->V[X] = sum & 0xFF; } break; case 0x5: { // Set Vx = Vx - Vy, set VF = NOT borrow chip->V[0xF] = (chip->V[X] > chip->V[Y]) ? 1 : 0; chip->V[X] -= chip->V[Y]; } break; case 0x6: { // Set Vx = Vx SHR 1, set VF = LSB before shift chip->V[0xF] = chip->V[X] & 0x1; if (chip->quirks[0]) { // COSMAC_SHIFT chip->V[X] = chip->V[Y] >> 1; } else { chip->V[X] >>= 1; } } break; case 0x7: { // Set Vx = Vy - Vx, set VF = NOT borrow chip->V[0xF] = (chip->V[Y] > chip->V[X]) ? 1 : 0; chip->V[X] = chip->V[Y] - chip->V[X]; } break; case 0xE: { // Set Vx = Vx SHL 1, set VF = MSB before shift chip->V[0xF] = (chip->V[X] & 0x80) >> 7; if (chip->quirks[0]) { // COSMAC_SHIFT chip->V[X] = chip->V[Y] << 1; } else { chip->V[X] <<= 1; } } break; default: fprintf(stderr, "Unknown opcode: 0x%04X\n", opcode); exit(EXIT_FAILURE); } chip->pc += 2; break; case 0x9: // Skip next instruction if Vx != Vy if (chip->V[X] != chip->V[Y]) chip->pc += 4; else chip->pc += 2; break; case 0xA: // Set I = NNN chip->I = NNN; chip->pc += 2; break; case 0xB: // Jump to location NNN + V0 if (chip->quirks[1]) { // COSMAC_JUMP_TABLE chip->pc = NNN + chip->V[0]; } else { chip->pc = NNN + chip->V[X]; } break; case 0xC: // Set Vx = random byte AND NN chip->V[X] = chip8_random_byte() & NN; chip->pc += 2; break; case 0xD: { // Display/draw uint8_t height = N; chip->V[0xF] = 0; uint8_t x = chip->V[X] % DISPLAY_WIDTH; uint8_t y = chip->V[Y] % DISPLAY_HEIGHT; for (uint8_t row = 0; row < height; row++) { uint8_t sprite_byte = chip->memory[chip->I + row]; for (int8_t bit = 7; bit >= 0; bit--) { uint8_t pixel = (sprite_byte >> bit) & 1; if (pixel) { uint16_t index = x + (y * DISPLAY_WIDTH); if (index >= DISPLAY_WIDTH * DISPLAY_HEIGHT) continue; if (chip->display[index]) { chip->V[0xF] = 1; } chip->display[index] ^= 1; x++; if (x >= DISPLAY_WIDTH) { x = 0; y = (y + 1) % DISPLAY_HEIGHT; } } else { x++; if (x >= DISPLAY_WIDTH) { x = 0; y = (y + 1) % DISPLAY_HEIGHT; } } } } chip->pc += 2; } break; case 0xE: switch (NN) { case 0x9E: // Skip next instruction if key with value Vx is pressed if (chip->key_down && chip->key == chip->V[X]) chip->pc += 4; else chip->pc += 2; break; case 0xA1: // Skip next instruction if key with value Vx is not pressed if (!chip->key_down || chip->key != chip->V[X]) chip->pc += 4; else chip->pc += 2; break; default: fprintf(stderr, "Unknown opcode: 0x%04X\n", opcode); exit(EXIT_FAILURE); } break; case 0xF: switch (NN) { case 0x07: // Set Vx = delay timer value chip->V[X] = chip->delay_timer; chip->pc += 2; break; case 0x15: // Set delay timer = Vx chip->delay_timer = chip->V[X]; chip->pc += 2; break; case 0x18: // Set sound timer = Vx chip->sound_timer = chip->V[X]; chip->pc += 2; break; case 0x1E: // Set I = I + Vx chip->I += chip->V[X]; if (chip->quirks[2]) { // AMIGA_FX1E_VF chip->V[0xF] = (chip->I > 0x0FFF) ? 1 : 0; } chip->pc += 2; break; case 0x0A: { // Wait for a key press, store in Vx if (!chip->key_down) { chip->pc -= 2; } else { chip->V[X] = chip->key; chip->pc += 2; } } break; case 0x29: // Set I = location of sprite for digit Vx chip->I = 0x50 + (chip->V[X] * 5); chip->pc += 2; break; case 0x33: { // Store BCD representation of Vx in memory locations I, I+1, and I+2 uint8_t value = chip->V[X]; chip->memory[chip->I] = value / 100; chip->memory[chip->I + 1] = (value / 10) % 10; chip->memory[chip->I + 2] = value % 10; chip->pc += 2; } break; case 0x55: { // Store V0 to Vx in memory starting at I for (uint8_t i = 0; i <= X; i++) { chip->memory[chip->I + i] = chip->V[i]; } if (!chip->quirks[3]) { // STORE_TEMP_VAR chip->I += X + 1; } chip->pc += 2; } break; case 0x65: { // Read V0 to Vx from memory starting at I for (uint8_t i = 0; i <= X; i++) { chip->V[i] = chip->memory[chip->I + i]; } if (!chip->quirks[3]) { // STORE_TEMP_VAR chip->I += X + 1; } chip->pc += 2; } break; default: fprintf(stderr, "Unknown opcode: 0x%04X\n", opcode); exit(EXIT_FAILURE); } break; default: fprintf(stderr, "Unrecognized opcode: 0x%04X\n", opcode); exit(EXIT_FAILURE); } } void chip8_update_timers(Chip8 *chip) { if (chip->delay_timer > 0) chip->delay_timer--; if (chip->sound_timer > 0) { if (chip->sound_timer == 1) { // Implement sound beep if desired printf("BEEP!\n"); } chip->sound_timer--; } }3.
fonts.cContains the CHIP-8 font set.
// fonts.c #include "cpu.h" const uint8_t chip8_fontset[80] = { // 0 0xF0, 0x90, 0x90, 0x90, 0xF0, // 1 0x20, 0x60, 0x20, 0x20, 0x70, // 2 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 3 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 4 0x90, 0x90, 0xF0, 0x10, 0x10, // 5 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 6 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 7 0xF0, 0x10, 0x20, 0x40, 0x40, // 8 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x10, 0xF0, // A 0xF0, 0x90, 0xF0, 0x90, 0x90, // B 0xE0, 0x90, 0xE0, 0x90, 0xE0, // C 0xF0, 0x80, 0x80, 0x80, 0xF0, // D 0xE0, 0x90, 0x90, 0x90, 0xE0, // E 0xF0, 0x80, 0xF0, 0x80, 0xF0, // F 0xF0, 0x80, 0xF0, 0x80, 0x80 };4.
screen.hDefines the structures and functions related to the display and input handling using SDL3.
// screen.h #ifndef SCREEN_H #define SCREEN_H #include <SDL3/SDL.h> #include "cpu.h" #include <stdbool.h> typedef struct { SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *texture; uint32_t window_width; uint32_t window_height; uint32_t scale; } Screen; // Initialize the SDL window and renderer bool screen_init(Screen *screen, uint32_t width, uint32_t height, uint32_t scale); // Handle input events bool screen_update(Screen *screen, bool *quit, uint8_t *key, bool *key_down); // Render the display void screen_render(Screen *screen, uint8_t *display); // Clean up SDL resources void screen_cleanup(Screen *screen); #endif // SCREEN_H5.
screen.cImplements the display rendering and input handling using SDL3.
// screen.c #include "screen.h" #include <stdio.h> bool screen_init(Screen *screen, uint32_t width, uint32_t height, uint32_t scale) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return false; } screen->window_width = width; screen->window_height = height; screen->scale = scale; screen->window = SDL_CreateWindow("CHIP-8 Emulator", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width * scale, height * scale, 0); if (!screen->window) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); return false; } screen->renderer = SDL_CreateRenderer(screen->window, -1, SDL_RENDERER_ACCELERATED); if (!screen->renderer) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); return false; } screen->texture = SDL_CreateTexture(screen->renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, width, height); if (!screen->texture) { fprintf(stderr, "SDL_CreateTexture Error: %s\n", SDL_GetError()); return false; } return true; } bool screen_update(Screen *screen, bool *quit, uint8_t *key, bool *key_down_flag) { SDL_Event event; *quit = false; *key_down_flag = false; *key = 0xFF; // Default to no key while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_EVENT_QUIT: *quit = true; break; case SDL_EVENT_KEY_DOWN: *key_down_flag = true; switch (event.key.keysym.scancode) { case SDL_SCANCODE_1: *key = 0x1; break; case SDL_SCANCODE_2: *key = 0x2; break; case SDL_SCANCODE_3: *key = 0x3; break; case SDL_SCANCODE_4: *key = 0xC; break; case SDL_SCANCODE_Q: *key = 0x4; break; case SDL_SCANCODE_W: *key = 0x5; break; case SDL_SCANCODE_E: *key = 0x6; break; case SDL_SCANCODE_R: *key = 0xD; break; case SDL_SCANCODE_A: *key = 0x7; break; case SDL_SCANCODE_S: *key = 0x8; break; case SDL_SCANCODE_D: *key = 0x9; break; case SDL_SCANCODE_F: *key = 0xE; break; case SDL_SCANCODE_Z: *key = 0xA; break; case SDL_SCANCODE_X: *key = 0x0; break; case SDL_SCANCODE_C: *key = 0xB; break; case SDL_SCANCODE_V: *key = 0xF; break; case SDL_SCANCODE_D: // Dump CPU state // This functionality should be handled elsewhere break; default: *key = 0xFF; break; } break; case SDL_EVENT_KEY_UP: if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) *quit = true; break; default: break; } } return true; } void screen_render(Screen *screen, uint8_t *display) { uint32_t *pixels = malloc(screen->window_width * screen->window_height * sizeof(uint32_t)); if (!pixels) { fprintf(stderr, "Failed to allocate memory for pixels.\n"); return; } for (uint32_t y = 0; y < screen->window_height; y++) { for (uint32_t x = 0; x < screen->window_width; x++) { uint8_t pixel = display[x + y * screen->window_width]; if (pixel) { pixels[x + y * screen->window_width] = 0xFFCC0101; // Bright color (e.g., red) } else { pixels[x + y * screen->window_width] = 0xFF996601; // Dark color (e.g., dark orange) } } } SDL_UpdateTexture(screen->texture, NULL, pixels, screen->window_width * sizeof(uint32_t)); free(pixels); SDL_RenderClear(screen->renderer); SDL_RenderCopy(screen->renderer, screen->texture, NULL, NULL); SDL_RenderPresent(screen->renderer); } void screen_cleanup(Screen *screen) { if (screen->texture) SDL_DestroyTexture(screen->texture); if (screen->renderer) SDL_DestroyRenderer(screen->renderer); if (screen->window) SDL_DestroyWindow(screen->window); SDL_Quit(); }6.
main.cThe entry point of the emulator, handling program loading, the main loop, and integrating CPU and screen modules.
// main.c #include "cpu.h" #include "screen.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> // Sleep for the given milliseconds void sleep_ms(int milliseconds) { usleep(milliseconds * 1000); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <ROM file>\n", argv[0]); return EXIT_FAILURE; } // Load the CHIP-8 program FILE *f = fopen(argv[1], "rb"); if (!f) { perror("Failed to open ROM file"); return EXIT_FAILURE; } fseek(f, 0, SEEK_END); long filesize = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *program = malloc(filesize); if (!program) { fprintf(stderr, "Failed to allocate memory for program.\n"); fclose(f); return EXIT_FAILURE; } fread(program, 1, filesize, f); fclose(f); // Initialize CHIP-8 CPU Chip8 chip; chip8_init(&chip); if (!chip8_load_program(&chip, program, filesize)) { free(program); return EXIT_FAILURE; } free(program); // Initialize SDL Screen Screen screen; if (!screen_init(&screen, 64, 32, 10)) { // 64x32 resolution scaled by 10 return EXIT_FAILURE; } bool quit = false; uint8_t current_key = 0xFF; bool key_down = false; // Timer setup const int cycle_speed = 700; // Adjust as needed const double cycle_delay = 1000.0 / cycle_speed; // in milliseconds // Main emulation loop while (!quit) { Uint32 frame_start = SDL_GetTicks(); // Handle input screen_update(&screen, &quit, ¤t_key, &key_down); chip.key = current_key; chip.key_down = key_down; // Dump CPU state if 'D' key is pressed if (current_key == 0xD) { printf("CPU STATE\n"); for (int i = 0; i < 16; i++) { printf(" - V%X = 0x%02X\n", i, chip.V[i]); } printf(" - PC = 0x%04X\n", chip.pc); printf(" - I = 0x%04X\n", chip.I); printf(" - DT = 0x%02X\n", chip.delay_timer); printf(" - ST = 0x%02X\n", chip.sound_timer); // Optionally, reset the key to avoid repeated dumps chip.key = 0xFF; } // Fetch, decode, execute uint16_t opcode = chip8_fetch_opcode(&chip); chip8_execute_opcode(&chip, opcode); // Update timers at 60Hz static Uint32 last_timer_update = 0; Uint32 now = SDL_GetTicks(); if (now > last_timer_update + 16) { // Approximately every 16 ms chip8_update_timers(&chip); last_timer_update = now; } // Render the display screen_render(&screen, chip.display); // Sound handling can be implemented here if desired // Cap the cycle speed Uint32 frame_time = SDL_GetTicks() - frame_start; if (frame_time < cycle_delay) { sleep_ms((int)(cycle_delay - frame_time)); } } // Clean up screen_cleanup(&screen); return EXIT_SUCCESS; }Additional Notes
-
Key Mapping: The key mapping in
screen.cmaps specific keyboard keys to CHIP-8 keys. You can adjust theSDL_SCANCODE_*mappings to fit your preferences. -
Sound Implementation: The current implementation prints "BEEP!" when the sound timer is active. To implement actual sound, you can use SDL's audio functionalities.
-
CPU State Dump: Pressing the
Dkey will dump the CPU's state to the console. This mimics the functionality in your Python code. -
Timing: The
cycle_speedis set to 700 Hz, similar to your Python implementation. Adjustcycle_speedandcycle_delayas needed to fine-tune the emulator's performance. -
Error Handling: The emulator exits if it encounters an unknown opcode or stack overflow/underflow. You can enhance error handling as needed.
-
SDL3 Installation: Ensure SDL3 is installed on your system. Refer to the SDL3 documentation for installation instructions specific to your operating system.
-
Extending Functionality:
- Sound: Integrate SDL's audio subsystem to play sound when
sound_timeris active. - Saving & Loading State: Implement functionality to save and load the emulator's state.
- Graphical Enhancements: Improve the rendering quality, add scaling options, or support fullscreen mode.
- Sound: Integrate SDL's audio subsystem to play sound when
Conclusion
This C implementation uses SDL3 to handle graphics and input, mirroring the structure and functionality of your original Python CHIP-8 emulator. By following the provided code structure and compilation instructions, you should be able to build and run the emulator. Further enhancements can be made to match additional features or optimize performance as needed.
-