Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec7a89d9da | ||
|
|
a6c12a986c | ||
|
|
762f43fd42 | ||
|
|
3a00497942 | ||
|
|
1d4c6c9e88 | ||
|
|
4f3dc85bb4 | ||
|
|
644e99c295 | ||
|
|
1ff4fda55b | ||
|
|
76b7e9d6ec | ||
|
|
e15659f6d2 | ||
|
|
a926f19f79 | ||
|
|
8ed1019b44 | ||
|
|
ff8353cacc | ||
|
|
0a8663a010 | ||
|
|
05d00eee5a |
Generated
+31
-1
@@ -232,6 +232,9 @@ name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "as-raw-xcb-connection"
|
||||
@@ -1571,6 +1574,8 @@ dependencies = [
|
||||
"allocator-api2",
|
||||
"equivalent",
|
||||
"foldhash 0.2.0",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2029,7 +2034,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "lemur"
|
||||
version = "0.13.1"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"atoi",
|
||||
@@ -2238,6 +2243,22 @@ dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "macro_rules_attribute"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c"
|
||||
dependencies = [
|
||||
"macro_rules_attribute-proc_macro",
|
||||
"pastey",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "macro_rules_attribute-proc_macro"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
@@ -2999,6 +3020,12 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "pdb-addr2line"
|
||||
version = "0.11.2"
|
||||
@@ -5094,6 +5121,7 @@ dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"indexmap",
|
||||
"log",
|
||||
"macro_rules_attribute",
|
||||
"naga",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
@@ -5101,6 +5129,7 @@ dependencies = [
|
||||
"profiling",
|
||||
"raw-window-handle",
|
||||
"rustc-hash 1.1.0",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"thiserror 2.0.18",
|
||||
"wgpu-core-deps-apple",
|
||||
@@ -5223,6 +5252,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
"serde",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@ description = "An emulator for the Virtual Boy."
|
||||
repository = "https://git.virtual-boy.com/PVB/lemur"
|
||||
publish = false
|
||||
license = "MIT"
|
||||
version = "0.13.1"
|
||||
version = "0.15.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -44,9 +44,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thread-priority = "3"
|
||||
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] }
|
||||
tracing = { version = "0.1", features = ["release_max_level_info"] }
|
||||
tracing = { version = "0.1", features = ["release_max_level_debug"] }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
wgpu = "29"
|
||||
wgpu = { version = "29", features = ["serde"] }
|
||||
wholesym = "0.8"
|
||||
winit = { version = "0.30", features = ["serde"] }
|
||||
|
||||
|
||||
+100
-53
@@ -14,16 +14,16 @@ use egui::{
|
||||
use egui_wgpu::winit::Painter;
|
||||
use egui_winit::EventResponse;
|
||||
use gilrs::{EventType, Gilrs};
|
||||
use tracing::{error, warn};
|
||||
use tracing::{debug, error, warn};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::WindowEvent,
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy, OwnedDisplayHandle},
|
||||
window::{Window, WindowId},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::CliArgs,
|
||||
config::{AppConfig, CliArgs},
|
||||
controller::ControllerManager,
|
||||
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
||||
images::ImageTextureLoader,
|
||||
@@ -48,9 +48,30 @@ fn load_icon() -> anyhow::Result<IconData> {
|
||||
|
||||
struct SharedViewportState {
|
||||
viewport_info: ViewportIdMap<ViewportInfo>,
|
||||
painter: Painter,
|
||||
wgpu: WgpuState,
|
||||
painter: Option<Painter>,
|
||||
resized_viewport: Option<ViewportId>,
|
||||
}
|
||||
impl SharedViewportState {
|
||||
fn init_painter(&mut self, ctx: &Context, window: &Window) -> &mut Painter {
|
||||
if self.painter.is_none() {
|
||||
let wgpu_config = egui_wgpu::WgpuConfiguration {
|
||||
present_mode: wgpu::PresentMode::AutoVsync,
|
||||
wgpu_setup: egui_wgpu::WgpuSetup::Existing(self.wgpu.init(window)),
|
||||
..egui_wgpu::WgpuConfiguration::default()
|
||||
};
|
||||
|
||||
let options = egui_wgpu::RendererOptions::default();
|
||||
let painter =
|
||||
pollster::block_on(Painter::new(ctx.clone(), wgpu_config, false, options));
|
||||
self.painter = Some(painter);
|
||||
}
|
||||
self.painter.as_mut().unwrap()
|
||||
}
|
||||
fn get_painter(&mut self) -> &mut Painter {
|
||||
self.painter.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Application {
|
||||
client: EmulatorClient,
|
||||
@@ -70,10 +91,12 @@ impl Application {
|
||||
pub fn new(
|
||||
client: EmulatorClient,
|
||||
proxy: EventLoopProxy<UserEvent>,
|
||||
handle: OwnedDisplayHandle,
|
||||
persistence: Persistence,
|
||||
args: CliArgs,
|
||||
config: AppConfig,
|
||||
) -> Self {
|
||||
let wgpu = WgpuState::new();
|
||||
let wgpu = WgpuState::new(handle, config);
|
||||
let icon = load_icon().ok().map(Arc::new);
|
||||
let mappings = MappingProvider::new(persistence.clone(), args.player2_controller);
|
||||
let shortcuts = ShortcutProvider::new(persistence.clone());
|
||||
@@ -131,20 +154,6 @@ impl Application {
|
||||
});
|
||||
}
|
||||
|
||||
let wgpu_config = egui_wgpu::WgpuConfiguration {
|
||||
present_mode: wgpu::PresentMode::AutoVsync,
|
||||
wgpu_setup: egui_wgpu::WgpuSetup::Existing(egui_wgpu::WgpuSetupExisting {
|
||||
instance: wgpu.instance.clone(),
|
||||
adapter: wgpu.adapter.clone(),
|
||||
device: wgpu.device.clone(),
|
||||
queue: wgpu.queue.clone(),
|
||||
}),
|
||||
..egui_wgpu::WgpuConfiguration::default()
|
||||
};
|
||||
|
||||
let options = egui_wgpu::RendererOptions::default();
|
||||
let painter = pollster::block_on(Painter::new(ctx.clone(), wgpu_config, false, options));
|
||||
|
||||
let mut initial_windows = vec![];
|
||||
if let Some(port) = args.debug_port {
|
||||
initial_windows.push(ChildWindow::Debugger { port: Some(port) });
|
||||
@@ -184,7 +193,8 @@ impl Application {
|
||||
ctx,
|
||||
shared: SharedViewportState {
|
||||
viewport_info: ViewportIdMap::default(),
|
||||
painter,
|
||||
wgpu,
|
||||
painter: None,
|
||||
resized_viewport: None,
|
||||
},
|
||||
icon,
|
||||
@@ -289,7 +299,7 @@ impl Application {
|
||||
}
|
||||
let clipped_primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
|
||||
viewport.window.pre_present_notify();
|
||||
self.shared.painter.paint_and_update_textures(
|
||||
self.shared.get_painter().paint_and_update_textures(
|
||||
viewport.id,
|
||||
output.pixels_per_point,
|
||||
[0.0, 0.0, 0.0, 0.0],
|
||||
@@ -325,7 +335,11 @@ impl Application {
|
||||
id,
|
||||
InitArgs {
|
||||
window: &manager.window,
|
||||
render_state: &self.shared.painter.render_state().unwrap(),
|
||||
render_state: &self
|
||||
.shared
|
||||
.get_painter()
|
||||
.render_state()
|
||||
.unwrap(),
|
||||
},
|
||||
);
|
||||
manager
|
||||
@@ -341,7 +355,9 @@ impl Application {
|
||||
if !active_viewports.contains(&ViewportId::ROOT) {
|
||||
event_loop.exit();
|
||||
}
|
||||
self.shared.painter.gc_viewports(&active_viewports);
|
||||
if let Some(painter) = self.shared.painter.as_mut() {
|
||||
painter.gc_viewports(&active_viewports);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,7 +375,7 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||
viewport_builder,
|
||||
&mut self.shared,
|
||||
);
|
||||
let render_state = self.shared.painter.render_state().unwrap();
|
||||
let render_state = self.shared.get_painter().render_state().unwrap();
|
||||
GameScreen::init_pipeline(&render_state);
|
||||
self.app.handle_init(
|
||||
ViewportId::ROOT,
|
||||
@@ -408,6 +424,9 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||
{
|
||||
self.controllers.handle_key_event(&event);
|
||||
}
|
||||
WindowEvent::DroppedFile(path) => {
|
||||
self.app.handle_dropped_file(viewport_id, path);
|
||||
}
|
||||
WindowEvent::Focused(new_focused) => {
|
||||
self.focused = new_focused.then_some(viewport_id);
|
||||
}
|
||||
@@ -448,6 +467,9 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||
self.controllers.handle_gamepad_event(&event);
|
||||
}
|
||||
}
|
||||
UserEvent::LowBattery(sim_id, pwr) => {
|
||||
self.controllers.handle_low_battery(sim_id, pwr);
|
||||
}
|
||||
UserEvent::Quit(sim_id) => match sim_id {
|
||||
SimId::Player1 => event_loop.exit(),
|
||||
SimId::Player2 => self.app.close(ChildWindow::Player2),
|
||||
@@ -480,47 +502,66 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||
|
||||
struct WgpuState {
|
||||
instance: wgpu::Instance,
|
||||
adapter: wgpu::Adapter,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
device_descriptor: Arc<dyn Fn(&wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> + Send + Sync>,
|
||||
config: AppConfig,
|
||||
}
|
||||
|
||||
impl WgpuState {
|
||||
fn new() -> Self {
|
||||
fn new(handle: OwnedDisplayHandle, config: AppConfig) -> Self {
|
||||
#[allow(unused_variables)]
|
||||
let egui_wgpu::WgpuConfiguration {
|
||||
wgpu_setup:
|
||||
egui_wgpu::WgpuSetup::CreateNew(egui_wgpu::WgpuSetupCreateNew {
|
||||
let egui_wgpu::WgpuSetupCreateNew {
|
||||
instance_descriptor: wgpu::InstanceDescriptor { backends, .. },
|
||||
device_descriptor,
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = egui_wgpu::WgpuConfiguration::default()
|
||||
else {
|
||||
panic!("required fields not found")
|
||||
};
|
||||
} = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
|
||||
#[cfg(windows)]
|
||||
let backends = wgpu::Backends::from_env()
|
||||
.unwrap_or((wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN);
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends,
|
||||
..wgpu::InstanceDescriptor::new_without_display_handle_from_env()
|
||||
..wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(handle))
|
||||
});
|
||||
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference:
|
||||
wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::LowPower),
|
||||
compatible_surface: None,
|
||||
force_fallback_adapter: false,
|
||||
}))
|
||||
.expect("could not create adapter");
|
||||
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&(*device_descriptor)(&adapter)))
|
||||
.expect("could not request device");
|
||||
Self {
|
||||
instance,
|
||||
device_descriptor,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
fn init(&mut self, window: &Window) -> egui_wgpu::WgpuSetupExisting {
|
||||
let power_preference =
|
||||
wgpu::PowerPreference::from_env().unwrap_or(self.config.power_preference);
|
||||
debug!("power preference: {power_preference:?}");
|
||||
|
||||
let force_fallback_adapter = std::env::var("WGPU_FORCE_FALLBACK")
|
||||
.map_or(self.config.force_fallback, |f| {
|
||||
f.eq_ignore_ascii_case("true") || f.eq_ignore_ascii_case("1")
|
||||
});
|
||||
debug!("force fallback: {force_fallback_adapter}");
|
||||
|
||||
let surface = self
|
||||
.instance
|
||||
.create_surface(window)
|
||||
.expect("could not create surface");
|
||||
|
||||
let adapter =
|
||||
pollster::block_on(self.instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference,
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter,
|
||||
}))
|
||||
.expect("could not create adapter");
|
||||
debug!("selected adapter: {:?}", adapter.get_info());
|
||||
|
||||
drop(surface);
|
||||
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&(*self.device_descriptor)(&adapter)))
|
||||
.expect("could not request device");
|
||||
|
||||
egui_wgpu::WgpuSetupExisting {
|
||||
instance: self.instance.clone(),
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
@@ -544,14 +585,15 @@ impl ViewportManager {
|
||||
shared: &mut SharedViewportState,
|
||||
) -> Self {
|
||||
let window = Arc::new(egui_winit::create_window(ctx, event_loop, &builder).unwrap());
|
||||
pollster::block_on(shared.painter.set_window(viewport_id, Some(window.clone()))).unwrap();
|
||||
let painter = shared.init_painter(ctx, &window);
|
||||
pollster::block_on(painter.set_window(viewport_id, Some(window.clone()))).unwrap();
|
||||
let state = egui_winit::State::new(
|
||||
ctx.clone(),
|
||||
viewport_id,
|
||||
event_loop,
|
||||
Some(window.scale_factor() as f32),
|
||||
event_loop.system_theme(),
|
||||
shared.painter.max_texture_side(),
|
||||
painter.max_texture_side(),
|
||||
);
|
||||
|
||||
let mut info = ViewportInfo {
|
||||
@@ -588,9 +630,13 @@ impl ViewportManager {
|
||||
{
|
||||
if shared.resized_viewport != Some(self.id) {
|
||||
shared.resized_viewport = Some(self.id);
|
||||
shared.painter.on_window_resize_state_change(self.id, true);
|
||||
shared
|
||||
.get_painter()
|
||||
.on_window_resize_state_change(self.id, true);
|
||||
}
|
||||
shared.painter.on_window_resized(self.id, width, height);
|
||||
shared
|
||||
.get_painter()
|
||||
.on_window_resized(self.id, width, height);
|
||||
}
|
||||
let response = self.state.on_window_event(&self.window, event);
|
||||
let info = shared.viewport_info.get_mut(&self.id).unwrap();
|
||||
@@ -630,6 +676,7 @@ impl ViewportManager {
|
||||
pub enum UserEvent {
|
||||
GamepadEvent(gilrs::Event),
|
||||
Quit(SimId),
|
||||
LowBattery(SimId, bool),
|
||||
RequestRedraw(ViewportId, Instant),
|
||||
}
|
||||
|
||||
|
||||
+157
-16
@@ -1,12 +1,16 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use audioadapter_buffers::direct::InterleavedSlice;
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use cpal::{
|
||||
Device, FromSample, Sample, SampleFormat, SizedSample, StreamConfig,
|
||||
traits::{DeviceTrait, HostTrait, StreamTrait},
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use rubato::{Adjustable as _, Resampler};
|
||||
use tracing::warn;
|
||||
|
||||
pub struct Audio {
|
||||
struct CpalAudio {
|
||||
#[allow(unused)]
|
||||
stream: cpal::Stream,
|
||||
sampler: rubato::Async<f32>,
|
||||
@@ -17,19 +21,31 @@ pub struct Audio {
|
||||
|
||||
const VB_FREQUENCY: usize = 41700;
|
||||
|
||||
impl Audio {
|
||||
pub fn init() -> Result<Self> {
|
||||
impl CpalAudio {
|
||||
fn init() -> Result<Self> {
|
||||
let host = cpal::default_host();
|
||||
let Some(device) = host.default_output_device() else {
|
||||
bail!("No output device available");
|
||||
};
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.context("no output device available")?;
|
||||
let default_rate = device.default_output_config()?.sample_rate();
|
||||
let Some(config) = device.supported_output_configs()?.find(|c| {
|
||||
c.channels() == 2 && c.sample_format().is_float() && c.contains_rate(default_rate)
|
||||
}) else {
|
||||
bail!("No suitable output config available");
|
||||
};
|
||||
let mut config = config.with_max_sample_rate().config();
|
||||
|
||||
let supported_config = device
|
||||
.supported_output_configs()?
|
||||
.filter(|c| {
|
||||
c.contains_rate(default_rate)
|
||||
&& matches!(
|
||||
c.sample_format(),
|
||||
SampleFormat::F32
|
||||
| SampleFormat::F64
|
||||
| SampleFormat::I32
|
||||
| SampleFormat::I16
|
||||
)
|
||||
})
|
||||
.max_by(|a, b| a.cmp_default_heuristics(b))
|
||||
.context("no suitable output config available")?
|
||||
.with_sample_rate(default_rate);
|
||||
let mut config = supported_config.config();
|
||||
|
||||
let resample_ratio = config.sample_rate as f64 / VB_FREQUENCY as f64;
|
||||
let chunk_size = (834.0 * resample_ratio) as usize;
|
||||
let sampler = rubato::Async::new_poly(
|
||||
@@ -42,6 +58,23 @@ impl Audio {
|
||||
)?;
|
||||
config.buffer_size = cpal::BufferSize::Fixed(sampler.output_frames_max() as u32);
|
||||
|
||||
match supported_config.sample_format() {
|
||||
SampleFormat::F32 if config.channels == 2 => {
|
||||
Self::new_f32_stereo(device, config, sampler)
|
||||
}
|
||||
SampleFormat::F32 => Self::new::<f32>(device, config, sampler),
|
||||
SampleFormat::F64 => Self::new::<f64>(device, config, sampler),
|
||||
SampleFormat::I32 => Self::new::<i32>(device, config, sampler),
|
||||
SampleFormat::I16 => Self::new::<i16>(device, config, sampler),
|
||||
_ => bail!("unsupported sample format"),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_f32_stereo(
|
||||
device: Device,
|
||||
config: StreamConfig,
|
||||
sampler: rubato::Async<f32>,
|
||||
) -> Result<Self> {
|
||||
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
|
||||
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
|
||||
let (sample_sink, mut sample_source) =
|
||||
@@ -79,7 +112,60 @@ impl Audio {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update(&mut self, mut samples: &[f32]) {
|
||||
fn new<S: SizedSample + FromSample<f32>>(
|
||||
device: Device,
|
||||
config: StreamConfig,
|
||||
sampler: rubato::Async<f32>,
|
||||
) -> Result<Self> {
|
||||
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
|
||||
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
|
||||
let (sample_sink, mut sample_source) =
|
||||
rtrb::RingBuffer::new(sampler.output_frames_max() * 4);
|
||||
|
||||
let channels = config.channels as usize;
|
||||
|
||||
let stream = device.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [S], _| {
|
||||
let requested = data.len() * 2 / channels;
|
||||
let chunk = match sample_source.read_chunk(requested) {
|
||||
Ok(c) => c,
|
||||
Err(rtrb::chunks::ChunkError::TooFewSlots(n)) => {
|
||||
sample_source.read_chunk(n).unwrap()
|
||||
}
|
||||
};
|
||||
let (first, second) = chunk.as_slices();
|
||||
|
||||
let new_samples = first
|
||||
.iter()
|
||||
.chain(second)
|
||||
.map(|s: &f32| (*s).to_sample())
|
||||
.chunks(2);
|
||||
let buffer = data.iter_mut().chunks(channels);
|
||||
for (dst, samples) in buffer.into_iter().zip(&new_samples) {
|
||||
// channels beyond the first two are zeroed
|
||||
let src = samples.chain(std::iter::repeat(S::EQUILIBRIUM));
|
||||
for (d, s) in dst.zip(src) {
|
||||
*d = s;
|
||||
}
|
||||
}
|
||||
|
||||
chunk.commit_all();
|
||||
},
|
||||
move |error| warn!(%error, "stream error"),
|
||||
None,
|
||||
)?;
|
||||
stream.play()?;
|
||||
Ok(Self {
|
||||
stream,
|
||||
sampler,
|
||||
input_buffer,
|
||||
output_buffer,
|
||||
sample_sink,
|
||||
})
|
||||
}
|
||||
|
||||
fn update(&mut self, mut samples: &[f32]) {
|
||||
while self.input_buffer.len() + samples.len() >= self.sampler.input_frames_next() * 2 {
|
||||
let samples_needed =
|
||||
(self.sampler.input_frames_next() * 2).saturating_sub(self.input_buffer.len());
|
||||
@@ -117,9 +203,64 @@ impl Audio {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
|
||||
fn set_speed(&mut self, speed: f64) -> Result<()> {
|
||||
self.sampler
|
||||
.set_resample_ratio_relative(1.0 / speed, false)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct NoAudio {
|
||||
speed: f64,
|
||||
}
|
||||
|
||||
impl NoAudio {
|
||||
fn new() -> Self {
|
||||
Self { speed: 1.0 }
|
||||
}
|
||||
|
||||
fn update(&mut self, samples: &[f32]) {
|
||||
let samples = (samples.len() / 2) as f64;
|
||||
let elapsed = Duration::from_secs_f64(samples / (VB_FREQUENCY as f64 * self.speed));
|
||||
std::thread::sleep(elapsed);
|
||||
}
|
||||
|
||||
fn set_speed(&mut self, speed: f64) -> Result<()> {
|
||||
self.speed = speed;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum AudioInner {
|
||||
Cpal(CpalAudio),
|
||||
None(NoAudio),
|
||||
}
|
||||
|
||||
pub struct Audio(AudioInner);
|
||||
|
||||
impl Audio {
|
||||
pub fn init() -> Self {
|
||||
match CpalAudio::init() {
|
||||
Ok(a) => Self(AudioInner::Cpal(a)),
|
||||
Err(e) => {
|
||||
warn!("could not play audio: {e}");
|
||||
Self(AudioInner::None(NoAudio::new()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, samples: &[f32]) {
|
||||
match &mut self.0 {
|
||||
AudioInner::Cpal(a) => a.update(samples),
|
||||
AudioInner::None(a) => a.update(samples),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
|
||||
match &mut self.0 {
|
||||
AudioInner::Cpal(a) => a.set_speed(speed),
|
||||
AudioInner::None(a) => a.set_speed(speed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+75
-4
@@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use clap::{Parser, ValueEnum};
|
||||
use egui::{Color32, Pos2, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -47,6 +47,28 @@ pub struct CliArgs {
|
||||
/// Map the first connected controller to Player 2
|
||||
#[arg(long)]
|
||||
pub player2_controller: bool,
|
||||
/// Force the application to render with CPU, rather than GPU.
|
||||
#[arg(long)]
|
||||
pub wgpu_force_fallback: Option<bool>,
|
||||
/// Set a preference for whether to use a low-power or high-performance GPU adapter
|
||||
#[arg(long)]
|
||||
pub wgpu_power_preference: Option<PowerPreferenceWrapper>,
|
||||
}
|
||||
|
||||
#[derive(ValueEnum, Clone, Copy)]
|
||||
pub enum PowerPreferenceWrapper {
|
||||
Low,
|
||||
High,
|
||||
None,
|
||||
}
|
||||
impl From<PowerPreferenceWrapper> for wgpu::PowerPreference {
|
||||
fn from(value: PowerPreferenceWrapper) -> Self {
|
||||
match value {
|
||||
PowerPreferenceWrapper::Low => wgpu::PowerPreference::LowPower,
|
||||
PowerPreferenceWrapper::High => wgpu::PowerPreference::HighPerformance,
|
||||
PowerPreferenceWrapper::None => wgpu::PowerPreference::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
|
||||
@@ -64,6 +86,49 @@ pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
|
||||
],
|
||||
];
|
||||
|
||||
const fn default_power_preference() -> wgpu::PowerPreference {
|
||||
wgpu::PowerPreference::LowPower
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
|
||||
pub struct AppConfig {
|
||||
#[serde(default = "default_power_preference")]
|
||||
pub power_preference: wgpu::PowerPreference,
|
||||
#[serde(default)]
|
||||
pub force_fallback: bool,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn load(persistence: &Persistence) -> Self {
|
||||
if let Ok(config) = persistence.load_config(APP_CONFIG_FILENAME) {
|
||||
return config;
|
||||
}
|
||||
Self {
|
||||
power_preference: default_power_preference(),
|
||||
force_fallback: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self, persistence: &Persistence) -> Result<()> {
|
||||
persistence.save_config(APP_CONFIG_FILENAME, &self)
|
||||
}
|
||||
|
||||
pub fn update(&mut self, args: &CliArgs) -> bool {
|
||||
let mut updated = false;
|
||||
if let Some(pref) = args.wgpu_power_preference {
|
||||
self.power_preference = pref.into();
|
||||
updated = true;
|
||||
}
|
||||
if let Some(force_fallback) = args.wgpu_force_fallback {
|
||||
self.force_fallback = force_fallback;
|
||||
updated = true;
|
||||
}
|
||||
updated
|
||||
}
|
||||
}
|
||||
|
||||
const APP_CONFIG_FILENAME: &str = "config";
|
||||
|
||||
const fn default_audio_enabled() -> bool {
|
||||
true
|
||||
}
|
||||
@@ -76,12 +141,16 @@ pub struct SimConfig {
|
||||
#[serde(default = "default_audio_enabled")]
|
||||
pub audio_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub low_battery: bool,
|
||||
#[serde(default)]
|
||||
pub watch_rom: bool,
|
||||
#[serde(default)]
|
||||
pub position: Option<Pos2>,
|
||||
}
|
||||
|
||||
impl SimConfig {
|
||||
pub fn load(persistence: &Persistence, sim_id: SimId) -> Self {
|
||||
if let Ok(config) = persistence.load_config(config_filename(sim_id)) {
|
||||
if let Ok(config) = persistence.load_config(sim_config_filename(sim_id)) {
|
||||
return config;
|
||||
}
|
||||
Self {
|
||||
@@ -89,16 +158,18 @@ impl SimConfig {
|
||||
colors: COLOR_PRESETS[0],
|
||||
dimensions: DisplayMode::Anaglyph.proportions() + Vec2::new(0.0, 22.0),
|
||||
audio_enabled: true,
|
||||
low_battery: false,
|
||||
watch_rom: false,
|
||||
position: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self, persistence: &Persistence, sim_id: SimId) -> Result<()> {
|
||||
persistence.save_config(config_filename(sim_id), self)
|
||||
persistence.save_config(sim_config_filename(sim_id), self)
|
||||
}
|
||||
}
|
||||
|
||||
fn config_filename(sim_id: SimId) -> &'static str {
|
||||
fn sim_config_filename(sim_id: SimId) -> &'static str {
|
||||
match sim_id {
|
||||
SimId::Player1 => "config_p1",
|
||||
SimId::Player2 => "config_p2",
|
||||
|
||||
@@ -77,6 +77,15 @@ impl Controller {
|
||||
self.update_state(pressed, released)
|
||||
}
|
||||
|
||||
pub fn low_battery(&mut self, pwr: bool) -> Option<VBKey> {
|
||||
let (pressed, released) = if pwr {
|
||||
(VBKey::PWR, VBKey::empty())
|
||||
} else {
|
||||
(VBKey::empty(), VBKey::PWR)
|
||||
};
|
||||
self.update_state(pressed, released)
|
||||
}
|
||||
|
||||
fn update_state(&mut self, pressed: VBKey, released: VBKey) -> Option<VBKey> {
|
||||
let old_state = self.state;
|
||||
self.state = self.state.union(pressed).difference(released);
|
||||
@@ -133,6 +142,14 @@ impl ControllerManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_low_battery(&mut self, sim_id: SimId, pwr: bool) {
|
||||
let controller = &mut self.controllers[sim_id.to_index()];
|
||||
if let Some(pressed) = controller.low_battery(pwr) {
|
||||
self.client
|
||||
.send_command(EmulatorCommand::SetKeys(controller.sim_id, pressed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn axis_presses(value: f32, pair_value: f32, neg: VBKey, pos: VBKey) -> (VBKey, VBKey) {
|
||||
|
||||
+5
-5
@@ -138,7 +138,7 @@ impl EmulatorBuilder {
|
||||
self.audio_on,
|
||||
self.watch_rom,
|
||||
self.linked,
|
||||
)?;
|
||||
);
|
||||
if let Some(path) = self.rom {
|
||||
emulator.load_cart(SimId::Player1, &path)?;
|
||||
}
|
||||
@@ -178,11 +178,11 @@ impl Emulator {
|
||||
audio_on: Arc<[AtomicBool; 2]>,
|
||||
watch_rom: Arc<[AtomicBool; 2]>,
|
||||
linked: Arc<AtomicBool>,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
) -> Self {
|
||||
Self {
|
||||
sims: vec![],
|
||||
carts: [None, None],
|
||||
audio: Audio::init()?,
|
||||
audio: Audio::init(),
|
||||
commands,
|
||||
sim_state,
|
||||
state,
|
||||
@@ -198,7 +198,7 @@ impl Emulator {
|
||||
eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]],
|
||||
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
|
||||
buffer: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reload_cart(&mut self, sim_id: SimId) -> Result<()> {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::fmt::Write as _;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct FilePicker {
|
||||
window: Option<Weak<Window>>,
|
||||
}
|
||||
|
||||
impl FilePicker {
|
||||
pub fn new() -> Self {
|
||||
Self { window: None }
|
||||
}
|
||||
|
||||
pub fn set_window(&mut self, window: &Arc<Window>) {
|
||||
self.window = Some(Arc::downgrade(window));
|
||||
}
|
||||
|
||||
pub fn pick_file_dialog(&self) -> FileDialogBuilder {
|
||||
self.new_dialog(FileDialogAction::PickFile, false)
|
||||
}
|
||||
|
||||
pub fn save_file_dialog(&self) -> FileDialogBuilder {
|
||||
self.new_dialog(FileDialogAction::SaveFile, cfg!(not(target_os = "windows")))
|
||||
}
|
||||
|
||||
fn new_dialog(&self, action: FileDialogAction, attach_window: bool) -> FileDialogBuilder {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let mut dialog = rfd::AsyncFileDialog::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut dialog = rfd::FileDialog::new();
|
||||
|
||||
if attach_window && let Some(window) = self.window.as_ref().and_then(|w| w.upgrade()) {
|
||||
dialog = dialog.set_parent(&window);
|
||||
}
|
||||
FileDialogBuilder { dialog, action }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FileDialogBuilder {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
dialog: rfd::AsyncFileDialog,
|
||||
#[cfg(target_os = "macos")]
|
||||
dialog: rfd::FileDialog,
|
||||
action: FileDialogAction,
|
||||
}
|
||||
|
||||
impl FileDialogBuilder {
|
||||
pub fn add_filter(self, name: impl Into<String>, extensions: &[impl ToString]) -> Self {
|
||||
#[cfg(target_os = "linux")]
|
||||
let exts = extensions
|
||||
.iter()
|
||||
.map(|ext| {
|
||||
let mut normalized = String::new();
|
||||
for char in ext.to_string().chars() {
|
||||
if char.is_ascii_lowercase() {
|
||||
let _ = write!(&mut normalized, "[{char}{}]", char.to_ascii_uppercase());
|
||||
} else {
|
||||
normalized.push(char);
|
||||
}
|
||||
}
|
||||
normalized
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
#[cfg(target_os = "linux")]
|
||||
let extensions = &exts;
|
||||
Self {
|
||||
dialog: self.dialog.add_filter(name, extensions),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_file_name(self, file_name: impl Into<String>) -> Self {
|
||||
Self {
|
||||
dialog: self.dialog.set_file_name(file_name),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open(self) -> Option<PathBuf> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn resolve(action: impl Future<Output = Option<rfd::FileHandle>>) -> Option<PathBuf> {
|
||||
pollster::block_on(action).map(Into::into)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
fn resolve(action: Option<PathBuf>) -> Option<PathBuf> {
|
||||
action
|
||||
}
|
||||
match self.action {
|
||||
FileDialogAction::PickFile => resolve(self.dialog.pick_file()),
|
||||
FileDialogAction::SaveFile => resolve(self.dialog.save_file()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum FileDialogAction {
|
||||
PickFile,
|
||||
SaveFile,
|
||||
}
|
||||
+15
-2
@@ -13,7 +13,7 @@ use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::Subscribe
|
||||
use winit::event_loop::{ControlFlow, EventLoop};
|
||||
|
||||
use crate::{
|
||||
config::{CliArgs, SimConfig},
|
||||
config::{AppConfig, CliArgs, SimConfig},
|
||||
emulator::SimId,
|
||||
persistence::Persistence,
|
||||
};
|
||||
@@ -23,6 +23,7 @@ mod audio;
|
||||
mod config;
|
||||
mod controller;
|
||||
mod emulator;
|
||||
mod filepicker;
|
||||
mod gdbserver;
|
||||
mod graphics;
|
||||
mod images;
|
||||
@@ -110,6 +111,10 @@ fn main() -> Result<()> {
|
||||
if args.profile {
|
||||
builder = builder.start_paused(true)
|
||||
}
|
||||
let mut config = AppConfig::load(&persistence);
|
||||
if config.update(&args) {
|
||||
let _ = config.save(&persistence);
|
||||
}
|
||||
let p1 = SimConfig::load(&persistence, SimId::Player1);
|
||||
let p2 = SimConfig::load(&persistence, SimId::Player2);
|
||||
|
||||
@@ -136,6 +141,14 @@ fn main() -> Result<()> {
|
||||
let event_loop = EventLoop::with_user_event().build().unwrap();
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
let proxy = event_loop.create_proxy();
|
||||
event_loop.run_app(&mut Application::new(client, proxy, persistence, args))?;
|
||||
let handle = event_loop.owned_display_handle();
|
||||
event_loop.run_app(&mut Application::new(
|
||||
client,
|
||||
proxy,
|
||||
handle,
|
||||
persistence,
|
||||
args,
|
||||
config,
|
||||
))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+5
-1
@@ -1,4 +1,4 @@
|
||||
use std::sync::Arc;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
pub use about::AboutWindow;
|
||||
use egui::{Ui, ViewportBuilder};
|
||||
@@ -47,6 +47,10 @@ pub trait AppWindow {
|
||||
let _ = event;
|
||||
false
|
||||
}
|
||||
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InitArgs<'a> {
|
||||
|
||||
+42
-14
@@ -1,5 +1,6 @@
|
||||
use std::{
|
||||
ops::{Deref, DerefMut},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex, atomic::AtomicBool, mpsc},
|
||||
time::Duration,
|
||||
};
|
||||
@@ -8,6 +9,7 @@ use crate::{
|
||||
app::UserEvent,
|
||||
config::{COLOR_PRESETS, SimConfig},
|
||||
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState},
|
||||
filepicker::FilePicker,
|
||||
images::ImageTextureLoader,
|
||||
input::{Command, MappingProvider, ShortcutProvider},
|
||||
memory::MemoryClient,
|
||||
@@ -46,7 +48,7 @@ pub struct GameWindow {
|
||||
messages: mpsc::Receiver<Toast>,
|
||||
message_sink: mpsc::Sender<Toast>,
|
||||
color_picker: Option<ColorPickerState>,
|
||||
window: Option<Arc<winit::window::Window>>,
|
||||
file_picker: FilePicker,
|
||||
memory: Arc<MemoryClient>,
|
||||
images: Arc<ImageTextureLoader>,
|
||||
mappings: MappingProvider,
|
||||
@@ -70,6 +72,8 @@ impl GameWindow {
|
||||
sim_id: SimId,
|
||||
) -> Self {
|
||||
let config = SimConfig::load(&persistence, sim_id);
|
||||
let _ = proxy.send_event(UserEvent::LowBattery(sim_id, config.low_battery));
|
||||
client.send_command(EmulatorCommand::WatchRom(sim_id, config.watch_rom));
|
||||
let toasts = Toasts::new()
|
||||
.with_anchor(Anchor::BottomLeft)
|
||||
.with_margin((10.0, 10.0).into())
|
||||
@@ -88,7 +92,7 @@ impl GameWindow {
|
||||
messages,
|
||||
message_sink,
|
||||
color_picker: None,
|
||||
window: None,
|
||||
file_picker: FilePicker::new(),
|
||||
memory: memory.clone(),
|
||||
images: images.clone(),
|
||||
mappings: mappings.clone(),
|
||||
@@ -180,7 +184,9 @@ impl GameWindow {
|
||||
let mut viewport = child.initial_viewport();
|
||||
let title = viewport.title.clone().unwrap();
|
||||
let sim_id = child.sim_id();
|
||||
if let Some(sim_id) = sim_id && self.show_player_name {
|
||||
if let Some(sim_id) = sim_id
|
||||
&& self.show_player_name
|
||||
{
|
||||
viewport.title = Some(format!("{title} ({sim_id})"));
|
||||
}
|
||||
if let Some(state) = self.child_states.get(&viewport_id) {
|
||||
@@ -211,6 +217,10 @@ impl GameWindow {
|
||||
self.handle_event(viewport_id, |window| window.handle_gamepad_event(event))
|
||||
}
|
||||
|
||||
pub fn handle_dropped_file(&mut self, viewport_id: ViewportId, path: PathBuf) -> bool {
|
||||
self.handle_event(viewport_id, |window| window.handle_dropped_file(path))
|
||||
}
|
||||
|
||||
fn handle_event<F, R>(&mut self, viewport_id: ViewportId, cb: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut dyn AppWindow) -> R,
|
||||
@@ -247,9 +257,11 @@ impl GameWindow {
|
||||
for command in ui.input_mut(|input| self.shortcuts.consume_all(input)) {
|
||||
match command {
|
||||
Command::OpenRom => {
|
||||
let rom = rfd::FileDialog::new()
|
||||
let rom = self
|
||||
.file_picker
|
||||
.pick_file_dialog()
|
||||
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
|
||||
.pick_file();
|
||||
.open();
|
||||
if let Some(path) = rom {
|
||||
self.client
|
||||
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
|
||||
@@ -303,9 +315,11 @@ impl GameWindow {
|
||||
.add(self.button_for(ui.ctx(), "Open ROM", Command::OpenRom))
|
||||
.clicked()
|
||||
{
|
||||
let rom = rfd::FileDialog::new()
|
||||
let rom = self
|
||||
.file_picker
|
||||
.pick_file_dialog()
|
||||
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
|
||||
.pick_file();
|
||||
.open();
|
||||
if let Some(path) = rom {
|
||||
self.client
|
||||
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
|
||||
@@ -320,6 +334,7 @@ impl GameWindow {
|
||||
}
|
||||
let watch_rom = self.client.is_rom_watched(self.sim_id);
|
||||
if ui.selectable_button(watch_rom, "Watch ROM").clicked() {
|
||||
self.update_config(|c| c.watch_rom = !watch_rom);
|
||||
self.client
|
||||
.send_command(EmulatorCommand::WatchRom(self.sim_id, !watch_rom));
|
||||
}
|
||||
@@ -377,6 +392,14 @@ impl GameWindow {
|
||||
{
|
||||
pollster::block_on(self.take_screenshot());
|
||||
}
|
||||
ui.separator();
|
||||
let low_battery = self.config.low_battery;
|
||||
if ui.selectable_button(low_battery, "Low Battery").clicked() {
|
||||
self.update_config(|c| c.low_battery = !low_battery);
|
||||
let _ = self
|
||||
.proxy
|
||||
.send_event(UserEvent::LowBattery(self.sim_id, !low_battery));
|
||||
}
|
||||
});
|
||||
ui.menu_button("Options", |ui| self.show_options_menu(ui));
|
||||
ui.menu_button("Multiplayer", |ui| {
|
||||
@@ -457,13 +480,12 @@ impl GameWindow {
|
||||
self.client
|
||||
.send_command(EmulatorCommand::Screenshot(self.sim_id, tx));
|
||||
let bytes = rx.await.context("Could not take screenshot")?;
|
||||
let mut file_dialog = rfd::FileDialog::new()
|
||||
let file = self
|
||||
.file_picker
|
||||
.save_file_dialog()
|
||||
.add_filter("PNG images", &["png"])
|
||||
.set_file_name("screenshot.png");
|
||||
if let Some(window) = self.window.as_ref() {
|
||||
file_dialog = file_dialog.set_parent(window);
|
||||
}
|
||||
let file = file_dialog.save_file();
|
||||
.set_file_name("screenshot.png")
|
||||
.open();
|
||||
let Some(path) = file else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -757,7 +779,13 @@ impl AppWindow for GameWindow {
|
||||
));
|
||||
self.screen = Some(screen);
|
||||
}
|
||||
self.window = Some(args.window.clone());
|
||||
self.file_picker.set_window(args.window);
|
||||
}
|
||||
|
||||
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
|
||||
self.client
|
||||
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-11
@@ -1,12 +1,12 @@
|
||||
use std::{fs, sync::Arc, time::Duration};
|
||||
use std::{fs, time::Duration};
|
||||
|
||||
use anyhow::Result;
|
||||
use egui::{Button, CentralPanel, Checkbox, Label, ViewportBuilder};
|
||||
use egui_notify::{Anchor, Toast, Toasts};
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::{
|
||||
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId},
|
||||
filepicker::FilePicker,
|
||||
profiler::{Profiler, ProfilerStatus},
|
||||
window::{AppWindow, InitArgs},
|
||||
};
|
||||
@@ -16,7 +16,7 @@ pub struct ProfileWindow {
|
||||
client: EmulatorClient,
|
||||
profiler: Profiler,
|
||||
toasts: Toasts,
|
||||
window: Option<Arc<Window>>,
|
||||
file_picker: FilePicker,
|
||||
}
|
||||
|
||||
impl ProfileWindow {
|
||||
@@ -29,7 +29,7 @@ impl ProfileWindow {
|
||||
.with_anchor(Anchor::BottomLeft)
|
||||
.with_margin((10.0, 10.0).into())
|
||||
.reverse(true),
|
||||
window: None,
|
||||
file_picker: FilePicker::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,13 +62,12 @@ impl ProfileWindow {
|
||||
|
||||
fn try_finish_recording(&mut self) -> Result<Option<String>> {
|
||||
let bytes_receiver = self.profiler.finish_recording();
|
||||
let mut file_dialog = rfd::FileDialog::new()
|
||||
let file = self
|
||||
.file_picker
|
||||
.save_file_dialog()
|
||||
.add_filter("Profiler files", &["json"])
|
||||
.set_file_name("profile.json");
|
||||
if let Some(window) = self.window.as_ref() {
|
||||
file_dialog = file_dialog.set_parent(window);
|
||||
}
|
||||
let file = file_dialog.save_file();
|
||||
.set_file_name("profile.json")
|
||||
.open();
|
||||
if let Some(path) = file {
|
||||
let bytes = pollster::block_on(bytes_receiver)?;
|
||||
let _ = fs::remove_file(&path);
|
||||
@@ -164,6 +163,6 @@ impl AppWindow for ProfileWindow {
|
||||
}
|
||||
|
||||
fn on_init(&mut self, args: InitArgs) {
|
||||
self.window = Some(args.window.clone());
|
||||
self.file_picker.set_window(args.window);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user