Skip to main content

ControllerState

Struct ControllerState 

Source
pub struct ControllerState { /* private fields */ }

Implementations§

Source§

impl ControllerState

Source

pub const fn new() -> Self

Examples found in repository?
examples/analyze_audio.rs (line 13)
7fn main() {
8    let rom_path = env::args().nth(1).expect("Usage: analyze_audio <rom-path>");
9    let rom = fs::read(&rom_path).expect("Failed to read ROM");
10    let mut runtime = FrontendRuntime::from_rom_bytes(&rom).expect("Failed to load ROM");
11
12    let input = FrontendInput {
13        controller1: ControllerState::new(),
14        ..Default::default()
15    };
16
17    // 运行几秒收集样本
18    let mut all_samples = Vec::new();
19    for _ in 0..300 {
20        let snapshot = runtime.step(input);
21        all_samples.extend_from_slice(snapshot.audio.samples);
22    }
23
24    // 分析
25    let min = all_samples.iter().cloned().reduce(f32::min).unwrap();
26    let max = all_samples.iter().cloned().reduce(f32::max).unwrap();
27    let avg = all_samples.iter().sum::<f32>() / all_samples.len() as f32;
28
29    // 计算方差(噪声水平)
30    let variance =
31        all_samples.iter().map(|&x| (x - avg).powi(2)).sum::<f32>() / all_samples.len() as f32;
32    let std_dev = variance.sqrt();
33
34    // 统计接近静音的样本
35    let near_zero_count = all_samples.iter().filter(|&&x| x.abs() < 1e-6).count();
36    let near_zero_ratio = near_zero_count as f32 / all_samples.len() as f32;
37
38    println!("=== 音频样本分析 ===");
39    println!("样本总数: {}", all_samples.len());
40    println!("最小值: {:.6}", min);
41    println!("最大值: {:.6}", max);
42    println!("平均值: {:.6}", avg);
43    println!("标准差 (噪声水平): {:.6}", std_dev);
44    println!(
45        "接近静音的样本 (<1e-6): {} ({:.2}%)",
46        near_zero_count,
47        near_zero_ratio * 100.0
48    );
49
50    // 找出典型静音期间的噪声范围
51    let mut silent_samples: Vec<f32> = all_samples
52        .iter()
53        .filter(|&&x| x.abs() < 0.001)
54        .copied()
55        .collect();
56    silent_samples.sort_by(|a, b| a.abs().partial_cmp(&b.abs()).unwrap());
57    if silent_samples.len() > 100 {
58        let quiet_max = silent_samples[silent_samples.len() / 2 + 50]; // 取中位数附近的最大值
59        println!("静音期间典型噪声范围: ±{:.6}", quiet_max);
60    }
61
62    // 保存所有样本供可视化(默认最多保存 10 秒)
63    let sample_rate = runtime.snapshot().audio.sample_rate;
64    let max_samples = (sample_rate as usize) * 10; // 最多 10 秒
65    let wav_samples = &all_samples[..max_samples.min(all_samples.len())];
66    let wav_path = Path::new(&rom_path).with_extension("wav");
67    write_wav(&wav_path, wav_samples, sample_rate);
68    println!(
69        "已保存 {} 个样本 (约 {:.1} 秒) 到: {}",
70        wav_samples.len(),
71        wav_samples.len() as f32 / sample_rate as f32,
72        wav_path.display()
73    );
74}
More examples
Hide additional examples
examples/analyze_state.rs (line 138)
68fn main() -> ExitCode {
69    let mut args = env::args();
70    let program = args.next().unwrap_or_else(|| "analyze_state".to_string());
71
72    let Some(rom_path) = args.next() else {
73        usage(&program);
74        return ExitCode::from(2);
75    };
76    let Some(state_path) = args.next() else {
77        usage(&program);
78        return ExitCode::from(2);
79    };
80    let frames = match args.next() {
81        Some(value) => match value.parse::<usize>() {
82            Ok(frames) => frames,
83            Err(error) => {
84                eprintln!("invalid frame count {value:?}: {error}");
85                return ExitCode::from(2);
86            }
87        },
88        None => 240,
89    };
90    let input_mode = args.next().unwrap_or_else(|| "none".to_string());
91    let out_dir = args.next();
92
93    let rom = match std::fs::read(&rom_path) {
94        Ok(rom) => rom,
95        Err(error) => {
96            eprintln!("failed to read ROM {rom_path:?}: {error}");
97            return ExitCode::from(1);
98        }
99    };
100    let state = match std::fs::read(&state_path) {
101        Ok(state) => state,
102        Err(error) => {
103            eprintln!("failed to read state {state_path:?}: {error}");
104            return ExitCode::from(1);
105        }
106    };
107
108    let mut nes = NES::new();
109    if let Err(error) = nes.load_cartridge_ines(&rom) {
110        eprintln!("failed to load ROM {rom_path:?}: {error}");
111        return ExitCode::from(1);
112    }
113    if let Err(error) = nes.load_state(&state) {
114        eprintln!("failed to load state {state_path:?}: {error}");
115        return ExitCode::from(1);
116    }
117
118    let mut prev = nes.frame_pixels().to_vec();
119    let mut prev_hash = stable_byte_hash(&frame_to_ppm(nes.video_frame()));
120    let mut same_hash_run = 0usize;
121    println!(
122        "start frame={} hash=0x{:016X}",
123        nes.frame_number(),
124        prev_hash
125    );
126
127    if let Some(ref out_dir) = out_dir {
128        if !out_dir.is_empty() {
129            let path = Path::new(out_dir);
130            if let Err(error) = std::fs::create_dir_all(path) {
131                eprintln!("failed to create output directory {:?}: {}", path, error);
132                return ExitCode::from(1);
133            }
134        }
135    }
136
137    for i in 1..=frames {
138        let mut controller = ControllerState::new();
139        if input_mode == "right" || input_mode == "right_a" {
140            controller.set_pressed(ControllerButton::Right, true);
141        }
142        if input_mode == "right_a" {
143            controller.set_pressed(ControllerButton::A, true);
144        }
145        nes.set_controller_state(0, controller);
146        nes.run_frame();
147        let frame = nes.frame_pixels().to_vec();
148        let hash = stable_byte_hash(&frame_to_ppm(nes.video_frame()));
149        let changed_all = changed_pixels(&prev, &frame);
150        let changed_top_hud = changed_pixels_region(&prev, &frame, 0, 48);
151        let changed_bottom_hud = changed_pixels_region(&prev, &frame, 208, 240);
152        let changed_gameplay = changed_pixels_region(&prev, &frame, 48, 208);
153        let debug = nes.debug_snapshot();
154
155        if hash == prev_hash {
156            same_hash_run += 1;
157        } else {
158            same_hash_run = 0;
159        }
160
161        if let Some((min_x, min_y, max_x, max_y)) = changed_bbox(&prev, &frame) {
162            println!(
163                "i={} frame={} hash=0x{:016X} changed_all={} changed_top_hud={} changed_bottom_hud={} changed_gameplay={} bbox=({},{})->({},{}) same_hash_run={} pc={:04X} ppu_scanline={} in_vblank={}",
164                i,
165                nes.frame_number(),
166                hash,
167                changed_all,
168                changed_top_hud,
169                changed_bottom_hud,
170                changed_gameplay,
171                min_x,
172                min_y,
173                max_x,
174                max_y,
175                same_hash_run,
176                debug.cpu.pc,
177                debug.ppu.scanline,
178                debug.ppu.in_vblank
179            );
180        } else {
181            println!(
182                "i={} frame={} hash=0x{:016X} changed_all=0 changed_top_hud=0 changed_bottom_hud=0 changed_gameplay=0 bbox=none same_hash_run={} pc={:04X} ppu_scanline={} in_vblank={}",
183                i,
184                nes.frame_number(),
185                hash,
186                same_hash_run,
187                debug.cpu.pc,
188                debug.ppu.scanline,
189                debug.ppu.in_vblank
190            );
191        }
192
193        if let Some(ref out_dir) = out_dir
194            && !out_dir.is_empty()
195            && (i <= 8 || same_hash_run >= 30 || i % 60 == 0)
196        {
197            let ppm = frame_to_ppm(nes.video_frame());
198            let output = Path::new(out_dir).join(format!("frame_{:04}.ppm", i));
199            if let Err(error) = std::fs::write(&output, ppm) {
200                eprintln!("failed to write {:?}: {}", output, error);
201                return ExitCode::from(1);
202            }
203        }
204
205        prev = frame;
206        prev_hash = hash;
207    }
208
209    ExitCode::SUCCESS
210}
Source

pub const fn from_bits(bits: u8) -> Self

Source

pub const fn bits(self) -> u8

Source

pub const fn pressed(self, button: ControllerButton) -> bool

Source

pub fn set_pressed(&mut self, button: ControllerButton, pressed: bool)

Examples found in repository?
examples/analyze_state.rs (line 140)
68fn main() -> ExitCode {
69    let mut args = env::args();
70    let program = args.next().unwrap_or_else(|| "analyze_state".to_string());
71
72    let Some(rom_path) = args.next() else {
73        usage(&program);
74        return ExitCode::from(2);
75    };
76    let Some(state_path) = args.next() else {
77        usage(&program);
78        return ExitCode::from(2);
79    };
80    let frames = match args.next() {
81        Some(value) => match value.parse::<usize>() {
82            Ok(frames) => frames,
83            Err(error) => {
84                eprintln!("invalid frame count {value:?}: {error}");
85                return ExitCode::from(2);
86            }
87        },
88        None => 240,
89    };
90    let input_mode = args.next().unwrap_or_else(|| "none".to_string());
91    let out_dir = args.next();
92
93    let rom = match std::fs::read(&rom_path) {
94        Ok(rom) => rom,
95        Err(error) => {
96            eprintln!("failed to read ROM {rom_path:?}: {error}");
97            return ExitCode::from(1);
98        }
99    };
100    let state = match std::fs::read(&state_path) {
101        Ok(state) => state,
102        Err(error) => {
103            eprintln!("failed to read state {state_path:?}: {error}");
104            return ExitCode::from(1);
105        }
106    };
107
108    let mut nes = NES::new();
109    if let Err(error) = nes.load_cartridge_ines(&rom) {
110        eprintln!("failed to load ROM {rom_path:?}: {error}");
111        return ExitCode::from(1);
112    }
113    if let Err(error) = nes.load_state(&state) {
114        eprintln!("failed to load state {state_path:?}: {error}");
115        return ExitCode::from(1);
116    }
117
118    let mut prev = nes.frame_pixels().to_vec();
119    let mut prev_hash = stable_byte_hash(&frame_to_ppm(nes.video_frame()));
120    let mut same_hash_run = 0usize;
121    println!(
122        "start frame={} hash=0x{:016X}",
123        nes.frame_number(),
124        prev_hash
125    );
126
127    if let Some(ref out_dir) = out_dir {
128        if !out_dir.is_empty() {
129            let path = Path::new(out_dir);
130            if let Err(error) = std::fs::create_dir_all(path) {
131                eprintln!("failed to create output directory {:?}: {}", path, error);
132                return ExitCode::from(1);
133            }
134        }
135    }
136
137    for i in 1..=frames {
138        let mut controller = ControllerState::new();
139        if input_mode == "right" || input_mode == "right_a" {
140            controller.set_pressed(ControllerButton::Right, true);
141        }
142        if input_mode == "right_a" {
143            controller.set_pressed(ControllerButton::A, true);
144        }
145        nes.set_controller_state(0, controller);
146        nes.run_frame();
147        let frame = nes.frame_pixels().to_vec();
148        let hash = stable_byte_hash(&frame_to_ppm(nes.video_frame()));
149        let changed_all = changed_pixels(&prev, &frame);
150        let changed_top_hud = changed_pixels_region(&prev, &frame, 0, 48);
151        let changed_bottom_hud = changed_pixels_region(&prev, &frame, 208, 240);
152        let changed_gameplay = changed_pixels_region(&prev, &frame, 48, 208);
153        let debug = nes.debug_snapshot();
154
155        if hash == prev_hash {
156            same_hash_run += 1;
157        } else {
158            same_hash_run = 0;
159        }
160
161        if let Some((min_x, min_y, max_x, max_y)) = changed_bbox(&prev, &frame) {
162            println!(
163                "i={} frame={} hash=0x{:016X} changed_all={} changed_top_hud={} changed_bottom_hud={} changed_gameplay={} bbox=({},{})->({},{}) same_hash_run={} pc={:04X} ppu_scanline={} in_vblank={}",
164                i,
165                nes.frame_number(),
166                hash,
167                changed_all,
168                changed_top_hud,
169                changed_bottom_hud,
170                changed_gameplay,
171                min_x,
172                min_y,
173                max_x,
174                max_y,
175                same_hash_run,
176                debug.cpu.pc,
177                debug.ppu.scanline,
178                debug.ppu.in_vblank
179            );
180        } else {
181            println!(
182                "i={} frame={} hash=0x{:016X} changed_all=0 changed_top_hud=0 changed_bottom_hud=0 changed_gameplay=0 bbox=none same_hash_run={} pc={:04X} ppu_scanline={} in_vblank={}",
183                i,
184                nes.frame_number(),
185                hash,
186                same_hash_run,
187                debug.cpu.pc,
188                debug.ppu.scanline,
189                debug.ppu.in_vblank
190            );
191        }
192
193        if let Some(ref out_dir) = out_dir
194            && !out_dir.is_empty()
195            && (i <= 8 || same_hash_run >= 30 || i % 60 == 0)
196        {
197            let ppm = frame_to_ppm(nes.video_frame());
198            let output = Path::new(out_dir).join(format!("frame_{:04}.ppm", i));
199            if let Err(error) = std::fs::write(&output, ppm) {
200                eprintln!("failed to write {:?}: {}", output, error);
201                return ExitCode::from(1);
202            }
203        }
204
205        prev = frame;
206        prev_hash = hash;
207    }
208
209    ExitCode::SUCCESS
210}

Trait Implementations§

Source§

impl Clone for ControllerState

Source§

fn clone(&self) -> ControllerState

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for ControllerState

Source§

impl Debug for ControllerState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ControllerState

Source§

fn default() -> ControllerState

Returns the “default value” for a type. Read more
Source§

impl Eq for ControllerState

Source§

impl PartialEq for ControllerState

Source§

fn eq(&self, other: &ControllerState) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for ControllerState

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.