it works :3

This commit is contained in:
blu-dev committed 2025-12-26 00:25:44 -07:00
commit 7fb0c8289b
10 files changed
+1127

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
**/*.nro
target
Generated
+226
View File
@@ -0,0 +1,226 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "itoa"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ee5b5339afb4c41626dde77b7a611bd4f2c202b897852b4bcf5d03eddc61010"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc-nnsdk"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ece4a9a361bf75974e2c18b719e8fd501e4e336d7a5db22d077c4f2367a94be9"
[[package]]
name = "memchr"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "ninput"
version = "0.1.0"
dependencies = [
"bitflags",
]
[[package]]
name = "nnsdk"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03213d51eb95956e62d59f902de5ad7cf48e1310340b8544e5f9536e48f08fd9"
dependencies = [
"libc-nnsdk",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "proc-macro2"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "serde_json"
version = "1.0.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6af14725505314343e673e9ecb7cd7e8a36aa9791eb936235a3567cc31447ae4"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "skyline"
version = "0.5.1"
source = "git+https://github.com/ultimate-research/skyline-rs#7bd379b25c926cb65a492412805258e49ce9136e"
dependencies = [
"libc-nnsdk",
"nnsdk",
"skyline_macro",
]
[[package]]
name = "skyline_macro"
version = "0.2.1"
source = "git+https://github.com/ultimate-research/skyline-rs#7bd379b25c926cb65a492412805258e49ce9136e"
dependencies = [
"lazy_static",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.111"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "testing"
version = "0.1.0"
dependencies = [
"ninput",
"paste",
"serde",
"serde_json",
"skyline",
"tracing",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicode-ident"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
[[package]]
name = "zmij"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0095ecd462946aa3927d9297b63ef82fb9a5316d7a37d134eeb36e58228615a"
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "testing"
version = "0.1.0"
authors = []
edition = "2021"
[package.metadata.skyline]
titleid = "01006A800016E000" # Smash Ultimate
[lib]
crate-type = ["cdylib"]
[dependencies]
ninput = { path = "../ninput", version = "0.1.0" }
paste = "1.0.15"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.147"
skyline = { git = "https://github.com/ultimate-research/skyline-rs" }
tracing = "0.1.44"
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
lto = true
+113
View File
@@ -0,0 +1,113 @@
use std::{
collections::BTreeMap,
fs::File,
io::Write,
sync::{
mpsc::{Receiver, Sender},
OnceLock,
},
};
pub type Tick = i64;
struct FrameElement {
name: &'static str,
frame_index: usize,
tick: Tick,
}
#[derive(serde::Serialize)]
struct MarkerElement {
name: &'static str,
tick: Tick,
}
enum Element {
Frame(FrameElement),
Marker(MarkerElement),
FinishFrame(usize),
}
static SUBMISSION_CHANNEL: OnceLock<Sender<Element>> = OnceLock::new();
pub fn initialize() {
let (sender, receiver) = std::sync::mpsc::channel();
SUBMISSION_CHANNEL
.set(sender)
.expect("Only call frametracer::initialize() once");
let _ = std::thread::spawn(move || frametracer_thread(receiver));
}
pub fn marker(name: &'static str, tick: Tick) {
if let Some(channel) = SUBMISSION_CHANNEL.get() {
let _ = channel.send(Element::Marker(MarkerElement { name, tick }));
}
}
pub fn frame(name: &'static str, frame: usize, tick: Tick) {
if let Some(channel) = SUBMISSION_CHANNEL.get() {
let _ = channel.send(Element::Frame(FrameElement {
name,
frame_index: frame,
tick,
}));
}
}
pub fn finish_frame(frame: usize) {
if let Some(channel) = SUBMISSION_CHANNEL.get() {
let _ = channel.send(Element::FinishFrame(frame));
}
}
fn frametracer_thread(receiver: Receiver<Element>) {
#[derive(serde::Serialize)]
struct NamedTick {
name: &'static str,
tick: Tick,
}
let mut frames_in_flight: BTreeMap<usize, Vec<NamedTick>> = BTreeMap::new();
let mut file = File::create("sd:/frametrace.jsonl").unwrap();
loop {
match receiver.recv() {
Ok(Element::Frame(frame)) => {
frames_in_flight
.entry(frame.frame_index)
.or_default()
.push(NamedTick {
name: frame.name,
tick: frame.tick,
});
}
Ok(Element::Marker(marker)) => {
if let Ok(mut line) = serde_json::to_string(&marker) {
line.push('\n');
let _ = file.write_all(line.as_bytes());
let _ = file.flush();
}
}
Ok(Element::FinishFrame(frame)) => {
#[derive(serde::Serialize)]
struct FrameEntry {
frame: usize,
elements: Vec<NamedTick>,
}
let frame = FrameEntry {
frame,
elements: frames_in_flight.remove(&frame).unwrap_or_default(),
};
if let Ok(mut line) = serde_json::to_string(&frame) {
line.push('\n');
let _ = file.write_all(line.as_bytes());
let _ = file.flush();
}
}
Err(_error) => break,
}
}
}
+19
View File
@@ -0,0 +1,19 @@
// mod frametracer;
mod off_by_one;
mod pacer;
mod swapchain;
mod vsync;
// mod vsync_history;
const DISABLE_VSYNC: bool = true;
#[skyline::main(name = "testing")]
pub fn main() {
swapchain::install(DISABLE_VSYNC);
off_by_one::install();
pacer::install();
if DISABLE_VSYNC {
vsync::install(false);
}
}
+154
View File
@@ -0,0 +1,154 @@
/** Updates the models of every battle object to match their animation
*
* We have to call this manually, normally it's called from TaskWorker2
*/
#[skyline::from_offset(0x3ab590)]
fn update_models(p: *const ());
/** This initializes a task worker, I'm not sure what the arguments do entirely but I believe that one of them
* is a TlsSlot
*/
#[skyline::from_offset(0x3549170)]
unsafe fn initialize_task_worker(ptr: *mut u8, func: *const (), arg1: u32, arg2: i32);
/** I believe this waits on a task worker to finish running, but I'm not entirely sure
*/
#[skyline::from_offset(0x354c720)]
unsafe fn wait_task_worker(arg1: u32, arg2: *mut u32);
unsafe fn start_task_worker_queue(pointer: *mut (), function_ptr: *const ()) {
// I could declare a struct for these members, but I don't really want to misrepresent them
// For now they will stay as offsets and raw pointer math
let flag = *pointer.add(0x20).cast::<u8>();
if flag == 1 {
return;
}
// This is supposed to be an atomic store and release, I don't do that though
*pointer.cast::<u8>().add(0x8) = 1;
let mut start = pointer.cast::<*mut u8>();
let mut ptr = *start;
while !ptr.is_null() {
let object = *ptr.add(0x48).cast::<*mut u8>();
let value = *ptr.add(0x70);
if value != 1 {
if value == 2 {
*start = object;
let vtable = *ptr.cast::<*mut u64>();
let func_ptr = *vtable.add(1).cast::<extern "C" fn(*mut u8)>();
(func_ptr)(ptr);
ptr = object;
if object.is_null() {
break;
}
continue;
}
initialize_task_worker(
ptr.add(8),
function_ptr,
*ptr.add(0x68).cast::<u32>(),
*ptr.add(0x6c).cast::<i32>(),
);
}
start = (*start).add(0x48).cast();
ptr = object;
}
*pointer.cast::<u8>().add(0x8) = 0;
}
/** Performs graphics updates manually, replacing the operations we patch out in the rest of this file
*
* This method runs immediately after the frame pacer check is done (so it encompasses all possible scene updates).
* TODO: This method should be profiled and benchmarked for how long some of these operations take. I'm pretty sure
* it's decently fast but I don't know
*/
#[skyline::hook(offset = 0x374c7b4, inline)]
unsafe fn post_scene_update_submit_render(_: &skyline::hooks::InlineCtx) {
// SAFETY: These are basically local variables or global constants, and we cache them so that we don't have to fetch them every time from the skyline API
static mut P_BATTLE_OBJECT_MANAGER: *const *const () = std::ptr::null();
static mut P_TASK_WORKER_QUEUE: *mut () = std::ptr::null_mut();
static mut SUBMIT_COMMANDS_FN_PTR: *const () = std::ptr::null();
static mut FIGHTER_RENDER_COMMANDS_FN_PTR: *const () = std::ptr::null();
static mut FIGHTER_ARRAY_START: *const () = std::ptr::null();
static mut DID_INIT: bool = false;
if !DID_INIT {
DID_INIT = true;
let base = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text).cast::<u8>();
P_BATTLE_OBJECT_MANAGER = base.add(0x5332120).cast::<*const ()>();
P_TASK_WORKER_QUEUE = base.add(0x5332558).cast();
SUBMIT_COMMANDS_FN_PTR = base.add(0x3548240).cast();
FIGHTER_RENDER_COMMANDS_FN_PTR = base.add(0x374f050).cast();
FIGHTER_ARRAY_START = base.add(0x5332f58).cast();
}
if !(*P_BATTLE_OBJECT_MANAGER).is_null() {
update_models(*P_BATTLE_OBJECT_MANAGER);
}
// I don't know how much memory this actually takes up but I'm sure it's not *that* much
let mut task_worker_info = [0u32; 16];
initialize_task_worker(
task_worker_info.as_mut_ptr().cast(),
FIGHTER_RENDER_COMMANDS_FN_PTR,
0, // 0, 0 taken from invocation we stub
0,
);
if task_worker_info[4] != 0 {
let tls_slot = *(*FIGHTER_ARRAY_START
.cast::<*const u8>()
.add(task_worker_info[5] as usize))
.add(0x10)
.cast::<u32>();
wait_task_worker(tls_slot, task_worker_info.as_mut_ptr().add(4));
}
start_task_worker_queue(P_TASK_WORKER_QUEUE, SUBMIT_COMMANDS_FN_PTR);
}
/** This prevents the render dispatch threads from starting
*
* This is an inlined call to an equivalent of `start_task_worker_queue`, which we reimplement for `post_scene_update_submit_render`
*/
fn prevent_render_dispatch_signal() {
skyline::patching::Patch::in_text(0x374c054)
.data(0x14000029u32)
.unwrap();
}
/** This patches a vtable function pointer that calls BattleObjectManager::UpdateObjectModels
*
* This is called by TaskWorker2. Other tasks executed by the same `start_task_worker` invocation are mission critical to the frame
* so they cannot be moved. Instead of moving the task worker updates, we just stub that function and call it ourself in
* `post_scene_update_submit_render`
*/
fn prevent_task_worker_updating_models() {
extern "C" fn stub() {}
skyline::patching::Patch::in_text(0x4f623d0)
.data(stub as *const () as u64)
.unwrap();
}
/** This prevents adding fighter render command recording tasks to the task worker
*
* By default this is called before updating the scene's state for the frame. We do this manually in `post_scene_update_submit_render`
*/
fn prevent_fighter_render_command_recording() {
skyline::patching::Patch::in_text(0x374b554).nop().unwrap();
}
pub fn install() {
prevent_render_dispatch_signal();
prevent_task_worker_updating_models();
prevent_fighter_render_command_recording();
skyline::install_hook!(post_scene_update_submit_render);
}
+13
View File
@@ -0,0 +1,13 @@
/** This replaces a check for how many frames we are behind with always assuming we are 0 frames behind
*
* This is to keep input latency measurements consistent until we can implement a better frame pacer
*/
fn disable_frame_pacer() {
skyline::patching::Patch::in_text(0x374c640)
.data(0x52800008u32)
.unwrap();
}
pub fn install() {
disable_frame_pacer();
}
+174
View File
@@ -0,0 +1,174 @@
/** Ultimate Render Pipeline Docs
* Ultimate makes use of multi-threaded rendering, and does so very poorly.
*
* Well, poorly is probably a harsh term for what they are doing. They
* are attempting to optimize for the switch hardware in such a way that
* there will never be frame drops, at the cost of more input delay.
*
* They do this in multiple ways, but basically you can imagine a swapchain
* class such that
* ```
* class SwapchainDispatches {
* RenderDispatchThread* pThreads[2];
* nvn::Queue* pQueue;
* RenderDispatches* pDispatchNow;
* RenderDispatches* pDispatchNext;
*
* void SubmitDispatch(RenderDispatches* next) {
* pDispatchNext = next;
* }
*
* void AwaitAndSubmitDispatches() {
* if (pDispatchNow != nullptr) {
* RenderDispatchThread* pThread = this->pThreads[pDispatchNow->ThreadId];
* while (pThread->CurrentBatch != pThread->BatchEnd) { std::this_thread::yield(); } // Awaits render dispatch thread to finish
* pDispatchNow->SubmitToQueue(pQueue);
* } else {
* pDispatchNow = pDispatchNext;
* pDispatchNext = nullptr;
* }
* }
* };
* ```
*
* This isn't exactly the class is implemented, however it's a close enough approximation.
*
* There are threads called "TaskWorkerX" where X is either 0, 1, or 2, that perform various asynchronous
* running tasks throughout the game's lifecycle, but they also include render tasks! They build onto the dispatches
* that are inevitably sent to the "render dispatch" threads. The main loop might look something a little like this
* (this is a very simplified view, and many things I do not understand are happening that I need to investigate further)
*
* ```
* void MainLoop() {
* while (true) {
* PresentAndAcquireNextTexture();
* pSwapchain->AwaitAndSubmitDispatches();
* UpdateTaskWorker(s_EffectManager); // Submits effect subsystem render commands to dispatcher
* UpdateTaskWorker(s_UiManager); // Submits ui subsystem render commands to dispatcher
* UpdatetaskWorker(s_BattleObjectManager); // Submits battle object render commands to dispatcher
* SignalRenderDispatchBegin(); // Signals that render dispatch threads can begin processing their submitted tasks
* PollInputs(); // Polls user inputs
* RunScene(); // Runs core game state update (updates UI, battles, everything)
* if (s_FramePacer->ShouldRunAgain()) { // Checks if we are running behind, then runs the scene again
* PollInputs();
* RunScene();
* }
* }
* }
* ```
* In this grossly oversimplified representation of the main loop, there are two concerning choices:
* 1. We are polling inputs and running the scene update *after* the current state is rendered. That means that
* when the frame is presented that is being rendered on any given invocation of the loop, it's going to represent the
* state that the last frame finished with.
* 2. Our frame pacer is just running a second frame without special casing input handling (such as by using timestamps)
* which means that sometimes, randomly, we will get a frame that has 1 frame less input lag. In practice, it's worse than that
* because you might think you have a 3 frame window for an input but you actually have a 2 frame window for an input.
*
* Another, more subtle, problem is the implementation of `PresentAndAcquireNextTexture`. Because we have to call it twice before it actually
* takes the path of processing a render dispatch, we have 2 frames of input lag. You might also realize that the texture index we acquire
* at the start of the loop is presented at the beginning of the next loop. So if we acquire texture index `2`, then we present texture index `2`.
*
* In order to accommodate the extra 2 frames, Ultimate's render pipeline is configured to render to the `index - 1`th texture since the commands
* do not get processed until 2 frames later.
*
* Yeah, it's a mess.
*/
/** Flushes the swapchain buffers before the call to nvnQueuePresentTexture
*
* This hook is placed on the callsite of `PresentAndAcquireNextTexture` as described above. The first operation of
* `PresentAndAcquireNextTexture` is to call `nvnQueuePresentTexture` on an acquired texture.
*
* This, in combination with the `full_swapchain_flush` hook will take the render commands generated during **this**
* iteration of the main loop and submit them. This means that we are now presenting state we rendered on the same frame.
*
* This has the possibility of taking a while if the render dispatch buffers are not done yet. Should be profiled and investigated
* in situations where frame drops happen.
*/
#[skyline::hook(offset = 0x3747b78, inline)]
unsafe fn flush_swap_buffers_before_present(_: &skyline::hooks::InlineCtx) {
// SAFETY: This method is only ever called in one spot, this is effectively a local variable that we are using
// to cache the pointer.
//
// We could fetch it from the stack but instead I would just like to cache it locally
static mut POINTER: Option<*const ()> = None;
#[allow(static_mut_refs)]
if POINTER.is_none() {
POINTER = Some(
*skyline::hooks::getRegionAddress(skyline::hooks::Region::Text)
.cast::<u8>()
.add(0x5334e90)
.cast::<*const ()>(),
);
}
let ptr = POINTER.unwrap_unchecked().cast::<*const ()>();
let ptr = **ptr.cast::<*const *const ()>().add(1);
let sub_ptr = *ptr.cast::<*const ()>().add(0x88 / 8);
let flag = *ptr.cast::<u8>().add(0xec);
let function = *(*sub_ptr.cast::<*const *const ()>())
.add(0x3)
.cast::<extern "C" fn(*const (), u8)>();
function(sub_ptr, flag);
*ptr.cast::<u8>().cast_mut().add(0xec) = 0;
}
/** Calls Swapchain::AwaitAndSubmitDispatches twice
*
* The main problem with the call of AwaitAndSubmitDispatches initially is that it sits after the first texture present/acquire and is initially called
* when there are no render dispatches to process. In combination with `flush_swap_buffers_before_present`, this hook will immediately move the pDispatchNext
* batch into the pDispatchNow batch (first invocation) then await the pDispatchNow batch
*/
#[skyline::hook(offset = 0x384f460)]
unsafe fn full_swapchain_flush(arg1: u64, arg2: u32) {
call_original!(arg1, arg2);
call_original!(arg1, arg2);
}
/** Prevents call to Swapchain::AwaitAndSubmitDispatches in the main loop
*
* Because we provide a new call in the `flush_swap_buffers_before_present` hook, we need to prevent the other one from being run.
* Technically it might do nothing? But it might also have unintendended side-effects so it's more reliable for us to prevent it altogether
*/
fn patch_swap_flush_call() {
skyline::patching::Patch::in_text(0x37495c8).nop().unwrap();
skyline::patching::Patch::in_text(0x37495cc).nop().unwrap();
}
/** This changes the behavior of the nu::FrameBufferRenderTarget render command to use the current frame index
*
* The default implementation is to get the `(currentFrameIndex + 2) % 3`th texture to render to. This is because
* the game intends for the render pipeline to be two frames behind. Because we are fully flushing out the swapchain
* buffers and rendering to the active texture for each frame, we want to use the current texture and not a future one.
*
* This patches an instruction `add w9, w9, #0x2` to be `nop`
*/
fn use_current_frame_index() {
skyline::patching::Patch::in_text(0x386ab4c).nop().unwrap();
}
/** This disables a sync that is signaled by rendering wrapping up
*
* When vsync is disabled, this sync can prevent the start of the frame on the CPU from progressing,
* which can cause frame drops because we are already forcing the game to "run behind". Disabling it doesn't
* appear to have any known side effects (at least not when the swapchain is being patched, hence why it is in this file)
*
*/
fn patch_render_sync_wait() {
skyline::patching::Patch::in_text(0x386fcec)
.data(0xD2800000u32)
.unwrap();
}
pub fn install(is_vsync_disabled: bool) {
patch_swap_flush_call();
use_current_frame_index();
if is_vsync_disabled {
patch_render_sync_wait();
}
skyline::install_hooks!(flush_swap_buffers_before_present, full_swapchain_flush);
}
+86
View File
@@ -0,0 +1,86 @@
/** This is a vsync hack to shave a frame of input delay off of the game
*
* This can come with frame drops, and it is not stable. It also doesn't work on emulator. Better solutions are desired but for now
* this can get the job done. It's also not very well understood (or rather, not well documented) as to why it works the way it does.
*/
use std::sync::atomic::{AtomicBool, Ordering};
use skyline::hooks::InlineCtx;
static mut OFFSET1: u64 = 0;
static mut OFFSET2: u64 = 0;
/** Helper method to calculate the base of nnSdk
*
* Since we are not using exlaunch (yet) this must be done manually with an assumed offset. If the version
* of nnSdk that SSBU uses ever updates, we will need to update this method/offset
*/
unsafe fn calc_nnsdk_offset() -> u64 {
let mut symbol = 0usize;
skyline::nn::ro::LookupSymbol(&mut symbol, b"_ZN7android7IBinderD1Ev\0".as_ptr());
(symbol - 0x240) as u64
}
#[skyline::hook(offset = 0x374c118, inline)]
unsafe fn run_scene_update(_: &skyline::hooks::InlineCtx) {
// SAFETY: This is basically a local variable (again)
static mut CONTROLLER: ninput::Controller = ninput::Controller::new(0);
while !RUN.swap(false, Ordering::SeqCst) {
#[allow(static_mut_refs)]
CONTROLLER.update();
}
}
/** Patches nvnWindowBuilderSetPresentInterval/nvnWindowSetPresentInterval (I don't remember which one)
*
* This forces it to always pass in 0, which disables vsync
*/
#[skyline::hook(replace = OFFSET1)]
unsafe fn set_present_interval_nvn(window: u64, _: i32) {
call_original!(window, 0);
}
/** Patches an internal presentation/surface device implementation for setting the present interval
*
* This method has some checks on the maximum and minimum supported values, but if we set it to zero it
* still works properly, so we forcibly set it to zero.
*/
#[skyline::hook(replace = OFFSET2, inline)]
unsafe fn set_present_interval_android(ctx: &mut InlineCtx) {
ctx.registers[8].set_x(0);
}
// This is public because it might need to be set from the profiling implementation
// if we enable profiling
pub static RUN: AtomicBool = AtomicBool::new(false);
/** Hooks into smash's VsyncUpdate method (which is basically just a physical frame counter)
*
* We use this to manually synchronize on a vsync. We try to synchronize one vsync later than the game would normally expect to be at
* to constantly be in a "running behind" state, which shaves a frame of input delay off.
*
* Note that it is not because we are forcing the frame pacer to work overtime, but rather because we are effectively only ever using 2 frame buffers
* (imagine the game was double buffered)
*/
#[skyline::hook(offset = 0x3810a64, inline)]
unsafe fn vsync_count_thread(_: &skyline::hooks::InlineCtx) {
RUN.store(true, Ordering::SeqCst);
}
pub fn install(profiling_enabled: bool) {
if !profiling_enabled {
skyline::install_hook!(vsync_count_thread);
}
unsafe {
OFFSET1 = calc_nnsdk_offset() + 0x429d60;
OFFSET2 = calc_nnsdk_offset() + 0x26e94;
}
skyline::install_hooks!(
run_scene_update,
set_present_interval_nvn,
set_present_interval_android
);
}
+314
View File
@@ -0,0 +1,314 @@
use std::{
collections::{BTreeMap, HashMap},
sync::Mutex,
};
use skyline::{hooks::InlineCtx, patching::Patch};
#[repr(u64)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord)]
pub enum FrameStatus {
#[default]
Unknown,
Enqueued,
Presented,
}
#[repr(C, align(16))]
pub struct SystemEvent([u8; 256]);
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Display(*mut ());
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Layer(*mut ());
unsafe impl Send for Display {}
unsafe impl Sync for Display {}
unsafe impl Send for Layer {}
unsafe impl Sync for Layer {}
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct FrameInfo {
pub status: FrameStatus,
pub frame_number: u64,
pub enqueue_time: i64,
pub present_time: i64,
pub vblank_time: i64,
}
unsafe extern "C" {
#[link_name = "_ZN2nn2vi16ListFrameHistoryEPNS0_9FrameInfoEiPKNS0_5LayerE"]
fn list_frame_info(frame_info: *mut FrameInfo, count: i32, layer: Layer) -> i32;
#[link_name = "_ZN2nn2vi20GetDisplayVsyncEventEPNS_2os15SystemEventTypeEPNS0_7DisplayE"]
fn get_display_vsync_event(event: *mut SystemEvent, display: Display) -> u32;
#[link_name = "_ZN2nn2os15WaitSystemEventEPNS0_15SystemEventTypeE"]
fn wait_system_event(event: *mut SystemEvent);
#[link_name = "_ZN2nn2vi20GetLatestFrameNumberEPmPKNS0_5LayerE"]
fn get_latest_frame_number(number: &mut u64, layer: Layer) -> u32;
#[link_name = "_ZN2nn2os13GetSystemTickEv"]
pub fn get_system_tick() -> i64;
#[link_name = "_ZN2nn2os17ConvertToTimeSpanENS0_4TickE"]
fn convert_to_timespan(tick: i64) -> i64;
}
static mut SYSTEM_EVENT: SystemEvent = SystemEvent([0u8; 256]);
#[derive(Default, Copy, Clone)]
pub struct ApplicationFrameInfo {
pub acquire_invocation: i64,
pub acquire_finish: i64,
pub sync_finish: i64,
pub init_exit: i64,
pub input: i64,
}
impl ApplicationFrameInfo {
const fn new() -> Self {
Self {
acquire_invocation: 0,
acquire_finish: 0,
sync_finish: 0,
init_exit: 0,
input: 0,
}
}
}
pub static mut FRAMES_IN_FLIGHT: [ApplicationFrameInfo; 3] =
[const { ApplicationFrameInfo::new() }; 3];
static mut LAYER: Layer = Layer(std::ptr::null_mut());
#[skyline::hook(offset = 0x386fca0, inline)]
unsafe fn call_acquire_texture_wrapper(ctx: &mut InlineCtx) {
static mut ACQUIRE_TEXTURE_PTR: Option<extern "C" fn(u64, u64, *mut i32) -> u32> = None;
if ACQUIRE_TEXTURE_PTR.is_none() {
let base = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text);
ACQUIRE_TEXTURE_PTR = Some(*base.cast::<u8>().add(0x593fb50).cast::<extern "C" fn(
u64,
u64,
*mut i32,
) -> u32>());
}
let ptr = ACQUIRE_TEXTURE_PTR.unwrap_unchecked();
let frame_ptr = ctx.registers[2].x() as *mut i32;
let invocation_tick = get_system_tick();
let result = ptr(ctx.registers[0].x(), ctx.registers[1].x(), frame_ptr);
let finish_tick = get_system_tick();
ctx.registers[0].set_w(result);
// println!("Acquired {}", *frame_ptr);
if result == 0 {
FRAMES_IN_FLIGHT[*frame_ptr as usize].acquire_invocation = invocation_tick;
FRAMES_IN_FLIGHT[*frame_ptr as usize].acquire_finish = finish_tick;
}
}
#[skyline::hook(offset = 0x386fce0, inline)]
unsafe fn record_sync_finish(ctx: &InlineCtx) {
let ptr = (ctx.registers[23].x() + 0x30) as *const i32;
FRAMES_IN_FLIGHT[*ptr as usize].sync_finish = get_system_tick();
}
#[skyline::hook(offset = 0x386fc80, inline)]
unsafe fn present_texture_wrapper(ctx: &InlineCtx) {
static mut PRESENT_TEXTURE_PTR: Option<extern "C" fn(u64, u64, i32)> = None;
if PRESENT_TEXTURE_PTR.is_none() {
let base = skyline::hooks::getRegionAddress(skyline::hooks::Region::Text);
PRESENT_TEXTURE_PTR = Some(
*base
.cast::<u8>()
.add(0x593fac8)
.cast::<extern "C" fn(u64, u64, i32)>(),
);
}
let ptr = PRESENT_TEXTURE_PTR.unwrap_unchecked();
let frame = ctx.registers[2].w() as i32;
let present_tick = get_system_tick();
ptr(ctx.registers[0].x(), ctx.registers[1].x(), frame);
let mut frame_number = 0u64;
if get_latest_frame_number(&mut frame_number, LAYER) == 0 {
let frame_in_flight = FRAMES_IN_FLIGHT[frame as usize];
crate::frametracer::frame(
"window_acquire",
frame_number as usize,
frame_in_flight.acquire_finish,
);
crate::frametracer::frame(
"wait_texture",
frame_number as usize,
frame_in_flight.sync_finish,
);
crate::frametracer::frame(
"previous_submit_finish",
frame_number as usize,
frame_in_flight.init_exit,
);
crate::frametracer::frame("poll_inputs", frame_number as usize, frame_in_flight.input);
crate::frametracer::frame("queue_present", frame_number as usize, present_tick);
}
}
pub fn vsync_thread(layer: Layer, display: Display) {
let mut system_event = SystemEvent([0u8; 256]);
unsafe {
assert_eq!(get_display_vsync_event(&mut system_event, display), 0);
}
let max_frame_info = unsafe { list_frame_info(std::ptr::null_mut(), 0, layer) };
let mut frame_infos = vec![FrameInfo::default(); max_frame_info as usize];
let mut last_frame_enqueued = 0;
let mut last_frame_presented = 0;
loop {
unsafe {
wait_system_event(&mut system_event);
}
let num_frames =
unsafe { list_frame_info(frame_infos.as_mut_ptr(), max_frame_info, layer) };
println!("{:?}", &frame_infos[..num_frames as usize]);
for frame_info in &frame_infos[..num_frames as usize] {
match frame_info.status {
FrameStatus::Unknown => {}
FrameStatus::Enqueued => {
if frame_info.frame_number > last_frame_enqueued {
crate::frametracer::frame(
"vi_enqueue",
frame_info.frame_number as usize,
frame_info.enqueue_time,
);
last_frame_enqueued = frame_info.frame_number;
}
}
FrameStatus::Presented => {
if frame_info.frame_number > last_frame_presented {
println!("Finishing!");
crate::frametracer::frame(
"vi_presented",
frame_info.frame_number as usize,
frame_info.enqueue_time,
);
crate::frametracer::frame(
"vi_vblank",
frame_info.frame_number as usize,
frame_info.vblank_time,
);
crate::frametracer::finish_frame(frame_info.frame_number as usize);
crate::frametracer::marker("vblank", frame_info.vblank_time);
last_frame_presented = frame_info.frame_number;
}
}
}
}
}
}
#[skyline::hook(offset = 0x3743ca0, inline)]
unsafe fn grab_vi_layer_handle(ctx: &InlineCtx) {
let p_display_info = ctx.registers[19].x();
let display = *((p_display_info + 0x70) as *const Display);
let layer = *((p_display_info + 0x78) as *const Layer);
LAYER = layer;
let _ = std::thread::spawn(move || {
vsync_thread(layer, display);
});
}
pub unsafe fn flush() {
static mut POINTER: Option<*const ()> = None;
if POINTER.is_none() {
POINTER = Some(
*skyline::hooks::getRegionAddress(skyline::hooks::Region::Text)
.cast::<u8>()
.add(0x5334e90)
.cast::<*const ()>(),
);
}
let ptr = POINTER.unwrap_unchecked().cast::<*const ()>();
let ptr = **ptr.cast::<*const *const ()>().add(1);
let sub_ptr = *ptr.cast::<*const ()>().add(0x88 / 8);
let flag = *ptr.cast::<u8>().add(0xec);
let function = *(*sub_ptr.cast::<*const *const ()>())
.add(0x3)
.cast::<extern "C" fn(*const (), u8)>();
function(sub_ptr, flag);
*ptr.cast::<u8>().cast_mut().add(0xec) = 0;
}
pub unsafe fn current_frame_in_flight() -> i32 {
static mut POINTER: Option<*const ()> = None;
if POINTER.is_none() {
POINTER = Some(
*skyline::hooks::getRegionAddress(skyline::hooks::Region::Text)
.cast::<u8>()
.add(0x5334e90)
.cast::<*const ()>(),
);
}
let ptr = POINTER.unwrap_unchecked().cast::<*const ()>();
let ptr = **ptr.cast::<*const *const ()>().add(1);
let ptr = *ptr.cast::<u8>().add(0xa8).cast::<*const ()>();
*ptr.cast::<u8>().add(0x30).cast::<i32>()
}
#[skyline::hook(offset = 0x386ff14, inline)]
unsafe fn record_init_exit(ctx: &InlineCtx) {
let tick = get_system_tick();
let p_frame = (*((ctx.registers[19].x() + 0xa8) as *const u64) + 0x30) as *const i32;
FRAMES_IN_FLIGHT[*p_frame as usize].init_exit = tick;
}
#[skyline::hook(offset = 0x374c118, inline)]
unsafe fn record_input(ctx: &InlineCtx) {
let tick = get_system_tick();
// println!("{}", current_frame_in_flight());
FRAMES_IN_FLIGHT[current_frame_in_flight() as usize].input = tick;
}
#[skyline::hook(offset = 0x386ff28, inline)]
fn print_sync_wait_result(ctx: &InlineCtx) {
println!("Sync Wait: {}", ctx.registers[8].x());
}
pub fn install() {
Patch::in_text(0x3860674).nop().unwrap();
Patch::in_text(0x386fca0).nop().unwrap();
Patch::in_text(0x386fc80).nop().unwrap();
Patch::in_text(0x3810a40).data(0xD65F03C0u32).unwrap();
skyline::install_hooks!(
grab_vi_layer_handle,
present_texture_wrapper,
call_acquire_texture_wrapper,
record_sync_finish,
record_init_exit,
record_input
);
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.