Compare commits
19 Commits
2c8e3cb726
...
61a869f0c5
|
@ -14,7 +14,8 @@ jobs:
|
|||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
# os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
runs-on: ${{matrix.os}}
|
||||
steps:
|
||||
- uses: goto-bus-stop/setup-zig@v2
|
||||
|
@ -39,7 +40,7 @@ jobs:
|
|||
with:
|
||||
submodules: true
|
||||
- name: build
|
||||
run: zig build -Doptimize=ReleaseSafe
|
||||
run: zig build -Doptimize=ReleaseSafe -Dcpu=baseline
|
||||
- name: upload
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
|
|
@ -11,4 +11,8 @@
|
|||
/lib/SDL2
|
||||
|
||||
# Any Custom Scripts for Debugging purposes
|
||||
*.sh
|
||||
*.sh
|
||||
|
||||
|
||||
# Dear ImGui
|
||||
**/imgui.ini
|
|
@ -13,3 +13,9 @@
|
|||
[submodule "lib/zig-toml"]
|
||||
path = lib/zig-toml
|
||||
url = https://github.com/aeronavery/zig-toml
|
||||
[submodule "lib/zgui"]
|
||||
path = lib/zgui
|
||||
url = https://git.musuka.dev/paoda/zgui
|
||||
[submodule "lib/nfd-zig"]
|
||||
path = lib/nfd-zig
|
||||
url = https://github.com/fabioarnold/nfd-zig
|
||||
|
|
10
README.md
10
README.md
|
@ -77,17 +77,19 @@ arm7wrestler GBA Fixed | [destoer](https://github.com/destoer)
|
|||
|
||||
## Compiling
|
||||
|
||||
Most recently built on Zig [v0.11.0-dev.1557+03cdb4fb5](https://github.com/ziglang/zig/tree/03cdb4fb5)
|
||||
Most recently built on Zig [v0.11.0-dev.1580+a5b34a61a](https://github.com/ziglang/zig/tree/a5b34a61a)
|
||||
|
||||
### Dependencies
|
||||
|
||||
Dependency | Source
|
||||
--- | ---
|
||||
SDL.zig | <https://github.com/MasterQ32/SDL.zig>
|
||||
zig-clap | <https://github.com/Hejsil/zig-clap>
|
||||
known-folders | <https://github.com/ziglibs/known-folders>
|
||||
zig-toml | <https://github.com/aeronavery/zig-toml>
|
||||
nfd-zig | <https://github.com/fabioarnold/nfd-zig>
|
||||
zgui | <https://github.com/michal-z/zig-gamedev/tree/main/libs/zgui>
|
||||
zig-clap | <https://github.com/Hejsil/zig-clap>
|
||||
zig-datetime | <https://github.com/frmdstryr/zig-datetime>
|
||||
zig-toml | <https://github.com/aeronavery/zig-toml>
|
||||
`bitfields.zig` | [https://github.com/FlorenceOS/Florence](https://github.com/FlorenceOS/Florence/blob/aaa5a9e568/lib/util/bitfields.zig)
|
||||
`gl.zig` | <https://github.com/MasterQ32/zig-opengl>
|
||||
|
||||
|
@ -96,7 +98,7 @@ Use `git submodule update --init` from the project root to pull the git relevant
|
|||
Be sure to provide SDL2 using:
|
||||
|
||||
- Linux: Your distro's package manager
|
||||
- MacOS: `brew` (install [this formula](https://formulae.brew.sh/formula/sdl2))
|
||||
- macOS: ¯\\\_(ツ)_/¯ (try [this formula](https://formulae.brew.sh/formula/sdl2)?)
|
||||
- Windows: [`vcpkg`](https://github.com/Microsoft/vcpkg) (install `sdl2:x64-windows`)
|
||||
|
||||
`SDL.zig` will provide a helpful compile error if the zig compiler is unable to find SDL2.
|
||||
|
|
14
build.zig
14
build.zig
|
@ -1,10 +1,13 @@
|
|||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const Sdk = @import("lib/SDL.zig/Sdk.zig");
|
||||
const zgui = @import("lib/zgui/build.zig");
|
||||
const nfd = @import("lib/nfd-zig/build.zig");
|
||||
|
||||
pub fn build(b: *std.build.Builder) void {
|
||||
// Minimum Zig Version
|
||||
const min_ver = std.SemanticVersion.parse("0.11.0-dev.1557+03cdb4fb5") catch return; // https://github.com/ziglang/zig/commit/03cdb4fb5
|
||||
const min_ver = std.SemanticVersion.parse("0.11.0-dev.1580+a5b34a61a") catch return; // https://github.com/ziglang/zig/commit/a5b34a61a
|
||||
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.os.exit(1);
|
||||
|
@ -40,11 +43,20 @@ pub fn build(b: *std.build.Builder) void {
|
|||
// OpenGL 3.3 Bindings
|
||||
exe.addAnonymousModule("gl", .{ .source_file = .{ .path = "lib/gl.zig" } });
|
||||
|
||||
// NativeFileDialog(ue) Bindings
|
||||
exe.linkLibrary(nfd.makeLib(b, target, optimize));
|
||||
exe.addModule("nfd", nfd.getModule(b));
|
||||
|
||||
// Zig SDL Bindings: https://github.com/MasterQ32/SDL.zig
|
||||
const sdk = Sdk.init(b, null);
|
||||
sdk.link(exe, .dynamic);
|
||||
exe.addModule("sdl2", sdk.getNativeModule());
|
||||
|
||||
// Dear ImGui bindings
|
||||
const zgui_pkg = zgui.package(b, .{ .options = .{ .backend = .sdl2_opengl3 } });
|
||||
exe.addModule("zgui", zgui_pkg.module);
|
||||
zgui.link(exe, zgui_pkg.options);
|
||||
|
||||
exe.install();
|
||||
|
||||
const run_cmd = exe.run();
|
||||
|
|
|
@ -1 +1 @@
|
|||
Subproject commit 6b33f1f4299ec8814e9fb3b206cda37791ced574
|
||||
Subproject commit 59c90e8ea2135384410817ccfdcc15ce5f7a245e
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 5e5098bcaf2643d35199ce556da8091626a4d2ef
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 12e480f30d1192eda18bd9245f41f6ff2d4055bd
|
|
@ -1 +1 @@
|
|||
Subproject commit 272d8e2088b2cae037349fb260dc05ec46bba422
|
||||
Subproject commit 861de651f3e1314973b1273ac7856e96b2625ff3
|
|
@ -1 +1 @@
|
|||
Subproject commit 932d2845210644ca736faf35f5bea31eb1a15465
|
||||
Subproject commit bf0ae0c27cfe92fdd9a92c8f1ac6d1939ae60c77
|
|
@ -105,7 +105,7 @@ pub fn deinit(self: *Self) void {
|
|||
fn fillReadTable(self: *Self, table: *[table_len]?*const anyopaque) void {
|
||||
const vramMirror = @import("ppu/Vram.zig").mirror;
|
||||
|
||||
for (table) |*ptr, i| {
|
||||
for (table, 0..) |*ptr, i| {
|
||||
const addr = @intCast(u32, page_size * i);
|
||||
|
||||
ptr.* = switch (addr) {
|
||||
|
@ -132,7 +132,7 @@ fn fillWriteTable(self: *Self, comptime T: type, table: *[table_len]?*const anyo
|
|||
comptime std.debug.assert(T == u32 or T == u16 or T == u8);
|
||||
const vramMirror = @import("ppu/Vram.zig").mirror;
|
||||
|
||||
for (table) |*ptr, i| {
|
||||
for (table, 0..) |*ptr, i| {
|
||||
const addr = @intCast(u32, page_size * i);
|
||||
|
||||
ptr.* = switch (addr) {
|
||||
|
|
|
@ -188,7 +188,7 @@ pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_pat
|
|||
const kind = Backup.guess(file_buf);
|
||||
const device = if (config.config().guest.force_rtc) .Rtc else guessDevice(file_buf);
|
||||
|
||||
logHeader(file_buf, &title);
|
||||
logHeader(file_buf, title);
|
||||
|
||||
return .{
|
||||
.buf = file_buf,
|
||||
|
@ -213,25 +213,24 @@ fn guessDevice(buf: []const u8) Gpio.Device.Kind {
|
|||
// Try to Guess if ROM uses RTC
|
||||
const needle = "RTC_V"; // I was told SIIRTC_V, though Pokemen Firered (USA) is a false negative
|
||||
|
||||
// TODO: Use new for loop syntax?
|
||||
var i: usize = 0;
|
||||
while ((i + needle.len) < buf.len) : (i += 1) {
|
||||
if (std.mem.eql(u8, needle, buf[i..(i + needle.len)])) return .Rtc;
|
||||
}
|
||||
|
||||
// TODO: Detect other GPIO devices
|
||||
|
||||
return .None;
|
||||
}
|
||||
|
||||
fn logHeader(buf: []const u8, title: *const [12]u8) void {
|
||||
const code = buf[0xAC..0xB0];
|
||||
const maker = buf[0xB0..0xB2];
|
||||
const version = buf[0xBC];
|
||||
fn logHeader(buf: []const u8, title: [12]u8) void {
|
||||
const ver = buf[0xBC];
|
||||
|
||||
log.info("Title: {s}", .{title});
|
||||
if (version != 0) log.info("Version: {}", .{version});
|
||||
log.info("Game Code: {s}", .{code});
|
||||
log.info("Maker Code: {s}", .{maker});
|
||||
if (ver != 0) log.info("Version: {}", .{ver});
|
||||
|
||||
log.info("Game Code: {s}", .{buf[0xAC..0xB0]});
|
||||
log.info("Maker Code: {s}", .{buf[0xB0..0xB2]});
|
||||
}
|
||||
|
||||
test "OOB Access" {
|
||||
|
|
|
@ -137,6 +137,7 @@ pub const Backup = struct {
|
|||
for (backup_kinds) |needle| {
|
||||
const needle_len = needle.str.len;
|
||||
|
||||
// TODO: Use new for loop syntax?
|
||||
var i: usize = 0;
|
||||
while ((i + needle_len) < rom.len) : (i += 1) {
|
||||
if (std.mem.eql(u8, needle.str, rom[i..][0..needle_len])) return needle.kind;
|
||||
|
|
|
@ -339,10 +339,7 @@ fn DmaController(comptime id: u2) type {
|
|||
}
|
||||
|
||||
pub fn onBlanking(bus: *Bus, comptime kind: DmaKind) void {
|
||||
comptime var i: usize = 0;
|
||||
inline while (i < 4) : (i += 1) {
|
||||
bus.dma[i].poll(kind);
|
||||
}
|
||||
inline for (0..4) |i| bus.dma[i].poll(kind);
|
||||
}
|
||||
|
||||
const Adjustment = enum(u2) {
|
||||
|
|
|
@ -293,13 +293,13 @@ pub const Clock = struct {
|
|||
self.cpu.sched.push(.RealTimeClock, (1 << 24) -| late); // Reschedule
|
||||
|
||||
const now = DateTime.now();
|
||||
self.year = bcd(u8, @intCast(u8, now.date.year - 2000));
|
||||
self.month = bcd(u5, now.date.month);
|
||||
self.day = bcd(u6, now.date.day);
|
||||
self.weekday = bcd(u3, (now.date.weekday() + 1) % 7); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6
|
||||
self.hour = bcd(u6, now.time.hour);
|
||||
self.minute = bcd(u7, now.time.minute);
|
||||
self.second = bcd(u7, now.time.second);
|
||||
self.year = bcd(@intCast(u8, now.date.year - 2000));
|
||||
self.month = @truncate(u5, bcd(now.date.month));
|
||||
self.day = @truncate(u6, bcd(now.date.day));
|
||||
self.weekday = @truncate(u3, bcd((now.date.weekday() + 1) % 7)); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6
|
||||
self.hour = @truncate(u6, bcd(now.time.hour));
|
||||
self.minute = @truncate(u7, bcd(now.time.minute));
|
||||
self.second = @truncate(u7, bcd(now.time.second));
|
||||
}
|
||||
|
||||
fn step(self: *Self, value: Data) u4 {
|
||||
|
@ -449,16 +449,8 @@ pub const Clock = struct {
|
|||
}
|
||||
};
|
||||
|
||||
fn bcd(comptime T: type, value: u8) T {
|
||||
var input = value;
|
||||
var ret: u8 = 0;
|
||||
var shift: u3 = 0;
|
||||
|
||||
while (input > 0) {
|
||||
ret |= (input % 10) << (shift << 2);
|
||||
shift += 1;
|
||||
input /= 10;
|
||||
}
|
||||
|
||||
return @truncate(T, ret);
|
||||
/// Converts an 8-bit unsigned integer to its BCD representation.
|
||||
/// Note: Algorithm only works for values between 0 and 99 inclusive.
|
||||
fn bcd(value: u8) u8 {
|
||||
return ((value / 10) << 4) + (value % 10);
|
||||
}
|
||||
|
|
|
@ -346,10 +346,10 @@ const InterruptEnable = extern union {
|
|||
vblank: Bit(u16, 0),
|
||||
hblank: Bit(u16, 1),
|
||||
coincidence: Bit(u16, 2),
|
||||
tm0_overflow: Bit(u16, 3),
|
||||
tm1_overflow: Bit(u16, 4),
|
||||
tm2_overflow: Bit(u16, 5),
|
||||
tm3_overflow: Bit(u16, 6),
|
||||
tim0: Bit(u16, 3),
|
||||
tim1: Bit(u16, 4),
|
||||
tim2: Bit(u16, 5),
|
||||
tim3: Bit(u16, 6),
|
||||
serial: Bit(u16, 7),
|
||||
dma0: Bit(u16, 8),
|
||||
dma1: Bit(u16, 9),
|
||||
|
|
|
@ -39,13 +39,12 @@ pub const arm = struct {
|
|||
}
|
||||
|
||||
fn populate() [0x1000]InstrFn {
|
||||
return comptime {
|
||||
comptime {
|
||||
@setEvalBranchQuota(0xE000);
|
||||
var ret = [_]InstrFn{und} ** 0x1000;
|
||||
var table = [_]InstrFn{und} ** 0x1000;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < ret.len) : (i += 1) {
|
||||
ret[i] = switch (@as(u2, i >> 10)) {
|
||||
for (&table, 0..) |*handler, i| {
|
||||
handler.* = switch (@as(u2, i >> 10)) {
|
||||
0b00 => if (i == 0x121) blk: {
|
||||
break :blk branchExchange;
|
||||
} else if (i & 0xFCF == 0x009) blk: {
|
||||
|
@ -107,8 +106,8 @@ pub const arm = struct {
|
|||
};
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
return table;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -136,13 +135,12 @@ pub const thumb = struct {
|
|||
}
|
||||
|
||||
fn populate() [0x400]InstrFn {
|
||||
return comptime {
|
||||
comptime {
|
||||
@setEvalBranchQuota(5025); // This is exact
|
||||
var ret = [_]InstrFn{und} ** 0x400;
|
||||
var table = [_]InstrFn{und} ** 0x400;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < ret.len) : (i += 1) {
|
||||
ret[i] = switch (@as(u3, i >> 7 & 0x7)) {
|
||||
for (&table, 0..) |*handler, i| {
|
||||
handler.* = switch (@as(u3, i >> 7 & 0x7)) {
|
||||
0b000 => if (i >> 5 & 0x3 == 0b11) blk: {
|
||||
const I = i >> 4 & 1 == 1;
|
||||
const is_sub = i >> 3 & 1 == 1;
|
||||
|
@ -230,8 +228,8 @@ pub const thumb = struct {
|
|||
};
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
return table;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -385,8 +383,7 @@ pub const Arm7tdmi = struct {
|
|||
const now = getModeChecked(self, self.cpsr.mode.read());
|
||||
|
||||
// Bank R8 -> r12
|
||||
var i: usize = 0;
|
||||
while (i < 5) : (i += 1) {
|
||||
for (0..5) |i| {
|
||||
self.bank.fiq[Bank.fiqIdx(i, now)] = self.r[8 + i];
|
||||
}
|
||||
|
||||
|
@ -404,8 +401,7 @@ pub const Arm7tdmi = struct {
|
|||
}
|
||||
|
||||
// Grab R8 -> R12
|
||||
i = 0;
|
||||
while (i < 5) : (i += 1) {
|
||||
for (0..5) |i| {
|
||||
self.r[8 + i] = self.bank.fiq[Bank.fiqIdx(i, next)];
|
||||
}
|
||||
|
||||
|
@ -470,8 +466,7 @@ pub const Arm7tdmi = struct {
|
|||
}
|
||||
|
||||
pub fn stepDmaTransfer(self: *Self) bool {
|
||||
comptime var i: usize = 0;
|
||||
inline while (i < 4) : (i += 1) {
|
||||
inline for (0..4) |i| {
|
||||
if (self.bus.dma[i].in_progress) {
|
||||
self.bus.dma[i].step(self);
|
||||
return true;
|
||||
|
@ -647,7 +642,7 @@ pub const PSR = extern union {
|
|||
}
|
||||
};
|
||||
|
||||
const Mode = enum(u5) {
|
||||
pub const Mode = enum(u5) {
|
||||
User = 0b10000,
|
||||
Fiq = 0b10001,
|
||||
Irq = 0b10010,
|
||||
|
@ -656,7 +651,7 @@ const Mode = enum(u5) {
|
|||
Undefined = 0b11011,
|
||||
System = 0b11111,
|
||||
|
||||
fn toString(self: Mode) []const u8 {
|
||||
pub fn toString(self: Mode) []const u8 {
|
||||
return switch (self) {
|
||||
.User => "usr",
|
||||
.Fiq => "fiq",
|
||||
|
|
|
@ -92,8 +92,7 @@ pub fn fmt15(comptime L: bool, comptime rb: u3) InstrFn {
|
|||
inline fn countRlist(opcode: u16) u32 {
|
||||
var count: u32 = 0;
|
||||
|
||||
comptime var i: u4 = 0;
|
||||
inline while (i < 8) : (i += 1) {
|
||||
inline for (0..8) |i| {
|
||||
if (opcode >> (7 - i) & 1 == 1) count += 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ const config = @import("../config.zig");
|
|||
|
||||
const Scheduler = @import("scheduler.zig").Scheduler;
|
||||
const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
|
||||
const FpsTracker = @import("../util.zig").FpsTracker;
|
||||
const Tracker = @import("../util.zig").FpsTracker;
|
||||
|
||||
const Timer = std.time.Timer;
|
||||
const Atomic = std.atomic.Atomic;
|
||||
|
@ -35,18 +35,18 @@ const RunKind = enum {
|
|||
LimitedFPS,
|
||||
};
|
||||
|
||||
pub fn run(quit: *Atomic(bool), scheduler: *Scheduler, cpu: *Arm7tdmi, tracker: *FpsTracker) void {
|
||||
pub fn run(quit: *Atomic(bool), pause: *Atomic(bool), cpu: *Arm7tdmi, scheduler: *Scheduler, tracker: *Tracker) void {
|
||||
const audio_sync = config.config().guest.audio_sync and !config.config().host.mute;
|
||||
if (audio_sync) log.info("Audio sync enabled", .{});
|
||||
|
||||
if (config.config().guest.video_sync) {
|
||||
inner(.LimitedFPS, audio_sync, quit, scheduler, cpu, tracker);
|
||||
inner(.LimitedFPS, audio_sync, quit, pause, cpu, scheduler, tracker);
|
||||
} else {
|
||||
inner(.UnlimitedFPS, audio_sync, quit, scheduler, cpu, tracker);
|
||||
inner(.UnlimitedFPS, audio_sync, quit, pause, cpu, scheduler, tracker);
|
||||
}
|
||||
}
|
||||
|
||||
fn inner(comptime kind: RunKind, audio_sync: bool, quit: *Atomic(bool), scheduler: *Scheduler, cpu: *Arm7tdmi, tracker: ?*FpsTracker) void {
|
||||
fn inner(comptime kind: RunKind, audio_sync: bool, quit: *Atomic(bool), pause: *Atomic(bool), cpu: *Arm7tdmi, scheduler: *Scheduler, tracker: ?*Tracker) void {
|
||||
if (kind == .UnlimitedFPS or kind == .LimitedFPS) {
|
||||
std.debug.assert(tracker != null);
|
||||
log.info("FPS tracking enabled", .{});
|
||||
|
@ -57,6 +57,8 @@ fn inner(comptime kind: RunKind, audio_sync: bool, quit: *Atomic(bool), schedule
|
|||
log.info("Emulation w/out video sync", .{});
|
||||
|
||||
while (!quit.load(.Monotonic)) {
|
||||
if (pause.load(.Monotonic)) continue;
|
||||
|
||||
runFrame(scheduler, cpu);
|
||||
audioSync(audio_sync, cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
|
||||
|
||||
|
@ -69,6 +71,8 @@ fn inner(comptime kind: RunKind, audio_sync: bool, quit: *Atomic(bool), schedule
|
|||
var wake_time: u64 = frame_period;
|
||||
|
||||
while (!quit.load(.Monotonic)) {
|
||||
if (pause.load(.Monotonic)) continue;
|
||||
|
||||
runFrame(scheduler, cpu);
|
||||
const new_wake_time = videoSync(&timer, wake_time);
|
||||
|
||||
|
@ -146,9 +150,8 @@ fn sleep(timer: *Timer, wake_time: u64) ?u64 {
|
|||
|
||||
const step = 2 * std.time.ns_per_ms; // Granularity of 2ms
|
||||
const times = sleep_for / step;
|
||||
var i: usize = 0;
|
||||
|
||||
while (i < times) : (i += 1) {
|
||||
for (0..times) |_| {
|
||||
std.time.sleep(step);
|
||||
|
||||
// Upon wakeup, check to see if this particular sleep was longer than expected
|
||||
|
|
|
@ -625,8 +625,7 @@ pub const Ppu = struct {
|
|||
const framebuf_base = width * @as(usize, scanline);
|
||||
if (obj_enable) self.fetchSprites();
|
||||
|
||||
var layer: usize = 0;
|
||||
while (layer < 4) : (layer += 1) {
|
||||
for (0..4) |layer| {
|
||||
self.drawSprites(@truncate(u2, layer));
|
||||
if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackground(0);
|
||||
if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackground(1);
|
||||
|
@ -640,8 +639,7 @@ pub const Ppu = struct {
|
|||
const framebuf_base = width * @as(usize, scanline);
|
||||
if (obj_enable) self.fetchSprites();
|
||||
|
||||
var layer: usize = 0;
|
||||
while (layer < 4) : (layer += 1) {
|
||||
for (0..4) |layer| {
|
||||
self.drawSprites(@truncate(u2, layer));
|
||||
if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackground(0);
|
||||
if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackground(1);
|
||||
|
@ -654,8 +652,7 @@ pub const Ppu = struct {
|
|||
const framebuf_base = width * @as(usize, scanline);
|
||||
if (obj_enable) self.fetchSprites();
|
||||
|
||||
var layer: usize = 0;
|
||||
while (layer < 4) : (layer += 1) {
|
||||
for (0..4) |layer| {
|
||||
self.drawSprites(@truncate(u2, layer));
|
||||
if (layer == self.bg[2].cnt.priority.read() and bg_enable >> 2 & 1 == 1) self.drawAffineBackground(2);
|
||||
if (layer == self.bg[3].cnt.priority.read() and bg_enable >> 3 & 1 == 1) self.drawAffineBackground(3);
|
||||
|
@ -671,7 +668,7 @@ pub const Ppu = struct {
|
|||
const vram_buf = @ptrCast([*]const u16, @alignCast(@alignOf(u16), self.vram.buf));
|
||||
const framebuf = @ptrCast([*]u32, @alignCast(@alignOf(u32), self.framebuf.get(.Emulator)));
|
||||
|
||||
for (vram_buf[vram_base .. vram_base + width]) |bgr555, i| {
|
||||
for (vram_buf[vram_base .. vram_base + width], 0..) |bgr555, i| {
|
||||
framebuf[framebuf_base + i] = rgba888(bgr555);
|
||||
}
|
||||
},
|
||||
|
@ -685,7 +682,7 @@ pub const Ppu = struct {
|
|||
const pal_buf = @ptrCast([*]const u16, @alignCast(@alignOf(u16), self.palette.buf));
|
||||
const framebuf = @ptrCast([*]u32, @alignCast(@alignOf(u32), self.framebuf.get(.Emulator)));
|
||||
|
||||
for (self.vram.buf[vram_base .. vram_base + width]) |pal_id, i| {
|
||||
for (self.vram.buf[vram_base .. vram_base + width], 0..) |pal_id, i| {
|
||||
framebuf[framebuf_base + i] = rgba888(pal_buf[pal_id]);
|
||||
}
|
||||
},
|
||||
|
@ -701,8 +698,7 @@ pub const Ppu = struct {
|
|||
const vram_buf = @ptrCast([*]const u16, @alignCast(@alignOf(u16), self.vram.buf));
|
||||
const framebuf = @ptrCast([*]u32, @alignCast(@alignOf(u32), self.framebuf.get(.Emulator)));
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < width) : (i += 1) {
|
||||
for (0..width) |i| {
|
||||
const bgr555 = if (scanline < m5_height and i < m5_width) vram_buf[vram_base + i] else self.palette.backdrop();
|
||||
framebuf[framebuf_base + i] = rgba888(bgr555);
|
||||
}
|
||||
|
@ -718,7 +714,7 @@ pub const Ppu = struct {
|
|||
// FIXME: @ptrCast between slices changing the length isn't implemented yet
|
||||
const framebuf = @ptrCast([*]u32, @alignCast(@alignOf(u32), self.framebuf.get(.Emulator)));
|
||||
|
||||
for (self.scanline.top()) |maybe_top, i| {
|
||||
for (self.scanline.top(), 0..) |maybe_top, i| {
|
||||
const maybe_btm = self.scanline.btm()[i];
|
||||
|
||||
const bgr555 = self.getBgr555(maybe_top, maybe_btm);
|
||||
|
|
|
@ -73,7 +73,7 @@ pub const Scheduler = struct {
|
|||
|
||||
/// Removes the **first** scheduled event of type `needle`
|
||||
pub fn removeScheduledEvent(self: *Self, needle: EventKind) void {
|
||||
for (self.queue.items) |event, i| {
|
||||
for (self.queue.items, 0..) |event, i| {
|
||||
if (std.meta.eql(event.kind, needle)) {
|
||||
|
||||
// invalidates the slice we're iterating over
|
||||
|
|
|
@ -13,8 +13,6 @@ const FilePaths = @import("util.zig").FilePaths;
|
|||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const log = std.log.scoped(.Cli);
|
||||
const width = @import("core/ppu.zig").width;
|
||||
const height = @import("core/ppu.zig").height;
|
||||
pub const log_level = if (builtin.mode != .Debug) .info else std.log.default_level;
|
||||
|
||||
// CLI Arguments + Help Text
|
||||
|
@ -87,13 +85,14 @@ pub fn main() void {
|
|||
cpu.fastBoot();
|
||||
}
|
||||
|
||||
var gui = Gui.init(&bus.pak.title, &bus.apu, width, height) catch |e| exitln("failed to init gui: {}", .{e});
|
||||
// TODO: Just copy the title instead of grabbing a pointer to it
|
||||
var gui = Gui.init(allocator, bus.pak.title, &bus.apu) catch |e| exitln("failed to init gui: {}", .{e});
|
||||
defer gui.deinit();
|
||||
|
||||
gui.run(&cpu, &scheduler) catch |e| exitln("failed to run gui thread: {}", .{e});
|
||||
}
|
||||
|
||||
pub fn handleArguments(allocator: Allocator, data_path: []const u8, result: *const clap.Result(clap.Help, ¶ms, clap.parsers.default)) !FilePaths {
|
||||
fn handleArguments(allocator: Allocator, data_path: []const u8, result: *const clap.Result(clap.Help, ¶ms, clap.parsers.default)) !FilePaths {
|
||||
const rom_path = romPath(result);
|
||||
log.info("ROM path: {s}", .{rom_path});
|
||||
|
||||
|
|
490
src/platform.zig
490
src/platform.zig
|
@ -1,6 +1,9 @@
|
|||
const std = @import("std");
|
||||
const SDL = @import("sdl2");
|
||||
const gl = @import("gl");
|
||||
const zgui = @import("zgui");
|
||||
const nfd = @import("nfd");
|
||||
|
||||
const emu = @import("core/emu.zig");
|
||||
const config = @import("config.zig");
|
||||
|
||||
|
@ -8,10 +11,19 @@ const Apu = @import("core/apu.zig").Apu;
|
|||
const Arm7tdmi = @import("core/cpu.zig").Arm7tdmi;
|
||||
const Scheduler = @import("core/scheduler.zig").Scheduler;
|
||||
const FpsTracker = @import("util.zig").FpsTracker;
|
||||
const RingBuffer = @import("util.zig").RingBuffer;
|
||||
|
||||
const gba_width = @import("core/ppu.zig").width;
|
||||
const gba_height = @import("core/ppu.zig").height;
|
||||
|
||||
const GLuint = gl.GLuint;
|
||||
const GLsizei = gl.GLsizei;
|
||||
const SDL_GLContext = *anyopaque;
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const width = 1280;
|
||||
const height = 720;
|
||||
|
||||
pub const sample_rate = 1 << 15;
|
||||
pub const sample_format = SDL.AUDIO_U16;
|
||||
|
||||
|
@ -19,9 +31,23 @@ const default_title = "ZBA";
|
|||
|
||||
pub const Gui = struct {
|
||||
const Self = @This();
|
||||
const SDL_GLContext = *anyopaque; // SDL.SDL_GLContext is a ?*anyopaque
|
||||
const log = std.log.scoped(.Gui);
|
||||
|
||||
const State = struct {
|
||||
fps_hist: RingBuffer(u32),
|
||||
should_quit: bool = false,
|
||||
|
||||
pub fn init(allocator: Allocator) !@This() {
|
||||
const history = try allocator.alloc(u32, 0x400);
|
||||
return .{ .fps_hist = RingBuffer(u32).init(history) };
|
||||
}
|
||||
|
||||
fn deinit(self: *@This(), allocator: Allocator) void {
|
||||
self.fps_hist.deinit(allocator);
|
||||
self.* = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// zig fmt: off
|
||||
const vertices: [32]f32 = [_]f32{
|
||||
// Positions // Colours // Texture Coords
|
||||
|
@ -39,25 +65,26 @@ pub const Gui = struct {
|
|||
|
||||
window: *SDL.SDL_Window,
|
||||
ctx: SDL_GLContext,
|
||||
title: []const u8,
|
||||
title: [:0]const u8,
|
||||
audio: Audio,
|
||||
|
||||
state: State,
|
||||
|
||||
allocator: Allocator,
|
||||
program_id: gl.GLuint,
|
||||
|
||||
pub fn init(title: *const [12]u8, apu: *Apu, width: i32, height: i32) !Self {
|
||||
pub fn init(allocator: Allocator, title: [12]u8, apu: *Apu) !Self {
|
||||
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0) panic();
|
||||
if (SDL.SDL_GL_SetAttribute(SDL.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GL_CONTEXT_PROFILE_CORE) < 0) panic();
|
||||
if (SDL.SDL_GL_SetAttribute(SDL.SDL_GL_CONTEXT_MAJOR_VERSION, 3) < 0) panic();
|
||||
if (SDL.SDL_GL_SetAttribute(SDL.SDL_GL_CONTEXT_MAJOR_VERSION, 3) < 0) panic();
|
||||
|
||||
const win_scale = @intCast(c_int, config.config().host.win_scale);
|
||||
|
||||
const window = SDL.SDL_CreateWindow(
|
||||
default_title,
|
||||
SDL.SDL_WINDOWPOS_CENTERED,
|
||||
SDL.SDL_WINDOWPOS_CENTERED,
|
||||
@as(c_int, width * win_scale),
|
||||
@as(c_int, height * win_scale),
|
||||
width,
|
||||
height,
|
||||
SDL.SDL_WINDOW_OPENGL | SDL.SDL_WINDOW_SHOWN,
|
||||
) orelse panic();
|
||||
|
||||
|
@ -67,19 +94,62 @@ pub const Gui = struct {
|
|||
gl.load(ctx, Self.glGetProcAddress) catch {};
|
||||
if (SDL.SDL_GL_SetSwapInterval(@boolToInt(config.config().host.vsync)) < 0) panic();
|
||||
|
||||
const program_id = try compileShaders();
|
||||
zgui.init(allocator);
|
||||
zgui.plot.init();
|
||||
zgui.backend.init(window, ctx, "#version 330 core");
|
||||
|
||||
// zgui.io.setIniFilename(null);
|
||||
|
||||
return Self{
|
||||
.window = window,
|
||||
.title = std.mem.sliceTo(title, 0),
|
||||
.title = try allocator.dupeZ(u8, &title),
|
||||
.ctx = ctx,
|
||||
.program_id = program_id,
|
||||
.program_id = try compileShaders(),
|
||||
.audio = Audio.init(apu),
|
||||
|
||||
.allocator = allocator,
|
||||
.state = try State.init(allocator),
|
||||
};
|
||||
}
|
||||
|
||||
fn compileShaders() !gl.GLuint {
|
||||
// TODO: Panic on Shader Compiler Failure + Error Message
|
||||
pub fn deinit(self: *Self) void {
|
||||
self.audio.deinit();
|
||||
self.state.deinit(self.allocator);
|
||||
|
||||
zgui.backend.deinit();
|
||||
zgui.plot.deinit();
|
||||
zgui.deinit();
|
||||
|
||||
gl.deleteProgram(self.program_id);
|
||||
SDL.SDL_GL_DeleteContext(self.ctx);
|
||||
SDL.SDL_DestroyWindow(self.window);
|
||||
SDL.SDL_Quit();
|
||||
|
||||
self.allocator.free(self.title);
|
||||
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");
|
||||
|
||||
|
@ -108,20 +178,25 @@ pub const Gui = struct {
|
|||
}
|
||||
|
||||
// Returns the VAO ID since it's used in run()
|
||||
fn generateBuffers() struct { c_uint, c_uint, c_uint } {
|
||||
var vao_id: c_uint = undefined;
|
||||
var vbo_id: c_uint = undefined;
|
||||
var ebo_id: c_uint = undefined;
|
||||
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);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(@TypeOf(vertices)), &vertices, gl.STATIC_DRAW);
|
||||
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
|
||||
|
@ -137,46 +212,242 @@ pub const Gui = struct {
|
|||
return .{ vao_id, vbo_id, ebo_id };
|
||||
}
|
||||
|
||||
fn generateTexture(buf: []const u8) c_uint {
|
||||
var tex_id: c_uint = undefined;
|
||||
fn genGbaTexture(buf: []const u8) GLuint {
|
||||
var tex_id: GLuint = undefined;
|
||||
gl.genTextures(1, &tex_id);
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex_id);
|
||||
|
||||
// gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
// gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
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);
|
||||
// gl.generateMipmap(gl.TEXTURE_2D); // TODO: Remove?
|
||||
|
||||
return tex_id;
|
||||
}
|
||||
|
||||
pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void {
|
||||
var quit = std.atomic.Atomic(bool).init(false);
|
||||
var tracker = FpsTracker.init();
|
||||
fn genOutTexture() GLuint {
|
||||
var tex_id: GLuint = undefined;
|
||||
gl.genTextures(1, &tex_id);
|
||||
|
||||
var buffer_ids = Self.generateBuffers();
|
||||
defer {
|
||||
gl.deleteBuffers(1, &buffer_ids[2]); // EBO
|
||||
gl.deleteBuffers(1, &buffer_ids[1]); // VBO
|
||||
gl.deleteVertexArrays(1, &buffer_ids[0]); // VAO
|
||||
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;
|
||||
}
|
||||
|
||||
fn draw(self: *Self, tex_id: GLuint, cpu: *const Arm7tdmi) void {
|
||||
const win_scale = config.config().host.win_scale;
|
||||
|
||||
{
|
||||
_ = zgui.beginMainMenuBar();
|
||||
defer zgui.endMainMenuBar();
|
||||
|
||||
if (zgui.beginMenu("File", true)) {
|
||||
defer zgui.endMenu();
|
||||
|
||||
if (zgui.menuItem("Quit", .{})) self.state.should_quit = true;
|
||||
if (zgui.menuItem("Insert ROM", .{})) blk: {
|
||||
const maybe_path = nfd.openFileDialog("gba", null) catch |e| {
|
||||
log.err("failed to open file dialog: {?}", .{e});
|
||||
break :blk;
|
||||
};
|
||||
|
||||
if (maybe_path) |file_path| {
|
||||
defer nfd.freePath(file_path);
|
||||
log.info("user chose: \"{s}\"", .{file_path});
|
||||
|
||||
// emu.loadRom(cpu, file_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (zgui.beginMenu("Emulation", true)) {
|
||||
defer zgui.endMenu();
|
||||
|
||||
if (zgui.menuItem("Restart", .{})) log.warn("TODO: Restart Emulator", .{});
|
||||
}
|
||||
}
|
||||
const vao_id = buffer_ids[0];
|
||||
|
||||
const tex_id = Self.generateTexture(cpu.bus.ppu.framebuf.get(.Renderer));
|
||||
defer gl.deleteTextures(1, &tex_id);
|
||||
{
|
||||
const w = @intToFloat(f32, gba_width * win_scale);
|
||||
const h = @intToFloat(f32, gba_height * win_scale);
|
||||
|
||||
const thread = try std.Thread.spawn(.{}, emu.run, .{ &quit, scheduler, cpu, &tracker });
|
||||
_ = zgui.begin(self.title, .{ .flags = .{ .no_resize = true, .always_auto_resize = true } });
|
||||
defer zgui.end();
|
||||
|
||||
zgui.image(@intToPtr(*anyopaque, tex_id), .{ .w = w, .h = h, .uv0 = .{ 0, 1 }, .uv1 = .{ 1, 0 } });
|
||||
}
|
||||
|
||||
{
|
||||
_ = zgui.begin("Information", .{});
|
||||
defer zgui.end();
|
||||
|
||||
{
|
||||
var i: usize = 0;
|
||||
while (i < 8) : (i += 1) {
|
||||
zgui.text("R{}: 0x{X:0>8}", .{ i, cpu.r[i] });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
|
||||
const prefix = if (8 + i < 10) " " else "";
|
||||
zgui.text("{s}R{}: 0x{X:0>8}", .{ prefix, 8 + i, cpu.r[8 + i] });
|
||||
}
|
||||
}
|
||||
|
||||
zgui.separator();
|
||||
|
||||
widgets.psr("CPSR", cpu.cpsr);
|
||||
widgets.psr("SPSR", cpu.spsr);
|
||||
|
||||
zgui.separator();
|
||||
|
||||
widgets.interrupts(" IE", cpu.bus.io.ie); // space is for padding
|
||||
widgets.interrupts("IRQ", cpu.bus.io.irq);
|
||||
}
|
||||
|
||||
{
|
||||
_ = zgui.begin("Performance", .{});
|
||||
defer zgui.end();
|
||||
|
||||
const tmp = blk: {
|
||||
var buf: [0x400]u32 = undefined;
|
||||
const len = self.state.fps_hist.copy(&buf);
|
||||
|
||||
break :blk .{ buf, len };
|
||||
};
|
||||
const values = tmp[0];
|
||||
const len = tmp[1];
|
||||
|
||||
if (len == values.len) _ = self.state.fps_hist.pop();
|
||||
|
||||
const sorted = blk: {
|
||||
var buf: @TypeOf(values) = undefined;
|
||||
|
||||
std.mem.copy(u32, buf[0..len], values[0..len]);
|
||||
std.sort.sort(u32, buf[0..len], {}, std.sort.asc(u32));
|
||||
|
||||
break :blk buf;
|
||||
};
|
||||
|
||||
const y_max = 2 * if (len != 0) @intToFloat(f64, sorted[len - 1]) else emu.frame_rate;
|
||||
const x_max = @intToFloat(f64, values.len);
|
||||
|
||||
const y_args = .{ .flags = .{ .no_grid_lines = true } };
|
||||
const x_args = .{ .flags = .{ .no_grid_lines = true, .no_tick_labels = true, .no_tick_marks = true } };
|
||||
|
||||
if (zgui.plot.beginPlot("Emulation FPS", .{ .w = 0.0, .flags = .{ .no_title = true, .no_frame = true } })) {
|
||||
defer zgui.plot.endPlot();
|
||||
|
||||
zgui.plot.setupLegend(.{ .north = true, .east = true }, .{});
|
||||
zgui.plot.setupAxis(.x1, x_args);
|
||||
zgui.plot.setupAxis(.y1, y_args);
|
||||
zgui.plot.setupAxisLimits(.y1, .{ .min = 0.0, .max = y_max, .cond = .always });
|
||||
zgui.plot.setupAxisLimits(.x1, .{ .min = 0.0, .max = x_max, .cond = .always });
|
||||
zgui.plot.setupFinish();
|
||||
|
||||
zgui.plot.plotLineValues("FPS", u32, .{ .v = values[0..len] });
|
||||
}
|
||||
|
||||
const stats: struct { u32, u32, u32 } = blk: {
|
||||
if (len == 0) break :blk .{ 0, 0, 0 };
|
||||
|
||||
const average = average: {
|
||||
var sum: u32 = 0;
|
||||
for (sorted[0..len]) |value| sum += value;
|
||||
|
||||
break :average @intCast(u32, sum / len);
|
||||
};
|
||||
const median = sorted[len / 2];
|
||||
const low = sorted[len / 100]; // 1% Low
|
||||
|
||||
break :blk .{ average, median, low };
|
||||
};
|
||||
|
||||
zgui.text("Average: {:0>3} fps", .{stats[0]});
|
||||
zgui.text(" Median: {:0>3} fps", .{stats[1]});
|
||||
zgui.text(" 1% Low: {:0>3} fps", .{stats[2]});
|
||||
}
|
||||
|
||||
{
|
||||
_ = zgui.begin("Scheduler", .{});
|
||||
defer zgui.end();
|
||||
|
||||
const scheduler = cpu.sched;
|
||||
|
||||
zgui.text("tick: {X:0>16}", .{scheduler.tick});
|
||||
zgui.separator();
|
||||
|
||||
const Event = std.meta.Child(@TypeOf(scheduler.queue.items));
|
||||
|
||||
var items: [20]Event = undefined;
|
||||
const len = scheduler.queue.len;
|
||||
|
||||
std.mem.copy(Event, &items, scheduler.queue.items);
|
||||
std.sort.sort(Event, items[0..len], {}, widgets.eventDesc(Event));
|
||||
|
||||
for (items[0..len]) |event| {
|
||||
zgui.text("{X:0>16} | {?}", .{ event.tick, event.kind });
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
zgui.showDemoWindow(null);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void {
|
||||
const obj_ids = Self.genBufferObjects();
|
||||
defer gl.deleteBuffers(3, @as(*const [3]c_uint, &obj_ids));
|
||||
|
||||
const emu_tex = Self.genGbaTexture(cpu.bus.ppu.framebuf.get(.Renderer));
|
||||
const out_tex = Self.genOutTexture();
|
||||
defer gl.deleteTextures(2, &[_]c_uint{ emu_tex, out_tex });
|
||||
|
||||
const fbo_id = try Self.genFrameBufObject(out_tex);
|
||||
defer gl.deleteFramebuffers(1, &fbo_id);
|
||||
|
||||
var tracker = FpsTracker.init();
|
||||
var quit = std.atomic.Atomic(bool).init(false);
|
||||
var pause = std.atomic.Atomic(bool).init(false);
|
||||
|
||||
const thread = try std.Thread.spawn(.{}, emu.run, .{ &quit, &pause, cpu, scheduler, &tracker });
|
||||
defer thread.join();
|
||||
|
||||
var title_buf: [0x100]u8 = undefined;
|
||||
defer quit.store(true, .Monotonic); // Terminate Emulator Thread
|
||||
|
||||
emu_loop: while (true) {
|
||||
var event: SDL.SDL_Event = undefined;
|
||||
|
||||
// Quit Signal from Dear Imgui
|
||||
if (self.state.should_quit) break :emu_loop;
|
||||
|
||||
while (SDL.SDL_PollEvent(&event) != 0) {
|
||||
_ = zgui.backend.processEvent(&event);
|
||||
|
||||
switch (event.type) {
|
||||
SDL.SDL_QUIT => break :emu_loop,
|
||||
SDL.SDL_KEYDOWN => {
|
||||
|
@ -214,12 +485,6 @@ pub const Gui = struct {
|
|||
SDL.SDLK_s => keyinput.shoulder_r.set(),
|
||||
SDL.SDLK_RETURN => keyinput.start.set(),
|
||||
SDL.SDLK_RSHIFT => keyinput.select.set(),
|
||||
SDL.SDLK_i => {
|
||||
comptime std.debug.assert(sample_format == SDL.AUDIO_U16);
|
||||
log.err("Sample Count: {}", .{@intCast(u32, SDL.SDL_AudioStreamAvailable(cpu.bus.apu.stream)) / (2 * @sizeOf(u16))});
|
||||
},
|
||||
// SDL.SDLK_j => log.err("Scheduler Capacity: {} | Scheduler Event Count: {}", .{ scheduler.queue.capacity(), scheduler.queue.count() }),
|
||||
SDL.SDLK_k => {},
|
||||
else => {},
|
||||
}
|
||||
|
||||
|
@ -229,29 +494,36 @@ pub const Gui = struct {
|
|||
}
|
||||
}
|
||||
|
||||
// Emulator has an internal Double Buffer
|
||||
const framebuf = cpu.bus.ppu.framebuf.get(.Renderer);
|
||||
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gba_width, gba_height, gl.RGBA, gl.UNSIGNED_INT_8_8_8_8, framebuf.ptr);
|
||||
// We Access non-atomic parts of the Emulator here
|
||||
{
|
||||
pause.store(true, .Monotonic);
|
||||
defer pause.store(false, .Monotonic);
|
||||
|
||||
self.state.fps_hist.push(tracker.value()) catch {};
|
||||
|
||||
// Draw GBA Screen to Texture
|
||||
{
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo_id);
|
||||
defer gl.bindFramebuffer(gl.FRAMEBUFFER, 0);
|
||||
|
||||
const buf = cpu.bus.ppu.framebuf.get(.Renderer);
|
||||
gl.viewport(0, 0, gba_width, gba_height);
|
||||
self.drawGbaTexture(obj_ids, emu_tex, buf);
|
||||
}
|
||||
|
||||
// Background Colour
|
||||
const size = zgui.io.getDisplaySize();
|
||||
gl.viewport(0, 0, @floatToInt(c_int, size[0]), @floatToInt(c_int, size[1]));
|
||||
gl.clearColor(0, 0, 0, 1.0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
|
||||
zgui.backend.newFrame(width, height);
|
||||
self.draw(out_tex, cpu);
|
||||
zgui.backend.draw();
|
||||
}
|
||||
|
||||
gl.useProgram(self.program_id);
|
||||
gl.bindVertexArray(vao_id);
|
||||
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
|
||||
SDL.SDL_GL_SwapWindow(self.window);
|
||||
|
||||
const dyn_title = std.fmt.bufPrintZ(&title_buf, "ZBA | {s} [Emu: {}fps] ", .{ self.title, tracker.value() }) catch unreachable;
|
||||
SDL.SDL_SetWindowTitle(self.window, dyn_title.ptr);
|
||||
}
|
||||
|
||||
quit.store(true, .Monotonic); // Terminate Emulator Thread
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Self) void {
|
||||
self.audio.deinit();
|
||||
gl.deleteProgram(self.program_id);
|
||||
SDL.SDL_GL_DeleteContext(self.ctx);
|
||||
SDL.SDL_DestroyWindow(self.window);
|
||||
SDL.SDL_Quit();
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
fn glGetProcAddress(ctx: SDL.SDL_GLContext, proc: [:0]const u8) ?*anyopaque {
|
||||
|
@ -329,3 +601,95 @@ fn panic() noreturn {
|
|||
const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
|
||||
@panic(std.mem.sliceTo(str, 0));
|
||||
}
|
||||
|
||||
const widgets = struct {
|
||||
fn interrupts(comptime label: []const u8, int: anytype) void {
|
||||
const h = 15.0;
|
||||
const w = 9.0 * 2 + 3.5;
|
||||
const ww = 9.0 * 3;
|
||||
|
||||
{
|
||||
zgui.text(label ++ ":", .{});
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("VBL", .{ .w = w, .h = h, .selected = int.vblank.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("HBL", .{ .w = w, .h = h, .selected = int.hblank.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("VCT", .{ .w = w, .h = h, .selected = int.coincidence.read() });
|
||||
|
||||
{
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("TIM0", .{ .w = ww, .h = h, .selected = int.tim0.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("TIM1", .{ .w = ww, .h = h, .selected = int.tim1.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("TIM2", .{ .w = ww, .h = h, .selected = int.tim2.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("TIM3", .{ .w = ww, .h = h, .selected = int.tim3.read() });
|
||||
}
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("SRL", .{ .w = w, .h = h, .selected = int.serial.read() });
|
||||
|
||||
{
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("DMA0", .{ .w = ww, .h = h, .selected = int.dma0.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("DMA1", .{ .w = ww, .h = h, .selected = int.dma1.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("DMA2", .{ .w = ww, .h = h, .selected = int.dma2.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("DMA3", .{ .w = ww, .h = h, .selected = int.dma3.read() });
|
||||
}
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("KPD", .{ .w = w, .h = h, .selected = int.keypad.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("GPK", .{ .w = w, .h = h, .selected = int.game_pak.read() });
|
||||
}
|
||||
}
|
||||
|
||||
fn psr(comptime label: []const u8, register: anytype) void {
|
||||
const Mode = @import("core/cpu.zig").Mode;
|
||||
|
||||
const maybe_mode = std.meta.intToEnum(Mode, register.mode.read()) catch null;
|
||||
const mode = if (maybe_mode) |mode| mode.toString() else "???";
|
||||
const w = 9.0;
|
||||
const h = 15.0;
|
||||
|
||||
zgui.text(label ++ ": 0x{X:0>8}", .{register.raw});
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("N", .{ .w = w, .h = h, .selected = register.n.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("Z", .{ .w = w, .h = h, .selected = register.z.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("C", .{ .w = w, .h = h, .selected = register.c.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
_ = zgui.selectable("V", .{ .w = w, .h = h, .selected = register.v.read() });
|
||||
|
||||
zgui.sameLine(.{});
|
||||
zgui.text("{s}", .{mode});
|
||||
}
|
||||
|
||||
fn eventDesc(comptime T: type) fn (void, T, T) bool {
|
||||
return struct {
|
||||
fn inner(_: void, left: T, right: T) bool {
|
||||
return left.tick > right.tick;
|
||||
}
|
||||
}.inner;
|
||||
}
|
||||
};
|
||||
|
|
75
src/util.zig
75
src/util.zig
|
@ -317,3 +317,78 @@ pub const FrameBuffer = struct {
|
|||
return self.layers[if (dev == .Emulator) self.current else ~self.current];
|
||||
}
|
||||
};
|
||||
|
||||
pub fn RingBuffer(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
const Index = usize;
|
||||
const max_capacity = (@as(Index, 1) << @typeInfo(Index).Int.bits - 1) - 1; // half the range of index type
|
||||
|
||||
const log = std.log.scoped(.RingBuffer);
|
||||
|
||||
read: Index,
|
||||
write: Index,
|
||||
buf: []T,
|
||||
|
||||
const Error = error{buffer_full};
|
||||
|
||||
pub fn init(buf: []T) Self {
|
||||
std.debug.assert(std.math.isPowerOfTwo(buf.len)); // capacity must be a power of two
|
||||
std.debug.assert(buf.len <= max_capacity);
|
||||
|
||||
std.mem.set(T, buf, 0);
|
||||
|
||||
return .{ .read = 0, .write = 0, .buf = buf };
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Self, allocator: Allocator) void {
|
||||
allocator.free(self.buf);
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
pub fn push(self: *Self, value: T) Error!void {
|
||||
if (self.isFull()) return error.buffer_full;
|
||||
defer self.write += 1;
|
||||
|
||||
self.buf[self.mask(self.write)] = value;
|
||||
}
|
||||
|
||||
pub fn pop(self: *Self) ?T {
|
||||
if (self.isEmpty()) return null;
|
||||
defer self.read += 1;
|
||||
|
||||
return self.buf[self.mask(self.read)];
|
||||
}
|
||||
|
||||
/// Returns the number of entries read
|
||||
pub fn copy(self: *const Self, cpy: []T) Index {
|
||||
const count = std.math.min(self.len(), cpy.len);
|
||||
var start: Index = self.read;
|
||||
|
||||
for (cpy, 0..) |*v, i| {
|
||||
if (i >= count) break;
|
||||
|
||||
v.* = self.buf[self.mask(start)];
|
||||
start += 1;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
fn len(self: *const Self) Index {
|
||||
return self.write - self.read;
|
||||
}
|
||||
|
||||
fn isFull(self: *const Self) bool {
|
||||
return self.len() == self.buf.len;
|
||||
}
|
||||
|
||||
fn isEmpty(self: *const Self) bool {
|
||||
return self.read == self.write;
|
||||
}
|
||||
|
||||
fn mask(self: *const Self, idx: Index) Index {
|
||||
return idx & (self.buf.len - 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue