16 Commits

Author SHA1 Message Date
79514b0cd0 fix(input): make use of atomic rmw intrinsics when handling input 2023-05-23 03:07:05 -05:00
a048263fd6 chore: make use of std.atomic.spinLoopHint() 2023-05-23 02:42:35 -05:00
d9e09a9cbe fix(ui): remove flickering on ui pause/timeout 2023-05-23 02:24:11 -05:00
2b9a479b96 feat(ui): add timeout for gui spinloop 2023-05-23 02:23:50 -05:00
21295b8d03 feat(ui): implement pausing 2023-05-23 01:39:06 -05:00
89671f767e chore: update dependencies 2023-05-21 11:30:59 -05:00
a92598d17d feat(platform): implement OS window resizing 2023-05-12 01:47:15 -05:00
c677957725 chore: update min ver. to v0.11.0-dev.2934+1b432072b 2023-05-02 00:09:46 -05:00
a5e636d9c5 chore(gui): namespace the majority of interactions w/ OpenGL 2023-04-25 00:32:03 -05:00
f6527da948 fix: respond to change in GeneralPurposeAllocator's deinit fn signature 2023-04-24 21:50:49 -05:00
53fb1d163b fix(cpu): respond to latest changes to comptime semantics 2023-04-13 22:14:47 -05:00
df005d7fb6 chore(build): update to latest zig changes 2023-04-13 22:14:31 -05:00
3c619df3dc fix(imgui): handle valid ROM titles which happen to be empty 2023-04-06 03:08:07 -05:00
13f5e7a480 feat(gui): add palette viewer 2023-04-05 01:18:36 -05:00
8519187d9b chore(gui): add ability to close imgui windows
also list dependencies (TODO: add hyperlinks)
2023-04-04 21:11:08 -05:00
a66428f24e chore: update dependencies 2023-04-02 21:05:45 -05:00
23 changed files with 534 additions and 309 deletions

View File

@@ -8,7 +8,7 @@ const nfd = @import("lib/nfd-zig/build.zig");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
// Minimum Zig Version // Minimum Zig Version
const min_ver = std.SemanticVersion.parse("0.11.0-dev.2168+322ace70f") catch return; // https://github.com/ziglang/zig/commit/322ace70f const min_ver = std.SemanticVersion.parse("0.11.0-dev.2934+1b432072b") catch return; // https://github.com/ziglang/zig/commit/1b432072b
if (builtin.zig_version.order(min_ver).compare(.lt)) { if (builtin.zig_version.order(min_ver).compare(.lt)) {
std.log.err("{s}", .{b.fmt("Zig v{} does not meet the minimum version requirement. (Zig v{})", .{ builtin.zig_version, min_ver })}); std.log.err("{s}", .{b.fmt("Zig v{} does not meet the minimum version requirement. (Zig v{})", .{ builtin.zig_version, min_ver })});
std.os.exit(1); std.os.exit(1);
@@ -65,9 +65,9 @@ pub fn build(b: *std.Build) void {
const zgui_pkg = zgui.package(b, target, optimize, .{ .options = .{ .backend = .sdl2_opengl3, .shared = true } }); const zgui_pkg = zgui.package(b, target, optimize, .{ .options = .{ .backend = .sdl2_opengl3, .shared = true } });
zgui_pkg.link(exe); zgui_pkg.link(exe);
exe.install(); b.installArtifact(exe);
const run_cmd = exe.run(); const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep()); run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| { if (b.args) |args| {
run_cmd.addArgs(args); run_cmd.addArgs(args);

View File

@@ -27,7 +27,7 @@ pub fn write(self: *const Self, comptime T: type, address: usize, value: T) void
pub fn init(allocator: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(u8, ewram_size); const buf = try allocator.alloc(u8, ewram_size);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
@@ -36,7 +36,7 @@ pub fn init(allocator: Allocator) !Self {
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@@ -27,7 +27,7 @@ pub fn write(self: *const Self, comptime T: type, address: usize, value: T) void
pub fn init(allocator: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(u8, iwram_size); const buf = try allocator.alloc(u8, iwram_size);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
@@ -36,7 +36,7 @@ pub fn init(allocator: Allocator) !Self {
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@@ -110,7 +110,7 @@ pub const Backup = struct {
}; };
const buf = try allocator.alloc(u8, buf_size); const buf = try allocator.alloc(u8, buf_size);
std.mem.set(u8, buf, 0xFF); @memset(buf, 0xFF);
var backup = Self{ var backup = Self{
.buf = buf, .buf = buf,
@@ -163,7 +163,7 @@ pub const Backup = struct {
switch (self.kind) { switch (self.kind) {
.Sram, .Flash, .Flash1M => { .Sram, .Flash, .Flash1M => {
if (self.buf.len == file_buf.len) { if (self.buf.len == file_buf.len) {
std.mem.copy(u8, self.buf, file_buf); @memcpy(self.buf, file_buf);
return log.info("Loaded Save from {s}", .{file_path}); return log.info("Loaded Save from {s}", .{file_path});
} }
@@ -174,7 +174,7 @@ pub const Backup = struct {
self.eeprom.kind = if (file_buf.len == 0x200) .Small else .Large; self.eeprom.kind = if (file_buf.len == 0x200) .Small else .Large;
self.buf = try allocator.alloc(u8, file_buf.len); self.buf = try allocator.alloc(u8, file_buf.len);
std.mem.copy(u8, self.buf, file_buf); @memcpy(self.buf, file_buf);
return log.info("Loaded Save from {s}", .{file_path}); return log.info("Loaded Save from {s}", .{file_path});
} }

View File

@@ -44,7 +44,7 @@ pub fn handleCommand(self: *Self, buf: []u8, byte: u8) void {
0xB0 => self.set_bank = true, 0xB0 => self.set_bank = true,
0x80 => self.prep_erase = true, 0x80 => self.prep_erase = true,
0x10 => { 0x10 => {
std.mem.set(u8, buf, 0xFF); @memset(buf, 0xFF);
self.prep_erase = false; self.prep_erase = false;
}, },
0xA0 => self.prep_write = true, 0xA0 => self.prep_write = true,
@@ -61,7 +61,7 @@ pub fn shouldEraseSector(self: *const Self, addr: usize, byte: u8) bool {
pub fn erase(self: *Self, buf: []u8, sector: usize) void { pub fn erase(self: *Self, buf: []u8, sector: usize) void {
const start = self.address() + (sector & 0xF000); const start = self.address() + (sector & 0xF000);
std.mem.set(u8, buf[start..][0..0x1000], 0xFF); @memset(buf[start..][0..0x1000], 0xFF);
self.prep_erase = false; self.prep_erase = false;
self.state = .Ready; self.state = .Ready;
} }

View File

@@ -58,7 +58,9 @@ pub const Eeprom = struct {
log.err("Failed to resize EEPROM buf to {} bytes", .{len}); log.err("Failed to resize EEPROM buf to {} bytes", .{len});
std.debug.panic("EEPROM entered irrecoverable state {}", .{e}); std.debug.panic("EEPROM entered irrecoverable state {}", .{e});
}; };
std.mem.set(u8, buf.*, 0xFF);
// FIXME: ptr to a slice?
@memset(buf.*, 0xFF);
} }
} }

View File

@@ -96,7 +96,7 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) ?T {
0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT", .{T}), 0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT", .{T}),
// Keypad Input // Keypad Input
0x0400_0130 => bus.io.keyinput.load(.Monotonic).raw, 0x0400_0130 => bus.io.keyinput.load(.Monotonic),
// Serial Communication 2 // Serial Communication 2
0x0400_0134 => util.io.read.todo(log, "Read {} from RCNT", .{T}), 0x0400_0134 => util.io.read.todo(log, "Read {} from RCNT", .{T}),
@@ -366,7 +366,7 @@ const InterruptEnable = extern union {
/// Read Only /// Read Only
/// 0 = Pressed, 1 = Released /// 0 = Pressed, 1 = Released
const KeyInput = extern union { pub const KeyInput = extern union {
a: Bit(u16, 0), a: Bit(u16, 0),
b: Bit(u16, 1), b: Bit(u16, 1),
select: Bit(u16, 2), select: Bit(u16, 2),
@@ -390,18 +390,19 @@ const AtomicKeyInput = struct {
return .{ .inner = value }; return .{ .inner = value };
} }
pub inline fn load(self: *const Self, comptime ordering: Ordering) KeyInput { pub inline fn load(self: *const Self, comptime ordering: Ordering) u16 {
return .{ .raw = switch (ordering) { return switch (ordering) {
.AcqRel, .Release => @compileError("not supported for atomic loads"), .AcqRel, .Release => @compileError("not supported for atomic loads"),
else => @atomicLoad(u16, &self.inner.raw, ordering), else => @atomicLoad(u16, &self.inner.raw, ordering),
} }; };
} }
pub inline fn store(self: *Self, value: u16, comptime ordering: Ordering) void { pub inline fn fetchOr(self: *Self, value: u16, comptime ordering: Ordering) void {
switch (ordering) { _ = @atomicRmw(u16, &self.inner.raw, .Or, value, ordering);
.AcqRel, .Acquire => @compileError("not supported for atomic stores"),
else => @atomicStore(u16, &self.inner.raw, value, ordering),
} }
pub inline fn fetchAnd(self: *Self, value: u16, comptime ordering: Ordering) void {
_ = @atomicRmw(u16, &self.inner.raw, .And, value, ordering);
} }
}; };

View File

@@ -39,7 +39,7 @@ pub const arm = struct {
} }
fn populate() [0x1000]InstrFn { fn populate() [0x1000]InstrFn {
comptime { return comptime comptime_blk: {
@setEvalBranchQuota(0xE000); @setEvalBranchQuota(0xE000);
var table = [_]InstrFn{und} ** 0x1000; var table = [_]InstrFn{und} ** 0x1000;
@@ -106,8 +106,8 @@ pub const arm = struct {
}; };
} }
return table; break :comptime_blk table;
} };
} }
}; };
@@ -135,7 +135,7 @@ pub const thumb = struct {
} }
fn populate() [0x400]InstrFn { fn populate() [0x400]InstrFn {
comptime { return comptime comptime_blk: {
@setEvalBranchQuota(5025); // This is exact @setEvalBranchQuota(5025); // This is exact
var table = [_]InstrFn{und} ** 0x400; var table = [_]InstrFn{und} ** 0x400;
@@ -228,8 +228,8 @@ pub const thumb = struct {
}; };
} }
return table; break :comptime_blk table;
} };
} }
}; };

