Compare commits

..

64 Commits

Author SHA1 Message Date
9baa15050e in progress refactor
Some checks reported errors
continuous-integration/drone/push Build was killed
Needs profiling
2021-09-17 23:29:55 -03:00
4516ca8477 chore: run cargo fix
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-12 04:56:39 -03:00
6087e3b20b chore: remove Cycle struct and begin scheduler design 2021-09-12 04:56:34 -03:00
10ac579c40 fix(main): Use LogicalSize and PhysicalSize properly 2021-09-11 22:56:40 -03:00
ee5504111b Merge branch 'main' of ssh://git.musuka.dev:2222/paoda/gb into main
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-11 20:48:05 -03:00
a628f64d28 chore: update dependencies 2021-09-11 20:47:45 -03:00
318a6e0386 fix(emu): remove GAMEPAD_ENABLED const flag
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-09 11:12:50 -03:00
db012c7f4b fix(main): remove code unrelated to audio sync
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-07 02:09:02 -03:00
e42c87aeb7 fix(apu): quiet gameboy APU 2021-09-07 01:52:02 -03:00
9113e95fa0 fix(apu): pass blargg apu sweep tests 2021-09-07 01:17:01 -03:00
9973dc8714 fix(cartridge): don't read from RAM that doesn't exist
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-06 23:45:04 -03:00
e128025208 fix(cartridge): improve accuracy of MBC1 with large file sizes 2021-09-06 23:37:55 -03:00
44ac0c8ebd feat(cartridge): implement MBC2
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-06 18:13:34 -03:00
01064bab69 chore(cpu): comment out blargg-specific code
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-22 01:49:01 -05:00
634bc2d2c0 fix(apu): remove redundant code 2021-08-22 01:48:34 -05:00
d794a94b68 fix(timer): increase accuracy of timer
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-20 00:17:28 -05:00
b87e31d3f4 fix(cartridge): remove unnecessary dbg statement 2021-08-20 00:17:05 -05:00
3c2456611e fix(cartridge): trim whitespace from cartridge title
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-19 21:56:07 -05:00
b829f05a34 chore(cartridge): clean-up code
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-19 20:39:04 -05:00
afd2d16371 chore(cartridge): re-rename RamInfo and RomRinfo 2021-08-19 20:05:48 -05:00
1f8fa48168 chore: add reccomended vscode extensions
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-19 17:05:36 -05:00
c6fbb79189 chore(cartridge): reognanize code 2021-08-19 16:10:39 -05:00
8b78b2943e fix(cartridge): specify intentional overflow in MBC5
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-19 16:09:58 -05:00
0af95a1dd3 feat(cartridge): implement MBC5 and cleanup code
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-18 22:40:15 -05:00
9fa40f8584 fix(main): do not drop output stream 2021-08-18 22:39:55 -05:00
b10bc7b4fd chore(main): add flag that enables audio 2021-08-18 16:34:26 -05:00
4658a0d106 fix(apu): ch4 set_len should set timer to 64 - len
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-18 02:32:48 -05:00
f92b9d61ef chore(apu_gen): cosmetic changes to sample generation
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-18 01:43:38 -05:00
360a9a7b65 chore(apu): improve code organization
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-18 00:04:27 -05:00
5d64e539a7 fix(apu): resolve off-by-one error 2021-08-17 23:14:56 -05:00
22f96a10e7 fix(apu): increase accuracy of apu emulation
Reintroduce the Frame Sequencer and it's state enum (needed so that we
can reset the FS on NR52 enable)
2021-08-17 22:18:40 -05:00
8fea8eb1ff fix(apu): better emulate behaviour of apu channel DACs 2021-08-17 21:26:22 -05:00
9b2c91445a chore: enable audio by default
even if it sounds really bad right now
2021-08-17 21:25:55 -05:00
b9046bceba fix(apu): disable channel if DAC is disabled 2021-08-17 20:42:41 -05:00
aa22e93049 chore: clean up TODO messages
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-15 23:31:27 -05:00
6215eccb2f chore(cpu): merge halted and state properties 2021-08-15 23:26:01 -05:00
a77d0a0f62 fix(apu): clock frame sequencer at correct Hz
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-15 02:46:20 -05:00
c2f2e2194b chore(ppu): improve accuracy of pixel fifo 2021-08-14 23:47:16 -05:00
d68257bb29 fix(ppu): improve accuracy of SCX discard 2021-08-14 22:03:01 -05:00
e27d6dc25b chore(ppu): rename discriminants of fetcher state 2021-08-14 22:02:41 -05:00
1acb5de19d fix(main): GB frametime should be 59.73 Hz 2021-08-14 17:59:59 -05:00
1b78b248a3 chore: minor edits to documentation 2021-08-14 17:51:09 -05:00
5d6df46a2d fix(cpu): reimplement instruction handling
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-14 17:23:45 -05:00
7e65d82fef chore(cpu): document fetch, decode, execute 2021-08-14 16:42:38 -05:00
8c9567b610 chore(cpu): rename discriminants of ImeState enum 2021-08-14 16:42:15 -05:00
53dfaf0de2 fix(apu): increase size of the audio buffer
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-14 15:29:35 -05:00
16c2dd81fc fix(bus): remove dead code 2021-08-14 15:02:25 -05:00
79be38a1e6 fix(main): rename constant SCALE to WINDOW_SCALE
All checks were successful
continuous-integration/drone/push Build is passing
2021-08-14 01:02:18 -05:00
8625bec059 feat: clock bus on instruction read-write
Some checks failed
continuous-integration/drone/push Build is failing
Commit also includes general work towards passing mem-timings.

Note: while cpu_instrs.gb passes, instr_timing.gb and mem_timing.gb both
are stuck in infinite loops (Currently, it seems like a timing issue).
This is a major regression that hopefully shouldn't last for too long.
2021-08-14 00:10:51 -05:00
0637b771e3 chore(instr): implement copy and clone on instruction enum
Some checks failed
continuous-integration/drone/push Build is failing
2021-08-05 20:04:39 -05:00
0107fa04c9 chore(apu): remove implemtation of register that always returns 0xFF 2021-08-05 16:39:04 -05:00
6265c8af04 chore(joypad): poll input every frame instead of every instruction
Some checks failed
continuous-integration/drone/push Build is failing
2021-08-03 20:36:55 -05:00
5482a8e75f fix(apu): fix out of bounds error with channel 3 wave ram 2021-08-03 20:35:22 -05:00
002dae6826 fix(joypad): improve handling of keyboard input 2021-08-03 20:23:43 -05:00
c863dc835c fix(apu): fix index out of bounds error on channel 3 write 2021-08-03 20:23:08 -05:00
d4407cf849 fix(apu): implement NR50 volume controls 2021-08-03 19:33:27 -05:00
de0d147685 fix(cartridge): put a bit more detail into the MBC3 RTC stub
Some checks failed
continuous-integration/drone/push Build is failing
2021-08-03 15:19:08 -05:00
dd8339e8de chore(cartridge): consistently capitalize MBC 2021-08-03 15:06:06 -05:00
05d6475015 fix(cartridge): Use default title instead of empty string 2021-08-03 14:53:30 -05:00
32b597a328 fix(apu): incremental improvements to APU accuracy
Some checks failed
continuous-integration/drone/push Build is failing
2021-08-03 14:10:08 -05:00
33be2e0e83 fix(main): tie emulation to 60Hz on host machine 2021-08-03 14:09:16 -05:00
832e1b7633 fix(apu): implement WAVE RAM blocking 2021-08-02 22:38:00 -05:00
a549b9feef chore(bus): suppress warning 2021-08-02 21:55:07 -05:00
4d6fc95130 chore: remove premature optimizations 2021-08-02 21:52:12 -05:00
19 changed files with 1869 additions and 1808 deletions

8
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,8 @@
{
"recommendations": [
"matklad.rust-analyzer",
"tamasfe.even-better-toml",
"serayuzgur.crates",
"vadimcn.vscode-lldb",
]
}

569
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@ name = "gb"
version = "0.1.0" version = "0.1.0"
authors = ["Rekai Musuka <rekai@musuka.dev>"] authors = ["Rekai Musuka <rekai@musuka.dev>"]
edition = "2018" edition = "2018"
resolver = "2"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -11,7 +12,7 @@ anyhow = "^1.0"
bitfield = "^0.13" bitfield = "^0.13"
clap = "^2.33" clap = "^2.33"
gilrs = "^0.8" gilrs = "^0.8"
pixels = "^0.5" pixels = "^0.6"
winit = "^0.25" winit = "^0.25"
winit_input_helper = "^0.10" winit_input_helper = "^0.10"
rodio = "^0.14" rodio = "^0.14"

View File

