Initial commit

This commit is contained in:
2025-11-18 07:43:19 +01:00
commit e3fee7e082
6 changed files with 455 additions and 0 deletions

165
src/chip8.zig Normal file
View File

@@ -0,0 +1,165 @@
const std = @import("std");
const structure = @import("stack.zig");
const sdl3 = @import("sdl3");
const str = @import("structs.zig");
pub const Emulator = struct {
const Self = @This();
const w_pixels = 64;
const h_pixels = 32;
const scale = 25;
const memory_size = 4096;
const StackType = structure.Stack(u16, 32);
const program_start = 0x200;
const font_start = 0x050;
display: [h_pixels][w_pixels]u1,
memory: [memory_size]u8, // programs start at 0x200 address
pc: u16,
i: u16,
// Each call to the stack pushes 2B, and stack should be 64B big
// 2B x 32 = 64B
stack: StackType,
timers: struct {
delay: u8,
sound: u8,
},
registers: [16]u8,
pub fn init(allocator: std.mem.Allocator) !Self {
return .{
.display = std.mem.zeroes([h_pixels][w_pixels]u1),
.memory = try initMemory(allocator),
.pc = 0,
.i = 0,
// stack init
.stack = StackType.init(),
.timers = .{
// u8 max
.delay = 0xFF,
.sound = 0xFF,
},
.registers = std.mem.zeroes([16]u8),
};
}
pub fn destroy(self: *Self) void {
self.stack.destroy();
}
fn initMemory(allocator: std.mem.Allocator) ![memory_size]u8 {
var memory = std.mem.zeroes([memory_size]u8);
const font_data = [_]u8{
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
};
// loading font data into the memory
for (font_data, font_start..) |value, i| {
memory[i] = value;
}
// reading game data
const filename = getFileName(allocator) catch |err| {
std.debug.print("Failed to parse the game filename: {}\n", .{err});
return err;
};
const file = readFile(allocator, filename) catch |err| {
std.debug.print("Failed to read the file '{s}: {}\n", .{ filename, err });
return err;
};
defer allocator.free(file);
// loading game data into the memory
for (file, program_start..) |value, i| {
memory[i] = value;
}
return memory;
}
// despite Linux not needing to use allocators to extract arguments we're using them to ensure
// our emulator will work on windows and WASI (Web Assembly System Interface)
// which should come in handy should we ever want to port it online (I'm not writing this shit in JavaScript)
fn getFileName(allocator: std.mem.Allocator) ![]u8 {
const args = try std.process.argsAlloc(allocator);
return if (args.len <= 1) error.NoArgs else args[1];
}
fn readFile(allocator: std.mem.Allocator, filename: []const u8) ![]u8 {
const file = try std.fs.cwd().openFile(filename, .{ .mode = .read_only });
defer file.close();
const len = try file.getEndPos();
const buffer = try allocator.alloc(u8, len);
// we will free it in the caller function
_ = try file.read(buffer);
return buffer;
}
pub fn printMemory(self: *Self) void {
var space = false;
for (self.memory, 1..) |value, i| {
const suffix: u8 = if (space) ' ' else 0x0;
const newline: u8 = if (i % 16 == 0) '\n' else 0x0;
std.debug.print("{X:0>2}{c}{c}", .{ value, suffix, newline });
space = !space;
}
}
pub fn returnDisplayData(_: *Self) str.DisplayData {
return .{
.screen_width = w_pixels,
.screen_height = h_pixels,
.scale = scale,
};
}
// TODO implement some sort of tracking system when display actually changes so we don't call SDL for nothing
// one idea is to make a sort of array that tracks modified/changed "pixels"
pub fn draw(self: *Self, surface: *sdl3.surface.Surface) !void {
for (self.display, 0..) |_, i| {
for (self.display[0], 0..) |value, j| {
const x = i * w_pixels;
const y = j * h_pixels;
const width = w_pixels;
const height = h_pixels;
const area: sdl3.rect.IRect = .{
.h = height * scale,
.w = width * scale,
.x = @intCast(x * scale),
.y = @intCast(y * scale),
};
const color: u8 = if (value == 1) str.WHITE else str.BLACK;
try surface.fillRect(area, surface.mapRgb(color, color, color));
}
}
}
};

56
src/main.zig Normal file
View File

@@ -0,0 +1,56 @@
const std = @import("std");
const sdl3 = @import("sdl3");
const chip8 = @import("chip8.zig");
const str = @import("structs.zig");
pub fn main() !void {
const fps = 60;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
// chip8 init
var emulator = try chip8.Emulator.init(allocator);
defer emulator.destroy();
emulator.printMemory();
defer sdl3.shutdown();
// initialise SDL with subsystems you need here
const init_flags = sdl3.InitFlags{ .video = true };
try sdl3.init(init_flags);
defer sdl3.quit(init_flags);
// initial window setup
const res = emulator.returnDisplayData();
const window = try sdl3.video.Window.init("CHIP-8 Emulator", res.screen_width * res.scale, res.screen_height * res.scale, .{});
defer window.deinit();
// useful for limiting the fps and getting the delta time
var fps_capper = sdl3.extras.FramerateCapper(f32){ .mode = .{ .limited = fps } };
var quit = false;
while (!quit) {
// delay to limit the fps, returned delta time not needed
_ = fps_capper.delay();
// update logic
var surface = try window.getSurface();
// set background (black)
try surface.fillRect(null, surface.mapRgb(str.BLACK, str.BLACK, str.BLACK));
try emulator.draw(&surface);
try window.updateSurface();
// event logic
while (sdl3.events.poll()) |event| {
switch (event) {
.quit => quit = true,
.terminating => quit = true,
else => {},
}
}
}
}

47
src/stack.zig Normal file
View File

@@ -0,0 +1,47 @@
const std = @import("std");
pub fn Stack(comptime T: type, comptime size: usize) type {
return struct {
array: [size]T,
i: ?usize,
const Self = @This();
pub fn init() Self {
return .{
.array = std.mem.zeroes([size]T),
.i = null,
};
}
// this function might as well not exist but might as well set it
// nothing else is necessary, because stack will only read what is set at i
// and if i gets increased it will only get so when we insert new number
pub fn destroy(self: *Self) void {
self.i = null;
}
pub fn push(self: *Self, value: T) !void {
if (self.i) |index| {
if (index >= self.array.len - 1) return error.StackFull;
// index points at the last currently stored element
self.i = index + 1;
} else {
// if stack is empty set it to point at first element
self.i = 0;
}
self.array[self.i.?] = value;
}
pub fn pop(self: *Self) ?T {
if (self.i) |index| {
// set the i pointer to the previous element (null if we're popping the only element so far)
self.i = if (self.i == 0) null else self.i - 1;
return self.array[index];
}
return null; // stack is empty we have nothing to return
}
};
}

8
src/structs.zig Normal file
View File

@@ -0,0 +1,8 @@
pub const DisplayData = struct {
screen_width: usize,
screen_height: usize,
scale: usize,
};
pub const BLACK = 0x0;
pub const WHITE = 0xFF;