View File

@@ -140,6 +140,10 @@ fn audioSync(audio_sync: bool, stream: *SDL.SDL_AudioStream, is_buffer_full: *bo
// If Busy is false, there's no need to sync here // If Busy is false, there's no need to sync here
if (!still_full) return; if (!still_full) return;
// TODO: Refactor!!!!
// while (SDL.SDL_AudioStreamAvailable(stream) > sample_size * max_buf_size >> 1)
// std.atomic.spinLoopHint();
while (true) { while (true) {
still_full = SDL.SDL_AudioStreamAvailable(stream) > sample_size * max_buf_size >> 1; still_full = SDL.SDL_AudioStreamAvailable(stream) > sample_size * max_buf_size >> 1;
if (!audio_sync or !still_full) break; if (!audio_sync or !still_full) break;
@@ -184,7 +188,8 @@ fn sleep(timer: *Timer, wake_time: u64) ?u64 {
} }
fn spinLoop(timer: *Timer, wake_time: u64) void { fn spinLoop(timer: *Timer, wake_time: u64) void {
while (true) if (timer.read() > wake_time) break; while (timer.read() < wake_time)
std.atomic.spinLoopHint();
} }
pub const EmuThing = struct { pub const EmuThing = struct {

View File

@@ -266,7 +266,7 @@ pub const Ppu = struct {
sched.push(.Draw, 240 * 4); // Add first PPU Event to Scheduler sched.push(.Draw, 240 * 4); // Add first PPU Event to Scheduler
const sprites = try allocator.create([128]?Sprite); const sprites = try allocator.create([128]?Sprite);
std.mem.set(?Sprite, sprites, null); @memset(sprites, null);
return Self{ return Self{
.vram = try Vram.init(allocator), .vram = try Vram.init(allocator),
@@ -307,7 +307,7 @@ pub const Ppu = struct {
self.vcount = .{ .raw = 0x0000 }; self.vcount = .{ .raw = 0x0000 };
self.scanline.reset(); self.scanline.reset();
std.mem.set(?Sprite, self.scanline_sprites, null); @memset(self.scanline_sprites, null);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {
@@ -744,7 +744,7 @@ pub const Ppu = struct {
// Reset Current Scanline Pixel Buffer and list of fetched sprites // Reset Current Scanline Pixel Buffer and list of fetched sprites
// in prep for next scanline // in prep for next scanline
self.scanline.reset(); self.scanline.reset();
std.mem.set(?Sprite, self.scanline_sprites, null); @memset(self.scanline_sprites, null);
} }
fn getBgr555(self: *Self, maybe_top: Scanline.Pixel, maybe_btm: Scanline.Pixel) u16 { fn getBgr555(self: *Self, maybe_top: Scanline.Pixel, maybe_btm: Scanline.Pixel) u16 {
@@ -1554,7 +1554,7 @@ const Scanline = struct {
fn init(allocator: Allocator) !Self { fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(Pixel, width * 2); // Top & Bottom Scanline const buf = try allocator.alloc(Pixel, width * 2); // Top & Bottom Scanline
std.mem.set(Pixel, buf, .unset); @memset(buf, .unset);
return .{ return .{
// Top & Bototm Layers // Top & Bototm Layers
@@ -1565,7 +1565,7 @@ const Scanline = struct {
} }
fn reset(self: *Self) void { fn reset(self: *Self) void {
std.mem.set(Pixel, self.buf, .unset); @memset(self.buf, .unset);
} }
fn deinit(self: *Self) void { fn deinit(self: *Self) void {

View File

@@ -29,13 +29,13 @@ pub fn write(self: *Self, comptime T: type, address: usize, value: T) void {
pub fn init(allocator: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(u8, buf_len); const buf = try allocator.alloc(u8, buf_len);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return Self{ .buf = buf, .allocator = allocator }; return Self{ .buf = buf, .allocator = allocator };
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@@ -32,13 +32,13 @@ pub fn write(self: *Self, comptime T: type, address: usize, value: T) void {
pub fn init(allocator: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(u8, buf_len); const buf = try allocator.alloc(u8, buf_len);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return Self{ .buf = buf, .allocator = allocator }; return Self{ .buf = buf, .allocator = allocator };
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@@ -40,13 +40,13 @@ pub fn write(self: *Self, comptime T: type, dispcnt: io.DisplayControl, address:
pub fn init(allocator: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try allocator.alloc(u8, buf_len); const buf = try allocator.alloc(u8, buf_len);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return Self{ .buf = buf, .allocator = allocator }; return Self{ .buf = buf, .allocator = allocator };
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@@ -12,6 +12,7 @@ const emu = @import("core/emu.zig");
const Gui = @import("platform.zig").Gui; const Gui = @import("platform.zig").Gui;
const Arm7tdmi = @import("core/cpu.zig").Arm7tdmi; const Arm7tdmi = @import("core/cpu.zig").Arm7tdmi;
const RingBuffer = @import("zba-util").RingBuffer; const RingBuffer = @import("zba-util").RingBuffer;
const Dimensions = @import("platform.zig").Dimensions;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const GLuint = gl.GLuint; const GLuint = gl.GLuint;
@@ -30,14 +31,34 @@ pub const State = struct {
fps_hist: RingBuffer(u32), fps_hist: RingBuffer(u32),
should_quit: bool = false, should_quit: bool = false,
emulation: Emulation,
win_stat: WindowStatus = .{},
const WindowStatus = struct {
show_deps: bool = false,
show_regs: bool = false,
show_schedule: bool = false,
show_perf: bool = false,
show_palette: bool = false,
};
const Emulation = union(enum) {
Active,
Inactive,
Transition: enum { Active, Inactive },
};
/// if zba is initialized with a ROM already provided, this initializer should be called /// if zba is initialized with a ROM already provided, this initializer should be called
/// with `title_opt` being non-null /// with `title_opt` being non-null
pub fn init(allocator: Allocator, title_opt: ?*const [12]u8) !@This() { pub fn init(allocator: Allocator, title_opt: ?*const [12]u8) !@This() {
const history = try allocator.alloc(u32, histogram_len); const history = try allocator.alloc(u32, histogram_len);
const title: [12:0]u8 = if (title_opt) |t| t.* ++ [_:0]u8{} else "[No Title]\x00\x00".*; return .{
return .{ .title = title, .fps_hist = RingBuffer(u32).init(history) }; .title = handleTitle(title_opt),
.emulation = if (title_opt == null) .Inactive else .Active,
.fps_hist = RingBuffer(u32).init(history),
};
} }
pub fn deinit(self: *@This(), allocator: Allocator) void { pub fn deinit(self: *@This(), allocator: Allocator) void {
@@ -46,8 +67,10 @@ pub const State = struct {
} }
}; };
pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void { pub fn draw(state: *State, win_dim: Dimensions, tex_id: GLuint, cpu: *Arm7tdmi) bool {
const win_scale = config.config().host.win_scale; const scn_scale = config.config().host.win_scale;
zgui.backend.newFrame(@intToFloat(f32, win_dim.width), @intToFloat(f32, win_dim.height));
{ {
_ = zgui.beginMainMenuBar(); _ = zgui.beginMainMenuBar();
@@ -56,7 +79,8 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
if (zgui.beginMenu("File", true)) { if (zgui.beginMenu("File", true)) {
defer zgui.endMenu(); defer zgui.endMenu();
if (zgui.menuItem("Quit", .{})) state.should_quit = true; if (zgui.menuItem("Quit", .{}))
state.should_quit = true;
if (zgui.menuItem("Insert ROM", .{})) blk: { if (zgui.menuItem("Insert ROM", .{})) blk: {
const maybe_path = nfd.openFileDialog("gba", null) catch |e| { const maybe_path = nfd.openFileDialog("gba", null) catch |e| {
@@ -76,22 +100,53 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
break :blk; break :blk;
}; };
state.title = cpu.bus.pak.title ++ [_:0]u8{}; state.title = handleTitle(&cpu.bus.pak.title);
state.emulation = .{ .Transition = .Active };
} }
} }
if (zgui.beginMenu("Emulation", true)) { if (zgui.beginMenu("Emulation", true)) {
defer zgui.endMenu(); defer zgui.endMenu();
if (zgui.menuItem("Restart", .{})) { if (zgui.menuItem("Registers", .{ .selected = state.win_stat.show_regs }))
state.win_stat.show_regs = true;
if (zgui.menuItem("Palette", .{ .selected = state.win_stat.show_palette }))
state.win_stat.show_palette = true;
if (zgui.menuItem("Schedule", .{ .selected = state.win_stat.show_schedule }))
state.win_stat.show_schedule = true;
if (zgui.menuItem("Paused", .{ .selected = state.emulation == .Inactive })) {
state.emulation = switch (state.emulation) {
.Active => .{ .Transition = .Inactive },
.Inactive => .{ .Transition = .Active },
else => state.emulation,
};
}
if (zgui.menuItem("Restart", .{}))
emu.reset(cpu); emu.reset(cpu);
} }
if (zgui.beginMenu("Stats", true)) {
defer zgui.endMenu();
if (zgui.menuItem("Performance", .{ .selected = state.win_stat.show_perf }))
state.win_stat.show_perf = true;
}
if (zgui.beginMenu("Help", true)) {
defer zgui.endMenu();
if (zgui.menuItem("Dependencies", .{ .selected = state.win_stat.show_deps }))
state.win_stat.show_deps = true;
} }
} }
{ {
const w = @intToFloat(f32, gba_width * win_scale); const w = @intToFloat(f32, gba_width * scn_scale);
const h = @intToFloat(f32, gba_height * win_scale); const h = @intToFloat(f32, gba_height * scn_scale);
const window_title = std.mem.sliceTo(&state.title, 0); const window_title = std.mem.sliceTo(&state.title, 0);
_ = zgui.begin(window_title, .{ .flags = .{ .no_resize = true, .always_auto_resize = true } }); _ = zgui.begin(window_title, .{ .flags = .{ .no_resize = true, .always_auto_resize = true } });
@@ -100,8 +155,51 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
zgui.image(@intToPtr(*anyopaque, tex_id), .{ .w = w, .h = h, .uv0 = .{ 0, 1 }, .uv1 = .{ 1, 0 } }); zgui.image(@intToPtr(*anyopaque, tex_id), .{ .w = w, .h = h, .uv0 = .{ 0, 1 }, .uv1 = .{ 1, 0 } });
} }
// TODO: Any other steps to respect the copyright of the libraries I use?
if (state.win_stat.show_deps) {
_ = zgui.begin("Dependencies", .{ .popen = &state.win_stat.show_deps });
defer zgui.end();
zgui.bulletText("SDL.zig by Felix Queißner", .{});
{ {
_ = zgui.begin("Information", .{}); zgui.indent(.{});
defer zgui.unindent(.{});
zgui.bulletText("SDL by Sam Lantinga", .{});
}
zgui.bulletText("known-folders by ziglibs", .{});
zgui.bulletText("nfd-zig by Fabio Arnold", .{});
{
zgui.indent(.{});
defer zgui.unindent(.{});
zgui.bulletText("nativefiledialog by Michael Labbe", .{});
}
zgui.bulletText("zba-gdbstub by Rekai Musuka", .{});
zgui.bulletText("zba-util by Rekai Musuka", .{});
zgui.bulletText("zgui by Michal Ziulek", .{});
{
zgui.indent(.{});
defer zgui.unindent(.{});
zgui.bulletText("DearImGui by Omar Cornut", .{});
}
zgui.bulletText("zig-clap by Jimmi Holst Christensen", .{});
zgui.bulletText("zig-datetime by Jairus Martin", .{});
zgui.bulletText("zig-opengl by Felix Queißner", .{});
{
zgui.indent(.{});
defer zgui.unindent(.{});
zgui.bulletText("OpenGL-Registry by The Khronos Group", .{});
}
zgui.bulletText("zig-toml by Aeron Avery", .{});
zgui.bulletText("bitfield.zig by Hannes Bredberg and FlorenceOS contributors", .{});
}
if (state.win_stat.show_regs) {
_ = zgui.begin("Guest Registers", .{ .popen = &state.win_stat.show_regs });
defer zgui.end(); defer zgui.end();
for (0..8) |i| { for (0..8) |i| {
@@ -124,8 +222,8 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
widgets.interrupts("IRQ", cpu.bus.io.irq); widgets.interrupts("IRQ", cpu.bus.io.irq);
} }
{ if (state.win_stat.show_perf) {
_ = zgui.begin("Performance", .{}); _ = zgui.begin("Performance", .{ .popen = &state.win_stat.show_perf });
defer zgui.end(); defer zgui.end();
const tmp = blk: { const tmp = blk: {
@@ -142,7 +240,7 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
const sorted = blk: { const sorted = blk: {
var buf: @TypeOf(values) = undefined; var buf: @TypeOf(values) = undefined;
std.mem.copy(u32, buf[0..len], values[0..len]); @memcpy(buf[0..len], values[0..len]);
std.sort.sort(u32, buf[0..len], {}, std.sort.asc(u32)); std.sort.sort(u32, buf[0..len], {}, std.sort.asc(u32));
break :blk buf; break :blk buf;
@@ -187,8 +285,8 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
zgui.text(" 1% Low: {:0>3} fps", .{stats[2]}); zgui.text(" 1% Low: {:0>3} fps", .{stats[2]});
} }
{ if (state.win_stat.show_schedule) {
_ = zgui.begin("Scheduler", .{}); _ = zgui.begin("Schedule", .{ .popen = &state.win_stat.show_schedule });
defer zgui.end(); defer zgui.end();
const scheduler = cpu.sched; const scheduler = cpu.sched;
@@ -201,7 +299,7 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
var items: [20]Event = undefined; var items: [20]Event = undefined;
const len = scheduler.queue.len; const len = scheduler.queue.len;
std.mem.copy(Event, &items, scheduler.queue.items); @memcpy(&items, scheduler.queue.items);
std.sort.sort(Event, items[0..len], {}, widgets.eventDesc(Event)); std.sort.sort(Event, items[0..len], {}, widgets.eventDesc(Event));
for (items[0..len]) |event| { for (items[0..len]) |event| {
@@ -209,12 +307,61 @@ pub fn draw(state: *State, tex_id: GLuint, cpu: *Arm7tdmi) void {
} }
} }
// { if (state.win_stat.show_palette) {
// zgui.showDemoWindow(null); _ = zgui.begin("Palette", .{ .popen = &state.win_stat.show_palette });
// } defer zgui.end();
widgets.paletteGrid(.Background, cpu);
zgui.sameLine(.{ .spacing = 20.0 });
widgets.paletteGrid(.Object, cpu);
}
{
zgui.showDemoWindow(null);
}
return true; // request redraw
} }
const widgets = struct { const widgets = struct {
const PaletteKind = enum { Background, Object };
fn paletteGrid(comptime kind: PaletteKind, cpu: *const Arm7tdmi) void {
_ = zgui.beginGroup();
defer zgui.endGroup();
const address: u32 = switch (kind) {
.Background => 0x0500_0000,
.Object => 0x0500_0200,
};
for (0..0x100) |i| {
const offset = @truncate(u32, i);
const bgr555 = cpu.bus.dbgRead(u16, address + offset * @sizeOf(u16));
widgets.colourSquare(bgr555);
if ((i + 1) % 0x10 != 0) zgui.sameLine(.{});
}
zgui.text(@tagName(kind), .{});
}
fn colourSquare(bgr555: u16) void {
// FIXME: working with the packed struct enum is currently broken :pensive:
const ImguiColorEditFlags_NoInputs: u32 = 1 << 5;
const ImguiColorEditFlags_NoPicker: u32 = 1 << 2;
const flags = @bitCast(zgui.ColorEditFlags, ImguiColorEditFlags_NoInputs | ImguiColorEditFlags_NoPicker);
const b = @intToFloat(f32, bgr555 >> 10 & 0x1f);
const g = @intToFloat(f32, bgr555 >> 5 & 0x1F);
const r = @intToFloat(f32, bgr555 & 0x1F);
var col = [_]f32{ r / 31.0, g / 31.0, b / 31.0 };
_ = zgui.colorEdit3("", .{ .col = &col, .flags = flags });
}
fn interrupts(comptime label: []const u8, int: anytype) void { fn interrupts(comptime label: []const u8, int: anytype) void {
const h = 15.0; const h = 15.0;
const w = 9.0 * 2 + 3.5; const w = 9.0 * 2 + 3.5;
@@ -305,3 +452,13 @@ const widgets = struct {
}.inner; }.inner;
} }
}; };
fn handleTitle(title_opt: ?*const [12]u8) [12:0]u8 {
if (title_opt == null) return "[N/A Title]\x00".*; // No ROM present
const title = title_opt.?;
// ROM Title is an empty string (ImGui hates these)
if (title[0] == '\x00') return "[No Title]\x00\x00".*;
return title.* ++ [_:0]u8{};
}

View File

@@ -31,7 +31,7 @@ const params = clap.parseParamsComptime(
pub fn main() void { pub fn main() void {
// Main Allocator for ZBA // Main Allocator for ZBA
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!gpa.deinit()); defer std.debug.assert(gpa.deinit() == .ok);
const allocator = gpa.allocator(); const allocator = gpa.allocator();
@@ -86,7 +86,7 @@ pub fn main() void {
bus.init(allocator, &scheduler, &cpu, paths) catch |e| exitln("failed to init zba bus: {}", .{e}); bus.init(allocator, &scheduler, &cpu, paths) catch |e| exitln("failed to init zba bus: {}", .{e});
defer bus.deinit(); defer bus.deinit();
if (config.config().guest.skip_bios or result.args.skip or paths.bios == null) { if (config.config().guest.skip_bios or result.args.skip != 0 or paths.bios == null) {
cpu.fastBoot(); cpu.fastBoot();
} }
@@ -101,7 +101,7 @@ pub fn main() void {
var items: [0x100]u8 = undefined; var items: [0x100]u8 = undefined;
var channel = TwoWayChannel.init(&items); var channel = TwoWayChannel.init(&items);
if (result.args.gdb) { if (result.args.gdb != 0) {
const Server = @import("gdbstub").Server; const Server = @import("gdbstub").Server;
const EmuThing = @import("core/emu.zig").EmuThing; const EmuThing = @import("core/emu.zig").EmuThing;
@@ -119,7 +119,7 @@ pub fn main() void {
const thread = std.Thread.spawn(.{}, Server.run, .{ &server, allocator, &quit }) catch |e| exitln("gdb server thread crashed: {}", .{e}); const thread = std.Thread.spawn(.{}, Server.run, .{ &server, allocator, &quit }) catch |e| exitln("gdb server thread crashed: {}", .{e});
defer thread.join(); defer thread.join();
gui.run(.{ gui.run(.Debug, .{
.cpu = &cpu, .cpu = &cpu,
.scheduler = &scheduler, .scheduler = &scheduler,
.channel = &channel, .channel = &channel,
@@ -127,10 +127,14 @@ pub fn main() void {
} else { } else {
var tracker = FpsTracker.init(); var tracker = FpsTracker.init();
// emu should start paused if there's no ROM to run
if (paths.rom == null)
channel.emu.push(.Pause);
const thread = std.Thread.spawn(.{}, emu.run, .{ &cpu, &scheduler, &tracker, &channel }) catch |e| exitln("emu thread panicked: {}", .{e}); const thread = std.Thread.spawn(.{}, emu.run, .{ &cpu, &scheduler, &tracker, &channel }) catch |e| exitln("emu thread panicked: {}", .{e});
defer thread.join(); defer thread.join();
gui.run(.{ gui.run(.Standard, .{
.cpu = &cpu, .cpu = &cpu,
.scheduler = &scheduler, .scheduler = &scheduler,
.channel = &channel, .channel = &channel,

View File

@@ -12,6 +12,7 @@ const Arm7tdmi = @import("core/cpu.zig").Arm7tdmi;
const Scheduler = @import("core/scheduler.zig").Scheduler; const Scheduler = @import("core/scheduler.zig").Scheduler;
const FpsTracker = @import("util.zig").FpsTracker; const FpsTracker = @import("util.zig").FpsTracker;
const TwoWayChannel = @import("zba-util").TwoWayChannel; const TwoWayChannel = @import("zba-util").TwoWayChannel;
const KeyInput = @import("core/bus/io.zig").KeyInput;
const gba_width = @import("core/ppu.zig").width; const gba_width = @import("core/ppu.zig").width;
const gba_height = @import("core/ppu.zig").height; const gba_height = @import("core/ppu.zig").height;
@@ -21,8 +22,8 @@ const GLsizei = gl.GLsizei;
const SDL_GLContext = *anyopaque; const SDL_GLContext = *anyopaque;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const width = 1280; pub const Dimensions = struct { width: u32, height: u32 };
const height = 720; const default_dim: Dimensions = .{ .width = 1280, .height = 720 };
pub const sample_rate = 1 << 15; pub const sample_rate = 1 << 15;
pub const sample_format = SDL.AUDIO_U16; pub const sample_format = SDL.AUDIO_U16;
@@ -33,29 +34,12 @@ pub const Gui = struct {
const Self = @This(); const Self = @This();
const log = std.log.scoped(.Gui); const log = std.log.scoped(.Gui);
// zig fmt: off
const vertices: [32]f32 = [_]f32{
// Positions // Colours // Texture Coords
1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // Top Right
1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // Bottom Right
-1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // Bottom Left
-1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // Top Left
};
const indices: [6]u32 = [_]u32{
0, 1, 3, // First Triangle
1, 2, 3, // Second Triangle
};
// zig fmt: on
window: *SDL.SDL_Window, window: *SDL.SDL_Window,
ctx: SDL_GLContext, ctx: SDL_GLContext,
audio: Audio, audio: Audio,
state: imgui.State, state: imgui.State,
allocator: Allocator, allocator: Allocator,
program_id: gl.GLuint,
pub fn init(allocator: Allocator, apu: *Apu, title_opt: ?*const [12]u8) !Self { pub fn init(allocator: Allocator, apu: *Apu, title_opt: ?*const [12]u8) !Self {
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0) panic(); if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0) panic();
@@ -67,9 +51,9 @@ pub const Gui = struct {
window_title, window_title,
SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
width, default_dim.width,
height, default_dim.height,
SDL.SDL_WINDOW_OPENGL | SDL.SDL_WINDOW_SHOWN, SDL.SDL_WINDOW_OPENGL | SDL.SDL_WINDOW_SHOWN | SDL.SDL_WINDOW_RESIZABLE,
) orelse panic(); ) orelse panic();
const ctx = SDL.SDL_GL_CreateContext(window) orelse panic(); const ctx = SDL.SDL_GL_CreateContext(window) orelse panic();
@@ -87,7 +71,6 @@ pub const Gui = struct {
return Self{ return Self{
.window = window, .window = window,
.ctx = ctx, .ctx = ctx,
.program_id = try compileShaders(),
.audio = Audio.init(apu), .audio = Audio.init(apu),
.allocator = allocator, .allocator = allocator,
@@ -103,7 +86,6 @@ pub const Gui = struct {
zgui.plot.deinit(); zgui.plot.deinit();
zgui.deinit(); zgui.deinit();
gl.deleteProgram(self.program_id);
SDL.SDL_GL_DeleteContext(self.ctx); SDL.SDL_GL_DeleteContext(self.ctx);
SDL.SDL_DestroyWindow(self.window); SDL.SDL_DestroyWindow(self.window);
SDL.SDL_Quit(); SDL.SDL_Quit();
@@ -111,137 +93,6 @@ pub const Gui = struct {
self.* = undefined; self.* = undefined;
} }
fn drawGbaTexture(self: *const Self, obj_ids: struct { GLuint, GLuint, GLuint }, tex_id: GLuint, buf: []const u8) void {
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gba_width, gba_height, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, buf.ptr);
// Bind VAO, EBO. VBO not bound
gl.bindVertexArray(obj_ids[0]); // VAO
defer gl.bindVertexArray(0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, obj_ids[2]); // EBO
defer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0);
// Use compiled frag + vertex shader
gl.useProgram(self.program_id);
defer gl.useProgram(0);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
}
fn compileShaders() !GLuint {
const vert_shader = @embedFile("shader/pixelbuf.vert");
const frag_shader = @embedFile("shader/pixelbuf.frag");
const vs = gl.createShader(gl.VERTEX_SHADER);
defer gl.deleteShader(vs);
gl.shaderSource(vs, 1, &[_][*c]const u8{vert_shader}, 0);
gl.compileShader(vs);
if (!shader.didCompile(vs)) return error.VertexCompileError;
const fs = gl.createShader(gl.FRAGMENT_SHADER);
defer gl.deleteShader(fs);
gl.shaderSource(fs, 1, &[_][*c]const u8{frag_shader}, 0);
gl.compileShader(fs);
if (!shader.didCompile(fs)) return error.FragmentCompileError;
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return program;
}
// Returns the VAO ID since it's used in run()
fn genBufferObjects() struct { GLuint, GLuint, GLuint } {
var vao_id: GLuint = undefined;
var vbo_id: GLuint = undefined;
var ebo_id: GLuint = undefined;
gl.genVertexArrays(1, &vao_id);
gl.genBuffers(1, &vbo_id);
gl.genBuffers(1, &ebo_id);
gl.bindVertexArray(vao_id);
defer gl.bindVertexArray(0);
gl.bindBuffer(gl.ARRAY_BUFFER, vbo_id);
defer gl.bindBuffer(gl.ARRAY_BUFFER, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebo_id);
defer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0);
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(@TypeOf(vertices)), &vertices, gl.STATIC_DRAW);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, @sizeOf(@TypeOf(indices)), &indices, gl.STATIC_DRAW);
// Position
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), null); // lmao
gl.enableVertexAttribArray(0);
// Colour
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), @intToPtr(?*anyopaque, (3 * @sizeOf(f32))));
gl.enableVertexAttribArray(1);
// Texture Coord
gl.vertexAttribPointer(2, 2, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), @intToPtr(?*anyopaque, (6 * @sizeOf(f32))));
gl.enableVertexAttribArray(2);
return .{ vao_id, vbo_id, ebo_id };
}
fn genGbaTexture(buf: []const u8) GLuint {
var tex_id: GLuint = undefined;
gl.genTextures(1, &tex_id);
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gba_width, gba_height, 0, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, buf.ptr);
return tex_id;
}
fn genOutTexture() GLuint {
var tex_id: GLuint = undefined;
gl.genTextures(1, &tex_id);
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gba_width, gba_height, 0, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, null);
return tex_id;
}
fn genFrameBufObject(tex_id: c_uint) !GLuint {
var fbo_id: GLuint = undefined;
gl.genFramebuffers(1, &fbo_id);
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo_id);
defer gl.bindFramebuffer(gl.FRAMEBUFFER, 0);
gl.framebufferTexture(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, tex_id, 0);
const draw_buffers: [1]GLuint = .{gl.COLOR_ATTACHMENT0};
gl.drawBuffers(1, &draw_buffers);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE)
return error.FrameBufferObejctInitFailed;
return fbo_id;
}
const RunOptions = struct { const RunOptions = struct {
channel: *TwoWayChannel, channel: *TwoWayChannel,
tracker: ?*FpsTracker = null, tracker: ?*FpsTracker = null,
@@ -249,29 +100,30 @@ pub const Gui = struct {
scheduler: *Scheduler, scheduler: *Scheduler,
}; };
pub fn run(self: *Self, opt: RunOptions) !void { const RunMode = enum { Standard, Debug };
pub fn run(self: *Self, comptime mode: RunMode, opt: RunOptions) !void {
const cpu = opt.cpu; const cpu = opt.cpu;
const tracker = opt.tracker; const tracker = opt.tracker;
const channel = opt.channel; const channel = opt.channel;
const obj_ids = Self.genBufferObjects(); const objects = opengl_impl.createObjects();
defer gl.deleteBuffers(3, @as(*const [3]c_uint, &obj_ids)); defer gl.deleteBuffers(3, @as(*const [3]GLuint, &.{ objects.vao, objects.vbo, objects.ebo }));
const emu_tex = Self.genGbaTexture(cpu.bus.ppu.framebuf.get(.Renderer)); const emu_tex = opengl_impl.createScreenTexture(cpu.bus.ppu.framebuf.get(.Renderer));
const out_tex = Self.genOutTexture(); const out_tex = opengl_impl.createOutputTexture();
defer gl.deleteTextures(2, &[_]c_uint{ emu_tex, out_tex }); defer gl.deleteTextures(2, &[_]GLuint{ emu_tex, out_tex });
const fbo_id = try Self.genFrameBufObject(out_tex); const fbo_id = try opengl_impl.createFrameBuffer(out_tex);
defer gl.deleteFramebuffers(1, &fbo_id); defer gl.deleteFramebuffers(1, &fbo_id);
emu_loop: while (true) { // TODO: Support dynamically switching shaders?
// `quit` from RunOptions may be modified by the GDBSTUB thread, const prog_id = try opengl_impl.compileShaders();
// so we want to recognize that it may change to `true` and exit the GUI thread defer gl.deleteProgram(prog_id);
if (channel.gui.pop()) |event| switch (event) {
.Quit => break :emu_loop,
.Paused => @panic("TODO: We want to peek (and then pop if it's .Quit), not always pop"),
};
var win_dim: Dimensions = default_dim;
emu_loop: while (true) {
// Outside of `SDL.SDL_QUIT` below, the DearImgui UI might signal that the program // Outside of `SDL.SDL_QUIT` below, the DearImgui UI might signal that the program
// should exit, in which case we should also handle this // should exit, in which case we should also handle this
if (self.state.should_quit) break :emu_loop; if (self.state.should_quit) break :emu_loop;
@@ -283,28 +135,9 @@ pub const Gui = struct {
switch (event.type) { switch (event.type) {
SDL.SDL_QUIT => break :emu_loop, SDL.SDL_QUIT => break :emu_loop,
SDL.SDL_KEYDOWN => { SDL.SDL_KEYDOWN => {
// TODO: Make use of compare_and_xor?
const key_code = event.key.keysym.sym; const key_code = event.key.keysym.sym;
var keyinput = cpu.bus.io.keyinput.load(.Monotonic); var keyinput: KeyInput = .{ .raw = 0x0000 };
switch (key_code) {
SDL.SDLK_UP => keyinput.up.unset(),
SDL.SDLK_DOWN => keyinput.down.unset(),
SDL.SDLK_LEFT => keyinput.left.unset(),
SDL.SDLK_RIGHT => keyinput.right.unset(),
SDL.SDLK_x => keyinput.a.unset(),
SDL.SDLK_z => keyinput.b.unset(),
SDL.SDLK_a => keyinput.shoulder_l.unset(),
SDL.SDLK_s => keyinput.shoulder_r.unset(),
SDL.SDLK_RETURN => keyinput.start.unset(),
SDL.SDLK_RSHIFT => keyinput.select.unset(),
else => {},
}
cpu.bus.io.keyinput.store(keyinput.raw, .Monotonic);
},
SDL.SDL_KEYUP => {
const key_code = event.key.keysym.sym;
var keyinput = cpu.bus.io.keyinput.load(.Monotonic);
switch (key_code) { switch (key_code) {
SDL.SDLK_UP => keyinput.up.set(), SDL.SDLK_UP => keyinput.up.set(),
@@ -320,21 +153,90 @@ pub const Gui = struct {
else => {}, else => {},
} }
cpu.bus.io.keyinput.store(keyinput.raw, .Monotonic); cpu.bus.io.keyinput.fetchAnd(~keyinput.raw, .Monotonic);
},
SDL.SDL_KEYUP => {
// TODO: Make use of compare_and_xor?
const key_code = event.key.keysym.sym;
var keyinput: KeyInput = .{ .raw = 0x0000 };
switch (key_code) {
SDL.SDLK_UP => keyinput.up.set(),
SDL.SDLK_DOWN => keyinput.down.set(),
SDL.SDLK_LEFT => keyinput.left.set(),
SDL.SDLK_RIGHT => keyinput.right.set(),
SDL.SDLK_x => keyinput.a.set(),
SDL.SDLK_z => keyinput.b.set(),
SDL.SDLK_a => keyinput.shoulder_l.set(),
SDL.SDLK_s => keyinput.shoulder_r.set(),
SDL.SDLK_RETURN => keyinput.start.set(),
SDL.SDLK_RSHIFT => keyinput.select.set(),
else => {},
}
cpu.bus.io.keyinput.fetchOr(keyinput.raw, .Monotonic);
},
SDL.SDL_WINDOWEVENT => {
if (event.window.event == SDL.SDL_WINDOWEVENT_RESIZED) {
log.debug("window resized to: {}x{}", .{ event.window.data1, event.window.data2 });
win_dim.width = @intCast(u32, event.window.data1);
win_dim.height = @intCast(u32, event.window.data2);
}
}, },
else => {}, else => {},
} }
} }
{ var zgui_redraw: bool = false;
channel.emu.push(.Pause);
defer channel.emu.push(.Resume);
// Spin Loop until we know that the emu is paused switch (self.state.emulation) {
wait: while (true) switch (channel.gui.pop() orelse continue) { .Transition => |inner| switch (inner) {
.Paused => break :wait, .Active => {
else => |any| std.debug.panic("[Gui/Channel]: Unhandled Event: {}", .{any}), _ = channel.gui.pop();
};
channel.emu.push(.Resume);
self.state.emulation = .Active;
},
.Inactive => {
// Assert that double pausing is impossible
if (channel.gui.peek()) |value|
std.debug.assert(value != .Paused);
channel.emu.push(.Pause);
self.state.emulation = .Inactive;
},
},
.Active => skip_draw: {
const is_std = mode == .Standard;
if (is_std) channel.emu.push(.Pause);
defer if (is_std) channel.emu.push(.Resume);
switch (mode) {
.Standard => blk: {
const limit = 15; // TODO: What should this be?
// TODO: learn more about std.atomic.spinLoopHint();
for (0..limit) |_| {
const message = channel.gui.pop() orelse continue;
switch (message) {
.Paused => break :blk,
.Quit => unreachable,
}
}
log.info("timed out waiting for emu thread to pause (limit: {})", .{limit});
break :skip_draw;
},
.Debug => blk: {
switch (channel.gui.pop() orelse break :blk) {
.Paused => unreachable, // only in standard mode
.Quit => break :emu_loop, // FIXME: gdb side of emu is seriously out-of-date...
}
},
}
// Add FPS count to the histogram // Add FPS count to the histogram
if (tracker) |t| self.state.fps_hist.push(t.value()) catch {}; if (tracker) |t| self.state.fps_hist.push(t.value()) catch {};
@@ -346,17 +248,21 @@ pub const Gui = struct {
const buf = cpu.bus.ppu.framebuf.get(.Renderer); const buf = cpu.bus.ppu.framebuf.get(.Renderer);
gl.viewport(0, 0, gba_width, gba_height); gl.viewport(0, 0, gba_width, gba_height);
self.drawGbaTexture(obj_ids, emu_tex, buf); opengl_impl.drawScreenTexture(emu_tex, prog_id, objects, buf);
} }
zgui_redraw = imgui.draw(&self.state, win_dim, out_tex, cpu);
},
.Inactive => zgui_redraw = imgui.draw(&self.state, win_dim, out_tex, cpu),
}
if (zgui_redraw) {
// Background Colour // Background Colour
const size = zgui.io.getDisplaySize(); const size = zgui.io.getDisplaySize();
gl.viewport(0, 0, @floatToInt(c_int, size[0]), @floatToInt(c_int, size[1])); gl.viewport(0, 0, @floatToInt(GLsizei, size[0]), @floatToInt(GLsizei, size[1]));
gl.clearColor(0, 0, 0, 1.0); gl.clearColor(0, 0, 0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT); gl.clear(gl.COLOR_BUFFER_BIT);
zgui.backend.newFrame(width, height);
imgui.draw(&self.state, out_tex, cpu);
zgui.backend.draw(); zgui.backend.draw();
} }
@@ -415,7 +321,161 @@ const Audio = struct {
} }
}; };
const shader = struct { fn panic() noreturn {
const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
@panic(std.mem.sliceTo(str, 0));
}
const opengl_impl = struct {
// zig fmt: off
const vertices: [32]f32 = [_]f32{
// Positions // Colours // Texture Coords
1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // Top Right
1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // Bottom Right
-1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // Bottom Left
-1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // Top Left
};
const indices: [6]u32 = [_]u32{
0, 1, 3, // First Triangle
1, 2, 3, // Second Triangle
};
// zig fmt: on
const Objects = struct { vao: GLuint, vbo: GLuint, ebo: GLuint };
fn drawScreenTexture(tex_id: GLuint, prog_id: GLuint, ids: Objects, buf: []const u8) void {
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gba_width, gba_height, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, buf.ptr);
// Bind VAO, EBO. VBO not bound
gl.bindVertexArray(ids.vao); // VAO
defer gl.bindVertexArray(0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ids.ebo); // EBO
defer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0);
// Use compiled frag + vertex shader
gl.useProgram(prog_id);
defer gl.useProgram(0);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
}
fn compileShaders() !GLuint {
const vert_shader = @embedFile("shader/pixelbuf.vert");
const frag_shader = @embedFile("shader/pixelbuf.frag");
const vs = gl.createShader(gl.VERTEX_SHADER);
defer gl.deleteShader(vs);
gl.shaderSource(vs, 1, &[_][*c]const u8{vert_shader}, 0);
gl.compileShader(vs);
if (!shader.didCompile(vs)) return error.VertexCompileError;
const fs = gl.createShader(gl.FRAGMENT_SHADER);
defer gl.deleteShader(fs);
gl.shaderSource(fs, 1, &[_][*c]const u8{frag_shader}, 0);
gl.compileShader(fs);
if (!shader.didCompile(fs)) return error.FragmentCompileError;
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return program;
}
// Returns the VAO ID since it's used in run()
fn createObjects() Objects {
var vao_id: GLuint = undefined;
var vbo_id: GLuint = undefined;
var ebo_id: GLuint = undefined;
gl.genVertexArrays(1, &vao_id);
gl.genBuffers(1, &vbo_id);
gl.genBuffers(1, &ebo_id);
gl.bindVertexArray(vao_id);
defer gl.bindVertexArray(0);
gl.bindBuffer(gl.ARRAY_BUFFER, vbo_id);
defer gl.bindBuffer(gl.ARRAY_BUFFER, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebo_id);
defer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0);
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(@TypeOf(vertices)), &vertices, gl.STATIC_DRAW);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, @sizeOf(@TypeOf(indices)), &indices, gl.STATIC_DRAW);
// Position
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), null); // lmao
gl.enableVertexAttribArray(0);
// Colour
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), @intToPtr(?*anyopaque, (3 * @sizeOf(f32))));
gl.enableVertexAttribArray(1);
// Texture Coord
gl.vertexAttribPointer(2, 2, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), @intToPtr(?*anyopaque, (6 * @sizeOf(f32))));
gl.enableVertexAttribArray(2);
return .{ .vao = vao_id, .vbo = vbo_id, .ebo = ebo_id };
}
fn createScreenTexture(buf: []const u8) GLuint {
var tex_id: GLuint = undefined;
gl.genTextures(1, &tex_id);
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gba_width, gba_height, 0, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, buf.ptr);
return tex_id;
}
fn createOutputTexture() GLuint {
var tex_id: GLuint = undefined;
gl.genTextures(1, &tex_id);
gl.bindTexture(gl.TEXTURE_2D, tex_id);
defer gl.bindTexture(gl.TEXTURE_2D, 0);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gba_width, gba_height, 0, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, null);
return tex_id;
}
fn createFrameBuffer(tex_id: GLuint) !GLuint {
var fbo_id: GLuint = undefined;
gl.genFramebuffers(1, &fbo_id);
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo_id);
defer gl.bindFramebuffer(gl.FRAMEBUFFER, 0);
gl.framebufferTexture(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, tex_id, 0);
const draw_buffers: [1]GLuint = .{gl.COLOR_ATTACHMENT0};
gl.drawBuffers(1, &draw_buffers);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE)
return error.FrameBufferObejctInitFailed;
return fbo_id;
}
const shader = struct {
const Kind = enum { vertex, fragment }; const Kind = enum { vertex, fragment };
const log = std.log.scoped(.Shader); const log = std.log.scoped(.Shader);
@@ -435,9 +495,5 @@ const shader = struct {
gl.getShaderInfoLog(id, buf_len, 0, &error_msg); gl.getShaderInfoLog(id, buf_len, 0, &error_msg);
log.err("{s}", .{std.mem.sliceTo(&error_msg, 0)}); log.err("{s}", .{std.mem.sliceTo(&error_msg, 0)});
} }
};
}; };
fn panic() noreturn {
const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
@panic(std.mem.sliceTo(str, 0));
}

View File

@@ -260,7 +260,7 @@ pub const FrameBuffer = struct {
pub fn init(allocator: Allocator, comptime len: comptime_int) !Self { pub fn init(allocator: Allocator, comptime len: comptime_int) !Self {
const buf = try allocator.alloc(u8, len * 2); const buf = try allocator.alloc(u8, len * 2);
std.mem.set(u8, buf, 0); @memset(buf, 0);
return .{ return .{
// Front and Back Framebuffers // Front and Back Framebuffers
@@ -272,7 +272,7 @@ pub const FrameBuffer = struct {
} }
pub fn reset(self: *Self) void { pub fn reset(self: *Self) void {
std.mem.set(u8, self.buf, 0); @memset(self.buf, 0);
self.current = 0; self.current = 0;
} }