@@ -5,7 +5,8 @@ use types::ch1::{Sweep, SweepDirection};
use types::ch3::Volume as Ch3Volume; use types::ch3::Volume as Ch3Volume;
use types::ch4::{CounterWidth, Frequency as Ch4Frequency, PolynomialCounter}; use types::ch4::{CounterWidth, Frequency as Ch4Frequency, PolynomialCounter};
use types::common::{EnvelopeDirection, FrequencyHigh, SoundDuty, VolumeEnvelope}; use types::common::{EnvelopeDirection, FrequencyHigh, SoundDuty, VolumeEnvelope};
use types::{ChannelControl, FrameSequencerState, SoundOutput}; use types::fs::{FrameSequencer, State as FrameSequencerState};
use types::{ChannelControl, SoundOutput};
pub mod gen; pub mod gen;
mod types; mod types;
@@ -25,9 +26,8 @@ pub struct Apu {
/// Noise /// Noise
ch4: Channel4, ch4: Channel4,
// Frame Sequencer sequencer: FrameSequencer,
frame_seq_state: FrameSequencerState, div_prev: Option<u16>,
div_prev: Option<u8>,
prod: Option<SampleProducer<f32>>, prod: Option<SampleProducer<f32>>,
sample_counter: u64, sample_counter: u64,
@@ -43,11 +43,9 @@ impl BusIo for Apu {
0x16 => self.ch2.duty(), 0x16 => self.ch2.duty(),
0x17 => self.ch2.envelope(), 0x17 => self.ch2.envelope(),
0x19 => self.ch2.freq_hi(), 0x19 => self.ch2.freq_hi(),
0x1A => self.ch3.enabled(), 0x1A => self.ch3.dac_enabled(),
0x1B => self.ch3.len(),
0x1C => self.ch3.volume(), 0x1C => self.ch3.volume(),
0x1E => self.ch3.freq_hi(), 0x1E => self.ch3.freq_hi(),
0x20 => self.ch4.len(),
0x21 => self.ch4.envelope(), 0x21 => self.ch4.envelope(),
0x22 => self.ch4.poly(), 0x22 => self.ch4.poly(),
0x23 => self.ch4.frequency(), 0x23 => self.ch4.frequency(),
@@ -64,28 +62,29 @@ impl BusIo for Apu {
fn write_byte(&mut self, addr: u16, byte: u8) { fn write_byte(&mut self, addr: u16, byte: u8) {
match addr & 0x00FF { match addr & 0x00FF {
0x10 => self.ch1.set_sweep(byte), 0x10 if self.ctrl.enabled => self.ch1.set_sweep(byte),
0x11 => self.ch1.set_duty(byte), 0x11 if self.ctrl.enabled => self.ch1.set_duty(byte),
0x12 => self.ch1.set_envelope(byte), 0x12 if self.ctrl.enabled => self.ch1.set_envelope(byte),
0x13 => self.ch1.set_freq_lo(byte), 0x13 if self.ctrl.enabled => self.ch1.set_freq_lo(byte),
0x14 => self.ch1.set_freq_hi(byte), 0x14 if self.ctrl.enabled => self.ch1.set_freq_hi(byte),
0x16 => self.ch2.set_duty(byte), 0x16 if self.ctrl.enabled => self.ch2.set_duty(byte),
0x17 => self.ch2.set_envelope(byte), 0x17 if self.ctrl.enabled => self.ch2.set_envelope(byte),
0x18 => self.ch2.set_freq_lo(byte), 0x18 if self.ctrl.enabled => self.ch2.set_freq_lo(byte),
0x19 => self.ch2.set_freq_hi(byte), 0x19 if self.ctrl.enabled => self.ch2.set_freq_hi(byte),
0x1A => self.ch3.set_enabled(byte), 0x1A if self.ctrl.enabled => self.ch3.set_dac_enabled(byte),
0x1B => self.ch3.set_len(byte), 0x1B if self.ctrl.enabled => self.ch3.set_len(byte),
0x1C => self.ch3.set_volume(byte), 0x1C if self.ctrl.enabled => self.ch3.set_volume(byte),
0x1D => self.ch3.set_freq_lo(byte), 0x1D if self.ctrl.enabled => self.ch3.set_freq_lo(byte),
0x1E => self.ch3.set_freq_hi(byte), 0x1E if self.ctrl.enabled => self.ch3.set_freq_hi(byte),
0x20 => self.ch4.set_len(byte), 0x20 if self.ctrl.enabled => self.ch4.set_len(byte),
0x21 => self.ch4.set_envelope(byte), 0x21 if self.ctrl.enabled => self.ch4.set_envelope(byte),
0x22 => self.ch4.set_poly(byte), 0x22 if self.ctrl.enabled => self.ch4.set_poly(byte),
0x23 => self.ch4.set_freq_data(byte), 0x23 if self.ctrl.enabled => self.ch4.set_frequency(byte),
0x24 => self.ctrl.set_channel(byte), 0x24 if self.ctrl.enabled => self.ctrl.set_channel(byte),
0x25 => self.ctrl.set_output(byte), 0x25 if self.ctrl.enabled => self.ctrl.set_output(byte),
0x26 => self.set_status(byte), 0x26 => self.set_status(byte),
0x30..=0x3F => self.ch3.write_byte(addr, byte), 0x30..=0x3F => self.ch3.write_byte(addr, byte),
_ if !self.ctrl.enabled => {}
_ => eprintln!( _ => eprintln!(
"Wrote {:#04X} to unused IO register {:#06X} [APU]", "Wrote {:#04X} to unused IO register {:#06X} [APU]",
byte, addr byte, addr
@@ -95,108 +94,112 @@ impl BusIo for Apu {
} }
impl Apu { impl Apu {
pub(crate) fn clock(&mut self, div: u16) { pub(crate) fn tick(&mut self, div: u16) {
use FrameSequencerState::*;
self.sample_counter += SAMPLE_INCREMENT; self.sample_counter += SAMPLE_INCREMENT;
// the 5th bit of the high byte // Frame Sequencer (512Hz)
let bit_5 = (div >> 13 & 0x01) as u8; if self.is_falling_edge(12, div) {
use FrameSequencerState::*;
if let Some(0x01) = self.div_prev { match self.sequencer.state() {
if bit_5 == 0x00 { Length => self.clock_length(),
// Falling Edge, step the Frame Sequencer LengthAndSweep => {
self.frame_seq_state.step(); self.clock_length();
self.clock_sweep();
match self.frame_seq_state { }
Step0Length => self.handle_length(), Envelope => self.clock_envelope(),
Step2LengthAndSweep => { Nothing => {}
self.handle_length();
self.handle_sweep();
}
Step4Length => self.handle_length(),
Step6LengthAndSweep => {
self.handle_length();
self.handle_sweep();
}
Step7VolumeEnvelope => self.handle_volume(),
Step1Nothing | Step3Nothing | Step5Nothing => {}
};
} }
self.sequencer.next();
} }
self.ch1.clock(); self.div_prev = Some(div);
self.ch2.clock();
self.ch3.clock();
self.ch4.clock();
self.div_prev = Some(bit_5); self.ch1.tick();
self.ch2.tick();
self.ch3.tick();
self.ch4.tick();
if self.sample_counter >= SM83_CLOCK_SPEED { if self.sample_counter >= SM83_CLOCK_SPEED {
self.sample_counter %= SM83_CLOCK_SPEED; self.sample_counter %= SM83_CLOCK_SPEED;
if let Some(ref mut prod) = self.prod { if let Some(ref mut prod) = self.prod {
if prod.two_available() { if prod.available_blocking() {
// Sample the APU // Sample the APU
let ch1_amplitude = self.ch1.amplitude();
let ch1_left = self.ctrl.output.ch1_left() as u8 as f32 * ch1_amplitude;
let ch1_right = self.ctrl.output.ch1_right() as u8 as f32 * ch1_amplitude;
let ch2_amplitude = self.ch2.amplitude(); let (left, right) = self.ctrl.out.ch1();
let ch2_left = self.ctrl.output.ch2_left() as u8 as f32 * ch2_amplitude; let ch1_left = if left { self.ch1.amplitude() } else { 0.0 };
let ch2_right = self.ctrl.output.ch2_right() as u8 as f32 * ch2_amplitude; let ch1_right = if right { self.ch1.amplitude() } else { 0.0 };
let ch3_amplitude = self.ch3.amplitude(); let (left, right) = self.ctrl.out.ch2();
let ch3_left = self.ctrl.output.ch3_left() as u8 as f32 * ch3_amplitude; let ch2_left = if left { self.ch2.amplitude() } else { 0.0 };
let ch3_right = self.ctrl.output.ch3_right() as u8 as f32 * ch3_amplitude; let ch2_right = if right { self.ch2.amplitude() } else { 0.0 };
let ch4_amplitude = self.ch4.amplitude(); let (left, right) = self.ctrl.out.ch3();
let ch4_left = self.ctrl.output.ch4_left() as u8 as f32 * ch4_amplitude; let ch3_left = if left { self.ch3.amplitude() } else { 0.0 };
let ch4_right = self.ctrl.output.ch4_right() as u8 as f32 * ch4_amplitude; let ch3_right = if right { self.ch3.amplitude() } else { 0.0 };
let left = (ch1_left + ch2_left + ch3_left + ch4_left) / 4.0; let (left, right) = self.ctrl.out.ch4();
let right = (ch1_right + ch2_right + ch3_right + ch4_right) / 4.0; let ch4_left = if left { self.ch4.amplitude() } else { 0.0 };
let ch4_right = if right { self.ch4.amplitude() } else { 0.0 };
prod.push(left) let left_mixed = (ch1_left + ch2_left + ch3_left + ch4_left) / 4.0;
.and(prod.push(right)) let right_mixed = (ch1_right + ch2_right + ch3_right + ch4_right) / 4.0;
let left_sample = (self.ctrl.channel.left_volume() + 1.0) * left_mixed;
let right_sample = (self.ctrl.channel.right_volume() + 1.0) * right_mixed;
prod.push(left_sample)
.and(prod.push(right_sample))
.expect("Add samples to ring buffer"); .expect("Add samples to ring buffer");
} }
} }
} }
} }
pub fn set_producer(&mut self, prod: SampleProducer<f32>) {
self.prod = Some(prod);
}
/// 0xFF26 | NR52 - Sound On/Off /// 0xFF26 | NR52 - Sound On/Off
pub(crate) fn set_status(&mut self, byte: u8) { pub(crate) fn set_status(&mut self, byte: u8) {
self.ctrl.enabled = (byte >> 7) & 0x01 == 0x01; self.ctrl.enabled = (byte >> 7) & 0x01 == 0x01;
if !self.ctrl.enabled { if self.ctrl.enabled {
self.reset(); // Frame Sequencer reset to Step 0
self.sequencer.reset();
// Square Duty units are reset to first step
self.ch1.duty_pos = 0;
self.ch2.duty_pos = 0;
// Wave Channel's sample buffer reset to 0
self.ch3.offset = 0;
} }
self.ch1.enabled = self.ctrl.enabled; if !self.ctrl.enabled {
self.ch2.enabled = self.ctrl.enabled; self.reset();
self.ch3.enabled = self.ctrl.enabled; } else {
self.ch4.enabled = self.ctrl.enabled; }
}
pub fn attach_producer(&mut self, prod: SampleProducer<f32>) {
self.prod = Some(prod);
} }
fn reset(&mut self) { fn reset(&mut self) {
// TODO: Clear readable sound registers
self.ch1.sweep = Default::default(); self.ch1.sweep = Default::default();
self.ch1.duty = Default::default(); self.ch1.duty = Default::default();
self.ch1.envelope = Default::default(); self.ch1.envelope = Default::default();
self.ch1.freq_hi = Default::default(); // FIXME: What about frequency low? self.ch1.freq_lo = Default::default();
self.ch1.freq_hi = Default::default();
self.ch2.duty = Default::default(); self.ch2.duty = Default::default();
self.ch2.envelope = Default::default(); self.ch2.envelope = Default::default();
self.ch2.freq_lo = Default::default();
self.ch2.freq_hi = Default::default(); self.ch2.freq_hi = Default::default();
self.ch3.enabled = Default::default(); self.ch3.dac_enabled = Default::default();
self.ch3.len = Default::default(); self.ch3.len = Default::default();
self.ch3.volume = Default::default(); self.ch3.volume = Default::default();
self.ch3.freq_lo = Default::default();
self.ch3.freq_hi = Default::default(); self.ch3.freq_hi = Default::default();
self.ch4.len = Default::default(); self.ch4.len = Default::default();
@@ -204,15 +207,18 @@ impl Apu {
self.ch4.poly = Default::default(); self.ch4.poly = Default::default();
self.ch4.freq = Default::default(); self.ch4.freq = Default::default();
self.ch2 = Default::default();
self.ch3 = Default::default();
self.ch4 = Default::default();
self.ctrl.channel = Default::default(); self.ctrl.channel = Default::default();
self.ctrl.output = Default::default(); self.ctrl.out = Default::default();
// Disable the Channels
self.ch1.enabled = Default::default();
self.ch2.enabled = Default::default();
self.ch3.enabled = Default::default();
self.ch4.enabled = Default::default();
} }
fn clock_length(freq_hi: &FrequencyHigh, length_timer: &mut u16, enabled: &mut bool) { fn process_length(freq_hi: &FrequencyHigh, length_timer: &mut u16, enabled: &mut bool) {
if freq_hi.idk() && *length_timer > 0 { if freq_hi.length_disable() && *length_timer > 0 {
*length_timer -= 1; *length_timer -= 1;
// Check in this scope ensures (only) the above subtraction // Check in this scope ensures (only) the above subtraction
@@ -223,8 +229,8 @@ impl Apu {
} }
} }
fn clock_length_ch4(freq_data: &Ch4Frequency, length_timer: &mut u16, enabled: &mut bool) { fn ch4_process_length(freq: &Ch4Frequency, length_timer: &mut u16, enabled: &mut bool) {
if freq_data.idk() && *length_timer > 0 { if freq.length_disable() && *length_timer > 0 {
*length_timer -= 1; *length_timer -= 1;
// Check in this scope ensures (only) the above subtraction // Check in this scope ensures (only) the above subtraction
@@ -235,50 +241,47 @@ impl Apu {
} }
} }
fn handle_length(&mut self) { fn clock_length(&mut self) {
Self::clock_length( Self::process_length(
&self.ch1.freq_hi, &self.ch1.freq_hi,
&mut self.ch1.length_timer, &mut self.ch1.length_timer,
&mut self.ch1.enabled, &mut self.ch1.enabled,
); );
Self::clock_length( Self::process_length(
&self.ch2.freq_hi, &self.ch2.freq_hi,
&mut self.ch2.length_timer, &mut self.ch2.length_timer,
&mut self.ch2.enabled, &mut self.ch2.enabled,
); );
Self::clock_length( Self::process_length(
&self.ch3.freq_hi, &self.ch3.freq_hi,
&mut self.ch3.length_timer, &mut self.ch3.length_timer,
&mut self.ch3.enabled, &mut self.ch3.enabled,
); );
Self::clock_length_ch4( Self::ch4_process_length(
&self.ch4.freq, &self.ch4.freq,
&mut self.ch4.length_timer, &mut self.ch4.length_timer,
&mut self.ch4.enabled, &mut self.ch4.enabled,
); );
} }
fn handle_sweep(&mut self) { fn clock_sweep(&mut self) {
if self.ch1.sweep_timer > 0 { if self.ch1.sweep_timer != 0 {
self.ch1.sweep_timer -= 1; self.ch1.sweep_timer -= 1;
} }
if self.ch1.sweep_timer == 0 { if self.ch1.sweep_timer == 0 {
self.ch1.sweep_timer = if self.ch1.sweep.period() != 0 { let period = self.ch1.sweep.period();
self.ch1.sweep.period() self.ch1.sweep_timer = if period == 0 { 8 } else { period };
} else {
8
};
if self.ch1.sweep_enabled && self.ch1.sweep.period() != 0 { if self.ch1.sweep_enabled && period != 0 {
let new_freq = self.ch1.calc_sweep_freq(); let new_freq = self.ch1.calc_sweep_freq();
if new_freq <= 2047 && self.ch1.sweep.shift_count() != 0 { if new_freq <= 2047 && self.ch1.sweep.shift_count() != 0 {
self.ch1.set_frequency(new_freq); self.ch1.set_frequency(new_freq);
self.ch1.shadow_freq = new_freq & 0x07FF; self.ch1.shadow_freq = new_freq;
let _ = self.ch1.calc_sweep_freq(); let _ = self.ch1.calc_sweep_freq();
} }
@@ -286,7 +289,7 @@ impl Apu {
} }
} }
fn clock_envelope(envelope: &VolumeEnvelope, period_timer: &mut u8, current_volume: &mut u8) { fn process_envelope(envelope: &VolumeEnvelope, period_timer: &mut u8, current_volume: &mut u8) {
use EnvelopeDirection::*; use EnvelopeDirection::*;
if envelope.period() != 0 { if envelope.period() != 0 {
@@ -306,27 +309,34 @@ impl Apu {
} }
} }
fn handle_volume(&mut self) { fn clock_envelope(&mut self) {
// Channels 1, 2 and 4 have Volume Envelopes // Channels 1, 2 and 4 have Volume Envelopes
Self::clock_envelope( Self::process_envelope(
&self.ch1.envelope, &self.ch1.envelope,
&mut self.ch1.period_timer, &mut self.ch1.period_timer,
&mut self.ch1.current_volume, &mut self.ch1.current_volume,
); );
Self::clock_envelope( Self::process_envelope(
&self.ch2.envelope, &self.ch2.envelope,
&mut self.ch2.period_timer, &mut self.ch2.period_timer,
&mut self.ch2.current_volume, &mut self.ch2.current_volume,
); );
Self::clock_envelope( Self::process_envelope(
&self.ch4.envelope, &self.ch4.envelope,
&mut self.ch4.period_timer, &mut self.ch4.period_timer,
&mut self.ch4.current_volume, &mut self.ch4.current_volume,
); );
} }
fn is_falling_edge(&self, bit: u8, div: u16) -> bool {
match self.div_prev {
Some(p) => (p >> bit & 0x01) == 0x01 && (div >> bit & 0x01) == 0x00,
None => false,
}
}
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -334,7 +344,7 @@ pub(crate) struct SoundControl {
/// 0xFF24 | NR50 - Channel Control /// 0xFF24 | NR50 - Channel Control
channel: ChannelControl, channel: ChannelControl,
/// 0xFF25 | NR51 - Selection of Sound output terminal /// 0xFF25 | NR51 - Selection of Sound output terminal
output: SoundOutput, out: SoundOutput,
enabled: bool, enabled: bool,
} }
@@ -354,13 +364,13 @@ impl SoundControl {
/// 0xFF25 | NR51 - Selection of Sound output terminal /// 0xFF25 | NR51 - Selection of Sound output terminal
pub(crate) fn output(&self) -> u8 { pub(crate) fn output(&self) -> u8 {
u8::from(self.output) u8::from(self.out)
} }
/// 0xFF25 | NR51 - Selection of Sound output terminal /// 0xFF25 | NR51 - Selection of Sound output terminal
pub(crate) fn set_output(&mut self, byte: u8) { pub(crate) fn set_output(&mut self, byte: u8) {
if self.enabled { if self.enabled {
self.output = byte.into(); self.out = byte.into();
} }
} }
@@ -371,6 +381,7 @@ impl SoundControl {
| (apu.ch3.enabled as u8) << 2 | (apu.ch3.enabled as u8) << 2
| (apu.ch2.enabled as u8) << 1 | (apu.ch2.enabled as u8) << 1
| apu.ch1.enabled as u8 | apu.ch1.enabled as u8
| 0x70
} }
} }
@@ -406,24 +417,6 @@ pub(crate) struct Channel1 {
} }
impl Channel1 { impl Channel1 {
fn amplitude(&self) -> f32 {
let dac_input = self.duty.wave_pattern().amplitude(self.duty_pos) * self.current_volume;
(dac_input as f32 / 7.5) - 1.0
}
fn clock(&mut self) {
if self.freq_timer != 0 {
self.freq_timer -= 1;
}
if self.freq_timer == 0 {
// TODO: Why is this 2048?
self.freq_timer = (2048 - self.frequency()) * 4;
self.duty_pos = (self.duty_pos + 1) % 8;
}
}
/// 0xFF10 | NR10 - Channel 1 Sweep Register /// 0xFF10 | NR10 - Channel 1 Sweep Register
pub(crate) fn sweep(&self) -> u8 { pub(crate) fn sweep(&self) -> u8 {
u8::from(self.sweep) | 0x80 u8::from(self.sweep) | 0x80
@@ -431,9 +424,7 @@ impl Channel1 {
/// 0xFF10 | NR10 - Channel 1 Sweep Register /// 0xFF10 | NR10 - Channel 1 Sweep Register
pub(crate) fn set_sweep(&mut self, byte: u8) { pub(crate) fn set_sweep(&mut self, byte: u8) {
if self.enabled { self.sweep = byte.into()
self.sweep = byte.into()
}
} }
/// 0xFF11 | NR11 - Channel 1 Sound length / Wave pattern duty /// 0xFF11 | NR11 - Channel 1 Sound length / Wave pattern duty
@@ -443,10 +434,8 @@ impl Channel1 {
/// 0xFF11 | NR11 - Channel 1 Sound length / Wave pattern duty /// 0xFF11 | NR11 - Channel 1 Sound length / Wave pattern duty
pub(crate) fn set_duty(&mut self, byte: u8) { pub(crate) fn set_duty(&mut self, byte: u8) {
if self.enabled { self.duty = byte.into();
self.duty = byte.into(); self.length_timer = 64 - self.duty.sound_length() as u16;
self.length_timer = 64 - self.duty.sound_length() as u16;
}
} }
/// 0xFF12 | NR12 - Channel 1 Volume Envelope /// 0xFF12 | NR12 - Channel 1 Volume Envelope
@@ -456,16 +445,16 @@ impl Channel1 {
/// 0xFF12 | NR12 - Channel 1 Volume Envelope /// 0xFF12 | NR12 - Channel 1 Volume Envelope
pub(crate) fn set_envelope(&mut self, byte: u8) { pub(crate) fn set_envelope(&mut self, byte: u8) {
if self.enabled { self.envelope = byte.into();
self.envelope = byte.into()
if !self.is_dac_enabled() {
self.enabled = false;
} }
} }
/// 0xFF13 | NR13 - Channel 1 Frequency low (lower 8 bits only) /// 0xFF13 | NR13 - Channel 1 Frequency low (lower 8 bits only)
pub(crate) fn set_freq_lo(&mut self, byte: u8) { pub(crate) fn set_freq_lo(&mut self, byte: u8) {
if self.enabled { self.freq_lo = byte;
self.freq_lo = byte;
}
} }
/// 0xFF14 | NR14 - Channel 1 Frequency high /// 0xFF14 | NR14 - Channel 1 Frequency high
@@ -475,46 +464,67 @@ impl Channel1 {
/// 0xFF14 | NR14 - Channel 1 Frequency high /// 0xFF14 | NR14 - Channel 1 Frequency high
pub(crate) fn set_freq_hi(&mut self, byte: u8) { pub(crate) fn set_freq_hi(&mut self, byte: u8) {
if self.enabled { self.freq_hi = byte.into();
self.freq_hi = byte.into();
// If this bit is set, a trigger event occurs // If this bit is set, a trigger event occurs
if self.freq_hi.initial() { if self.freq_hi.initial() {
// Envelope Behaviour during trigger event if self.is_dac_enabled() {
self.period_timer = self.envelope.period(); self.enabled = true;
self.current_volume = self.envelope.init_vol();
// Sweep behaviour during trigger event
self.shadow_freq = self.frequency() & 0x07FF; // Mask should be redundant
self.sweep_timer = if self.sweep.period() != 0 {
self.sweep.period()
} else {
8
};
if self.sweep.period() != 0 || self.sweep.shift_count() != 0 {
self.sweep_enabled = true;
}
if self.sweep.shift_count() != 0 {
let _ = self.calc_sweep_freq();
}
// Length behaviour during trigger event
if self.length_timer == 0 {
self.length_timer = 64;
}
} }
// Length behaviour during trigger event
if self.length_timer == 0 {
self.length_timer = 64;
}
// Envelope Behaviour during trigger event
self.period_timer = self.envelope.period();
self.current_volume = self.envelope.init_vol();
// Sweep behaviour during trigger event
let sweep_period = self.sweep.period();
let sweep_shift = self.sweep.shift_count();
self.shadow_freq = self.frequency();
self.sweep_timer = if sweep_period == 0 { 8 } else { sweep_period };
self.sweep_enabled = sweep_period != 0 || sweep_shift != 0;
if sweep_shift != 0 {
let _ = self.calc_sweep_freq();
}
}
}
fn tick(&mut self) {
if self.freq_timer != 0 {
self.freq_timer -= 1;
}
if self.freq_timer == 0 {
self.freq_timer = (2048 - self.frequency()) * 4;
self.duty_pos = (self.duty_pos + 1) % 8;
}
}
fn amplitude(&self) -> f32 {
if self.is_dac_enabled() {
let sample = self.duty.wave_pattern().amplitude(self.duty_pos) * self.current_volume;
let input = if self.enabled { sample } else { 0 };
(input as f32 / 7.5) - 1.0
} else {
0.0
} }
} }
fn calc_sweep_freq(&mut self) -> u16 { fn calc_sweep_freq(&mut self) -> u16 {
use SweepDirection::*; use SweepDirection::*;
let shifted_shadow_freq = self.shadow_freq >> self.sweep.shift_count();
let shadow_freq_shifted = self.shadow_freq >> self.sweep.shift_count();
let new_freq = match self.sweep.direction() { let new_freq = match self.sweep.direction() {
Increase => self.shadow_freq + shifted_shadow_freq, Increase => self.shadow_freq + shadow_freq_shifted,
Decrease => self.shadow_freq - shifted_shadow_freq, Decrease => self.shadow_freq - shadow_freq_shifted,
}; };
// Overflow check // Overflow check
@@ -535,6 +545,10 @@ impl Channel1 {
fn frequency(&self) -> u16 { fn frequency(&self) -> u16 {
(self.freq_hi.freq_bits() as u16) << 8 | self.freq_lo as u16 (self.freq_hi.freq_bits() as u16) << 8 | self.freq_lo as u16
} }
fn is_dac_enabled(&self) -> bool {
self.envelope.0 & 0xF8 != 0x00
}
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -562,24 +576,6 @@ pub(crate) struct Channel2 {
} }
impl Channel2 { impl Channel2 {
fn amplitude(&self) -> f32 {
let dac_input = self.duty.wave_pattern().amplitude(self.duty_pos) * self.current_volume;
(dac_input as f32 / 7.5) - 1.0
}
fn clock(&mut self) {
if self.freq_timer != 0 {
self.freq_timer -= 1;
}
if self.freq_timer == 0 {
// TODO: Why is this 2048?
self.freq_timer = (2048 - self.frequency()) * 4;
self.duty_pos = (self.duty_pos + 1) % 8;
}
}
/// 0xFF16 | NR21 - Channel 2 Sound length / Wave Pattern Duty /// 0xFF16 | NR21 - Channel 2 Sound length / Wave Pattern Duty
pub(crate) fn duty(&self) -> u8 { pub(crate) fn duty(&self) -> u8 {
u8::from(self.duty) | 0x3F u8::from(self.duty) | 0x3F
@@ -587,10 +583,8 @@ impl Channel2 {
/// 0xFF16 | NR21 - Channel 2 Sound length / Wave Pattern Duty /// 0xFF16 | NR21 - Channel 2 Sound length / Wave Pattern Duty
pub(crate) fn set_duty(&mut self, byte: u8) { pub(crate) fn set_duty(&mut self, byte: u8) {
if self.enabled { self.duty = byte.into();
self.duty = byte.into(); self.length_timer = 64 - self.duty.sound_length() as u16;
self.length_timer = 64 - self.duty.sound_length() as u16;
}
} }
/// 0xFF17 | NR22 - Channel 2 Volume ENvelope /// 0xFF17 | NR22 - Channel 2 Volume ENvelope
@@ -600,16 +594,16 @@ impl Channel2 {
/// 0xFF17 | NR22 - Channel 2 Volume ENvelope /// 0xFF17 | NR22 - Channel 2 Volume ENvelope
pub(crate) fn set_envelope(&mut self, byte: u8) { pub(crate) fn set_envelope(&mut self, byte: u8) {
if self.enabled { self.envelope = byte.into();
self.envelope = byte.into()
if !self.is_dac_enabled() {
self.enabled = false;
} }
} }
/// 0xFF18 | NR23 - Channel 2 Frequency low (lower 8 bits only) /// 0xFF18 | NR23 - Channel 2 Frequency low (lower 8 bits only)
pub(crate) fn set_freq_lo(&mut self, byte: u8) { pub(crate) fn set_freq_lo(&mut self, byte: u8) {
if self.enabled { self.freq_lo = byte;
self.freq_lo = byte;
}
} }
/// 0xFF19 | NR24 - Channel 2 Frequency high /// 0xFF19 | NR24 - Channel 2 Frequency high
@@ -619,31 +613,59 @@ impl Channel2 {
/// 0xFF19 | NR24 - Channel 2 Frequency high /// 0xFF19 | NR24 - Channel 2 Frequency high
pub(crate) fn set_freq_hi(&mut self, byte: u8) { pub(crate) fn set_freq_hi(&mut self, byte: u8) {
if self.enabled { self.freq_hi = byte.into();
self.freq_hi = byte.into();
if self.freq_hi.initial() { if self.freq_hi.initial() {
// Envelope behaviour during trigger event // Envelope behaviour during trigger event
self.period_timer = self.envelope.period(); self.period_timer = self.envelope.period();
self.current_volume = self.envelope.init_vol(); self.current_volume = self.envelope.init_vol();
// Length behaviour during trigger event // Length behaviour during trigger event
if self.length_timer == 0 { if self.length_timer == 0 {
self.length_timer = 64; self.length_timer = 64;
}
} }
if self.is_dac_enabled() {
self.enabled = true;
}
}
}
fn amplitude(&self) -> f32 {
if self.is_dac_enabled() {
let sample = self.duty.wave_pattern().amplitude(self.duty_pos) * self.current_volume;
let input = if self.enabled { sample } else { 0 };
(input as f32 / 7.5) - 1.0
} else {
0.0
}
}
fn tick(&mut self) {
if self.freq_timer != 0 {
self.freq_timer -= 1;
}
if self.freq_timer == 0 {
self.freq_timer = (2048 - self.frequency()) * 4;
self.duty_pos = (self.duty_pos + 1) % 8;
} }
} }
fn frequency(&self) -> u16 { fn frequency(&self) -> u16 {
(self.freq_hi.freq_bits() as u16) << 8 | self.freq_lo as u16 (self.freq_hi.freq_bits() as u16) << 8 | self.freq_lo as u16
} }
fn is_dac_enabled(&self) -> bool {
self.envelope.0 & 0xF8 != 0x00
}
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(crate) struct Channel3 { pub(crate) struct Channel3 {
/// 0xFF1A | NR30 - Channel 3 Sound on/off /// 0xFF1A | NR30 - Channel 3 Sound on/off
enabled: bool, dac_enabled: bool,
/// 0xFF1B | NR31 - Sound Length /// 0xFF1B | NR31 - Sound Length
len: u8, len: u8,
/// 0xFF1C | NR32 - Channel 3 Volume /// 0xFF1C | NR32 - Channel 3 Volume
@@ -660,15 +682,25 @@ pub(crate) struct Channel3 {
freq_timer: u16, freq_timer: u16,
offset: u8, offset: u8,
enabled: bool,
} }
impl BusIo for Channel3 { impl BusIo for Channel3 {
fn read_byte(&self, addr: u16) -> u8 { fn read_byte(&self, addr: u16) -> u8 {
self.wave_ram[(addr - Self::WAVE_RAM_START_ADDR) as usize] if self.enabled {
self.wave_ram[self.offset as usize / 2]
} else {
self.wave_ram[(addr - Self::WAVE_RAM_START_ADDR) as usize]
}
} }
fn write_byte(&mut self, addr: u16, byte: u8) { fn write_byte(&mut self, addr: u16, byte: u8) {
self.wave_ram[(addr - Self::WAVE_RAM_START_ADDR) as usize] = byte; if self.enabled {
self.wave_ram[self.offset as usize / 2] = byte;
} else {
self.wave_ram[(addr - Self::WAVE_RAM_START_ADDR) as usize] = byte;
}
} }
} }
@@ -676,26 +708,23 @@ impl Channel3 {
const WAVE_RAM_START_ADDR: u16 = 0xFF30; const WAVE_RAM_START_ADDR: u16 = 0xFF30;
/// 0xFF1A | NR30 - Channel 3 Sound on/off /// 0xFF1A | NR30 - Channel 3 Sound on/off
pub(crate) fn enabled(&self) -> u8 { pub(crate) fn dac_enabled(&self) -> u8 {
((self.enabled as u8) << 7) | 0x7F ((self.dac_enabled as u8) << 7) | 0x7F
} }
/// 0xFF1A | NR30 - Channel 3 Sound on/off /// 0xFF1A | NR30 - Channel 3 Sound on/off
pub(crate) fn set_enabled(&mut self, byte: u8) { pub(crate) fn set_dac_enabled(&mut self, byte: u8) {
self.enabled = (byte >> 7) & 0x01 == 0x01; self.dac_enabled = (byte >> 7) & 0x01 == 0x01;
}
/// 0xFF1B | NR31 - Sound Length if !self.dac_enabled {
pub(crate) fn len(&self) -> u8 { self.enabled = false;
self.len | 0xFF }
} }
/// 0xFF1B | NR31 - Sound Length /// 0xFF1B | NR31 - Sound Length
pub(crate) fn set_len(&mut self, byte: u8) { pub(crate) fn set_len(&mut self, byte: u8) {
if self.enabled { self.len = byte;
self.len = byte; self.length_timer = 256 - self.len as u16;
self.length_timer = 256 - self.len as u16;
}
} }
/// 0xFF1C | NR32 - Channel 3 Volume /// 0xFF1C | NR32 - Channel 3 Volume
@@ -707,22 +736,18 @@ impl Channel3 {
pub(crate) fn set_volume(&mut self, byte: u8) { pub(crate) fn set_volume(&mut self, byte: u8) {
use Ch3Volume::*; use Ch3Volume::*;
if self.enabled { self.volume = match (byte >> 5) & 0x03 {
self.volume = match (byte >> 5) & 0x03 { 0b00 => Mute,
0b00 => Mute, 0b01 => Full,
0b01 => Full, 0b10 => Half,
0b10 => Half, 0b11 => Quarter,
0b11 => Quarter, _ => unreachable!("{:#04X} is not a valid value for Channel3Volume", byte),
_ => unreachable!("{:#04X} is not a valid value for Channel3Volume", byte), };
};
}
} }
/// 0xFF1D | NR33 - Channel 3 Frequency low (lower 8 bits) /// 0xFF1D | NR33 - Channel 3 Frequency low (lower 8 bits)
pub(crate) fn set_freq_lo(&mut self, byte: u8) { pub(crate) fn set_freq_lo(&mut self, byte: u8) {
if self.enabled { self.freq_lo = byte;
self.freq_lo = byte;
}
} }
/// 0xFF1E | NR34 - Channel 3 Frequency high /// 0xFF1E | NR34 - Channel 3 Frequency high
@@ -732,37 +757,44 @@ impl Channel3 {
/// 0xFF1E | NR34 - Channel 3 Frequency high /// 0xFF1E | NR34 - Channel 3 Frequency high
pub(crate) fn set_freq_hi(&mut self, byte: u8) { pub(crate) fn set_freq_hi(&mut self, byte: u8) {
if self.enabled { self.freq_hi = byte.into();
self.freq_hi = byte.into();
if self.freq_hi.initial() { if self.freq_hi.initial() {
// Length behaviour during trigger event // Length behaviour during trigger event
if self.length_timer == 0 { if self.length_timer == 0 {
self.length_timer = 256; self.length_timer = 256;
} }
if self.dac_enabled {
self.enabled = true;
} }
} }
} }
fn amplitude(&self) -> f32 { fn tick(&mut self) {
let dac_input = self.read_sample(self.offset) >> self.volume.shift_count();
(dac_input as f32 / 7.5) - 1.0
}
fn clock(&mut self) {
if self.freq_timer != 0 { if self.freq_timer != 0 {
self.freq_timer -= 1; self.freq_timer -= 1;
} }
if self.freq_timer == 0 { if self.freq_timer == 0 {
self.freq_timer = (2048 - self.frequency()) * 4; self.freq_timer = (2048 - self.frequency()) * 2;
self.offset = (self.offset + 1) % 8; self.offset = (self.offset + 1) % (WAVE_PATTERN_RAM_LEN * 2) as u8;
}
}
fn amplitude(&self) -> f32 {
if self.dac_enabled {
let sample = self.read_sample(self.offset) >> self.volume.shift_count();
let input = if self.enabled { sample } else { 0 };
(input as f32 / 7.5) - 1.0
} else {
0.0
} }
} }
fn read_sample(&self, index: u8) -> u8 { fn read_sample(&self, index: u8) -> u8 {
let i = index as usize / 2; let i = (index / 2) as usize;
if index % 2 == 0 { if index % 2 == 0 {
// We grab the high nibble on even indexes // We grab the high nibble on even indexes
@@ -805,17 +837,10 @@ pub(crate) struct Channel4 {
} }
impl Channel4 { impl Channel4 {
/// 0xFF20 | NR41 - Channel 4 Sound Length
pub(crate) fn len(&self) -> u8 {
self.len | 0xFF
}
/// 0xFF20 | NR41 - Channel 4 Sound Length /// 0xFF20 | NR41 - Channel 4 Sound Length
pub(crate) fn set_len(&mut self, byte: u8) { pub(crate) fn set_len(&mut self, byte: u8) {
if self.enabled { self.len = byte & 0x3F;
self.len = byte & 0x3F; self.length_timer = 64 - self.len as u16;
self.length_timer = 256 - self.len as u16;
}
} }
/// 0xFF21 | NR42 - Channel 4 Volume Envelope /// 0xFF21 | NR42 - Channel 4 Volume Envelope
@@ -825,8 +850,10 @@ impl Channel4 {
/// 0xFF21 | NR42 - Channel 4 Volume Envelope /// 0xFF21 | NR42 - Channel 4 Volume Envelope
pub(crate) fn set_envelope(&mut self, byte: u8) { pub(crate) fn set_envelope(&mut self, byte: u8) {
if self.enabled { self.envelope = byte.into();
self.envelope = byte.into()
if !self.is_dac_enabled() {
self.enabled = false;
} }
} }
@@ -837,9 +864,7 @@ impl Channel4 {
/// 0xFF22 | NR43 - Chanel 4 Polynomial Counter /// 0xFF22 | NR43 - Chanel 4 Polynomial Counter
pub(crate) fn set_poly(&mut self, byte: u8) { pub(crate) fn set_poly(&mut self, byte: u8) {
if self.enabled { self.poly = byte.into();
self.poly = byte.into();
}
} }
/// 0xFF23 | NR44 - Channel 4 Counter / Consecutive Selector and Restart /// 0xFF23 | NR44 - Channel 4 Counter / Consecutive Selector and Restart
@@ -848,33 +873,29 @@ impl Channel4 {
} }
/// 0xFF23 | NR44 - Channel 4 Counter / Consecutive Selector and Restart /// 0xFF23 | NR44 - Channel 4 Counter / Consecutive Selector and Restart
pub(crate) fn set_freq_data(&mut self, byte: u8) { pub(crate) fn set_frequency(&mut self, byte: u8) {
if self.enabled { self.freq = byte.into();
self.freq = byte.into();
if self.freq.initial() { if self.freq.initial() {
// Envelope behaviour during trigger event // Envelope behaviour during trigger event
self.period_timer = self.envelope.period(); self.period_timer = self.envelope.period();
self.current_volume = self.envelope.init_vol(); self.current_volume = self.envelope.init_vol();
// Length behaviour during trigger event // Length behaviour during trigger event
if self.length_timer == 0 { if self.length_timer == 0 {
self.length_timer = 64; self.length_timer = 64;
} }
// LFSR behaviour during trigger event // LFSR behaviour during trigger event
self.lf_shift = 0x7FFF; self.lf_shift = 0x7FFF;
if self.is_dac_enabled() {
self.enabled = true;
} }
} }
} }
fn amplitude(&self) -> f32 { fn tick(&mut self) {
let dac_input = (!self.lf_shift & 0x01) as u8 * self.current_volume;
(dac_input as f32 / 7.5) - 1.0
}
fn clock(&mut self) {
if self.freq_timer != 0 { if self.freq_timer != 0 {
self.freq_timer -= 1; self.freq_timer -= 1;
} }
@@ -892,6 +913,21 @@ impl Channel4 {
} }
} }
fn amplitude(&self) -> f32 {
if self.is_dac_enabled() {
let sample = (!self.lf_shift & 0x01) as u8 * self.current_volume;
let input = if self.enabled { sample } else { 0 };
(input as f32 / 7.5) - 1.0
} else {
0.0
}
}
fn is_dac_enabled(&self) -> bool {
self.envelope.0 & 0xF8 != 0x00
}
fn divisor(code: u8) -> u8 { fn divisor(code: u8) -> u8 {
if code == 0 { if code == 0 {
return 8; return 8;

View File

@@ -3,7 +3,7 @@ use rtrb::{Consumer, Producer, PushError, RingBuffer};
pub(crate) const SAMPLE_RATE: u32 = 48000; // Hz pub(crate) const SAMPLE_RATE: u32 = 48000; // Hz
const CHANNEL_COUNT: usize = 2; const CHANNEL_COUNT: usize = 2;
const BUFFER_CAPACITY: usize = 4096 * CHANNEL_COUNT; // # of samples * the # of channels const BUFFER_CAPACITY: usize = 2048 * CHANNEL_COUNT; // # of samples * the # of channels
pub struct AudioSPSC<T> { pub struct AudioSPSC<T> {
inner: RingBuffer<T>, inner: RingBuffer<T>,
@@ -43,10 +43,18 @@ impl<T> SampleProducer<T> {
self.inner.push(value) self.inner.push(value)
} }
#[inline] #[allow(dead_code)]
pub(crate) fn two_available(&self) -> bool { pub(crate) fn available(&self) -> bool {
self.inner.slots() > 2 self.inner.slots() > 2
} }
pub(crate) fn available_blocking(&self) -> bool {
loop {
if self.inner.slots() > 2 {
break true;
}
}
}
} }
impl<T> std::fmt::Debug for SampleProducer<T> { impl<T> std::fmt::Debug for SampleProducer<T> {

View File

@@ -73,7 +73,7 @@ pub(crate) mod ch1 {
} }
} }
pub(crate) mod ch3 { pub(super) mod ch3 {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(crate) enum Volume { pub(crate) enum Volume {
Mute = 0, Mute = 0,
@@ -102,7 +102,7 @@ pub(crate) mod ch3 {
} }
} }
pub(crate) mod ch4 { pub(super) mod ch4 {
use super::bitfield; use super::bitfield;
bitfield! { bitfield! {
@@ -178,12 +178,12 @@ pub(crate) mod ch4 {
pub struct Frequency(u8); pub struct Frequency(u8);
impl Debug; impl Debug;
_initial, _: 7; _initial, _: 7;
_idk, _: 6; // TODO: same as FrequencyHigh, figure out what this is _length_disable, _: 6;
} }
impl Frequency { impl Frequency {
pub(crate) fn idk(&self) -> bool { pub(crate) fn length_disable(&self) -> bool {
self._idk() self._length_disable()
} }
pub(crate) fn initial(&self) -> bool { pub(crate) fn initial(&self) -> bool {
@@ -217,14 +217,14 @@ pub(crate) mod ch4 {
} }
} }
pub(crate) mod common { pub(super) mod common {
use super::bitfield; use super::bitfield;
bitfield! { bitfield! {
pub struct FrequencyHigh(u8); pub struct FrequencyHigh(u8);
impl Debug; impl Debug;
_initial, _: 7; _initial, _: 7;
_idk, _: 6; // TODO: Figure out what the hell this is _length_disable, _: 6;
pub freq_bits, set_freq_bits: 2, 0; pub freq_bits, set_freq_bits: 2, 0;
} }
@@ -233,8 +233,8 @@ pub(crate) mod common {
self._initial() self._initial()
} }
pub(crate) fn idk(&self) -> bool { pub(crate) fn length_disable(&self) -> bool {
self._idk() self._length_disable()
} }
} }
@@ -342,7 +342,7 @@ pub(crate) mod common {
pub struct SoundDuty(u8); pub struct SoundDuty(u8);
impl Debug; impl Debug;
from into WavePattern, _wave_pattern, _: 7, 6; from into WavePattern, _wave_pattern, _: 7, 6;
_sound_length, _: 5, 0; // TODO: Getter only used if bit 6 in NR14 is set _sound_length, _: 5, 0;
} }
impl SoundDuty { impl SoundDuty {
@@ -427,41 +427,6 @@ pub(crate) mod common {
} }
} }
#[derive(Debug, Clone, Copy)]
pub(crate) enum FrameSequencerState {
Step0Length,
Step1Nothing,
Step2LengthAndSweep,
Step3Nothing,
Step4Length,
Step5Nothing,
Step6LengthAndSweep,
Step7VolumeEnvelope,
}
impl FrameSequencerState {
pub(crate) fn step(&mut self) {
use FrameSequencerState::*;
*self = match *self {
Step0Length => Step1Nothing,
Step1Nothing => Step2LengthAndSweep,
Step2LengthAndSweep => Step3Nothing,
Step3Nothing => Step4Length,
Step4Length => Step5Nothing,
Step5Nothing => Step6LengthAndSweep,
Step6LengthAndSweep => Step7VolumeEnvelope,
Step7VolumeEnvelope => Step0Length,
};
}
}
impl Default for FrameSequencerState {
fn default() -> Self {
Self::Step0Length
}
}
bitfield! { bitfield! {
pub struct SoundOutput(u8); pub struct SoundOutput(u8);
impl Debug; impl Debug;
@@ -475,6 +440,24 @@ bitfield! {
pub ch1_right, _: 0; pub ch1_right, _: 0;
} }
impl SoundOutput {
pub(super) fn ch1(&self) -> (bool, bool) {
(self.ch1_left(), self.ch1_right())
}
pub(super) fn ch2(&self) -> (bool, bool) {
(self.ch2_left(), self.ch2_right())
}
pub(super) fn ch3(&self) -> (bool, bool) {
(self.ch3_left(), self.ch3_right())
}
pub(super) fn ch4(&self) -> (bool, bool) {
(self.ch4_left(), self.ch4_right())
}
}
impl Copy for SoundOutput {} impl Copy for SoundOutput {}
impl Clone for SoundOutput { impl Clone for SoundOutput {
fn clone(&self) -> Self { fn clone(&self) -> Self {
@@ -503,10 +486,20 @@ impl From<SoundOutput> for u8 {
bitfield! { bitfield! {
pub struct ChannelControl(u8); pub struct ChannelControl(u8);
impl Debug; impl Debug;
vin_so2, _: 7; vin_left, _: 7;
so2_level, _: 6, 4; _left_volume, _: 6, 4;
vin_so1, _: 3; vin_right, _: 3;
so1_level, _: 2, 0; _right_volume, _: 2, 0;
}
impl ChannelControl {
pub(crate) fn left_volume(&self) -> f32 {
self._left_volume() as f32
}
pub(crate) fn right_volume(&self) -> f32 {
self._right_volume() as f32
}
} }
impl Copy for ChannelControl {} impl Copy for ChannelControl {}
@@ -533,3 +526,52 @@ impl From<ChannelControl> for u8 {
ctrl.0 ctrl.0
} }
} }
pub(super) mod fs {
#[derive(Debug)]
pub(crate) struct FrameSequencer {
step: u8,
state: State,
}
impl Default for FrameSequencer {
fn default() -> Self {
Self {
step: Default::default(),
state: State::Length,
}
}
}
impl FrameSequencer {
pub(crate) fn next(&mut self) {
use State::*;
self.step = (self.step + 1) % 8;
self.state = match self.step {
1 | 3 | 5 => Nothing,
0 | 4 => Length,
2 | 6 => LengthAndSweep,
7 => Envelope,
_ => unreachable!("Step {} is invalid for the Frame Sequencer", self.step),
};
}
pub(crate) fn state(&self) -> State {
self.state
}
pub(crate) fn reset(&mut self) {
self.step = Default::default();
self.state = State::Length;
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum State {
Length,
Nothing,
LengthAndSweep,
Envelope,
}
}

View File

@@ -7,14 +7,13 @@ use crate::ppu::{Ppu, PpuMode};
use crate::serial::Serial; use crate::serial::Serial;
use crate::timer::Timer; use crate::timer::Timer;
use crate::work_ram::{VariableWorkRam, WorkRam}; use crate::work_ram::{VariableWorkRam, WorkRam};
use std::{fs::File, io::Read};
const BOOT_ROM_SIZE: usize = 0x100; pub(crate) const BOOT_SIZE: usize = 0x100;
#[derive(Debug)] #[derive(Debug)]
pub struct Bus { pub struct Bus {
boot: Option<[u8; BOOT_ROM_SIZE]>, // Boot ROM is 256b long boot: Option<[u8; BOOT_SIZE]>, // Boot ROM is 256b long
cartridge: Option<Cartridge>, cart: Option<Cartridge>,
pub(crate) ppu: Ppu, pub(crate) ppu: Ppu,
work_ram: WorkRam, work_ram: WorkRam,
var_ram: VariableWorkRam, var_ram: VariableWorkRam,
@@ -30,7 +29,7 @@ impl Default for Bus {
fn default() -> Self { fn default() -> Self {
Self { Self {
boot: None, boot: None,
cartridge: None, cart: None,
ppu: Default::default(), ppu: Default::default(),
work_ram: Default::default(), work_ram: Default::default(),
var_ram: Default::default(), var_ram: Default::default(),
@@ -45,40 +44,41 @@ impl Default for Bus {
} }
impl Bus { impl Bus {
pub(crate) fn with_boot(path: &str) -> anyhow::Result<Self> { pub(crate) fn with_boot(rom: [u8; 256]) -> Self {
let mut file = File::open(path)?; Self {
let mut boot_rom = [0u8; 256]; boot: Some(rom),
file.read_exact(&mut boot_rom)?;
Ok(Self {
boot: Some(boot_rom),
..Default::default() ..Default::default()
}) }
} }
pub(crate) fn load_cartridge(&mut self, path: &str) -> std::io::Result<()> { pub(crate) fn load_cart(&mut self, rom: Vec<u8>) {
self.cartridge = Some(Cartridge::new(path)?); self.cart = Some(Cartridge::new(rom));
Ok(())
} }
pub(crate) fn rom_title(&self) -> Option<&str> { pub(crate) fn cart_title(&self) -> Option<&str> {
self.cartridge.as_ref()?.title() self.cart.as_ref()?.title()
} }
#[allow(dead_code)]
pub(crate) fn boot_mapped(&self) -> bool { pub(crate) fn boot_mapped(&self) -> bool {
self.boot.is_some() self.boot.is_some()
} }
pub(crate) fn clock(&mut self) { pub(crate) fn clock(&mut self) {
self.ppu.clock(); self.tick(4);
self.timer.clock();
self.apu.clock(self.timer.divider);
self.clock_dma();
} }
fn clock_dma(&mut self) { fn tick(&mut self, limit: u8) {
if let Some((src_addr, dest_addr)) = self.ppu.dma.clock() { for _ in 0..limit {
self.timer.tick();
self.ppu.tick();
self.apu.tick(self.timer.divider);
self.dma_tick()
}
}
fn dma_tick(&mut self) {
if let Some((src_addr, dest_addr)) = self.ppu.dma.tick() {
let byte = self.oam_read_byte(src_addr); let byte = self.oam_read_byte(src_addr);
self.oam_write_byte(dest_addr, byte); self.oam_write_byte(dest_addr, byte);
} }
@@ -97,13 +97,13 @@ impl Bus {
} }
} }
match self.cartridge.as_ref() { match self.cart.as_ref() {
Some(cart) => cart.read_byte(addr), Some(cart) => cart.read_byte(addr),
None => panic!("Tried to read from a non-existent cartridge"), None => panic!("Tried to read from a non-existent cartridge"),
} }
} }
0x8000..=0x9FFF => self.ppu.read_byte(addr), // 8KB Video RAM 0x8000..=0x9FFF => self.ppu.read_byte(addr), // 8KB Video RAM
0xA000..=0xBFFF => match self.cartridge.as_ref() { 0xA000..=0xBFFF => match self.cart.as_ref() {
// 8KB External RAM // 8KB External RAM
Some(cart) => cart.read_byte(addr), Some(cart) => cart.read_byte(addr),
None => panic!("Tried to read from a non-existent cartridge"), None => panic!("Tried to read from a non-existent cartridge"),
@@ -150,7 +150,7 @@ impl BusIo for Bus {
} }
} }
match self.cartridge.as_ref() { match self.cart.as_ref() {
Some(cart) => cart.read_byte(addr), Some(cart) => cart.read_byte(addr),
None => panic!("Tried to read from a non-existent cartridge"), None => panic!("Tried to read from a non-existent cartridge"),
} }
@@ -162,7 +162,7 @@ impl BusIo for Bus {
_ => self.ppu.read_byte(addr), _ => self.ppu.read_byte(addr),
} }
} }
0xA000..=0xBFFF => match self.cartridge.as_ref() { 0xA000..=0xBFFF => match self.cart.as_ref() {
// 8KB External RAM // 8KB External RAM
Some(cart) => cart.read_byte(addr), Some(cart) => cart.read_byte(addr),
None => panic!("Tried to read from a non-existent cartridge"), None => panic!("Tried to read from a non-existent cartridge"),
@@ -216,7 +216,7 @@ impl BusIo for Bus {
0x01 => self.serial.next, 0x01 => self.serial.next,
0x02 => self.serial.ctrl.into(), 0x02 => self.serial.ctrl.into(),
0x04 => (self.timer.divider >> 8) as u8, 0x04 => (self.timer.divider >> 8) as u8,
0x05 => self.timer.counter, 0x05 => self.timer.tima(),
0x06 => self.timer.modulo, 0x06 => self.timer.modulo,
0x07 => self.timer.ctrl.into(), 0x07 => self.timer.ctrl.into(),
0x0F => self.interrupt_flag().into(), 0x0F => self.interrupt_flag().into(),
@@ -233,7 +233,6 @@ impl BusIo for Bus {
0x49 => self.ppu.monochrome.obj_palette_1.into(), 0x49 => self.ppu.monochrome.obj_palette_1.into(),
0x4A => self.ppu.pos.window_y, 0x4A => self.ppu.pos.window_y,
0x4B => self.ppu.pos.window_x, 0x4B => self.ppu.pos.window_x,
0x4D => 0xFF, // TODO: CGB Specific Register
_ => { _ => {
eprintln!("Read 0xFF from unused IO register {:#06X}.", addr); eprintln!("Read 0xFF from unused IO register {:#06X}.", addr);
0xFF 0xFF
@@ -256,7 +255,7 @@ impl BusIo for Bus {
0x0000..=0x7FFF => { 0x0000..=0x7FFF => {
// 16KB ROM bank 00 (ends at 0x3FFF) // 16KB ROM bank 00 (ends at 0x3FFF)
// and 16KB ROM Bank 01 -> NN (switchable via MB) // and 16KB ROM Bank 01 -> NN (switchable via MB)
match self.cartridge.as_mut() { match self.cart.as_mut() {
Some(cart) => cart.write_byte(addr, byte), Some(cart) => cart.write_byte(addr, byte),
None => panic!("Tried to write into non-existent cartridge"), None => panic!("Tried to write into non-existent cartridge"),
} }
@@ -270,7 +269,7 @@ impl BusIo for Bus {
} }
0xA000..=0xBFFF => { 0xA000..=0xBFFF => {
// 8KB External RAM // 8KB External RAM
match self.cartridge.as_mut() { match self.cart.as_mut() {
Some(cart) => cart.write_byte(addr, byte), Some(cart) => cart.write_byte(addr, byte),
None => panic!("Tried to write into non-existent cartridge"), None => panic!("Tried to write into non-existent cartridge"),
} }
@@ -305,7 +304,7 @@ impl BusIo for Bus {
_ => {} _ => {}
} }
} }
0xFEA0..=0xFEFF => {} // TODO: As far as I know, writes to here do nothing. 0xFEA0..=0xFEFF => {} // FIXME: As far as I know, writes to here do nothing.
0xFF00..=0xFF7F => { 0xFF00..=0xFF7F => {
// IO Registers // IO Registers
@@ -316,7 +315,7 @@ impl BusIo for Bus {
0x01 => self.serial.next = byte, 0x01 => self.serial.next = byte,
0x02 => self.serial.ctrl = byte.into(), 0x02 => self.serial.ctrl = byte.into(),
0x04 => self.timer.divider = 0x0000, 0x04 => self.timer.divider = 0x0000,
0x05 => self.timer.counter = byte, 0x05 => self.timer.set_tima(byte),
0x06 => self.timer.modulo = byte, 0x06 => self.timer.modulo = byte,
0x07 => self.timer.ctrl = byte.into(), 0x07 => self.timer.ctrl = byte.into(),
0x0F => self.set_interrupt_flag(byte), 0x0F => self.set_interrupt_flag(byte),
@@ -367,17 +366,6 @@ impl BusIo for Bus {
} }
} }
impl Bus {
pub(crate) fn read_word(&self, addr: u16) -> u16 {
(self.read_byte(addr + 1) as u16) << 8 | self.read_byte(addr) as u16
}
pub(crate) fn write_word(&mut self, addr: u16, word: u16) {
self.write_byte(addr + 1, (word >> 8) as u8);
self.write_byte(addr, (word & 0x00FF) as u8);
}
}
impl Bus { impl Bus {
fn interrupt_flag(&self) -> InterruptFlag { fn interrupt_flag(&self) -> InterruptFlag {
// Read the current interrupt information from the PPU // Read the current interrupt information from the PPU

View File

@@ -1,137 +1,99 @@
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use crate::bus::BusIo; use crate::bus::BusIo;
const RAM_SIZE_ADDRESS: usize = 0x0149; const RAM_SIZE_ADDRESS: usize = 0x0149;
const ROM_SIZE_ADDRESS: usize = 0x0148; const ROM_SIZE_ADDRESS: usize = 0x0148;
const MBC_TYPE_ADDRESS: usize = 0x0147; const MBC_TYPE_ADDRESS: usize = 0x0147;
const ROM_TITLE_RANGE: std::ops::RangeInclusive<usize> = 0x0134..=0x0143;
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(crate) struct Cartridge { pub(crate) struct Cartridge {
memory: Vec<u8>, memory: Vec<u8>,
title: Option<String>, title: Option<String>,
mbc: Box<dyn MemoryBankController>, mbc: Box<dyn MBCIo>,
} }
impl Cartridge { impl Cartridge {
pub(crate) fn new<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<Self> { pub(crate) fn new(memory: Vec<u8>) -> Self {
let mut memory = vec![];
let mut rom = File::open(path)?;
rom.read_to_end(&mut memory)?;
let title = Self::find_title(&memory); let title = Self::find_title(&memory);
eprintln!("Cartridge Title: {:?}", title); eprintln!("Cartridge Title: {:?}", title);
Ok(Self { Self {
mbc: Self::detect_mbc(&memory), mbc: Self::detect_mbc(&memory),
title, title,
memory, memory,
}) }
} }
fn detect_mbc(memory: &[u8]) -> Box<dyn MemoryBankController> { fn detect_mbc(memory: &[u8]) -> Box<dyn MBCIo> {
let ram_size = Self::find_ram_size(memory); let ram_size = Self::detect_ram_info(memory);
let bank_count = Self::find_bank_count(memory); let rom_size = Self::detect_rom_info(memory);
let mbc_kind = Self::find_mbc(memory); let mbc_kind = Self::find_mbc(memory);
let ram_byte_count = ram_size.len(); let ram_cap = ram_size.capacity();
let rom_cap = rom_size.capacity();
eprintln!("Cartridge Ram Size: {} bytes", ram_size.len()); eprintln!("Cartridge Ram Size: {} bytes", ram_cap);
eprintln!("Cartridge ROM Size: {} bytes", bank_count.size()); eprintln!("Cartridge ROM Size: {} bytes", rom_size.capacity());
eprintln!("MBC Type: {:?}", mbc_kind); eprintln!("MBC Type: {:?}", mbc_kind);
match mbc_kind { match mbc_kind {
MbcKind::None => Box::new(NoMbc {}), MBCKind::None => Box::new(NoMBC),
MbcKind::Mbc1 => { MBCKind::MBC1 => Box::new(MBC1::new(ram_size, rom_size)),
let mbc = Mbc1 { MBCKind::MBC1WithBattery => Box::new(MBC1::new(ram_size, rom_size)), // TODO: Implement Saving
ram_size, MBCKind::MBC2 => Box::new(MBC2::new(rom_cap)),
ram: vec![0; ram_byte_count as usize], MBCKind::MBC2WithBattery => Box::new(MBC2::new(rom_cap)), // TODO: Implement Saving
bank_count, MBCKind::MBC3 => Box::new(MBC3::new(ram_cap)),
..Default::default() MBCKind::MBC3WithBattery => Box::new(MBC3::new(ram_cap)), // TODO: Implement Saving
}; MBCKind::MBC5 => Box::new(MBC5::new(ram_cap, rom_cap)),
MBCKind::MBC5WithBattery => Box::new(MBC5::new(ram_cap, rom_cap)), // TDO: Implement Saving
Box::new(mbc)
}
MbcKind::Mbc1WithBattery => {
// TODO: Implement Saving
let mbc = Mbc1 {
ram_size,
ram: vec![0; ram_byte_count as usize],
bank_count,
..Default::default()
};
Box::new(mbc)
}
MbcKind::Mbc3WithBattery => {
// TODO: Implement Saving
let mbc = MBC3 {
ram_size,
ram: vec![0; ram_byte_count as usize],
..Default::default()
};
Box::new(mbc)
}
MbcKind::Mbc3 => {
let mbc = MBC3 {
ram_size,
ram: vec![0; ram_byte_count as usize],
..Default::default()
};
Box::new(mbc)
}
MbcKind::Mbc5 => todo!("Implement MBC5"),
} }
} }
fn find_title(memory: &[u8]) -> Option<String> { fn find_title(memory: &[u8]) -> Option<String> {
// FIXME: Get rid of magic values and handle cases let slice = &memory[ROM_TITLE_RANGE];
// where 0x134..0x143 reads past the length of the let with_nulls = std::str::from_utf8(slice).ok();
// string let trimmed = with_nulls.map(|s| s.trim_matches('\0').trim());
let slice = &memory[0x134..0x143]; match trimmed {
Some("") | None => None,
let str_with_nulls = std::str::from_utf8(slice).ok(); Some(_) => trimmed.map(String::from),
str_with_nulls.map(|s| s.trim_matches('\0').to_string()) }
} }
pub(crate) fn title(&self) -> Option<&str> { pub(crate) fn title(&self) -> Option<&str> {
self.title.as_deref() self.title.as_deref()
} }
fn find_ram_size(memory: &[u8]) -> RamSize { fn detect_ram_info(memory: &[u8]) -> RamSize {
let id = memory[RAM_SIZE_ADDRESS]; let id = memory[RAM_SIZE_ADDRESS];
id.into() id.into()
} }
fn find_bank_count(memory: &[u8]) -> BankCount { fn detect_rom_info(memory: &[u8]) -> RomSize {
let id = memory[ROM_SIZE_ADDRESS]; let id = memory[ROM_SIZE_ADDRESS];
id.into() id.into()
} }
fn find_mbc(memory: &[u8]) -> MbcKind { fn find_mbc(memory: &[u8]) -> MBCKind {
let id = memory[MBC_TYPE_ADDRESS]; use MBCKind::*;
// TODO: Refactor this to match the other enums in this module match memory[MBC_TYPE_ADDRESS] {
match id { 0x00 => None,
0x00 => MbcKind::None, 0x01 | 0x02 => MBC1,
0x01 => MbcKind::Mbc1, 0x03 => MBC1WithBattery,
0x02 => MbcKind::Mbc1, 0x05 => MBC2,
0x03 => MbcKind::Mbc1WithBattery, 0x06 => MBC2WithBattery,
0x19 => MbcKind::Mbc5, 0x19 | 0x1A => MBC5,
0x13 => MbcKind::Mbc3WithBattery, 0x1B => MBC5WithBattery,
0x11 => MbcKind::Mbc3, 0x13 => MBC3WithBattery,
_ => unimplemented!("id {:#04X} is an unsupported MBC", id), 0x11 | 0x12 => MBC3,
id => unimplemented!("id {:#04X} is an unsupported MBC", id),
} }
} }
} }
impl BusIo for Cartridge { impl BusIo for Cartridge {
fn read_byte(&self, addr: u16) -> u8 { fn read_byte(&self, addr: u16) -> u8 {
use MbcResult::*; use MBCResult::*;
match self.mbc.handle_read(addr) { match self.mbc.handle_read(addr) {
Address(addr) => self.memory[addr], Address(addr) => self.memory[addr],
@@ -145,91 +107,89 @@ impl BusIo for Cartridge {
} }
#[derive(Debug)] #[derive(Debug)]
struct Mbc1 { struct MBC1 {
/// 5-bit number /// 5-bit number
rom_bank: u8, rom_bank: u8,
/// 2-bit number /// 2-bit number
ram_bank: u8, ram_bank: u8,
mode: bool, mode: bool,
ram_size: RamSize, ram_size: RamSize,
ram: Vec<u8>, memory: Vec<u8>,
bank_count: BankCount, rom_size: RomSize,
ram_enabled: bool, mem_enabled: bool,
} }
impl Default for Mbc1 { impl MBC1 {
fn default() -> Self { fn new(ram_size: RamSize, rom_size: RomSize) -> Self {
Self { Self {
rom_bank: 0x01, rom_bank: 0x01,
memory: vec![0; ram_size.capacity() as usize],
ram_size,
rom_size,
ram_bank: Default::default(), ram_bank: Default::default(),
mode: Default::default(), mode: Default::default(),
ram_size: Default::default(), mem_enabled: Default::default(),
ram: Default::default(),
bank_count: Default::default(),
ram_enabled: Default::default(),
} }
} }
}
impl Mbc1 {
fn zero_bank(&self) -> u8 { fn zero_bank(&self) -> u8 {
use BankCount::*; use RomSize::*;
match self.bank_count { match self.rom_size {
None | Four | Eight | Sixteen | ThirtyTwo => 0x00, None | Four | Eight | Sixteen | ThirtyTwo => 0x00,
SixtyFour => (self.ram_bank & 0x01) << 5, SixtyFour => (self.ram_bank & 0x01) << 5,
OneHundredTwentyEight => (self.ram_bank & 0x03) << 5, OneTwentyEight => (self.ram_bank & 0x03) << 5,
_ => unreachable!("{:?} is not a valid MBC1 BankCount", self.bank_count), _ => unreachable!("{:?} is not a valid MBC1 BankCount", self.rom_size),
} }
} }
fn _mbcm_zero_bank(&self) -> u8 { fn _mbcm_zero_bank(&self) -> u8 {
use BankCount::*; use RomSize::*;
match self.bank_count { match self.rom_size {
None | Four | Eight | Sixteen | ThirtyTwo => 0x00, None | Four | Eight | Sixteen | ThirtyTwo => 0x00,
SixtyFour => (self.ram_bank & 0x03) << 4, SixtyFour => (self.ram_bank & 0x03) << 4,
OneHundredTwentyEight => (self.ram_bank & 0x03) << 5, OneTwentyEight => (self.ram_bank & 0x03) << 5,
_ => unreachable!("{:?} is not a valid MBC1 BankCount", self.bank_count), _ => unreachable!("{:?} is not a valid MBC1 BankCount", self.rom_size),
} }
} }
fn high_bank(&self) -> u8 { fn high_bank(&self) -> u8 {
use BankCount::*; use RomSize::*;
let base = self.rom_bank & self.rom_size_mask(); let base = self.rom_bank & self.rom_size_mask();
match self.bank_count { match self.rom_size {
None | Four | Eight | Sixteen | ThirtyTwo => base, None | Four | Eight | Sixteen | ThirtyTwo => base,
SixtyFour => base & !(0x01 << 5) | ((self.ram_bank & 0x01) << 5), SixtyFour => base & !(0x01 << 5) | ((self.ram_bank & 0x01) << 5),
OneHundredTwentyEight => base & !(0x03 << 5) | ((self.ram_bank & 0x03) << 5), OneTwentyEight => base & !(0x03 << 5) | ((self.ram_bank & 0x03) << 5),
_ => unreachable!("{:?} is not a valid MBC1 BankCount", self.bank_count), _ => unreachable!("{:?} is not a valid MBC1 BankCount", self.rom_size),
} }
} }
fn rom_size_mask(&self) -> u8 { fn rom_size_mask(&self) -> u8 {
use BankCount::*; use RomSize::*;
match self.bank_count { match self.rom_size {
None => 0b00000001, None => 0b00000001,
Four => 0b00000011, Four => 0b00000011,
Eight => 0b00000111, Eight => 0b00000111,
Sixteen => 0b00001111, Sixteen => 0b00001111,
ThirtyTwo | SixtyFour | OneHundredTwentyEight => 0b00011111, ThirtyTwo | SixtyFour | OneTwentyEight => 0b00011111,
_ => unreachable!("{:?} is not a valid MBC1 BankCount", self.bank_count), _ => unreachable!("{:?} is not a valid MBC1 BankCount", self.rom_size),
} }
} }
fn ram_addr(&self, addr: u16) -> u16 { fn ram_addr(&self, addr: u16) -> usize {
use RamSize::*; use RamSize::*;
match self.ram_size { match self.ram_size {
_2KB | _8KB => (addr - 0xA000) % self.ram_size.len() as u16, Unused | One => (addr as usize - 0xA000) % self.ram_size.capacity(),
_32KB => { Four => {
if self.mode { if self.mode {
0x2000 * self.ram_bank as u16 + (addr - 0xA000) 0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)
} else { } else {
addr - 0xA000 addr as usize - 0xA000
} }
} }
_ => unreachable!("RAM size can not be greater than 32KB on MBC1"), _ => unreachable!("RAM size can not be greater than 32KB on MBC1"),
@@ -237,49 +197,39 @@ impl Mbc1 {
} }
} }
impl MemoryBankController for Mbc1 { impl MBCIo for MBC1 {
fn handle_read(&self, addr: u16) -> MbcResult { fn handle_read(&self, addr: u16) -> MBCResult {
use MbcResult::*; use MBCResult::*;
match addr { match addr {
0x0000..=0x3FFF => { 0x0000..=0x3FFF if self.mode => {
if self.mode { Address(0x4000 * self.zero_bank() as usize + addr as usize)
Address(0x4000 * self.zero_bank() as usize + addr as usize)
} else {
Address(addr as usize)
}
} }
0x0000..=0x3FFF => Address(addr as usize),
0x4000..=0x7FFF => { 0x4000..=0x7FFF => {
Address(0x4000 * self.high_bank() as usize + (addr as usize - 0x4000)) Address(0x4000 * self.high_bank() as usize + (addr as usize - 0x4000))
} }
0xA000..=0xBFFF => { 0xA000..=0xBFFF if self.mem_enabled && self.ram_size != RamSize::None => {
if self.ram_enabled { Value(self.memory[self.ram_addr(addr)])
Value(self.ram[self.ram_addr(addr) as usize])
} else {
Value(0xFF)
}
} }
0xA000..=0xBFFF => Value(0xFF),
_ => unreachable!("A read from {:#06X} should not be handled by MBC1", addr), _ => unreachable!("A read from {:#06X} should not be handled by MBC1", addr),
} }
} }
fn handle_write(&mut self, addr: u16, byte: u8) { fn handle_write(&mut self, addr: u16, byte: u8) {
match addr { match addr {
0x0000..=0x1FFF => self.ram_enabled = (byte & 0x0F) == 0x0A, 0x0000..=0x1FFF => self.mem_enabled = (byte & 0x0F) == 0x0A,
0x2000..=0x3FFF => { 0x2000..=0x3FFF => {
self.rom_bank = if byte == 0x00 { let value = byte & 0x1F;
0x01 let masked_value = byte & self.rom_size_mask();
} else { self.rom_bank = if value == 0 { 0x01 } else { masked_value };
byte & self.rom_size_mask()
};
self.rom_bank &= 0x1F;
} }
0x4000..=0x5FFF => self.ram_bank = byte & 0x03, 0x4000..=0x5FFF => self.ram_bank = byte & 0x03,
0x6000..=0x7FFF => self.mode = (byte & 0x01) == 0x01, 0x6000..=0x7FFF => self.mode = (byte & 0x01) == 0x01,
0xA000..=0xBFFF if self.ram_enabled => { 0xA000..=0xBFFF if self.mem_enabled && self.ram_size != RamSize::None => {
let ram_addr = self.ram_addr(addr) as usize; let ram_addr = self.ram_addr(addr);
self.ram[ram_addr] = byte; self.memory[ram_addr] = byte;
} }
0xA000..=0xBFFF => {} // Ram isn't enabled, ignored write 0xA000..=0xBFFF => {} // Ram isn't enabled, ignored write
_ => unreachable!("A write to {:#06X} should not be handled by MBC1", addr), _ => unreachable!("A write to {:#06X} should not be handled by MBC1", addr),
@@ -293,32 +243,47 @@ enum MBC3Device {
RealTimeClock, RealTimeClock,
} }
#[derive(Debug, Default)] #[derive(Debug)]
struct MBC3 { struct MBC3 {
/// 7-bit Number /// 7-bit Number
rom_bank: u8, rom_bank: u8,
/// 2-bit Number /// 2-bit Number
ram_bank: u8, ram_bank: u8,
devices_enabled: bool, devs_enabled: bool,
currently_mapped: Option<MBC3Device>, mapped: Option<MBC3Device>,
ram_size: RamSize, memory: Vec<u8>,
ram: Vec<u8>,
// RTC Data Latch Previous Write
prev_latch_write: Option<u8>,
} }
impl MemoryBankController for MBC3 { impl MBC3 {
fn handle_read(&self, addr: u16) -> MbcResult { fn new(ram_cap: usize) -> Self {
use MbcResult::*; Self {
memory: vec![0; ram_cap],
rom_bank: Default::default(),
ram_bank: Default::default(),
devs_enabled: Default::default(),
mapped: Default::default(),
prev_latch_write: Default::default(),
}
}
}
impl MBCIo for MBC3 {
fn handle_read(&self, addr: u16) -> MBCResult {
use MBCResult::*;
let res = match addr { let res = match addr {
0x0000..=0x3FFF => Address(addr as usize), 0x0000..=0x3FFF => Address(addr as usize),
0x4000..=0x7FFF => Address(0x4000 * self.rom_bank as usize + (addr as usize - 0x4000)), 0x4000..=0x7FFF => Address(0x4000 * self.rom_bank as usize + (addr as usize - 0x4000)),
0xA000..=0xBFFF => match self.currently_mapped { 0xA000..=0xBFFF => match self.mapped {
Some(MBC3Device::ExternalRam) if self.devices_enabled => { Some(MBC3Device::ExternalRam) if self.devs_enabled => {
Value(self.ram[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)]) Value(self.memory[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)])
} }
Some(MBC3Device::RealTimeClock) if self.devices_enabled => { Some(MBC3Device::RealTimeClock) if self.devs_enabled => {
unimplemented!("Reading from MBC3 RTC is currently unsupported") todo!("Return Latched value of register")
} }
_ => Value(0xFF), _ => Value(0xFF),
}, },
@@ -330,29 +295,37 @@ impl MemoryBankController for MBC3 {
fn handle_write(&mut self, addr: u16, byte: u8) { fn handle_write(&mut self, addr: u16, byte: u8) {
match addr { match addr {
0x000..=0x1FFF => self.devices_enabled = (byte & 0x0F) == 0x0A, // Enable External RAM and Access to RTC if there is one 0x000..=0x1FFF => self.devs_enabled = (byte & 0x0F) == 0x0A, // Enable External RAM and Access to RTC if there is one
0x2000..=0x3FFF => match byte { 0x2000..=0x3FFF => {
0x00 => self.rom_bank = 0x01, self.rom_bank = match byte {
byte => self.rom_bank = byte & 0x7F, 0x00 => 0x01,
}, byte => byte & 0x7F,
}
}
0x4000..=0x5FFF => match byte { 0x4000..=0x5FFF => match byte {
0x00 | 0x01 | 0x02 | 0x03 => { 0x00 | 0x01 | 0x02 | 0x03 => {
self.ram_bank = byte & 0x03; self.ram_bank = byte & 0x03;
self.currently_mapped = Some(MBC3Device::ExternalRam); self.mapped = Some(MBC3Device::ExternalRam);
} }
0x08 | 0x09 | 0x0A | 0x0B | 0x0C => { 0x08 | 0x09 | 0x0A | 0x0B | 0x0C => {
self.currently_mapped = Some(MBC3Device::RealTimeClock); self.mapped = Some(MBC3Device::RealTimeClock);
unimplemented!("RTC in MBC3 is currently unimplemented")
} }
_ => {} _ => {}
}, },
0x6000..=0x7FFF => unimplemented!("RTC Data Latch is currently unimplemented"), 0x6000..=0x7FFF => {
0xA000..=0xBFFF => match self.currently_mapped { if let Some(0x00) = self.prev_latch_write {
Some(MBC3Device::ExternalRam) if self.devices_enabled => { if byte == 0x01 {
self.ram[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)] = byte todo!("Perform Data Latch")
}
} }
Some(MBC3Device::RealTimeClock) if self.devices_enabled => { self.prev_latch_write = Some(byte);
unimplemented!("Writing to MBC3 RTC is currently unsupported") }
0xA000..=0xBFFF => match self.mapped {
Some(MBC3Device::ExternalRam) if self.devs_enabled => {
self.memory[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)] = byte
}
Some(MBC3Device::RealTimeClock) if self.devs_enabled => {
todo!("Write to RTC")
} }
_ => {} _ => {}
}, },
@@ -362,11 +335,131 @@ impl MemoryBankController for MBC3 {
} }
#[derive(Debug)] #[derive(Debug)]
struct NoMbc {} struct MBC5 {
/// 9-bit number
rom_bank: u16,
/// 4-bit number
ram_bank: u8,
impl MemoryBankController for NoMbc { rom_cap: usize,
fn handle_read(&self, addr: u16) -> MbcResult {
MbcResult::Address(addr as usize) memory: Vec<u8>,
mem_enabled: bool,
}
impl MBC5 {
fn new(ram_cap: usize, rom_cap: usize) -> Self {
Self {
rom_bank: 0x01,
memory: vec![0; ram_cap],
rom_cap,
ram_bank: Default::default(),
mem_enabled: Default::default(),
}
}
fn bank_addr(&self, addr: u16) -> usize {
(0x4000 * self.rom_bank as usize + (addr as usize - 0x4000)) % self.rom_cap
}
}
impl MBCIo for MBC5 {
fn handle_read(&self, addr: u16) -> MBCResult {
use MBCResult::*;
match addr {
0x0000..=0x3FFF => Address(addr as usize),
0x4000..=0x7FFF => Address(self.bank_addr(addr)),
0xA000..=0xBFFF if self.mem_enabled => {
Value(self.memory[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)])
}
0xA000..=0xBFFF => Value(0xFF),
_ => unreachable!("A read from {:#06X} should not be handled by MBC5", addr),
}
}
fn handle_write(&mut self, addr: u16, byte: u8) {
match addr {
0x0000..=0x1FFF => self.mem_enabled = (byte & 0x0F) == 0x0A,
0x2000..=0x2FFF => self.rom_bank = (self.rom_bank & 0x0100) | byte as u16,
0x3000..=0x3FFF => self.rom_bank = (self.rom_bank & 0x00FF) | (byte as u16 & 0x01) << 8,
0x4000..=0x5FFF => self.ram_bank = byte & 0x0F,
0xA000..=0xBFFF if self.mem_enabled => {
self.memory[0x2000 * self.ram_bank as usize + (addr as usize - 0xA000)] = byte;
}
0xA000..=0xBFFF => {}
_ => unreachable!("A write to {:#06X} should not be handled by MBC5", addr),
}
}
}
#[derive(Debug)]
struct MBC2 {
/// 4-bit number
rom_bank: u8,
memory: Box<[u8; Self::RAM_SIZE]>,
mem_enabled: bool,
rom_cap: usize,
}
impl MBC2 {
const RAM_SIZE: usize = 0x0200;
fn new(rom_cap: usize) -> Self {
Self {
rom_bank: 0x01,
memory: Box::new([0; Self::RAM_SIZE]),
mem_enabled: Default::default(),
rom_cap,
}
}
fn rom_addr(&self, addr: u16) -> usize {
(0x4000 * self.rom_bank as usize + (addr as usize - 0x4000)) % self.rom_cap
}
}
impl MBCIo for MBC2 {
fn handle_read(&self, addr: u16) -> MBCResult {
use MBCResult::*;
match addr {
0x0000..=0x3FFF => Address(addr as usize),
0x4000..=0x7FFF => Address(self.rom_addr(addr)),
0xA000..=0xBFFF if self.mem_enabled => {
let mbc2_addr = addr as usize & (Self::RAM_SIZE - 1);
Value(self.memory[mbc2_addr] | 0xF0)
}
0xA000..=0xBFFF => Value(0xFF),
_ => unreachable!("A read from {:#06X} should not be handled by MBC2", addr),
}
}
fn handle_write(&mut self, addr: u16, byte: u8) {
let nybble = byte & 0x0F;
match addr {
0x0000..=0x3FFF if addr >> 8 & 0x01 == 0x01 => {
self.rom_bank = if nybble == 0x00 { 0x01 } else { nybble };
}
0x0000..=0x3FFF => self.mem_enabled = nybble == 0x0A,
0xA000..=0xBFFF if self.mem_enabled => {
let mbc2_addr = addr as usize & (Self::RAM_SIZE - 1);
self.memory[mbc2_addr] = nybble;
}
0x4000..=0x7FFF | 0xA000..=0xBFFF => {}
_ => unreachable!("A write to {:#06X} should not be handled by MBC2", addr),
}
}
}
#[derive(Debug)]
struct NoMBC;
impl MBCIo for NoMBC {
fn handle_read(&self, addr: u16) -> MBCResult {
MBCResult::Address(addr as usize)
} }
fn handle_write(&mut self, _addr: u16, _byte: u8) { fn handle_write(&mut self, _addr: u16, _byte: u8) {
@@ -374,54 +467,57 @@ impl MemoryBankController for NoMbc {
} }
} }
trait MemoryBankController { trait MBCIo {
fn handle_read(&self, addr: u16) -> MbcResult; fn handle_read(&self, addr: u16) -> MBCResult;
fn handle_write(&mut self, addr: u16, byte: u8); fn handle_write(&mut self, addr: u16, byte: u8);
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum MbcResult { enum MBCResult {
Address(usize), Address(usize),
Value(u8), Value(u8),
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum MbcKind { enum MBCKind {
None, None,
Mbc1, MBC1,
Mbc1WithBattery, MBC1WithBattery,
Mbc5, MBC2,
Mbc3WithBattery, MBC2WithBattery,
Mbc3, MBC3,
MBC3WithBattery,
MBC5,
MBC5WithBattery,
} }
impl Default for MbcKind { impl Default for MBCKind {
fn default() -> Self { fn default() -> Self {
Self::None Self::None
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, PartialEq)]
enum RamSize { enum RamSize {
None = 0x00, None = 0x00,
_2KB = 0x01, Unused = 0x01,
_8KB = 0x02, One = 0x02,
_32KB = 0x03, // Split into 4 RAM banks Four = 0x03,
_128KB = 0x04, // Split into 16 RAM banks Sixteen = 0x04,
_64KB = 0x05, // Split into 8 RAm Banks Eight = 0x05,
} }
impl RamSize { impl RamSize {
fn len(&self) -> u32 { fn capacity(&self) -> usize {
use RamSize::*; use RamSize::*;
match *self { match *self {
None => 0, None => 0,
_2KB => 2_048, Unused => 0x800,
_8KB => 8_192, One => 0x2000,
_32KB => 32_768, Four => 0x8000,
_128KB => 131_072, Sixteen => 0x20000,
_64KB => 65_536, Eight => 0x10000,
} }
} }
} }
@@ -438,63 +534,49 @@ impl From<u8> for RamSize {
match byte { match byte {
0x00 => None, 0x00 => None,
0x01 => _2KB, 0x01 => Unused,
0x02 => _8KB, 0x02 => One,
0x03 => _32KB, 0x03 => Four,
0x04 => _128KB, 0x04 => Sixteen,
0x05 => _64KB, 0x05 => Eight,
_ => unreachable!("{:#04X} is not a valid value for RAMSize", byte), _ => unreachable!("{:#04X} is not a valid value for RAMSize", byte),
} }
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum BankCount { enum RomSize {
None = 0x00, // 32KB (also called Two) None = 0x00, // 32KB (also called Two)
Four = 0x01, // 64KB Four = 0x01, // 64KB
Eight = 0x02, // 128KB Eight = 0x02, // 128KB
Sixteen = 0x03, // 256KB Sixteen = 0x03, // 256KB
ThirtyTwo = 0x04, // 512KB ThirtyTwo = 0x04, // 512KB
SixtyFour = 0x05, // 1MB SixtyFour = 0x05, // 1MB
OneHundredTwentyEight = 0x06, // 2MB OneTwentyEight = 0x06, // 2MB
TwoHundredFiftySix = 0x07, // 4MB TwoFiftySix = 0x07, // 4MB
FiveHundredTwelve = 0x08, // 8MB FiveHundredTwelve = 0x08, // 8MB
SeventyTwo = 0x52, // 1.1MB SeventyTwo = 0x52, // 1.1MB
Eighty = 0x53, // 1.2MB Eighty = 0x53, // 1.2MB
NinetySix = 0x54, // 1.5MB NinetySix = 0x54, // 1.5MB
} }
impl Default for BankCount { impl RomSize {
fn default() -> Self {
Self::None
}
}
impl BankCount {
// https://hacktix.github.io/GBEDG/mbcs/#rom-size // https://hacktix.github.io/GBEDG/mbcs/#rom-size
fn size(&self) -> u32 { fn capacity(&self) -> usize {
use BankCount::*; use RomSize::*;
match self { match self {
None => 32_768, SeventyTwo => 0x120000,
Four => 65_536, Eighty => 0x140000,
Eight => 131_072, NinetySix => 0x180000,
Sixteen => 262_144, _ => 0x8000 << *self as u8,
ThirtyTwo => 524_288,
SixtyFour => 1_048_576,
OneHundredTwentyEight => 2_097_152,
TwoHundredFiftySix => 4_194_304,
FiveHundredTwelve => 8_388_608,
SeventyTwo => 1_179_648,
Eighty => 1_310_720,
NinetySix => 1_572_864,
} }
} }
} }
impl From<u8> for BankCount { impl From<u8> for RomSize {
fn from(byte: u8) -> Self { fn from(byte: u8) -> Self {
use BankCount::*; use RomSize::*;
match byte { match byte {
0x00 => None, 0x00 => None,
@@ -503,8 +585,8 @@ impl From<u8> for BankCount {
0x03 => Sixteen, 0x03 => Sixteen,
0x04 => ThirtyTwo, 0x04 => ThirtyTwo,
0x05 => SixtyFour, 0x05 => SixtyFour,
0x06 => OneHundredTwentyEight, 0x06 => OneTwentyEight,
0x07 => TwoHundredFiftySix, 0x07 => TwoFiftySix,
0x08 => FiveHundredTwelve, 0x08 => FiveHundredTwelve,
0x52 => SeventyTwo, 0x52 => SeventyTwo,
0x53 => Eighty, 0x53 => Eighty,
@@ -514,14 +596,14 @@ impl From<u8> for BankCount {
} }
} }
impl std::fmt::Debug for Box<dyn MemoryBankController> { impl std::fmt::Debug for Box<dyn MBCIo> {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
todo!("Implement Debug for Box<dyn MBC> Trait Object"); todo!("Implement Debug for Box<dyn MBC> Trait Object");
} }
} }
impl Default for Box<dyn MemoryBankController> { impl Default for Box<dyn MBCIo> {
fn default() -> Self { fn default() -> Self {
Box::new(Mbc1::default()) Box::new(NoMBC)
} }
} }

View File

@@ -1,10 +1,7 @@
use crate::apu::Apu; use crate::bus::{Bus, BusIo, BOOT_SIZE};
use crate::bus::{Bus, BusIo};
use crate::instruction::cycle::Cycle;
use crate::instruction::Instruction; use crate::instruction::Instruction;
use crate::interrupt::{InterruptEnable, InterruptFlag}; use crate::interrupt::{InterruptEnable, InterruptFlag};
use crate::joypad::Joypad; use crate::Cycle;
use crate::ppu::Ppu;
use bitfield::bitfield; use bitfield::bitfield;
use std::fmt::{Display, Formatter, Result as FmtResult}; use std::fmt::{Display, Formatter, Result as FmtResult};
@@ -14,13 +11,11 @@ pub struct Cpu {
reg: Registers, reg: Registers,
flags: Flags, flags: Flags,
ime: ImeState, ime: ImeState,
// TODO: Merge halted and state properties
halted: Option<HaltState>,
state: State, state: State,
} }
impl Cpu { impl Cpu {
pub fn new() -> Self { pub(crate) fn without_boot() -> Self {
Self { Self {
reg: Registers { reg: Registers {
a: 0x01, a: 0x01,
@@ -38,114 +33,115 @@ impl Cpu {
} }
} }
pub fn boot_new(path: &str) -> anyhow::Result<Self> { pub(crate) fn with_boot(rom: [u8; BOOT_SIZE]) -> Self {
Ok(Self { Self {
bus: Bus::with_boot(path)?, bus: Bus::with_boot(rom),
..Default::default() ..Default::default()
}) }
} }
pub(crate) fn ime(&self) -> &ImeState { pub(crate) fn ime(&self) -> ImeState {
&self.ime self.ime
} }
pub(crate) fn set_ime(&mut self, state: ImeState) { pub(crate) fn set_ime(&mut self, state: ImeState) {
self.ime = state; self.ime = state;
} }
pub(crate) fn halt(&mut self, state: HaltState) { pub(crate) fn halt_cpu(&mut self, kind: HaltKind) {
self.halted = Some(state); self.state = State::Halt(kind);
} }
fn resume(&mut self) { fn resume_execution(&mut self) {
self.halted = None; self.state = State::Execute;
} }
pub(crate) fn halted(&self) -> Option<&HaltState> { pub(crate) fn is_halted(&self) -> bool {
self.halted.as_ref() match self.state {
State::Halt(_) => true,
_ => false,
}
} }
fn inc_pc(&mut self) { pub(crate) fn halt_kind(&self) -> Option<HaltKind> {
self.reg.pc += 1; match self.state {
} State::Halt(kind) => Some(kind),
_ => None,
pub fn load_cartridge(&mut self, path: &str) -> std::io::Result<()> { }
self.bus.load_cartridge(path)
}
pub fn rom_title(&self) -> Option<&str> {
self.bus.rom_title()
} }
} }
impl Cpu { impl Cpu {
fn fetch(&self) -> u8 { /// Fetch an [Instruction] from the memory bus
self.bus.read_byte(self.reg.pc) /// (4 cycles)
} fn fetch(&mut self) -> u8 {
let byte = self.read_byte(self.reg.pc);
pub(crate) fn imm_byte(&mut self) -> u8 { self.bus.clock();
let byte = self.bus.read_byte(self.reg.pc);
self.reg.pc += 1; self.reg.pc += 1;
byte byte
} }
pub(crate) fn imm_word(&mut self) -> u16 { /// Decode a byte into an [SM83](Cpu) [Instruction]
let word = self.bus.read_word(self.reg.pc); ///
self.reg.pc += 2; /// If opcode == 0xCB, then decoding costs 4 cycles.
word /// Otherwise, decoding is free
}
pub(crate) fn decode(&mut self, opcode: u8) -> Instruction { pub(crate) fn decode(&mut self, opcode: u8) -> Instruction {
if opcode == 0xCB { if opcode == 0xCB {
Instruction::decode(self.imm_byte(), true) Instruction::decode(self.fetch(), true)
} else { } else {
Instruction::decode(opcode, false) Instruction::decode(opcode, false)
} }
} }
/// Execute an [Instruction].
///
/// The amount of cycles necessary to execute an instruction range from
/// 0 to 20 T-cycles
fn execute(&mut self, instruction: Instruction) -> Cycle { fn execute(&mut self, instruction: Instruction) -> Cycle {
Instruction::execute(self, instruction) Instruction::execute(self, instruction)
} }
/// Perform the [`Cpu::fetch()`] [`Cpu::decode()`] [`Cpu::execute()`]
/// routine.
///
/// Handle HALT and interrupts.
pub fn step(&mut self) -> Cycle { pub fn step(&mut self) -> Cycle {
// Log instructions // Log instructions
// if !self.bus.boot_mapped() { // if self.reg.pc > 0xFF {
// let out = std::io::stdout(); // let out = std::io::stdout();
// let _ = self._log_state(out.lock()); // let _ = self._print_logs(out.lock());
// } // }
// FIXME: The Halt instruction takes less cycles than it should in Blargg's 2nd cpu_instrs test if let Some(elapsed) = self.handle_interrupt() {
let cycles = match self.halted() { return elapsed;
Some(state) => {
use HaltState::*;
match state {
ImeEnabled | NonePending => Cycle::new(4),
SomePending => todo!("Implement HALT bug"),
}
}
None => {
let opcode = self.fetch();
self.inc_pc();
let instr = self.decode(opcode);
let cycles = self.execute(instr);
self.check_ime();
cycles
}
};
let pending: u32 = cycles.into();
for _ in 0..pending {
self.bus.clock();
} }
// TODO: This is in the wrong place if let Some(kind) = self.halt_kind() {
self.handle_interrupts(); use HaltKind::*;
cycles self.bus.clock();
let elapsed = match kind {
ImeEnabled | NonePending => 4,
SomePending => todo!("Implement HALT bug"),
};
return elapsed;
}
let opcode = self.fetch();
let instr = self.decode(opcode);
let elapsed = self.execute(instr);
self.handle_ei();
// For use in Blargg's Test ROMs
if self.read_byte(0xFF02) == 0x81 {
let c = self.read_byte(0xFF01) as char;
self.write_byte(0xFF02, 0x00);
eprint!("{}", c);
}
elapsed
} }
} }
@@ -160,105 +156,100 @@ impl BusIo for Cpu {
} }
impl Cpu { impl Cpu {
pub(crate) fn write_word(&mut self, addr: u16, word: u16) { pub(crate) fn bus(&self) -> &Bus {
self.bus.write_word(addr, word) &self.bus
}
}
impl Cpu {
pub fn ppu(&mut self) -> &Ppu {
&self.bus.ppu
} }
pub fn apu_mut(&mut self) -> &mut Apu { pub(crate) fn bus_mut(&mut self) -> &mut Bus {
&mut self.bus.apu &mut self.bus
} }
pub(crate) fn joypad_mut(&mut self) -> &mut Joypad { fn handle_ei(&mut self) {
&mut self.bus.joypad
}
fn check_ime(&mut self) {
match self.ime { match self.ime {
ImeState::Pending => { ImeState::EiExecuted => self.ime = ImeState::Pending,
// This is within the context of the EI instruction, we need to not update EI until the end of the ImeState::Pending => self.ime = ImeState::Enabled,
// next executed Instruction ImeState::Disabled | ImeState::Enabled => {}
self.ime = ImeState::PendingEnd;
}
ImeState::PendingEnd => {
// The Instruction after EI has now been executed, so we want to enable the IME flag here
self.ime = ImeState::Enabled;
}
ImeState::Disabled | ImeState::Enabled => {} // Do Nothing
} }
} }
fn handle_interrupts(&mut self) { pub(crate) fn int_request(&self) -> u8 {
let req = self.read_byte(0xFF0F); self.read_byte(0xFF0F)
let enabled = self.read_byte(0xFFFF); }
if self.halted.is_some() { pub(crate) fn int_enable(&self) -> u8 {
self.read_byte(0xFFFF)
}
fn handle_interrupt(&mut self) -> Option<Cycle> {
let irq = self.int_request();
let enable = self.int_enable();
// TODO: Ensure that this behaviour is correct
if self.is_halted() {
// When we're here either a HALT with IME set or // When we're here either a HALT with IME set or
// a HALT with IME not set and No pending Interrupts was called // a HALT with IME not set and No pending Interrupts was called
if req & enabled != 0 { if irq & enable != 0 {
// The if self.ime() below correctly follows the "resuming from HALT" behaviour so // The if self.ime() below correctly follows the "resuming from HALT" behaviour so
// nothing actually needs to be added here. This is just documentation // nothing actually needs to be added here. This is just documentation
// since it's a bit weird why nothing is being done // since it's a bit weird why nothing is being done
self.resume() self.resume_execution();
} }
} }
if let ImeState::Enabled = self.ime() { match self.ime() {
let mut req: InterruptFlag = req.into(); ImeState::Enabled => {
let enabled: InterruptEnable = enabled.into(); let mut irq: InterruptFlag = irq.into();
let enable: InterruptEnable = enable.into();
let vector = if req.vblank() && enabled.vblank() { let rst_vector = if irq.vblank() && enable.vblank() {
// Handle VBlank Interrupt // Handle VBlank Interrupt
req.set_vblank(false); irq.set_vblank(false);
// INT 40h // INT 40h
Some(0x40) Some(0x40)
} else if req.lcd_stat() && enabled.lcd_stat() { } else if irq.lcd_stat() && enable.lcd_stat() {
// Handle LCD STAT Interrupt // Handle LCD STAT Interrupt
req.set_lcd_stat(false); irq.set_lcd_stat(false);
// INT 48h // INT 48h
Some(0x48) Some(0x48)
} else if req.timer() && enabled.timer() { } else if irq.timer() && enable.timer() {
// Handle Timer Interrupt // Handle Timer Interrupt
req.set_timer(false); irq.set_timer(false);
// INT 50h // INT 50h
Some(0x50) Some(0x50)
} else if req.serial() && enabled.serial() { } else if irq.serial() && enable.serial() {
// Handle Serial Interrupt // Handle Serial Interrupt
req.set_serial(false); irq.set_serial(false);
// INT 58h // INT 58h
Some(0x58) Some(0x58)
} else if req.joypad() && enabled.joypad() { } else if irq.joypad() && enable.joypad() {
// Handle Joypad Interrupt // Handle Joypad Interrupt
req.set_joypad(false); irq.set_joypad(false);
// INT 60h // INT 60h
Some(0x60) Some(0x60)
} else { } else {
None None
}; };
let _ = match vector { match rst_vector {
Some(address) => { Some(vector) => {
// Write the Changes to 0xFF0F and 0xFFFF registers // Write the Changes to 0xFF0F and 0xFFFF registers
self.write_byte(0xFF0F, req.into()); self.write_byte(0xFF0F, irq.into());
// Disable all future interrupts // Disable all future interrupts
self.set_ime(ImeState::Disabled); self.set_ime(ImeState::Disabled);
Instruction::reset(self, address) Some(Instruction::reset(self, vector))
}
None => None,
} }
None => Cycle::new(0), // NO Interrupts were enabled and / or requested }
}; _ => None,
} }
} }
} }
@@ -266,7 +257,7 @@ impl Cpu {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum State { enum State {
Execute, Execute,
// Halt, Halt(HaltKind),
// Stop, // Stop,
} }
@@ -363,10 +354,9 @@ impl Cpu {
} }
impl Cpu { impl Cpu {
fn _debug_log(&self, mut w: impl std::io::Write, instr: &Instruction) -> std::io::Result<()> { fn _print_debug(&self, mut w: impl std::io::Write) -> std::io::Result<()> {
let pc = self.reg.pc - 1;
write!(w, "A: {:02X} ", self.reg.a)?; write!(w, "A: {:02X} ", self.reg.a)?;
write!(w, "F: {:04b} ", u8::from(self.flags) >> 4)?; write!(w, "F: {:02X} ", u8::from(self.flags))?;
write!(w, "B: {:02X} ", self.reg.b)?; write!(w, "B: {:02X} ", self.reg.b)?;
write!(w, "C: {:02X} ", self.reg.c)?; write!(w, "C: {:02X} ", self.reg.c)?;
write!(w, "D: {:02X} ", self.reg.d)?; write!(w, "D: {:02X} ", self.reg.d)?;
@@ -374,31 +364,40 @@ impl Cpu {
write!(w, "H: {:02X} ", self.reg.h)?; write!(w, "H: {:02X} ", self.reg.h)?;
write!(w, "L: {:02X} ", self.reg.l)?; write!(w, "L: {:02X} ", self.reg.l)?;
write!(w, "SP: {:04X} ", self.reg.sp)?; write!(w, "SP: {:04X} ", self.reg.sp)?;
write!(w, "PC: 00:{:04X} ", pc)?; write!(w, "PC: 00:{:04X} ", self.reg.pc)?;
write!(w, "({:02X} ", self.read_byte(pc))?; write!(w, "({:02X} ", self.read_byte(self.reg.pc))?;
write!(w, "{:02X} ", self.read_byte(pc + 1))?; write!(w, "{:02X} ", self.read_byte(self.reg.pc + 1))?;
write!(w, "{:02X} ", self.read_byte(pc + 2))?; write!(w, "{:02X} ", self.read_byte(self.reg.pc + 2))?;
write!(w, "{:02X}) ", self.read_byte(pc + 3))?; write!(w, "{:02X})", self.read_byte(self.reg.pc + 3))?;
writeln!(w, "| {:?}", instr)?; writeln!(w, "| {:?}", self._dbg_instr())?;
w.flush() w.flush()
} }
fn _log_state(&self, mut writer: impl std::io::Write) -> std::io::Result<()> { fn _print_logs(&self, mut w: impl std::io::Write) -> std::io::Result<()> {
write!(writer, "A: {:02X} ", self.reg.a)?; write!(w, "A: {:02X} ", self.reg.a)?;
write!(writer, "F: {:02X} ", u8::from(self.flags))?; write!(w, "F: {:02X} ", u8::from(self.flags))?;
write!(writer, "B: {:02X} ", self.reg.b)?; write!(w, "B: {:02X} ", self.reg.b)?;
write!(writer, "C: {:02X} ", self.reg.c)?; write!(w, "C: {:02X} ", self.reg.c)?;
write!(writer, "D: {:02X} ", self.reg.d)?; write!(w, "D: {:02X} ", self.reg.d)?;
write!(writer, "E: {:02X} ", self.reg.e)?; write!(w, "E: {:02X} ", self.reg.e)?;
write!(writer, "H: {:02X} ", self.reg.h)?; write!(w, "H: {:02X} ", self.reg.h)?;
write!(writer, "L: {:02X} ", self.reg.l)?; write!(w, "L: {:02X} ", self.reg.l)?;
write!(writer, "SP: {:04X} ", self.reg.sp)?; write!(w, "SP: {:04X} ", self.reg.sp)?;
write!(writer, "PC: 00:{:04X} ", self.reg.pc)?; write!(w, "PC: 00:{:04X} ", self.reg.pc)?;
write!(writer, "({:02X} ", self.read_byte(self.reg.pc))?; write!(w, "({:02X} ", self.read_byte(self.reg.pc))?;
write!(writer, "{:02X} ", self.read_byte(self.reg.pc + 1))?; write!(w, "{:02X} ", self.read_byte(self.reg.pc + 1))?;
write!(writer, "{:02X} ", self.read_byte(self.reg.pc + 2))?; write!(w, "{:02X} ", self.read_byte(self.reg.pc + 2))?;
writeln!(writer, "{:02X})", self.read_byte(self.reg.pc + 3))?; writeln!(w, "{:02X})", self.read_byte(self.reg.pc + 3))?;
writer.flush() w.flush()
}
fn _dbg_instr(&self) -> Instruction {
let byte = self.read_byte(self.reg.pc);
if byte == 0xCB {
Instruction::decode(self.read_byte(self.reg.pc + 1), true)
} else {
Instruction::decode(byte, false)
}
} }
} }
@@ -508,7 +507,7 @@ impl From<u8> for Flags {
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(crate) enum HaltState { pub(crate) enum HaltKind {
ImeEnabled, ImeEnabled,
NonePending, NonePending,
SomePending, SomePending,
@@ -517,8 +516,8 @@ pub(crate) enum HaltState {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(crate) enum ImeState { pub(crate) enum ImeState {
Disabled, Disabled,
EiExecuted,
Pending, Pending,
PendingEnd,
Enabled, Enabled,
} }

View File

@@ -1,60 +1,121 @@
use crate::cpu::Cpu as SM83; use crate::apu::gen::SampleProducer;
use crate::instruction::cycle::Cycle; use crate::cpu::Cpu;
use crate::joypad; use crate::joypad::{self, Joypad};
use crate::ppu::Ppu; use crate::{Cycle, GB_HEIGHT, GB_WIDTH};
use anyhow::Result;
use gilrs::Gilrs; use gilrs::Gilrs;
use std::time::Duration; use std::time::Duration;
use winit_input_helper::WinitInputHelper; use winit_input_helper::WinitInputHelper;
pub const SM83_CYCLE_TIME: Duration = Duration::from_nanos(1_000_000_000 / SM83_CLOCK_SPEED); pub const SM83_CYCLE_TIME: Duration = Duration::from_nanos(1_000_000_000 / SM83_CLOCK_SPEED);
pub const CYCLES_IN_FRAME: Cycle = Cycle::new(456 * 154); // 456 Cycles times 154 scanlines pub const CYCLES_IN_FRAME: Cycle = 456 * 154; // 456 Cycles times 154 scanlines
pub(crate) const SM83_CLOCK_SPEED: u64 = 0x40_0000; // Hz which is 4.194304Mhz pub(crate) const SM83_CLOCK_SPEED: u64 = 0x40_0000; // Hz which is 4.194304Mhz
const DEFAULT_TITLE: &str = "DMG-01 Emulator"; const DEFAULT_TITLE: &str = "DMG-01 Emulator";
const GAMEPAD_ENABLED: bool = false;
pub fn init(boot_path: Option<&str>, rom_path: &str) -> Result<SM83> { pub fn run_frame(emu: &mut Emulator, gamepad: &mut Gilrs, key: &WinitInputHelper) -> Cycle {
let mut cpu = match boot_path { let mut elapsed = 0;
Some(path) => SM83::boot_new(path)?,
None => SM83::new(),
};
eprintln!("Initialized GB Emulator"); if let Some(event) = gamepad.next_event() {
joypad::handle_gamepad_input(emu.joyp_mut(), event);
}
cpu.load_cartridge(rom_path)?; joypad::handle_keyboard_input(emu.joyp_mut(), key);
Ok(cpu) while elapsed < CYCLES_IN_FRAME {
} elapsed += emu.step();
pub fn rom_title(game_boy: &SM83) -> &str {
game_boy.rom_title().unwrap_or(DEFAULT_TITLE)
}
pub fn run(
game_boy: &mut SM83,
gamepad: &mut Gilrs,
input: &WinitInputHelper,
pending: Cycle,
) -> Cycle {
let mut elapsed = Cycle::new(0);
while elapsed < pending {
elapsed += run_unsynced(game_boy, gamepad, input);
} }
elapsed elapsed
} }
pub fn run_unsynced(game_boy: &mut SM83, gamepad: &mut Gilrs, input: &WinitInputHelper) -> Cycle { pub fn draw_frame(emu: &Emulator, buf: &mut [u8; GB_HEIGHT * GB_WIDTH * 4]) {
if GAMEPAD_ENABLED { buf.copy_from_slice(emu.cpu.bus().ppu.frame_buf());
if let Some(event) = gamepad.next_event() { }
joypad::handle_gamepad_input(game_boy.joypad_mut(), event);
pub struct Emulator {
cpu: Cpu,
timestamp: Cycle,
}
impl Emulator {
fn new(cpu: Cpu) -> Self {
Self {
cpu,
timestamp: Default::default(),
} }
} }
joypad::handle_keyboard_input(game_boy.joypad_mut(), input); fn step(&mut self) -> Cycle {
game_boy.step() self.cpu.step()
}
fn load_cart(&mut self, rom: Vec<u8>) {
self.cpu.bus_mut().load_cart(rom)
}
fn joyp_mut(&mut self) -> &mut Joypad {
&mut self.cpu.bus_mut().joypad
}
pub fn set_prod(&mut self, prod: SampleProducer<f32>) {
self.cpu.bus_mut().apu.attach_producer(prod)
}
pub fn title(&self) -> &str {
self.cpu.bus().cart_title().unwrap_or(DEFAULT_TITLE)
}
} }
pub fn draw(ppu: &Ppu, frame: &mut [u8]) { pub mod build {
ppu.copy_to_gui(frame); use std::fs::File;
use std::io::{Read, Result};
use std::path::Path;
use crate::bus::BOOT_SIZE;
use crate::cpu::Cpu;
use super::Emulator;
#[derive(Debug, Default)]
pub struct EmulatorBuilder {
boot: Option<[u8; BOOT_SIZE]>,
cart: Option<Vec<u8>>,
}
impl EmulatorBuilder {
pub fn new() -> Self {
Default::default()
}
pub fn with_boot<P: AsRef<Path>>(mut self, path: P) -> Result<Self> {
let mut file = File::open(path.as_ref())?;
let mut buf = [0x00; BOOT_SIZE];
file.read_exact(&mut buf)?;
self.boot = Some(buf);
Ok(self)
}
pub fn with_cart<P: AsRef<Path>>(mut self, path: P) -> Result<Self> {
let mut file = File::open(path.as_ref())?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
self.cart = Some(buf);
Ok(self)
}
pub fn finish(mut self) -> Emulator {
let mut emu = Emulator::new(match self.boot {
Some(rom) => Cpu::with_boot(rom),
None => Cpu::without_boot(),
});
if let Some(rom) = self.cart.take() {
emu.load_cart(rom)
}
emu
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -120,49 +120,57 @@ pub fn handle_keyboard_input(pad: &mut Joypad, input: &WinitInputHelper) {
if input.key_pressed(VirtualKeyCode::Down) { if input.key_pressed(VirtualKeyCode::Down) {
state.dpad_down.update(true, irq); state.dpad_down.update(true, irq);
} else if input.key_released(VirtualKeyCode::Down) { }
if input.key_released(VirtualKeyCode::Down) {
state.dpad_down.update(false, irq); state.dpad_down.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::Up) { if input.key_pressed(VirtualKeyCode::Up) {
state.dpad_up.update(true, irq); state.dpad_up.update(true, irq);
} else if input.key_released(VirtualKeyCode::Up) { }
if input.key_released(VirtualKeyCode::Up) {
state.dpad_up.update(false, irq); state.dpad_up.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::Left) { if input.key_pressed(VirtualKeyCode::Left) {
state.dpad_left.update(true, irq); state.dpad_left.update(true, irq);
} else if input.key_released(VirtualKeyCode::Left) { }
if input.key_released(VirtualKeyCode::Left) {
state.dpad_left.update(false, irq); state.dpad_left.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::Right) { if input.key_pressed(VirtualKeyCode::Right) {
state.dpad_right.update(true, irq); state.dpad_right.update(true, irq);
} else if input.key_released(VirtualKeyCode::Right) { }
if input.key_released(VirtualKeyCode::Right) {
state.dpad_right.update(false, irq); state.dpad_right.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::T) { if input.key_pressed(VirtualKeyCode::T) {
state.start.update(true, irq); state.start.update(true, irq);
} else if input.key_released(VirtualKeyCode::T) { }
if input.key_released(VirtualKeyCode::T) {
state.start.update(false, irq); state.start.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::Y) { if input.key_pressed(VirtualKeyCode::Y) {
state.select.update(true, irq); state.select.update(true, irq);
} else if input.key_released(VirtualKeyCode::Y) { }
if input.key_released(VirtualKeyCode::Y) {
state.select.update(false, irq); state.select.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::Z) { if input.key_pressed(VirtualKeyCode::Z) {
state.south.update(true, irq); state.south.update(true, irq);
} else if input.key_released(VirtualKeyCode::Z) { }
if input.key_released(VirtualKeyCode::Z) {
state.south.update(false, irq); state.south.update(false, irq);
} }
if input.key_pressed(VirtualKeyCode::X) { if input.key_pressed(VirtualKeyCode::X) {
state.east.update(true, irq); state.east.update(true, irq);
} else if input.key_released(VirtualKeyCode::X) { }
if input.key_released(VirtualKeyCode::X) {
state.east.update(false, irq); state.east.update(false, irq);
} }
} }

View File

@@ -1,5 +1,5 @@
pub use apu::gen::AudioSPSC; pub use apu::gen::AudioSPSC;
pub use instruction::cycle::Cycle; pub type Cycle = u64;
pub const GB_WIDTH: usize = 160; pub const GB_WIDTH: usize = 160;
pub const GB_HEIGHT: usize = 144; pub const GB_HEIGHT: usize = 144;

View File

@@ -1,17 +1,20 @@
use std::convert::TryInto;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg}; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg};
use gb::emu::build::EmulatorBuilder;
use gb::{AudioSPSC, Cycle, GB_HEIGHT, GB_WIDTH}; use gb::{AudioSPSC, Cycle, GB_HEIGHT, GB_WIDTH};
use gilrs::Gilrs; use gilrs::Gilrs;
use pixels::{PixelsBuilder, SurfaceTexture}; use pixels::{PixelsBuilder, SurfaceTexture};
use rodio::{OutputStream, Sink}; use rodio::{OutputStream, Sink};
use std::time::Instant; use winit::dpi::{LogicalSize, PhysicalSize};
use winit::dpi::LogicalSize;
use winit::event::{Event, VirtualKeyCode}; use winit::event::{Event, VirtualKeyCode};
use winit::event_loop::{ControlFlow, EventLoop}; use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::{Window, WindowBuilder}; use winit::window::{Window, WindowBuilder};
use winit_input_helper::WinitInputHelper; use winit_input_helper::WinitInputHelper;
const SCALE: f64 = 2.0; const WINDOW_SCALE: usize = 3;
const AUDIO_ENABLED: bool = false;
fn main() -> Result<()> { fn main() -> Result<()> {
let app = App::new(crate_name!()) let app = App::new(crate_name!())
@@ -38,23 +41,22 @@ fn main() -> Result<()> {
) )
.get_matches(); .get_matches();
// `rom` is a required value in every situation so this will let mut emu_build =
// always exist. EmulatorBuilder::new().with_cart(m.value_of("rom").expect("ROM path provided"))?;
let rom_path = m
.value_of("rom")
.expect("Required value 'rom' was provided");
let mut game_boy = if let Some(path) = m.value_of("boot") {
gb::emu::init(m.value_of("boot"), rom_path).expect("Initialized DMG-01 Emulator"); emu_build = emu_build.with_boot(path)?;
let cartridge_title = gb::emu::rom_title(&game_boy); }
// Initialize Gamepad Support let mut emu = emu_build.finish();
let mut gamepad = Gilrs::new().expect("Initialized Gilrs for Controller Input"); let rom_title = emu.title();
let mut gamepad = Gilrs::new().expect("Initialize Controller Support");
// Initialize GUI // Initialize GUI
let event_loop = EventLoop::new(); let event_loop = EventLoop::new();
let mut input = WinitInputHelper::new(); let mut input = WinitInputHelper::new();
let window = create_window(&event_loop, cartridge_title)?; let window = create_window(&event_loop, rom_title)?;
let mut pixels = { let mut pixels = {
let size = window.inner_size(); let size = window.inner_size();
@@ -65,21 +67,26 @@ fn main() -> Result<()> {
.build()? .build()?
}; };
let spsc: AudioSPSC<f32> = Default::default();
let (prod, cons) = spsc.init();
game_boy.apu_mut().set_producer(prod);
// Initialize Audio // Initialize Audio
let (_stream, stream_handle) = OutputStream::try_default().expect("Initialized Audio"); let (_stream, stream_handle) = OutputStream::try_default().expect("Initialized Audio");
let sink = Sink::try_new(&stream_handle)?;
sink.append(cons);
std::thread::spawn(move || { if AUDIO_ENABLED {
sink.sleep_until_end(); let spsc: AudioSPSC<f32> = Default::default();
}); let (prod, cons) = spsc.init();
let sink = {
let s = Sink::try_new(&stream_handle)?;
s.append(cons);
s.set_volume(0.1);
s
};
emu.set_prod(prod);
std::thread::spawn(move || {
sink.sleep_until_end();
});
}
let mut now = Instant::now();
let mut cycle_count: Cycle = Default::default(); let mut cycle_count: Cycle = Default::default();
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
@@ -104,48 +111,34 @@ fn main() -> Result<()> {
pixels.resize_surface(size.width, size.height); pixels.resize_surface(size.width, size.height);
} }
let delta = now.elapsed().subsec_nanos(); cycle_count += gb::emu::run_frame(&mut emu, &mut gamepad, &input);
now = Instant::now();
let pending = Cycle::new(delta / gb::emu::SM83_CYCLE_TIME.subsec_nanos());
cycle_count += gb::emu::run(&mut game_boy, &mut gamepad, &input, pending);
if cycle_count >= gb::emu::CYCLES_IN_FRAME { if cycle_count >= gb::emu::CYCLES_IN_FRAME {
// Draw Frame
cycle_count %= gb::emu::CYCLES_IN_FRAME; cycle_count %= gb::emu::CYCLES_IN_FRAME;
gb::emu::draw(game_boy.ppu(), pixels.get_frame()); let buf: &mut [u8; GB_WIDTH * GB_HEIGHT * 4] = pixels
.get_frame()
.try_into()
.expect("Size of Pixel Buffer is GB_WIDTH * GB_HEIGHT * 4");
gb::emu::draw_frame(&emu, buf);
window.request_redraw(); window.request_redraw();
} }
} }
}); });
} }
#[cfg(not(windows))]
fn create_window(event_loop: &EventLoop<()>, title: &str) -> Result<Window> { fn create_window(event_loop: &EventLoop<()>, title: &str) -> Result<Window> {
let size = LogicalSize::new((GB_WIDTH as f64) * SCALE, (GB_HEIGHT as f64) * SCALE); let logical = LogicalSize::new(GB_WIDTH as f64, GB_HEIGHT as f64);
let physical = PhysicalSize::new(
(GB_WIDTH * WINDOW_SCALE) as f32,
(GB_HEIGHT * WINDOW_SCALE) as f32,
);
Ok(WindowBuilder::new() Ok(WindowBuilder::new()
.with_title(title) .with_title(title)
.with_inner_size(size) .with_min_inner_size(logical)
.with_min_inner_size(size) .with_inner_size(physical)
.with_resizable(true) .with_resizable(true)
.with_decorations(true)
.with_transparent(false)
.build(event_loop)?)
}
#[cfg(windows)]
fn create_window(event_loop: &EventLoop<()>, title: &str) -> Result<Window> {
use winit::platform::windows::WindowBuilderExtWindows;
let size = LogicalSize::new((GB_WIDTH as f64) * SCALE, (GB_HEIGHT as f64) * SCALE);
Ok(WindowBuilder::new()
.with_title(title)
.with_inner_size(size)
.with_min_inner_size(size)
.with_resizable(true)
.with_decorations(true)
.with_transparent(false)
.with_drag_and_drop(false)
.build(event_loop)?) .build(event_loop)?)
} }

View File

@@ -1,5 +1,5 @@
use crate::bus::BusIo; use crate::bus::BusIo;
use crate::instruction::cycle::Cycle; use crate::Cycle;
use crate::GB_HEIGHT; use crate::GB_HEIGHT;
use crate::GB_WIDTH; use crate::GB_WIDTH;
use dma::DirectMemoryAccess; use dma::DirectMemoryAccess;
@@ -70,7 +70,7 @@ impl BusIo for Ppu {
} }
impl Ppu { impl Ppu {
pub(crate) fn clock(&mut self) { pub(crate) fn tick(&mut self) {
self.cycle += 1; self.cycle += 1;
if !self.ctrl.lcd_enabled() { if !self.ctrl.lcd_enabled() {
@@ -79,7 +79,7 @@ impl Ppu {
match self.stat.mode() { match self.stat.mode() {
PpuMode::OamScan => { PpuMode::OamScan => {
if self.cycle >= 80.into() { if self.cycle >= 80 {
self.stat.set_mode(PpuMode::Drawing); self.stat.set_mode(PpuMode::Drawing);
} }
@@ -88,7 +88,7 @@ impl Ppu {
PpuMode::Drawing => { PpuMode::Drawing => {
if self.ctrl.lcd_enabled() { if self.ctrl.lcd_enabled() {
// Only Draw when the LCD Is Enabled // Only Draw when the LCD Is Enabled
self.draw(self.cycle.into()); self.draw(self.cycle);
} else { } else {
self.reset(); self.reset();
} }
@@ -125,7 +125,7 @@ impl Ppu {
PpuMode::HBlank => { PpuMode::HBlank => {
// This mode will always end at 456 cycles // This mode will always end at 456 cycles
if self.cycle >= 456.into() { if self.cycle >= 456 {
self.cycle %= 456; self.cycle %= 456;
self.pos.line_y += 1; self.pos.line_y += 1;
@@ -167,7 +167,7 @@ impl Ppu {
} }
} }
PpuMode::VBlank => { PpuMode::VBlank => {
if self.cycle > 456.into() { if self.cycle > 456 {
self.cycle %= 456; self.cycle %= 456;
self.pos.line_y += 1; self.pos.line_y += 1;
@@ -228,23 +228,26 @@ impl Ppu {
self.scan_state.next(); self.scan_state.next();
} }
fn draw(&mut self, _cycle: u32) { fn draw(&mut self, _cycle: Cycle) {
use FetcherState::*; use FetcherState::*;
let iter = &mut self.obj_buffer.iter(); let mut iter = self.obj_buffer.iter_mut();
let default = &mut None;
let obj_attr = loop { let obj_attr = loop {
match iter.flatten().next() { match iter.next() {
Some(attr) => { Some(attr_opt) => {
if attr.x <= (self.x_pos + 8) { if let Some(attr) = attr_opt {
self.fetch.back.reset(); if attr.x <= (self.x_pos + 8) {
self.fetch.back.pause(); self.fetch.back.reset();
self.fifo.pause(); self.fetch.back.pause();
self.fifo.pause();
break Some(*attr); break attr_opt;
}
} }
} }
None => break None, None => break default,
} }
}; };
@@ -252,10 +255,10 @@ impl Ppu {
match self.fetch.obj.state { match self.fetch.obj.state {
TileNumber => { TileNumber => {
self.fetch.obj.tile.with_id(attr.tile_index); self.fetch.obj.tile.with_id(attr.tile_index);
self.fetch.obj.next(ToLowByteSleep); self.fetch.obj.next(SleepOne);
} }
ToLowByteSleep => self.fetch.obj.next(TileLowByte), SleepOne => self.fetch.obj.next(TileLow),
TileLowByte => { TileLow => {
let obj_size = self.ctrl.obj_size(); let obj_size = self.ctrl.obj_size();
let addr = PixelFetcher::get_obj_addr(&attr, &self.pos, obj_size); let addr = PixelFetcher::get_obj_addr(&attr, &self.pos, obj_size);
@@ -263,10 +266,10 @@ impl Ppu {
let byte = self.read_byte(addr); let byte = self.read_byte(addr);
self.fetch.obj.tile.with_low_byte(byte); self.fetch.obj.tile.with_low_byte(byte);
self.fetch.obj.next(ToHighByteSleep); self.fetch.obj.next(SleepTwo);
} }
ToHighByteSleep => self.fetch.obj.next(TileHighByte), SleepTwo => self.fetch.obj.next(TileHigh),
TileHighByte => { TileHigh => {
let obj_size = self.ctrl.obj_size(); let obj_size = self.ctrl.obj_size();
let addr = PixelFetcher::get_obj_addr(&attr, &self.pos, obj_size); let addr = PixelFetcher::get_obj_addr(&attr, &self.pos, obj_size);
@@ -274,10 +277,10 @@ impl Ppu {
let byte = self.read_byte(addr + 1); let byte = self.read_byte(addr + 1);
self.fetch.obj.tile.with_high_byte(byte); self.fetch.obj.tile.with_high_byte(byte);
self.fetch.obj.next(ToFifoSleep); self.fetch.obj.next(SleepThree);
} }
ToFifoSleep => self.fetch.obj.next(SendToFifoOne), SleepThree => self.fetch.obj.next(ToFifoOne),
SendToFifoOne => { ToFifoOne => {
// Load into Fifo // Load into Fifo
let (high, low) = self let (high, low) = self
.fetch .fetch
@@ -289,13 +292,12 @@ impl Ppu {
let tbpp = Pixels::from_bytes(high, low); let tbpp = Pixels::from_bytes(high, low);
let palette_kind = attr.flags.palette(); let palette_kind = attr.flags.palette();
let end = Pixels::PIXEL_COUNT - self.fifo.obj.len();
let start = Pixels::PIXEL_COUNT - end;
let x_flip = attr.flags.x_flip(); let x_flip = attr.flags.x_flip();
for i in start..Pixels::PIXEL_COUNT { let pixel_count = (attr.x - self.x_pos) as usize;
let start = self.fifo.obj.len();
for i in start..pixel_count {
let x = if x_flip { 7 - i } else { i }; let x = if x_flip { 7 - i } else { i };
let priority = attr.flags.priority(); let priority = attr.flags.priority();
@@ -312,11 +314,11 @@ impl Ppu {
self.fetch.back.resume(); self.fetch.back.resume();
self.fifo.resume(); self.fifo.resume();
self.obj_buffer.remove(&attr); let _ = std::mem::take(obj_attr);
self.fetch.obj.next(SendToFifoTwo); self.fetch.obj.next(ToFifoTwo);
} }
SendToFifoTwo => self.fetch.obj.reset(), ToFifoTwo => self.fetch.obj.reset(),
} }
} }
@@ -346,31 +348,31 @@ impl Ppu {
self.fetch.back.tile.with_id(id); self.fetch.back.tile.with_id(id);
// Move on to the Next state in 2 T-cycles // Move on to the Next state in 2 T-cycles
self.fetch.back.next(ToLowByteSleep); self.fetch.back.next(SleepOne);
} }
ToLowByteSleep => self.fetch.back.next(TileLowByte), SleepOne => self.fetch.back.next(TileLow),
TileLowByte => { TileLow => {
let addr = self.fetch.bg_byte_addr(&self.ctrl, &self.pos); let addr = self.fetch.bg_byte_addr(&self.ctrl, &self.pos);
let low = self.read_byte(addr); let low = self.read_byte(addr);
self.fetch.back.tile.with_low_byte(low); self.fetch.back.tile.with_low_byte(low);
self.fetch.back.next(ToHighByteSleep); self.fetch.back.next(SleepTwo);
} }
ToHighByteSleep => self.fetch.back.next(TileHighByte), SleepTwo => self.fetch.back.next(TileHigh),
TileHighByte => { TileHigh => {
let addr = self.fetch.bg_byte_addr(&self.ctrl, &self.pos); let addr = self.fetch.bg_byte_addr(&self.ctrl, &self.pos);
let high = self.read_byte(addr + 1); let high = self.read_byte(addr + 1);
self.fetch.back.tile.with_high_byte(high); self.fetch.back.tile.with_high_byte(high);
self.fetch.back.next(ToFifoSleep); self.fetch.back.next(SleepThree);
} }
ToFifoSleep => self.fetch.back.next(SendToFifoOne), SleepThree => self.fetch.back.next(ToFifoOne),
SendToFifoOne => { ToFifoOne => {
self.fetch.back.next(SendToFifoTwo); self.fetch.back.next(ToFifoTwo);
} }
SendToFifoTwo => { ToFifoTwo => {
if let Ok(()) = self.fetch.send_to_fifo(&mut self.fifo) { if let Ok(()) = self.fetch.send_to_fifo(&mut self.fifo) {
self.fetch.x_pos += 1; self.fetch.x_pos += 1;
self.fetch.back.next(TileNumber); self.fetch.back.next(TileNumber);
@@ -381,12 +383,12 @@ impl Ppu {
} }
if self.fifo.is_enabled() { if self.fifo.is_enabled() {
if self.x_pos == 0 && !self.fifo.back.is_empty() && self.scanline_start { if self.x_pos == 0 && self.scanline_start {
self.to_discard = self.pos.scroll_x % 8; self.to_discard = self.pos.scroll_x % 8;
self.scanline_start = false; self.scanline_start = false;
} }
if self.to_discard > 0 { if self.to_discard > 0 && !self.fifo.back.is_empty() {
let _ = self.fifo.back.pop_front(); let _ = self.fifo.back.pop_front();
self.to_discard -= 1; self.to_discard -= 1;
@@ -416,8 +418,8 @@ impl Ppu {
self.frame_buf.swap_with_slice(&mut blank); self.frame_buf.swap_with_slice(&mut blank);
} }
pub fn copy_to_gui(&self, frame: &mut [u8]) { pub(crate) fn frame_buf(&self) -> &[u8; GB_HEIGHT * GB_WIDTH * 4] {
frame.copy_from_slice(self.frame_buf.as_ref()); &self.frame_buf
} }
fn clock_fifo(&mut self) -> Option<GrayShade> { fn clock_fifo(&mut self) -> Option<GrayShade> {
@@ -468,7 +470,7 @@ impl Default for Ppu {
fn default() -> Self { fn default() -> Self {
Self { Self {
vram: Box::new([0u8; VRAM_SIZE]), vram: Box::new([0u8; VRAM_SIZE]),
cycle: Cycle::new(0), cycle: Default::default(),
frame_buf: Box::new([0; GB_WIDTH * GB_HEIGHT * 4]), frame_buf: Box::new([0; GB_WIDTH * GB_HEIGHT * 4]),
int: Default::default(), int: Default::default(),
ctrl: Default::default(), ctrl: Default::default(),
@@ -608,67 +610,34 @@ impl<'a> From<&'a [u8; 4]> for ObjectAttribute {
#[derive(Debug)] #[derive(Debug)]
struct ObjectBuffer { struct ObjectBuffer {
buf: [Option<ObjectAttribute>; OBJECT_LIMIT], inner: [Option<ObjectAttribute>; OBJECT_LIMIT],
len: usize, len: usize,
} }
impl ObjectBuffer {
fn iter(&self) -> std::slice::Iter<'_, Option<ObjectAttribute>> {
self.into_iter()
}
}
impl<'a> IntoIterator for &'a ObjectBuffer {
type Item = &'a Option<ObjectAttribute>;
type IntoIter = std::slice::Iter<'a, Option<ObjectAttribute>>;
fn into_iter(self) -> Self::IntoIter {
self.buf.iter()
}
}
impl<'a> IntoIterator for &'a mut ObjectBuffer {
type Item = &'a Option<ObjectAttribute>;
type IntoIter = std::slice::Iter<'a, Option<ObjectAttribute>>;
fn into_iter(self) -> Self::IntoIter {
self.buf.iter()
}
}
impl ObjectBuffer { impl ObjectBuffer {
fn is_full(&self) -> bool { fn is_full(&self) -> bool {
self.len == OBJECT_LIMIT self.len == OBJECT_LIMIT
} }
fn clear(&mut self) { fn clear(&mut self) {
self.buf = [Default::default(); 10]; self.inner = [Default::default(); 10];
self.len = 0; self.len = 0;
} }
fn add(&mut self, attr: ObjectAttribute) { fn add(&mut self, attr: ObjectAttribute) {
self.buf[self.len] = Some(attr); self.inner[self.len] = Some(attr);
self.len += 1; self.len += 1;
} }
fn remove(&mut self, attr: &ObjectAttribute) { fn iter_mut(&mut self) -> std::slice::IterMut<'_, Option<ObjectAttribute>> {
let maybe_index = self.buf.iter().position(|maybe_attr| match maybe_attr { self.inner.iter_mut()
Some(other_attr) => attr == other_attr,
None => false,
});
if let Some(i) = maybe_index {
self.buf[i] = None;
}
} }
} }
impl Default for ObjectBuffer { impl Default for ObjectBuffer {
fn default() -> Self { fn default() -> Self {
Self { Self {
buf: [Default::default(); OBJECT_LIMIT], inner: [Default::default(); OBJECT_LIMIT],
len: Default::default(), len: Default::default(),
} }
} }
@@ -903,13 +872,13 @@ impl WindowLineCounter {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum FetcherState { enum FetcherState {
TileNumber, TileNumber,
ToLowByteSleep, SleepOne,
TileLowByte, TileLow,
ToHighByteSleep, SleepTwo,
TileHighByte, TileHigh,
ToFifoSleep, SleepThree,
SendToFifoOne, ToFifoOne,
SendToFifoTwo, ToFifoTwo,
} }
impl Default for FetcherState { impl Default for FetcherState {

View File

@@ -1,4 +1,4 @@
use crate::instruction::cycle::Cycle; use crate::Cycle;
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(crate) struct DirectMemoryAccess { pub(crate) struct DirectMemoryAccess {
@@ -9,7 +9,7 @@ pub(crate) struct DirectMemoryAccess {
} }
impl DirectMemoryAccess { impl DirectMemoryAccess {
pub(crate) fn clock(&mut self) -> Option<(u16, u16)> { pub(crate) fn tick(&mut self) -> Option<(u16, u16)> {
match self.state { match self.state {
DmaState::Pending => { DmaState::Pending => {
self.cycle += 1; self.cycle += 1;
@@ -56,7 +56,7 @@ impl DirectMemoryAccess {
} }
fn reset(&mut self) { fn reset(&mut self) {
self.cycle = Cycle::new(0); self.cycle = 0;
self.state = DmaState::Disabled; self.state = DmaState::Disabled;
self.start.0 = None; self.start.0 = None;
} }

79
src/scheduler.rs Normal file
View File

@@ -0,0 +1,79 @@
use crate::Cycle;
use std::collections::BinaryHeap;
#[derive(Debug)]
pub(crate) struct Scheduler {
timestamp: Cycle,
queue: BinaryHeap<Event>,
}
impl Scheduler {
pub(crate) fn init() -> Self {
let mut scheduler = Self {
timestamp: Default::default(),
queue: Default::default(),
};
scheduler.push(Event {
kind: EventKind::TimestampOverflow,
timestamp: Cycle::MAX,
cb: |_delay| panic!("Reached Cycle::MAX"),
});
scheduler
}
pub(crate) fn push(&mut self, event: Event) {
self.queue.push(event);
}
pub(crate) fn step(&mut self, cycles: Cycle) {
self.timestamp += cycles;
loop {
let should_pop = match self.queue.peek() {
Some(event) => self.timestamp >= event.timestamp,
None => false,
};
if !should_pop {
break;
}
let event = self.queue.pop().expect("Pop Event from Scheduler Queue");
(event.cb)(self.timestamp - event.timestamp);
}
}
}
#[derive(Debug)]
pub(crate) struct Event {
kind: EventKind,
cb: fn(Cycle),
pub(crate) timestamp: Cycle,
}
impl Eq for Event {}
impl PartialEq for Event {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind && self.timestamp == other.timestamp
}
}
impl PartialOrd for Event {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Event {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.timestamp.cmp(&other.timestamp)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EventKind {
TimestampOverflow,
}

View File

@@ -5,19 +5,33 @@ pub(crate) struct Timer {
/// 0xFF07 | TAC - Timer Control /// 0xFF07 | TAC - Timer Control
pub(crate) ctrl: TimerControl, pub(crate) ctrl: TimerControl,
/// 0xFF05 | TIMA - Timer Counter /// 0xFF05 | TIMA - Timer Counter
pub(crate) counter: u8, counter: u8,
/// 0xFF06 | TMA - Timer Modulo /// 0xFF06 | TMA - Timer Modulo
pub(crate) modulo: u8, pub(crate) modulo: u8,
/// 0xFF04 | DIV - Divider Register /// 0xFF04 | DIV - Divider Register
pub(crate) divider: u16, pub(crate) divider: u16,
prev_and_result: Option<u8>,
and_result: Option<u8>,
interrupt: bool, interrupt: bool,
state: State,
} }
impl Timer { impl Timer {
pub(crate) fn clock(&mut self) { pub(crate) fn tick(&mut self) {
use State::*;
use TimerSpeed::*; use TimerSpeed::*;
match self.state {
TIMAOverflow(_) | AbortedTIMAOverflow(_) => self.next(),
LoadTMA => {
self.counter = self.modulo;
self.interrupt = true;
self.next();
}
Normal => {}
}
self.divider = self.divider.wrapping_add(1); self.divider = self.divider.wrapping_add(1);
// Get Bit Position // Get Bit Position
@@ -29,27 +43,34 @@ impl Timer {
}; };
let bit = (self.divider >> bit) as u8 & 0x01; let bit = (self.divider >> bit) as u8 & 0x01;
let timer_enable = self.ctrl.enabled() as u8; let new_result = bit & self.ctrl.enabled() as u8;
let and_result = bit & timer_enable;
if let Some(0x01) = self.prev_and_result { if let Some(0x01) = self.and_result {
if and_result == 0x00 { if new_result == 0x00 {
// Falling Edge, increase TIMA Register // Falling Edge, increase TIMA Register
self.increment_tima(); self.inc_counter();
} }
} }
self.prev_and_result = Some(and_result); self.and_result = Some(new_result);
} }
fn increment_tima(&mut self) { /// 0xFF05 | TIMA - Timer Counter
let (result, did_overflow) = self.counter.overflowing_add(1); pub(crate) fn tima(&self) -> u8 {
self.counter
}
self.counter = if did_overflow { /// 0xFF05 | TIMA - Timer Counter
self.interrupt = true; pub(crate) fn set_tima(&mut self, byte: u8) {
self.modulo use State::*;
} else {
result match self.state {
Normal | AbortedTIMAOverflow(_) => self.counter = byte,
TIMAOverflow(step) => {
self.counter = byte;
self.state = AbortedTIMAOverflow(step);
}
LoadTMA => {}
} }
} }
@@ -60,6 +81,27 @@ impl Timer {
pub(crate) fn set_interrupt(&mut self, value: bool) { pub(crate) fn set_interrupt(&mut self, value: bool) {
self.interrupt = value; self.interrupt = value;
} }
fn inc_counter(&mut self) {
let (sum, did_overflow) = self.counter.overflowing_add(1);
self.counter = if did_overflow { 0 } else { sum };
if did_overflow {
self.state = State::TIMAOverflow(0);
}
}
fn next(&mut self) {
use State::*;
self.state = match self.state {
Normal | LoadTMA => Normal,
AbortedTIMAOverflow(4) => Normal,
TIMAOverflow(4) => LoadTMA,
AbortedTIMAOverflow(step) => AbortedTIMAOverflow(step + 1),
TIMAOverflow(step) => TIMAOverflow(step + 1),
}
}
} }
impl Default for Timer { impl Default for Timer {
@@ -70,7 +112,8 @@ impl Default for Timer {
modulo: 0, modulo: 0,
divider: 0, divider: 0,
interrupt: false, interrupt: false,
prev_and_result: None, and_result: None,
state: State::Normal,
} }
} }
} }
@@ -132,3 +175,11 @@ impl From<TimerControl> for u8 {
ctrl.0 ctrl.0
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
TIMAOverflow(u8),
AbortedTIMAOverflow(u8),
Normal,
LoadTMA,
}

View File

@@ -28,48 +28,25 @@ impl Default for WorkRam {
} }
} }
#[derive(Debug, Clone, Copy)]
enum BankNumber {
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
}
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct VariableWorkRam { pub(crate) struct VariableWorkRam {
current: BankNumber, buf: Box<[u8; VARIABLE_WORK_RAM_SIZE]>, // 4K for Variable amount of Banks (Banks 1 -> 7) in Game Boy Colour
bank_n: Box<[[u8; VARIABLE_WORK_RAM_SIZE]; 7]>, // 4K for Variable amount of Banks (Banks 1 -> 7) in Game Boy Colour
} }
impl Default for VariableWorkRam { impl Default for VariableWorkRam {
fn default() -> Self { fn default() -> Self {
Self { Self {
current: BankNumber::One, buf: Box::new([0u8; VARIABLE_WORK_RAM_SIZE]),
bank_n: Box::new([[0u8; VARIABLE_WORK_RAM_SIZE]; 7]),
} }
} }
} }
impl VariableWorkRam {
fn set_current_bank(&mut self, bank: BankNumber) {
self.current = bank;
}
fn get_current_bank(&self) -> &BankNumber {
&self.current
}
}
impl BusIo for VariableWorkRam { impl BusIo for VariableWorkRam {
fn write_byte(&mut self, addr: u16, byte: u8) { fn write_byte(&mut self, addr: u16, byte: u8) {
self.bank_n[self.current as usize][addr as usize - VARIABLE_WORK_RAM_START_ADDRESS] = byte; self.buf[addr as usize - VARIABLE_WORK_RAM_START_ADDRESS] = byte;
} }
fn read_byte(&self, addr: u16) -> u8 { fn read_byte(&self, addr: u16) -> u8 {
self.bank_n[self.current as usize][addr as usize - VARIABLE_WORK_RAM_START_ADDRESS] self.buf[addr as usize - VARIABLE_WORK_RAM_START_ADDRESS]
} }
} }