A GameCube/Wii emulator and debugger written in Rust.
mimalloc + optimize allocations
Layle94c4eaf6ad26
diff --git a/Cargo.lock b/Cargo.lockindex 0e3406d..8fa35ba 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2203,6 +2203,15 @@ version = "0.2.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+[[package]]+name = "libmimalloc-sys"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d1eacfa31c33ec25e873c136ba5669f00f9866d0688bea7be4d3f7e43067df6"+dependencies = [+ "cc",+]+[[package]]name = "libredox"version = "0.1.15"@@ -2386,6 +2395,15 @@ dependencies = ["paste",]+[[package]]+name = "mimalloc"+version = "0.1.50"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3627c4272df786b9260cabaa46aec1d59c93ede723d4c3ef646c503816b0640"+dependencies = [+ "libmimalloc-sys",+]+[[package]]name = "miniz_oxide"version = "0.8.9"@@ -3970,6 +3988,7 @@ dependencies = ["egui-winit","gecko","image 0.1.0",+ "mimalloc","pollster","ringbuf","scripting",diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.tomlindex 4a3529f..de97e7b 100644--- a/crates/gecko/Cargo.toml+++ b/crates/gecko/Cargo.toml@@ -25,6 +25,7 @@ jit = []jit-stats = ["jit", "dep:backtrace"]fps-counter = []+gx-stats = []profile = ["dep:backtrace", "dep:windows-sys"][build-dependencies]diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex 7949050..e7da95b 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -15,7 +15,7 @@ use crate::flipper::gx::draw::Matrix4;use crate::flipper::gx::regs::{AlphaCompare, BlendMode, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode};#[cfg(feature = "efb-writeback")]use crate::host::EfbWriteback;-use crate::host::{GxAction, RenderSink, TextureKey, XfbPart};+use crate::host::{DrawVertex, GxAction, RenderSink, TextureKey, XfbPart};use crate::mmio::Mmio;use crate::system::{System, SystemId};use rustc_hash::FxHashMap;@@ -70,6 +70,10 @@ pub struct GraphicsProcessor {// XFB copies accumulated since the last vblank. `present_xfb()` drains// this at each field boundary to emit a PresentXfb action.pub xfb_copies: Vec<XfbCopy>,+ pub vertices_scratch: Vec<draw::Vertex>,+ pub draw_vertices_scratch: Vec<DrawVertex>,+ #[cfg(feature = "gx-stats")]+ pub(crate) stats: GxStats,// Hash of the raw texture data at each cache key; used to detect when// texture content changes and avoid redundant decodes + LoadTexture// sends. Keyed by the same `TextureKey` sent to the renderer in@@ -91,6 +95,20 @@ pub struct XfbCopy {pub src_h: u32,}+#[cfg(feature = "gx-stats")]+#[derive(Default, Clone)]+pub(crate) struct GxStats {+ pub draw_calls: u64,+ pub vertices: u64,+ pub fifo_bytes: u64,+ pub create_draw_call_ns: u64,+ pub draws_by_primitive: [u64; 8],+ pub texture_loads: u64,+ pub xfb_presents: u64,+ pub bp_writes: u64,+ pub xf_writes: u64,+}+impl GraphicsProcessor {pub fn new() -> Self {GraphicsProcessor {@@ -130,6 +148,10 @@ impl GraphicsProcessor {cur_scissor_offset_x: 0,cur_scissor_offset_y: 0,xfb_copies: Vec::new(),+ vertices_scratch: Vec::with_capacity(256),+ draw_vertices_scratch: Vec::with_capacity(256),+ #[cfg(feature = "gx-stats")]+ stats: GxStats::default(),texture_hashes: FxHashMap::default(),#[cfg(feature = "efb-writeback")]efb_writeback_rx: None,@@ -154,6 +176,11 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {return;}+ #[cfg(feature = "gx-stats")]+ {+ sys.gx.stats.xfb_presents += 1;+ }+let (frame_w, frame_h) = sys.vi.frame_dimensions();let vi_base = sys.vi.xfb_addr();diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex 6cbe241..ae78d98 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -12,6 +12,11 @@ impl GraphicsProcessor {let val = u32::from_be_bytes([0, data[1], data[2], data[3]]);self.bp_regs[idx] = val;+ #[cfg(feature = "gx-stats")]+ {+ self.stats.bp_writes += 1;+ }+tracing::debug!(reg_idx = format!("{idx:02X}"),value = format!("{val:08X}"),@@ -276,6 +281,12 @@ impl GraphicsProcessor {mag_filter: mode0.mag_filter(),min_filter: mode0.min_filter(),};++ #[cfg(feature = "gx-stats")]+ {+ self.stats.texture_loads += 1;+ }+renderer.exec(GxAction::LoadTexture {id: cache_id,width,diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rsindex fd21379..37aba40 100644--- a/crates/gecko/src/flipper/gx/vertex.rs+++ b/crates/gecko/src/flipper/gx/vertex.rs@@ -48,6 +48,9 @@ impl GraphicsProcessor {cmd: u8,data: Vec<u8>,) {+ #[cfg(feature = "gx-stats")]+ let _gx_stats_t0 = std::time::Instant::now();+let Some(primitive) = draw::Primitive::from_cmd(cmd) else {tracing::error!(cmd, "goofy draw command");return;@@ -62,20 +65,30 @@ impl GraphicsProcessor {let vertex_count = data.len() / vf.vertex_stride;- let mut vertices: Vec<draw::Vertex> = Vec::with_capacity(vertex_count);+ #[cfg(feature = "gx-stats")]+ {+ self.stats.draw_calls += 1;+ self.stats.vertices += vertex_count as u64;+ self.stats.fifo_bytes += data.len() as u64;+ self.stats.draws_by_primitive[(primitive as usize) & 0x7] += 1;+ }++ self.vertices_scratch.clear();+ self.vertices_scratch.reserve(vertex_count);+let mut cur = Cursor::new(&data);let view = mmio.ram_view();for i in 0..vertex_count {let vertex = self.decode_vertex(&mut cur, &data, &view, &vf, i);- vertices.push(vertex);+ self.vertices_scratch.push(vertex);}let modelview = self.build_modelview_matrix(vf.default_pos_mtx_idx);tracing::debug!(primitive = format!("{:?}", primitive),- vertices = format!("{:?}", vertices),+ vertices = format!("{:?}", self.vertices_scratch),pos_mtx_idx = vf.default_pos_mtx_idx,modelview = format!("{:?}", modelview),projection = format!("{:?}", self.projection),@@ -110,18 +123,19 @@ impl GraphicsProcessor {unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR1]),];- // Emit action to the render sink- let draw_vertices: Vec<DrawVertex> = vertices- .iter()- .map(|v| DrawVertex {+ self.draw_vertices_scratch.clear();+ self.draw_vertices_scratch.reserve(self.vertices_scratch.len());+ for v in &self.vertices_scratch {+ self.draw_vertices_scratch.push(DrawVertex {position: v.position,normal: v.normal,color0: v.color0,color1: v.color1,pos_view: v.pos_view,texcoords: std::array::from_fn(|i| v.texcoords[i].unwrap_or([0.0, 0.0, 1.0])),- })- .collect();+ });+ }+ let draw_vertices = std::mem::take(&mut self.draw_vertices_scratch);let lights: [LightData; 8] = std::array::from_fn(|i| LightData {color: light_colors[i],@@ -164,10 +178,10 @@ impl GraphicsProcessor {primitive,vertices: draw_vertices,modelview: modelview.0,- tev_color_env: self.cur_tev_color_env.iter().map(|e| e.raw()).collect(),- tev_alpha_env: self.cur_tev_alpha_env.iter().map(|e| e.raw()).collect(),- tev_orders: tev_orders.iter().map(|o| o.raw()).collect(),- tev_ksel: (0..8).map(|i| self.bp_regs[BP_TEV_KSEL_0 + i]).collect(),+ tev_color_env: std::array::from_fn(|i| self.cur_tev_color_env[i].raw()),+ tev_alpha_env: std::array::from_fn(|i| self.cur_tev_alpha_env[i].raw()),+ tev_orders: std::array::from_fn(|i| tev_orders[i].raw()),+ tev_ksel: std::array::from_fn(|i| self.bp_regs[BP_TEV_KSEL_0 + i]),tev_color_regs,tev_konst_colors: self.cur_tev_konst_colors,num_tev_stages: self.cur_num_tev_stages,@@ -176,13 +190,18 @@ impl GraphicsProcessor {indirect_refs: self.cur_indirect_refs.raw(),num_indirect_stages: self.cur_num_indirect_stages,bump_imask: self.cur_bump_imask,- tev_indirect: self.cur_tev_indirect.iter().map(|c| c.raw()).collect(),+ tev_indirect: std::array::from_fn(|i| self.cur_tev_indirect[i].raw()),color_ctrl,alpha_ctrl,ambient_color,material_color,lights,}));++ #[cfg(feature = "gx-stats")]+ {+ self.stats.create_draw_call_ns += _gx_stats_t0.elapsed().as_nanos() as u64;+ }}fn build_vertex_format(&self, cmd: u8) -> VertexFormat {diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rsindex 90764a5..79b8a4c 100644--- a/crates/gecko/src/flipper/gx/xf.rs+++ b/crates/gecko/src/flipper/gx/xf.rs@@ -102,6 +102,11 @@ impl GraphicsProcessor {let n = length + 1;let end = addr + n;+ #[cfg(feature = "gx-stats")]+ {+ self.stats.xf_writes += n as u64;+ }+for i in 0..n {let offset = 4 + i * 4;let val = u32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 4831ffa..d8c05cc 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -173,10 +173,10 @@ pub struct DrawData {pub vertices: Vec<DrawVertex>,pub modelview: [[f32; 4]; 4],// TEV combiner state- pub tev_color_env: Vec<u32>,- pub tev_alpha_env: Vec<u32>,- pub tev_orders: Vec<u32>,- pub tev_ksel: Vec<u32>,+ pub tev_color_env: [u32; 16],+ pub tev_alpha_env: [u32; 16],+ pub tev_orders: [u32; 8],+ pub tev_ksel: [u32; 8],pub tev_color_regs: [[f32; 4]; 4],pub tev_konst_colors: [[f32; 4]; 16],pub num_tev_stages: u8,@@ -189,7 +189,7 @@ pub struct DrawData {pub indirect_refs: u32,pub num_indirect_stages: u8,pub bump_imask: u32,- pub tev_indirect: Vec<u32>,+ pub tev_indirect: [u32; 16],// Lighting state (2 channels: COLOR0/ALPHA0 and COLOR1/ALPHA1)pub color_ctrl: [ChanCtrl; 2],pub alpha_ctrl: [ChanCtrl; 2],diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rsindex 90c212e..b80aae5 100644--- a/crates/gecko/src/lib.rs+++ b/crates/gecko/src/lib.rs@@ -11,7 +11,7 @@ pub mod host;pub mod input;pub mod ipl;pub mod mmio;-#[cfg(any(feature = "jit-stats", feature = "profile"))]+#[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]pub mod profile;pub mod scheduler;pub mod starlet;diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex e268f22..d203d2b 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -68,10 +68,10 @@ pub struct System<const SYSTEM: SystemId> {#[cfg(feature = "fps-counter")]pub fps_counter: FpsCounter,- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]pub heatmap: crate::profile::HeatmapConfig,- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]pub vsync_count: u64,#[cfg(feature = "profile")]@@ -119,10 +119,10 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {#[cfg(feature = "fps-counter")]fps_counter: FpsCounter::new(),- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]heatmap: crate::profile::HeatmapConfig::default(),- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]vsync_count: 0,#[cfg(feature = "profile")]@@ -224,21 +224,86 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {self.drain_events();}- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]self.on_vsync_boundary();}- #[cfg(any(feature = "jit-stats", feature = "profile"))]+ #[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]fn on_vsync_boundary(&mut self) {self.vsync_count = self.vsync_count.wrapping_add(1);#[cfg(feature = "jit-stats")]self.dump_heatmap_if_due();+ #[cfg(feature = "gx-stats")]+ self.dump_gx_stats_if_due();+#[cfg(feature = "profile")]self.tick_pprof_session();}+ #[cfg(feature = "gx-stats")]+ fn dump_gx_stats_if_due(&self) {+ if !self.heatmap.enabled || self.heatmap.interval_frames == 0 {+ return;+ }++ if self.vsync_count % self.heatmap.interval_frames as u64 != 0 {+ return;+ }++ use std::io::Write;++ let path = self.heatmap.out_dir.join("gx-stats.txt");+ let s = &self.gx.stats;+ let avg_draw_ns = if s.draw_calls > 0 {+ s.create_draw_call_ns / s.draw_calls+ } else {+ 0+ };++ let result = crate::profile::write_file_atomic(&path, |f| {+ writeln!(+ f,+ "vsync_count={}\ndraw_calls={}\nvertices={}\nfifo_bytes={}\ntexture_loads={}\nxfb_presents={}\nbp_writes={}\nxf_writes={}\ncreate_draw_call_ns={}\navg_draw_call_ns={}",+ self.vsync_count,+ s.draw_calls,+ s.vertices,+ s.fifo_bytes,+ s.texture_loads,+ s.xfb_presents,+ s.bp_writes,+ s.xf_writes,+ s.create_draw_call_ns,+ avg_draw_ns,+ )?;+ writeln!(f, "\n--- draws by primitive ---")?;++ use crate::flipper::gx::draw::Primitive;++ const VARIANTS: [Primitive; 7] = [+ Primitive::Quads,+ Primitive::Triangles,+ Primitive::TriangleStrip,+ Primitive::TriangleFan,+ Primitive::Lines,+ Primitive::LineStrip,+ Primitive::Points,+ ];++ for p in VARIANTS {+ let count = s.draws_by_primitive[(p as usize) & 0x7];+ writeln!(f, " {:>16} {:?}", count, p)?;+ }++ Ok(())+ });++ if let Err(err) = result {+ tracing::warn!(?err, "gx-stats sidecar write failed");+ }+ }+#[cfg(feature = "jit-stats")]fn dump_heatmap_if_due(&mut self) {if !self.heatmap.enabled || self.heatmap.interval_frames == 0 {diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.tomlindex a82f534..4339089 100644--- a/crates/tinyapp/Cargo.toml+++ b/crates/tinyapp/Cargo.toml@@ -11,6 +11,7 @@ efb-writeback = ["backend-wgpu/efb-writeback"]audio-wav-dump = ["gecko/audio-wav-dump"]fps-counter = ["gecko/fps-counter"]jit-stats = ["gecko/jit-stats"]+gx-stats = ["gecko/gx-stats"]profile = ["gecko/profile"][dependencies]@@ -30,3 +31,4 @@ clap = { version = "4.6.0", features = ["derive"] }cpal = "0.17.3"ringbuf = "0.5.0"ctrlc = "3.5.2"+mimalloc = { version = "0.1.50", default-features = false }diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex b2d5bfa..9f980a4 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -2,6 +2,9 @@ mod app;mod audio;mod thread;+#[global_allocator]+static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;+use backend_wgpu::sink::TargetAspect;use clap::Parser;use gecko::HostInput;