mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-25 18:48:51 -04:00
Triforce v0.8.0
Evil HD (SMAA Ultra, 16x filtering, full textures, ambient occlusion with bounce light, sunlight shafts, foliage drawn 4x as far, the remastered texture pack's loader and the launcher's download of it), FSR 3.1 frame generation for every GPU, Intel XeSS, FSR 4 model choice, ReShade presets, Auto (this PC), HUD placement, the options menu in 13 languages, a second input for every control, hold to toggle, DualSense speaker and haptics, NFC from the player's own dumps, the above-60 fps game fixes, the Debug tab's flight and Inventory fixes, the launcher's full settings, and over 250 fixes.
This commit is contained in:
32
third_party/renhdrum/Cargo.lock
generated
vendored
Normal file
32
third_party/renhdrum/Cargo.lock
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "renhdrum"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
28
third_party/renhdrum/Cargo.toml
vendored
Normal file
28
third_party/renhdrum/Cargo.toml
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "renhdrum"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
authors = ["Three-Dola"]
|
||||
description = "Real-time Nintendo Switch HD Rumble & Sony DualSense audio haptics engine in Rust with a zero-allocation C ABI"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/trzz1214/RenHDrum"
|
||||
homepage = "https://ryuhdr.threedola.workers.dev"
|
||||
readme = "README.md"
|
||||
keywords = ["hd-rumble", "dualsense", "haptics", "sdl3", "emulation"]
|
||||
categories = ["game-development", "hardware-support", "multimedia::audio"]
|
||||
|
||||
[lib]
|
||||
name = "renhdrum"
|
||||
crate-type = ["cdylib", "staticlib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = "symbols"
|
||||
201
third_party/renhdrum/LICENSE-APACHE
vendored
Normal file
201
third_party/renhdrum/LICENSE-APACHE
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
lienne to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Three-Dola
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
21
third_party/renhdrum/LICENSE-MIT
vendored
Normal file
21
third_party/renhdrum/LICENSE-MIT
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Three-Dola
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
118
third_party/renhdrum/NOTICE
vendored
Normal file
118
third_party/renhdrum/NOTICE
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
RenHDrum
|
||||
Copyright (c) 2026 Three-Dola
|
||||
|
||||
This product includes software developed by Three-Dola (https://github.com/trzz1214/RenHDrum).
|
||||
|
||||
The RenHDrum core library (src/, include/, tests/, examples/, and docs/) is dual-licensed
|
||||
under either:
|
||||
* MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
|
||||
* Apache License, Version 2.0 (LICENSE-APACHE or http://opensource.org/licenses/LICENSE-2.0)
|
||||
at your option.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Attributions & Third-Party Credits
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
1. Ryujinx & Ryubing
|
||||
Parts of the HD Rumble DSP logic, packet structures, and state transitions
|
||||
originated from Ryujinx and the Ryuhdr project (with contributions from GreemDev).
|
||||
Copyright (c) Ryujinx Team and Contributors.
|
||||
Licensed under the MIT License.
|
||||
|
||||
2. dekuNukem (Nintendo_Switch_Reverse_Engineering)
|
||||
HD Rumble frequency encoding formulas, 101-entry non-linear amplitude lookup
|
||||
table, neutral stop packet, and Subcommand 0x10 protocol documentation
|
||||
(rumble_data_table.md and bluetooth_hid_notes.md).
|
||||
https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
|
||||
|
||||
3. Switchbrew Wiki Contributors
|
||||
Reverse engineering documentation of Nintendo Switch HidMotorData,
|
||||
VibrationAmFmPackTag 4-byte bit-packing layouts, and AmFmCodes unpacking tables.
|
||||
https://switchbrew.org/wiki/Joy-Con
|
||||
|
||||
4. felipearmat (OGX-Mini-2026 PR #116)
|
||||
5-bit logarithmic amplitude decoder scale -0.5 * (code - 1) with -0.84375 offset
|
||||
relative to 7-bit peak in HdRumble.cpp and HdRumble.h, and Steam UI tick packet analysis
|
||||
(repo MegaCadeDev/OGX-Mini-2026, fork of wiredopposite/OGX-Mini).
|
||||
Referenced only; no code copied.
|
||||
https://github.com/MegaCadeDev/OGX-Mini-2026/pull/116
|
||||
|
||||
5. rei-github, ClearlyClaire (dekuNukem Issue #11) & CTCaer (jc_toolkit)
|
||||
Oscilloscope exponential amplitude decay measurements, alternative bit-layouts,
|
||||
and hardware packet captures.
|
||||
https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/issues/11
|
||||
https://github.com/CTCaer/jc_toolkit
|
||||
|
||||
6. Nielk1 & DualSense Reverse-Engineering Community
|
||||
DualSense 10-zone Adaptive Trigger bit-packing, Linux hid-playstation, and
|
||||
4-channel 48 kHz USB Audio Class VCM routing.
|
||||
https://gist.github.com/Nielk1/6d54cc2c00d2201ccb8c2720ad7538db
|
||||
|
||||
7. Simple DirectMedia Layer (SDL)
|
||||
Patches in integrations/sdl3/sdl3-patches/ are derived from SDL (libsdl-org/SDL,
|
||||
with contributions from Valve Corporation and SDL Contributors).
|
||||
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>.
|
||||
Licensed under the zlib License (see integrations/sdl3/sdl3-patches/LICENSE).
|
||||
|
||||
8. Brontide Reference Integration Patches
|
||||
Patches in integrations/brontide/ apply to Eden / Yuzu emulation codebases.
|
||||
Copyright (c) 2026 Three-Dola and the Eden / Yuzu Contributors.
|
||||
Licensed under the GNU General Public License, version 3 or later (GPL-3.0-or-later)
|
||||
(see integrations/brontide/LICENSE).
|
||||
|
||||
9. egormanga (SAxense)
|
||||
DualSense Bluetooth haptics report 0x32 layout documentation (packet 0x11 + 0x12,
|
||||
s8 3 kHz PCM, CRC seed 0xA2).
|
||||
Format reference only; no code copied.
|
||||
Licensed under Mozilla Public License 2.0 (MPL-2.0).
|
||||
https://github.com/egormanga/SAxense
|
||||
https://apps.sdore.me/SAxense
|
||||
|
||||
10. Franseven (PokeDinner)
|
||||
Author of PokeDinner 2.5.0 (commit 216b5034c6, tag 2.5.0), the baseline
|
||||
Switch 2 emulator testbed used for Brontide-NS2.
|
||||
Licensed under the GNU General Public License, version 3 or later (GPL-3.0-or-later).
|
||||
|
||||
11. neo Luigi (Eglantine PR #155)
|
||||
Original implementation of nn::hid::IHidServer command 214
|
||||
(SendVibrationValuesInMode) dispatching (commits 2b413a46a2 and 465aa33077).
|
||||
Licensed under the GNU General Public License, version 3 or later (GPL-3.0-or-later).
|
||||
|
||||
12. samaBR85 (renhdrum-eden)
|
||||
Patch adaptations porting RenHDrum into Eglantine and Lichii, independent Switch 2
|
||||
in-game trace verification, and SDL Raw Input deadlock resolution.
|
||||
Licensed under the GNU General Public License, version 3 or later (GPL-3.0-or-later).
|
||||
https://github.com/samaBR85/renhdrum-eden
|
||||
|
||||
13. Frizti, zortos293, Dark (Fritchii v5.5 / Lichii / Dynamic FPS)
|
||||
Authors of Fritchii v5.5 (commit 4012e5271e), Lichii, and Dynamic FPS, providing
|
||||
the baseline Switch 2 emulator platform used for Brontide-oot.
|
||||
Licensed under the GNU General Public License, version 3 or later (GPL-3.0-or-later).
|
||||
|
||||
14. NotRexed & Hookshot Contributors (Hookshot)
|
||||
Authors of Hookshot (OoT Switch 2 Recompiler, tag v2.1.0, synced to commit fa734ed),
|
||||
providing the reference static recompilation testbed for integrations/recomp-c/
|
||||
(see integrations/recomp-c/reference/).
|
||||
Licensed under the GNU General Public License, version 3 (GPL-3.0).
|
||||
https://github.com/NotRexed/Hookshot
|
||||
|
||||
15. iafx, LiveHaptics, and hckrman101 (Hookshot PR #1213)
|
||||
Steam Controller (2026) grip HID report 0x86 / 0x88 protocol and hardware
|
||||
measurements by iafx (RenHDrum#5, iafx/Lichii); PCM stream format discovery
|
||||
by LiveHaptics (MIT); Bluetooth newest-sample fallback pacing idea from
|
||||
Hookshot PR #1213 by hckrman101 (GPL-3.0).
|
||||
Referenced only; no code copied.
|
||||
|
||||
16. ragnarok179 (Enhanced-PS5-DualSense-Haptics-Bridge)
|
||||
DualSense Bluetooth combined output report 0x36 layout (sub-packets 0x11 / 0x10 / 0x12 / 0x13,
|
||||
CRC32 seed 0xA2, 10 ms / 480-sample Opus CBR 160 kb/s speaker framing), from
|
||||
Source/bluetooth_audio_packets.go, Source/dualsense_reports.go,
|
||||
Source/bluetooth_opus_ffmpeg_windows.go, and Source/speaker_opus_assets.go.
|
||||
Layout and resampling reimplemented in Rust. Licensed under the MIT License.
|
||||
https://github.com/ragnarok179/Enhanced-PS5-DualSense-Haptics-Bridge
|
||||
|
||||
17. Xiph.Org Foundation, Skype Limited, Jean-Marc Valin, Koen Vos & Opus Contributors (libopus)
|
||||
Reference Opus audio codec (xiph/opus v1.5.2), vendored in vendor/opus/ and statically linked
|
||||
for DualSense Bluetooth speaker encoding (48 kHz stereo CBR 160 kb/s).
|
||||
Licensed under the 3-Clause BSD License (see vendor/opus/COPYING).
|
||||
https://opus-codec.org/ · https://github.com/xiph/opus
|
||||
35
third_party/renhdrum/PROVENANCE.md
vendored
Normal file
35
third_party/renhdrum/PROVENANCE.md
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
# RenHDrum
|
||||
|
||||
RenHDrum is the HD Rumble and DualSense haptics core the game's fine haptics come from: it turns the console's own
|
||||
vibration values (a low and a high band, an amplitude and a frequency each, per side) into the four-channel 48 kHz audio
|
||||
a DualSense's voice coils play on a USB cable. Copyright (c) 2026 Three-Dola, MIT OR Apache-2.0 (`LICENSE-MIT`,
|
||||
`LICENSE-APACHE`, `NOTICE`).
|
||||
|
||||
These are the files of <https://github.com/trzz1214/RenHDrum> at the **v0.5.0** tag (commit
|
||||
`e778da6e169640e225a7f898b77cbb40af97c60f`) that the library is built from, unmodified: `Cargo.toml`, `Cargo.lock` (no
|
||||
dependency the library links; one build dependency, the `cc` crate, with the two it needs), `build.rs`, `src/`,
|
||||
`include/renhdrum.h` (the C ABI `host/rumble_renhdrum.c` binds at run time; `RENHDRUM_VERSION 0x000500`, and any 0.5.x
|
||||
keeps it), the licences and the notice. Its tests, examples, documentation and integrations are left out, and so are the
|
||||
repository's GPL-3.0-or-later parts (`integrations/brontide`, `integrations/recomp-c/reference`).
|
||||
|
||||
`vendor/opus/` (libopus 1.5.2, BSD 3-clause, which `build.rs` compiles into the library for the DualSense's Bluetooth
|
||||
speaker) is left out too: it is the same release as `third_party/opus`, file for file but for its Windows line endings
|
||||
and three headers no file it builds includes (`celt/fixed_c5x.h`, `celt/fixed_c6x.h`, `src/tansig_table.h`), and
|
||||
`scripts/renhdrum.py` puts `third_party/opus` where `build.rs` reads it (without `celt/opus_custom_demo.c`, a program of
|
||||
its own that upstream's copy does not have). Its licence is `third_party/opus/COPYING`.
|
||||
|
||||
upstream: https://github.com/trzz1214/RenHDrum/archive/refs/tags/v0.5.0.tar.gz
|
||||
upstream-sha256: 4e922ffb6ac15cba85dd6bf29277def7daaa28459c6e2690e04df58c49594cf7
|
||||
upstream-root: RenHDrum-0.5.0
|
||||
|
||||
**How it reaches the game.** (Triforce) `py -3 -I scripts/renhdrum.py build` compiles it by hand into `renhdrum.dll`
|
||||
(ignored by git) for x86_64-pc-windows-gnullvm, with a pinned Rust and the llvm-mingw the game is built with (its clang
|
||||
compiles libopus too), and the `cc` crate downloaded by the SHA-256 `Cargo.lock` gives it; the same source gives the same
|
||||
bytes. Triforce's release scripts do not build it yet. When it is in this folder, `nx2/build.py` copies it beside the
|
||||
game. `host/rumble_renhdrum.c` loads it (`renhdrum.dll`, `renhdrum.so` on Linux) from the game's own folder by full path;
|
||||
without it, or with a file that will not load, every controller keeps its motors or its own HD rumble, as before, and the
|
||||
log and the Controls tab's Vibration row say why.
|
||||
|
||||
**A newer RenHDrum.** Replace these files with the new tag's, change the commit and the three `upstream` lines, and check
|
||||
`host/rumble_renhdrum.c`'s `RH_ABI` against the new `include/renhdrum.h`. If its `vendor/opus` is a new libopus,
|
||||
`third_party/opus` moves to it first (the game builds it too).
|
||||
62
third_party/renhdrum/build.rs
vendored
Normal file
62
third_party/renhdrum/build.rs
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn collect_c_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.unwrap_or_else(|e| panic!("failed to read {}: {e}", dir.display()))
|
||||
.filter_map(|res| res.ok().map(|e| e.path()))
|
||||
.filter(|p| p.extension().is_some_and(|ext| ext == "c"))
|
||||
.collect();
|
||||
entries.sort();
|
||||
out.extend(entries);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let opus_dir = Path::new("vendor/opus");
|
||||
println!("cargo:rerun-if-changed={}", opus_dir.display());
|
||||
|
||||
let mut sources = Vec::new();
|
||||
collect_c_files(&opus_dir.join("celt"), &mut sources);
|
||||
collect_c_files(&opus_dir.join("silk"), &mut sources);
|
||||
collect_c_files(&opus_dir.join("silk/float"), &mut sources);
|
||||
for core_file in [
|
||||
"opus.c",
|
||||
"opus_encoder.c",
|
||||
"opus_decoder.c",
|
||||
"repacketizer.c",
|
||||
"extensions.c",
|
||||
"analysis.c",
|
||||
"mlp.c",
|
||||
"mlp_data.c",
|
||||
] {
|
||||
sources.push(opus_dir.join("src").join(core_file));
|
||||
}
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build
|
||||
.include(opus_dir.join("include"))
|
||||
.include(opus_dir.join("celt"))
|
||||
.include(opus_dir.join("silk"))
|
||||
.include(opus_dir.join("silk/float"))
|
||||
.include(opus_dir.join("src"))
|
||||
.define("OPUS_BUILD", None)
|
||||
.define("USE_ALLOCA", None)
|
||||
.define("HAVE_LRINTF", None)
|
||||
.define("HAVE_LRINT", None)
|
||||
.define("FLOAT_APPROX", None)
|
||||
.define("DISABLE_DEBUG_FLOAT", None)
|
||||
.define("ENABLE_HARDENING", None)
|
||||
.define("PACKAGE_VERSION", "\"1.5.2\"")
|
||||
.warnings(false);
|
||||
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
||||
let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
|
||||
if target_os != "windows" {
|
||||
build.define("HAVE_ALLOCA_H", None);
|
||||
}
|
||||
if target_env == "msvc" {
|
||||
build.define("_CRT_SECURE_NO_WARNINGS", None);
|
||||
}
|
||||
|
||||
build.files(&sources);
|
||||
build.compile("opus");
|
||||
}
|
||||
441
third_party/renhdrum/include/renhdrum.h
vendored
Normal file
441
third_party/renhdrum/include/renhdrum.h
vendored
Normal file
@@ -0,0 +1,441 @@
|
||||
#ifndef RENHDRUM_H
|
||||
#define RENHDRUM_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define RENHDRUM_VERSION 0x000500
|
||||
|
||||
#define RENHDRUM_OK 0
|
||||
#define RENHDRUM_ERR_NULL_PTR -1
|
||||
#define RENHDRUM_ERR_INVALID_ARG -2
|
||||
#define RENHDRUM_ERR_DECODE_FAILED -3
|
||||
|
||||
typedef struct RenHdcSettings {
|
||||
bool enabled;
|
||||
int32_t usb_interval_ms;
|
||||
int32_t bluetooth_level; /* 1-4, 4 = Compatible (default) */
|
||||
bool usb_auto_slow;
|
||||
bool sync_to_input;
|
||||
bool click_pulse;
|
||||
bool sync_bluetooth;
|
||||
bool usb_no_queue;
|
||||
int32_t usb_pause_ms;
|
||||
bool envelope_5ms;
|
||||
bool frequency_in_packet;
|
||||
bool frequency_both_bands;
|
||||
bool bt_after_input;
|
||||
bool crisp_notes;
|
||||
bool bt_crisp_notes;
|
||||
bool bt_fast;
|
||||
} RenHdcSettings;
|
||||
|
||||
typedef struct RenHdcConfig {
|
||||
bool enable_hd_rumble;
|
||||
int32_t hd_rumble_usb_interval_ms;
|
||||
int32_t hd_rumble_bluetooth_level;
|
||||
bool hd_rumble_usb_auto_slow;
|
||||
bool hd_rumble_experimental_usb_no_queue;
|
||||
bool hd_rumble_experimental_envelope_5ms;
|
||||
bool hd_rumble_experimental_frequency_in_packet;
|
||||
bool hd_rumble_experimental_frequency_both_bands;
|
||||
bool hd_rumble_experimental_bt_after_input;
|
||||
bool hd_rumble_experimental_bt_fast;
|
||||
bool hd_rumble_experimental_crisp_notes;
|
||||
bool hd_rumble_experimental_bt_crisp_notes;
|
||||
bool hd_rumble_experimental_sync_to_input;
|
||||
bool hd_rumble_experimental_click_pulse;
|
||||
bool hd_rumble_experimental_sync_bluetooth;
|
||||
bool hd_rumble_sync_auto_slow;
|
||||
float strong_rumble;
|
||||
float weak_rumble;
|
||||
bool enable_rumble;
|
||||
bool enable_adaptive_triggers;
|
||||
bool enable_dualsense_haptics;
|
||||
int32_t dualsense_haptics_volume;
|
||||
bool dualsense_crisp_notes;
|
||||
bool dualsense_bt_crisp_notes;
|
||||
bool dualsense_hd_haptics_off; /* false = HD Haptics on (default): DualSense USB speaker + trigger kick */
|
||||
} RenHdcConfig;
|
||||
|
||||
typedef struct RenHdSideSample {
|
||||
float amp_low;
|
||||
float freq_low;
|
||||
float amp_high;
|
||||
float freq_high;
|
||||
} RenHdSideSample;
|
||||
|
||||
typedef struct RenHdClickSide {
|
||||
int32_t kind; /* 0 = DualResonance3Pulse, 1 = SingleWaveResonance */
|
||||
int32_t res_high_code;
|
||||
int32_t res_low_code;
|
||||
int32_t pulse1_code;
|
||||
int32_t pulse2_code;
|
||||
bool res_high_off;
|
||||
bool res_low_off;
|
||||
bool pulse1_off;
|
||||
bool pulse2_off;
|
||||
int32_t amp7;
|
||||
int32_t freq7;
|
||||
bool freq_is_high;
|
||||
} RenHdClickSide;
|
||||
|
||||
uint32_t renhdrum_version(void);
|
||||
|
||||
int32_t renhdrum_settings_default(RenHdcSettings *out_settings);
|
||||
int32_t renhdrum_settings_resolve(const RenHdcConfig *config, RenHdcSettings *out_settings);
|
||||
/* Use this when the host is not Brontide: reads no IPC and no flag files, only `config`. */
|
||||
/* NULL config gives the same result as renhdrum_settings_default. */
|
||||
int32_t renhdrum_settings_resolve_pure(const RenHdcConfig *config, RenHdcSettings *out_settings);
|
||||
|
||||
int32_t renhdrum_preset_apply(int32_t kind, RenHdcConfig *config);
|
||||
int32_t renhdrum_preset_detect(const RenHdcConfig *config, int32_t *out_kind);
|
||||
|
||||
/* Settings table + value store (see docs/integration/c-abi-reference.md "Settings table"). */
|
||||
typedef struct RenHdcOption {
|
||||
const char *key; /* never changes after release */
|
||||
const char *label; /* EN */
|
||||
const char *help; /* EN, may be empty */
|
||||
const char *choices; /* CHOICE kind: "Detailed (5 ms)|Compatible"; else empty */
|
||||
int32_t kind; /* 0 BOOL, 1 PERCENT/INT, 2 CHOICE (value = index) */
|
||||
int32_t min, max, step, def;
|
||||
uint32_t devices; /* bit: 1 Switch, 2 DualSense, 4 Xbox, 8 Steam */
|
||||
int32_t tier; /* 0 Basic, 1 Advanced */
|
||||
int32_t link; /* 0 any, 1 USB only, 2 Bluetooth only */
|
||||
int32_t requires_row; /* (not "requires": C++20 keyword) row index that must be non-zero for this row to matter, -1 = none */
|
||||
} RenHdcOption;
|
||||
const RenHdcOption *renhdrum_options(int32_t *out_count, int32_t *out_stride);
|
||||
|
||||
typedef struct RenHdcStore RenHdcStore; /* values; host-owned, not thread-safe */
|
||||
RenHdcStore *renhdrum_store_create(void); /* recommended defaults */
|
||||
void renhdrum_store_destroy(RenHdcStore *s);
|
||||
int32_t renhdrum_store_get(const RenHdcStore *s, const char *key, int32_t *out);
|
||||
int32_t renhdrum_store_set(RenHdcStore *s, const char *key, int32_t value); /* clamped to [min,max]; unknown key = RENHDRUM_ERR_INVALID_ARG */
|
||||
int32_t renhdrum_store_reset(RenHdcStore *s);
|
||||
int32_t renhdrum_store_is_recommended(const RenHdcStore *s, bool *out);
|
||||
int32_t renhdrum_store_to_config(const RenHdcStore *s, RenHdcConfig *out);
|
||||
/* Intensity (`gain`) + weak-rumble lift (`low_boost`) of the store applied to one amplitude 0..1. */
|
||||
float renhdrum_store_shape_amplitude(const RenHdcStore *s, float amplitude);
|
||||
|
||||
/* Xbox "Direct" mode (store key xbox_mode = 1). Returns a mask: bit 0 = send grips out_motors4[0..2]
|
||||
(SDL_RumbleJoystick, 2000 ms), bit 1 = send triggers out_motors4[2..4] (SDL_RumbleJoystickTriggers,
|
||||
2000 ms), 0 = nothing to send, <0 = error. Pass raw game amplitudes; gain / low_boost / xbox_* come
|
||||
from the store. `triggers`: the pad has trigger motors the host drives. */
|
||||
typedef struct RenHdcXboxDirect RenHdcXboxDirect;
|
||||
RenHdcXboxDirect *renhdrum_xbox_direct_create(void);
|
||||
void renhdrum_xbox_direct_destroy(RenHdcXboxDirect *d);
|
||||
int32_t renhdrum_xbox_direct_push(
|
||||
RenHdcXboxDirect *d,
|
||||
const RenHdcStore *s,
|
||||
int64_t now_us,
|
||||
bool is_right,
|
||||
float low_amp,
|
||||
float high_amp,
|
||||
bool triggers,
|
||||
uint16_t *out_motors4
|
||||
);
|
||||
/* Host timer: when a burst ends, returns the settled motor values (same mask). */
|
||||
int32_t renhdrum_xbox_direct_tick(RenHdcXboxDirect *d, int64_t now_us, bool triggers, uint16_t *out_motors4);
|
||||
|
||||
int32_t renhdrum_encode_standard_side(
|
||||
float low_freq,
|
||||
float low_amp,
|
||||
float high_freq,
|
||||
float high_amp,
|
||||
uint8_t *out_bytes4
|
||||
);
|
||||
|
||||
int32_t renhdrum_encode_standard_packet(
|
||||
float left_lf,
|
||||
float left_la,
|
||||
float left_hf,
|
||||
float left_ha,
|
||||
float right_lf,
|
||||
float right_la,
|
||||
float right_hf,
|
||||
float right_ha,
|
||||
uint8_t *out_bytes8
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_game_amplitude(int32_t code, float *out_amp);
|
||||
int32_t renhdrum_amfm_code(float game_amp);
|
||||
int32_t renhdrum_amfm_freq7(int32_t high, float freq);
|
||||
int32_t renhdrum_amfm_amp7(float game_amplitude);
|
||||
int32_t renhdrum_amfm_preset_code(int32_t high, int32_t freq7);
|
||||
|
||||
int32_t renhdrum_amfm_pack_three(
|
||||
int32_t lo0,
|
||||
int32_t hi0,
|
||||
int32_t lo1,
|
||||
int32_t hi1,
|
||||
int32_t lo2,
|
||||
int32_t hi2,
|
||||
uint32_t *out_val
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_pack_three_7bit(
|
||||
int32_t high,
|
||||
int32_t is_fm,
|
||||
int32_t value7,
|
||||
int32_t lo1,
|
||||
int32_t hi1,
|
||||
int32_t lo2,
|
||||
int32_t hi2,
|
||||
uint32_t *out_val
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_pack_two_14bit(
|
||||
int32_t high,
|
||||
int32_t freq7,
|
||||
int32_t amp7,
|
||||
int32_t other0,
|
||||
int32_t lo1,
|
||||
int32_t hi1,
|
||||
uint32_t *out_val
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_pack_two_14bit_level(
|
||||
int32_t high,
|
||||
int32_t freq7,
|
||||
float game_amplitude,
|
||||
int32_t other0,
|
||||
int32_t lo1,
|
||||
int32_t hi1,
|
||||
uint32_t *out_val
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_pack_two_14bit_reach(
|
||||
int32_t high,
|
||||
int32_t freq7,
|
||||
float game_amplitude,
|
||||
int32_t reach_code,
|
||||
float other_amplitude,
|
||||
int32_t lo1,
|
||||
int32_t hi1,
|
||||
uint32_t *out_val
|
||||
);
|
||||
|
||||
int32_t renhdrum_amfm_is_three_sample_side(const uint8_t *in_bytes4);
|
||||
|
||||
int32_t renhdrum_click_amp4(float amplitude);
|
||||
int32_t renhdrum_click_amp7(float amplitude);
|
||||
int32_t renhdrum_click_build_packet(float amp_l, float amp_r, uint8_t *out_packet10);
|
||||
|
||||
int32_t renhdrum_click_encode_side(const RenHdClickSide *side, uint8_t *out_bytes4);
|
||||
int32_t renhdrum_click_decode_side(const uint8_t *in_bytes4, RenHdClickSide *out_side);
|
||||
int32_t renhdrum_click_is_dual_wave_side(const uint8_t *in_bytes4);
|
||||
int32_t renhdrum_click_is_click_packet(const uint8_t *in_bytes10);
|
||||
|
||||
float renhdrum_crisp_slot_gain(int32_t slots_since_onset);
|
||||
int32_t renhdrum_crisp_apply(
|
||||
const RenHdSideSample *s,
|
||||
float gain,
|
||||
RenHdSideSample *out_sample,
|
||||
int32_t *out_capped
|
||||
);
|
||||
int32_t renhdrum_crisp_shape_slot(
|
||||
int32_t *slots_since_onset,
|
||||
const RenHdSideSample *s,
|
||||
RenHdSideSample *out_sample,
|
||||
int32_t *out_onset,
|
||||
int32_t *out_capped
|
||||
);
|
||||
|
||||
/* Opaque pointer types for stateful engines */
|
||||
typedef struct RenHdcEngine RenHdcEngine;
|
||||
typedef struct RenHdcDualSenseDsp RenHdcDualSenseDsp;
|
||||
typedef struct RenHdcXboxRumble RenHdcXboxRumble;
|
||||
|
||||
/* Thread safety: never call a handle's destroy in parallel with any other call on the same handle. */
|
||||
RenHdcEngine *renhdrum_engine_create(bool is_bluetooth, bool is_pro_controller);
|
||||
void renhdrum_engine_destroy(RenHdcEngine *engine);
|
||||
int32_t renhdrum_engine_apply_settings(RenHdcEngine *engine, const RenHdcSettings *settings);
|
||||
int32_t renhdrum_engine_push_sample(
|
||||
RenHdcEngine *engine,
|
||||
int64_t now_us,
|
||||
float left_al,
|
||||
float left_fl,
|
||||
float left_ah,
|
||||
float left_fh,
|
||||
float right_al,
|
||||
float right_fl,
|
||||
float right_ah,
|
||||
float right_fh
|
||||
);
|
||||
int32_t renhdrum_engine_push_half_sample(
|
||||
RenHdcEngine *engine,
|
||||
int64_t now_us,
|
||||
bool is_right,
|
||||
float al,
|
||||
float fl,
|
||||
float ah,
|
||||
float fh
|
||||
);
|
||||
int32_t renhdrum_engine_tick(RenHdcEngine *engine, int64_t now_us, uint8_t *out_packet10);
|
||||
|
||||
// volume_percent (clamped 10..100) is the final output gain; the core already applies it.
|
||||
// The host must NOT scale samples again before pushing them. The core exports no volume
|
||||
// setter yet: to change it, destroy and re-create the DSP object (no need to reopen the
|
||||
// audio stream). If the Brontide-App config is present in shared memory, it overrides both arguments.
|
||||
RenHdcDualSenseDsp *renhdrum_dualsense_dsp_create(int32_t volume_percent, bool crisp_notes);
|
||||
void renhdrum_dualsense_dsp_destroy(RenHdcDualSenseDsp *dsp);
|
||||
int32_t renhdrum_dualsense_dsp_set_target(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
float left_al,
|
||||
float left_fl,
|
||||
float left_ah,
|
||||
float left_fh,
|
||||
float right_al,
|
||||
float right_fl,
|
||||
float right_ah,
|
||||
float right_fh
|
||||
);
|
||||
int32_t renhdrum_dualsense_dsp_set_half_target(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
bool is_right,
|
||||
float al,
|
||||
float fl,
|
||||
float ah,
|
||||
float fh
|
||||
);
|
||||
/* Speaker channel (channel 1, USB) level 0..100 percent; 0 = off (default). */
|
||||
#define RENHDRUM_HD_HAPTICS_SPEAKER_PERCENT 60
|
||||
int32_t renhdrum_dualsense_dsp_set_speaker(RenHdcDualSenseDsp *dsp, int32_t percent);
|
||||
/* out_interleaved_4ch must hold frame_count * 4 floats. */
|
||||
int32_t renhdrum_dualsense_dsp_fill_f32(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
float *out_interleaved_4ch,
|
||||
size_t frame_count
|
||||
);
|
||||
/* DualSense over Bluetooth: one HID output report 0x32 every RENHDRUM_DS5_BT_PERIOD_NS.
|
||||
Report layout from SAxense by egormanga (https://apps.sdore.me/SAxense). */
|
||||
#define RENHDRUM_DS5_BT_REPORT_SIZE 142
|
||||
#define RENHDRUM_DS5_BT_PERIOD_NS 10666666ULL
|
||||
#define RENHDRUM_DS5_BT_BUFFER_LENGTH_DEFAULT 0xFF
|
||||
/* out_report142 must be a buffer of at least 142 bytes (RENHDRUM_DS5_BT_REPORT_SIZE). */
|
||||
int32_t renhdrum_dualsense_dsp_build_bt_report(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
uint8_t buffer_length,
|
||||
uint8_t *out_report142
|
||||
);
|
||||
/* DualSense over Bluetooth, combined report 0x36 (rumble + adaptive triggers + speaker), one per
|
||||
RENHDRUM_DS5_BT_PERIOD_NS. The speaker is one Opus frame (200 bytes) per report, on while HD Haptics is on
|
||||
(the core turns it on by itself if the host never called renhdrum_dualsense_dsp_set_speaker; hosts should
|
||||
call it on Bluetooth too). Layout after Enhanced-PS5-DualSense-Haptics-Bridge (MIT, ragnarok179).
|
||||
state47_or_null: 47-byte block (byte 0 bits 0x04 R2 / 0x08 L2, R2 effect [10..21], L2 [21..32]);
|
||||
NULL = triggers untouched. seq is reserved/unused. out_report398 needs 398 bytes.
|
||||
Returns 1 = send out_report398, 0 = nothing to send (rumble + triggers idle over 2 s), < 0 on error. */
|
||||
#define RENHDRUM_DS5_BT36_REPORT_SIZE 398
|
||||
int32_t renhdrum_dualsense_dsp_build_bt36_report(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
const uint8_t *state47_or_null,
|
||||
uint8_t seq,
|
||||
uint8_t *out_report398
|
||||
);
|
||||
/* Experimental: Steam Controller (2026) grips, report 0x88, built from iafx's measurements (RenHDrum#5).
|
||||
Create with renhdrum_valve_grip_dsp_create[_ex], then use renhdrum_dualsense_dsp_set_half_target and
|
||||
renhdrum_dualsense_dsp_destroy on the handle. One report every RENHDRUM_VALVE_GRIP_PERIOD_NS_*.
|
||||
build_report returns 1 when vibrating, 0 when silent, 2 (RENHDRUM_VALVE_GRIP_SKIP) when 40 ppm drift
|
||||
compensation skips this packet (only if created with drift_compensation = true; do not send, phase
|
||||
unchanged), < 0 on error (unknown format -> RENHDRUM_ERR_INVALID_ARG). out_report64: 64 bytes.
|
||||
mode_tick evaluates the 0x86 PCM mode keep-alive (on at first vibration, refresh every 3 s or on
|
||||
stalled=true, off after 100 ms silence) and writes 0 or 2 reports (4 bytes each) into out_reports8.
|
||||
mode_off writes 2 off reports (channels 2 and 5) into out_reports8 for detach/exit paths. */
|
||||
#define RENHDRUM_VALVE_GRIP_REPORT_SIZE 64
|
||||
#define RENHDRUM_VALVE_GRIP_FORMAT_MULAW_8K 8
|
||||
#define RENHDRUM_VALVE_GRIP_FORMAT_MULAW_4K 9
|
||||
#define RENHDRUM_VALVE_GRIP_PERIOD_NS_8K 3875000ULL
|
||||
#define RENHDRUM_VALVE_GRIP_PERIOD_NS_4K 7750000ULL
|
||||
#define RENHDRUM_VALVE_GRIP_SKIP 2
|
||||
#define RENHDRUM_VALVE_GRIP_MODE_REPORT_SIZE 4
|
||||
#define RENHDRUM_VALVE_GRIP_MODE_REPORT_COUNT 2
|
||||
#define RENHDRUM_VALVE_GRIP_MODE_REPORTS_SIZE 8
|
||||
RenHdcDualSenseDsp *renhdrum_valve_grip_dsp_create(int32_t volume_percent, bool crisp_notes);
|
||||
RenHdcDualSenseDsp *renhdrum_valve_grip_dsp_create_ex(
|
||||
int32_t volume_percent,
|
||||
bool crisp_notes,
|
||||
bool drift_compensation
|
||||
);
|
||||
int32_t renhdrum_valve_grip_build_report(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
uint8_t format,
|
||||
uint8_t *out_report64
|
||||
);
|
||||
int32_t renhdrum_valve_grip_mode_tick(
|
||||
RenHdcDualSenseDsp *dsp,
|
||||
uint8_t format,
|
||||
uint64_t now_ns,
|
||||
bool stalled,
|
||||
uint8_t *out_reports8
|
||||
);
|
||||
int32_t renhdrum_valve_grip_mode_off(
|
||||
uint8_t format,
|
||||
uint8_t *out_reports8
|
||||
);
|
||||
/* Vibration-reactive trigger (one handle per trigger). update: 1 = changed (11 bytes written to
|
||||
out11, pack with the DS5 effects state), 0 = unchanged, <0 = error. */
|
||||
typedef struct RenHdcTriTrigger RenHdcTriTrigger;
|
||||
RenHdcTriTrigger *renhdrum_tri_trigger_create(void);
|
||||
void renhdrum_tri_trigger_destroy(RenHdcTriTrigger *h);
|
||||
int32_t renhdrum_tri_trigger_update(
|
||||
RenHdcTriTrigger *h,
|
||||
uint32_t now_ms,
|
||||
uint8_t depth,
|
||||
float amp_low,
|
||||
float freq_low,
|
||||
float amp_high,
|
||||
float freq_high,
|
||||
bool fresh,
|
||||
uint8_t *out11
|
||||
);
|
||||
/* Player is pressing another button (call every tick while held, before update, same clock):
|
||||
a streak started strictly before this trigger was held counts as a posture and does not mute;
|
||||
a streak started with or after trigger hold (gap > 30 ms starts a new streak) mutes new pulses
|
||||
while held and for 500 ms after the last call. */
|
||||
void renhdrum_tri_trigger_note_action(RenHdcTriTrigger *h, uint32_t now_ms);
|
||||
/* 47-byte DS5EffectsState_t USB blocks for HD Haptics (speaker open/release, single-trigger update/off).
|
||||
Returns 0 on success, -1 (RENHDRUM_ERR_NULL_PTR) if out47 is NULL. */
|
||||
#define RENHDRUM_DS5_EFFECTS_SIZE 47
|
||||
int32_t renhdrum_hd_haptics_speaker_block(int32_t on, uint8_t *out47);
|
||||
int32_t renhdrum_hd_haptics_trigger_block(
|
||||
int32_t is_right,
|
||||
const uint8_t *effect11_or_null,
|
||||
uint8_t *out47
|
||||
);
|
||||
int32_t renhdrum_dualsense_evaluate_triggers(
|
||||
uint64_t title_id,
|
||||
bool zl_held,
|
||||
bool zr_held,
|
||||
bool rumble_on,
|
||||
int64_t rumble_on_ms,
|
||||
int64_t pulse_age_ms,
|
||||
uint8_t *out_ds5_effects47
|
||||
);
|
||||
|
||||
RenHdcXboxRumble *renhdrum_xbox_rumble_create(bool is_bluetooth);
|
||||
void renhdrum_xbox_rumble_destroy(RenHdcXboxRumble *rumble);
|
||||
int32_t renhdrum_xbox_rumble_push_half_sample(
|
||||
RenHdcXboxRumble *rumble,
|
||||
int64_t now_us,
|
||||
bool is_right,
|
||||
float low_amp,
|
||||
float low_freq,
|
||||
float high_amp,
|
||||
float high_freq
|
||||
);
|
||||
/* out_motors4: left grip, right grip, left trigger, right trigger. Returns 1 when they must be sent now. */
|
||||
int32_t renhdrum_xbox_rumble_tick(RenHdcXboxRumble *rumble, int64_t now_us, uint16_t *out_motors4);
|
||||
int32_t renhdrum_xbox_rumble_resend(RenHdcXboxRumble *rumble);
|
||||
|
||||
/* Switch 2 rumble mode: 0 = Switch 1 default / untouched, 2 = Switch 2 Mode 2 translation */
|
||||
void renhdrum_set_nx2_mode(int32_t mode);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RENHDRUM_H */
|
||||
7
third_party/renhdrum/src/backend/mod.rs
vendored
Normal file
7
third_party/renhdrum/src/backend/mod.rs
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
pub mod nintendo_hd;
|
||||
|
||||
pub use nintendo_hd::{
|
||||
HdSample, NintendoHdEngine, AM_FM_NO_QUEUE_GAP_MS, BT_SYNC_FEED_MS, BT_SYNC_MAX_GAP_MS,
|
||||
BT_SYNC_MIN_GAP_MS, BT_SYNC_SKIP_AMP, BT_SYNC_SKIP_HIGH_FREQ, BT_SYNC_SKIP_LOW_FREQ,
|
||||
KEEP_ALIVE_TIMEOUT_MS, NO_QUEUE_FEED_MS, SYNC_FEED_MS,
|
||||
};
|
||||
946
third_party/renhdrum/src/backend/nintendo_hd.rs
vendored
Normal file
946
third_party/renhdrum/src/backend/nintendo_hd.rs
vendored
Normal file
@@ -0,0 +1,946 @@
|
||||
use crate::detectors::{HdClickDetector, HdDenseDetector, HdShortPulseCounter};
|
||||
use crate::encoding::click::HdClickEncoding;
|
||||
use crate::encoding::crisp_notes::{HdCrispNotes, HdSideSample};
|
||||
use crate::encoding::standard::{
|
||||
hd_amp_index, hd_encode_side, hd_is_neutral, hd_is_silent_packet, hd_is_small_change,
|
||||
HdBtLevel, HD_BT_LEVELS,
|
||||
};
|
||||
use crate::planner::amfm_planner::HdAmFmPlanner;
|
||||
use crate::settings::HdRumbleSettings;
|
||||
|
||||
/// Bluetooth sync profile constants.
|
||||
pub const BT_SYNC_MIN_GAP_MS: i32 = 60;
|
||||
pub const BT_SYNC_MAX_GAP_MS: i32 = 120;
|
||||
pub const BT_SYNC_SKIP_AMP: i32 = 2;
|
||||
pub const BT_SYNC_SKIP_HIGH_FREQ: i32 = 16;
|
||||
pub const BT_SYNC_SKIP_LOW_FREQ: i32 = 4;
|
||||
|
||||
/// Cadence constants.
|
||||
pub const BT_SYNC_FEED_MS: i32 = 15;
|
||||
pub const SYNC_FEED_MS: i32 = 8;
|
||||
pub const NO_QUEUE_FEED_MS: i32 = 4;
|
||||
pub const AM_FM_NO_QUEUE_GAP_MS: i32 = 10;
|
||||
pub const KEEP_ALIVE_TIMEOUT_MS: i32 = 150;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct HdSample {
|
||||
pub amp_low: f32,
|
||||
pub freq_low: f32,
|
||||
pub amp_high: f32,
|
||||
pub freq_high: f32,
|
||||
}
|
||||
|
||||
impl HdSample {
|
||||
pub fn new(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> Self {
|
||||
Self {
|
||||
amp_low,
|
||||
freq_low,
|
||||
amp_high,
|
||||
freq_high,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_silent(&self) -> bool {
|
||||
hd_amp_index(self.amp_low) == 0 && hd_amp_index(self.amp_high) == 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn same_as(&self, other: &HdSample) -> bool {
|
||||
self.amp_low == other.amp_low
|
||||
&& self.freq_low == other.freq_low
|
||||
&& self.amp_high == other.amp_high
|
||||
&& self.freq_high == other.freq_high
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn hd_peak(acc: &mut HdSample, s: &HdSample) {
|
||||
if s.amp_low > acc.amp_low {
|
||||
acc.amp_low = s.amp_low;
|
||||
acc.freq_low = s.freq_low;
|
||||
}
|
||||
if s.amp_high > acc.amp_high {
|
||||
acc.amp_high = s.amp_high;
|
||||
acc.freq_high = s.freq_high;
|
||||
}
|
||||
if acc.freq_low <= 0.0 {
|
||||
acc.freq_low = s.freq_low;
|
||||
}
|
||||
if acc.freq_high <= 0.0 {
|
||||
acc.freq_high = s.freq_high;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure state-machine engine for Nintendo HD Rumble output report scheduling.
|
||||
/// Decoupled from SDL or physical timer calls so it is 100% testable with simulated timestamps.
|
||||
pub struct NintendoHdEngine {
|
||||
pub is_bluetooth: bool,
|
||||
pub is_pro_controller: bool,
|
||||
pub settings: HdRumbleSettings,
|
||||
|
||||
dense_detector: HdDenseDetector,
|
||||
click_detector: Option<HdClickDetector>,
|
||||
short_pulses: Option<HdShortPulseCounter>,
|
||||
amfm_planner: Option<HdAmFmPlanner>,
|
||||
/// A window that had ended when a sample arrived (Ryuhdr Push: HdAmFmSend before Add); sent by the next tick.
|
||||
amfm_pending: Option<[u8; 8]>,
|
||||
|
||||
bt_level: HdBtLevel,
|
||||
interval_ms: i32,
|
||||
bt_tokens: f64,
|
||||
bt_token_time_us: i64,
|
||||
|
||||
latest_l: HdSample,
|
||||
latest_r: HdSample,
|
||||
peak_l: HdSample,
|
||||
peak_r: HdSample,
|
||||
dirty: bool,
|
||||
|
||||
last_send_us: Option<i64>,
|
||||
last_write_us: Option<i64>,
|
||||
last_packet: [u8; 10],
|
||||
has_last: bool,
|
||||
last_was_click: bool,
|
||||
|
||||
bt_crisp_restore_at_us: i64,
|
||||
bt_crisp_fresh: bool,
|
||||
|
||||
packet_counter: u8,
|
||||
/// Sends the newest sample instead of the slot peak when enabled.
|
||||
send_latest: bool,
|
||||
}
|
||||
|
||||
impl NintendoHdEngine {
|
||||
pub fn new(is_bluetooth: bool, is_pro_controller: bool) -> Self {
|
||||
let settings = HdRumbleSettings::default();
|
||||
let mut engine = Self {
|
||||
is_bluetooth,
|
||||
is_pro_controller,
|
||||
settings: settings.clone(),
|
||||
dense_detector: HdDenseDetector::new(),
|
||||
click_detector: None,
|
||||
short_pulses: None,
|
||||
amfm_planner: None,
|
||||
amfm_pending: None,
|
||||
bt_level: HD_BT_LEVELS[0],
|
||||
interval_ms: if is_bluetooth { 60 } else { 15 },
|
||||
bt_tokens: 2.0,
|
||||
bt_token_time_us: 0,
|
||||
latest_l: HdSample::default(),
|
||||
latest_r: HdSample::default(),
|
||||
peak_l: HdSample::default(),
|
||||
peak_r: HdSample::default(),
|
||||
dirty: false,
|
||||
last_send_us: None,
|
||||
last_write_us: None,
|
||||
last_packet: [0; 10],
|
||||
has_last: false,
|
||||
last_was_click: false,
|
||||
bt_crisp_restore_at_us: 0,
|
||||
bt_crisp_fresh: false,
|
||||
packet_counter: 0,
|
||||
send_latest: crate::nx2::flag_present_in(crate::nx2::LATEST_FLAG, None),
|
||||
};
|
||||
engine.apply_settings(&settings);
|
||||
engine
|
||||
}
|
||||
|
||||
pub fn apply_settings(&mut self, settings: &HdRumbleSettings) {
|
||||
self.settings = settings.clone();
|
||||
|
||||
let bt_idx = (settings.bluetooth_level.clamp(1, 4) - 1) as usize;
|
||||
self.bt_level = HD_BT_LEVELS[bt_idx];
|
||||
self.interval_ms = if self.is_bluetooth {
|
||||
self.bt_level.spacing_ms
|
||||
} else {
|
||||
settings.usb_interval_ms
|
||||
};
|
||||
|
||||
self.dense_detector = HdDenseDetector::new();
|
||||
|
||||
// Click pulses are USB only and for Pro Controller only
|
||||
let click_wanted = settings.enabled
|
||||
&& settings.click_pulse
|
||||
&& !self.is_bluetooth
|
||||
&& self.is_pro_controller;
|
||||
if click_wanted {
|
||||
if self.click_detector.is_none() {
|
||||
self.click_detector =
|
||||
Some(HdClickDetector::new(HdClickDetector::DEFAULT_MAX_PULSE_MS));
|
||||
}
|
||||
} else {
|
||||
self.click_detector = None;
|
||||
}
|
||||
|
||||
// Short pulse counter on Bluetooth
|
||||
let short_wanted = settings.enabled && self.is_bluetooth;
|
||||
if short_wanted {
|
||||
if self.short_pulses.is_none() {
|
||||
self.short_pulses = Some(HdShortPulseCounter::new());
|
||||
}
|
||||
} else {
|
||||
self.short_pulses = None;
|
||||
}
|
||||
|
||||
// AM/FM 5 ms envelope (Ryuhdr HdApplyEnvelope): wired with card 3 on top of USB no-queue, Bluetooth with B1 at any level.
|
||||
// usb_no_queue / bt_fast mean "running in SDL": the host clears them when SDL refused the idle-gated writes
|
||||
// (eden-hdr: SDL3 patch 0002), otherwise Bluetooth would get a packet every 15 ms.
|
||||
let amfm_wanted = settings.enabled
|
||||
&& if self.is_bluetooth {
|
||||
settings.bt_fast
|
||||
} else {
|
||||
settings.envelope_5ms && settings.usb_no_queue
|
||||
};
|
||||
if amfm_wanted {
|
||||
let crisp = if self.is_bluetooth {
|
||||
settings.bt_crisp_notes
|
||||
} else {
|
||||
settings.crisp_notes
|
||||
};
|
||||
if let Some(ref mut planner) = self.amfm_planner {
|
||||
planner.frequency_in_packet = settings.enabled && settings.frequency_in_packet;
|
||||
planner.frequency_high_and_both = settings.enabled && settings.frequency_both_bands;
|
||||
if planner.crisp_notes() != crisp {
|
||||
planner.set_crisp_notes(crisp);
|
||||
}
|
||||
} else {
|
||||
let mut planner = HdAmFmPlanner::new();
|
||||
planner.frequency_in_packet = settings.enabled && settings.frequency_in_packet;
|
||||
planner.frequency_high_and_both = settings.enabled && settings.frequency_both_bands;
|
||||
planner.set_crisp_notes(crisp);
|
||||
self.amfm_planner = Some(planner);
|
||||
}
|
||||
} else {
|
||||
self.amfm_planner = None;
|
||||
self.amfm_pending = None;
|
||||
}
|
||||
|
||||
self.bt_tokens = self.bt_tokens.min(self.bt_level.burst);
|
||||
}
|
||||
|
||||
/// USB auto slow-down (Ryuhdr HdUsbAutoSlow): off while USB no-queue runs, SDL merges the packets then.
|
||||
fn usb_auto_slow(&self) -> bool {
|
||||
!self.is_bluetooth && self.settings.usb_auto_slow && !self.settings.usb_no_queue
|
||||
}
|
||||
|
||||
fn resend_due(&self, now_us: i64) -> bool {
|
||||
let rs = self.bt_level.resend_ms as i64 * 1000;
|
||||
self.is_bluetooth
|
||||
&& rs > 0
|
||||
&& self.has_last
|
||||
&& !hd_is_silent_packet(&self.last_packet)
|
||||
&& self.last_write_us.is_some_and(|t| now_us - t >= rs)
|
||||
}
|
||||
|
||||
pub fn push_sample(
|
||||
&mut self,
|
||||
now_us: i64,
|
||||
left_al: f32,
|
||||
left_fl: f32,
|
||||
left_ah: f32,
|
||||
left_fh: f32,
|
||||
right_al: f32,
|
||||
right_fl: f32,
|
||||
right_ah: f32,
|
||||
right_fh: f32,
|
||||
) {
|
||||
if !self.settings.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let l = HdSample::new(left_al, left_fl, left_ah, left_fh);
|
||||
let r = HdSample::new(right_al, right_fl, right_ah, right_fh);
|
||||
let now_ms = now_us / 1000;
|
||||
|
||||
if let Some(ref mut amfm) = self.amfm_planner {
|
||||
// Ryuhdr Push: a window that has ended goes out first, then the sample lands in the running window
|
||||
if self.amfm_pending.is_none() {
|
||||
let mut sides = [0u8; 8];
|
||||
if amfm.poll(now_ms, &mut sides) {
|
||||
self.amfm_pending = Some(sides);
|
||||
}
|
||||
}
|
||||
let side_l = HdSideSample::new(l.amp_low, l.freq_low, l.amp_high, l.freq_high);
|
||||
let side_r = HdSideSample::new(r.amp_low, r.freq_low, r.amp_high, r.freq_high);
|
||||
amfm.add(now_ms, &side_l, &side_r);
|
||||
self.latest_l = l;
|
||||
self.latest_r = r;
|
||||
self.dirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
hd_peak(&mut self.peak_l, &l);
|
||||
hd_peak(&mut self.peak_r, &r);
|
||||
|
||||
if let Some(ref mut pulses) = self.short_pulses {
|
||||
let silent = l.is_silent() && r.is_silent();
|
||||
pulses.on_sample(now_ms, silent, !silent && !pulses.in_pulse());
|
||||
}
|
||||
|
||||
self.latest_l = l;
|
||||
self.latest_r = r;
|
||||
self.dirty = true;
|
||||
self.bt_crisp_fresh = true;
|
||||
|
||||
if let Some(ref mut click) = self.click_detector {
|
||||
let silent = l.is_silent() && r.is_silent();
|
||||
let max_l = l.amp_low.max(l.amp_high);
|
||||
let max_r = r.amp_low.max(r.amp_high);
|
||||
click.on_sample(now_ms, silent, max_l, max_r);
|
||||
}
|
||||
|
||||
if self.usb_auto_slow() {
|
||||
self.dense_detector.add_sample(now_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes a half-sample (either left or right) preserving the most recent sample of the other side.
|
||||
/// This prevents channel clobbering when Eden calls SetVibration separately for Left and Right.
|
||||
pub fn push_half_sample(
|
||||
&mut self,
|
||||
now_us: i64,
|
||||
is_right: bool,
|
||||
al: f32,
|
||||
fl: f32,
|
||||
ah: f32,
|
||||
fh: f32,
|
||||
) {
|
||||
if !self.settings.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let s = HdSample::new(al, fl, ah, fh);
|
||||
if is_right {
|
||||
hd_peak(&mut self.peak_r, &s);
|
||||
self.latest_r = s;
|
||||
} else {
|
||||
hd_peak(&mut self.peak_l, &s);
|
||||
self.latest_l = s;
|
||||
}
|
||||
|
||||
let l = self.latest_l;
|
||||
let r = self.latest_r;
|
||||
let now_ms = now_us / 1000;
|
||||
|
||||
if let Some(ref mut amfm) = self.amfm_planner {
|
||||
if self.amfm_pending.is_none() {
|
||||
let mut sides = [0u8; 8];
|
||||
if amfm.poll(now_ms, &mut sides) {
|
||||
self.amfm_pending = Some(sides);
|
||||
}
|
||||
}
|
||||
let side_l = HdSideSample::new(l.amp_low, l.freq_low, l.amp_high, l.freq_high);
|
||||
let side_r = HdSideSample::new(r.amp_low, r.freq_low, r.amp_high, r.freq_high);
|
||||
amfm.add(now_ms, &side_l, &side_r);
|
||||
self.dirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(ref mut pulses) = self.short_pulses {
|
||||
let silent = l.is_silent() && r.is_silent();
|
||||
pulses.on_sample(now_ms, silent, !silent && !pulses.in_pulse());
|
||||
}
|
||||
|
||||
self.dirty = true;
|
||||
self.bt_crisp_fresh = true;
|
||||
|
||||
if let Some(ref mut click) = self.click_detector {
|
||||
let silent = l.is_silent() && r.is_silent();
|
||||
let max_l = l.amp_low.max(l.amp_high);
|
||||
let max_r = r.amp_low.max(r.amp_high);
|
||||
click.on_sample(now_ms, silent, max_l, max_r);
|
||||
}
|
||||
|
||||
if self.usb_auto_slow() && is_right {
|
||||
self.dense_detector.add_sample(now_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ticks the engine. If a packet is ready to be transmitted, writes it to `out_packet` and returns `true`.
|
||||
pub fn tick(&mut self, now_us: i64, out_packet: &mut [u8; 10]) -> bool {
|
||||
if !self.settings.enabled {
|
||||
return false;
|
||||
}
|
||||
|
||||
let now_ms = now_us / 1000;
|
||||
|
||||
if self.usb_auto_slow() {
|
||||
self.dense_detector.update(now_ms);
|
||||
}
|
||||
|
||||
// AM/FM Planner path (Ryuhdr HdAmFmSend). No keep-alive here: SDL restates a running two-wave packet itself.
|
||||
if let Some(ref mut amfm) = self.amfm_planner {
|
||||
let mut sides = [0u8; 8];
|
||||
let ready = match self.amfm_pending.take() {
|
||||
Some(pending) => {
|
||||
sides = pending;
|
||||
true
|
||||
}
|
||||
None => amfm.poll(now_ms, &mut sides),
|
||||
};
|
||||
if ready {
|
||||
out_packet[0] = 0x10;
|
||||
out_packet[1] = self.packet_counter;
|
||||
self.packet_counter = (self.packet_counter + 1) & 0x0F;
|
||||
out_packet[2..10].copy_from_slice(&sides);
|
||||
|
||||
self.last_packet.copy_from_slice(out_packet);
|
||||
self.has_last = true;
|
||||
self.last_was_click = false;
|
||||
self.last_send_us = Some(now_us);
|
||||
self.last_write_us = Some(now_us);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if !self.dirty {
|
||||
// Level 4: keep a still-rumbling packet alive (idea of Hookshot PR #1213, own code).
|
||||
if self.resend_due(now_us) {
|
||||
self.last_packet[1] = self.packet_counter;
|
||||
self.packet_counter = (self.packet_counter + 1) & 0x0F;
|
||||
out_packet.copy_from_slice(&self.last_packet);
|
||||
self.last_send_us = Some(now_us);
|
||||
self.last_write_us = Some(now_us);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut interval_ms = if self.usb_auto_slow() {
|
||||
HdDenseDetector::spacing(self.interval_ms, self.dense_detector.dense())
|
||||
} else {
|
||||
self.interval_ms
|
||||
};
|
||||
|
||||
if self.is_bluetooth && self.settings.sync_bluetooth {
|
||||
interval_ms = interval_ms.min(BT_SYNC_FEED_MS);
|
||||
} else if !self.is_bluetooth && self.settings.sync_to_input {
|
||||
interval_ms = interval_ms.min(SYNC_FEED_MS);
|
||||
} else if !self.is_bluetooth && self.settings.usb_no_queue {
|
||||
interval_ms = interval_ms.min(NO_QUEUE_FEED_MS);
|
||||
}
|
||||
|
||||
if let Some(ref mut click) = self.click_detector {
|
||||
click.poll(now_ms);
|
||||
}
|
||||
|
||||
if let Some(last_send) = self.last_send_us {
|
||||
if (now_us - last_send) < (interval_ms as i64 * 1000) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let mut click_ready = false;
|
||||
if let Some(ref click) = self.click_detector {
|
||||
if click.has_click_ready() {
|
||||
click_ready = true;
|
||||
} else if click.holds_normal_send() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let (send_l, send_r) =
|
||||
if self.send_latest || (self.is_bluetooth && self.bt_level.send_latest) {
|
||||
(self.latest_l, self.latest_r)
|
||||
} else {
|
||||
(self.peak_l, self.peak_r)
|
||||
};
|
||||
|
||||
// Bluetooth crisp note hold check
|
||||
if self.settings.bt_crisp_notes
|
||||
&& !self.bt_level.send_latest
|
||||
&& self.bt_crisp_restore_at_us != 0
|
||||
&& !self.bt_crisp_fresh
|
||||
&& now_us < self.bt_crisp_restore_at_us
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Bluetooth token bucket check
|
||||
if self.is_bluetooth && !self.settings.sync_bluetooth {
|
||||
if self.bt_token_time_us != 0 {
|
||||
let elapsed_ms = (now_us - self.bt_token_time_us) as f64 / 1000.0;
|
||||
self.bt_tokens = (self.bt_tokens + elapsed_ms / self.bt_level.refill_ms)
|
||||
.min(self.bt_level.burst);
|
||||
}
|
||||
self.bt_token_time_us = now_us;
|
||||
|
||||
let stop_after_peak = self.bt_level.stop_priority
|
||||
&& self.has_last
|
||||
&& !hd_is_silent_packet(&self.last_packet)
|
||||
&& send_l.is_silent()
|
||||
&& send_r.is_silent();
|
||||
|
||||
if self.bt_tokens < 1.0 && !stop_after_peak {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Try click packet
|
||||
if click_ready {
|
||||
if let Some(ref mut click) = self.click_detector {
|
||||
let mut click_l = 0.0f32;
|
||||
let mut click_r = 0.0f32;
|
||||
if click.try_take_click(&mut click_l, &mut click_r) {
|
||||
let mut click_packet = [0u8; 10];
|
||||
if HdClickEncoding::build_click_packet(&mut click_packet, click_l, click_r) {
|
||||
click_packet[1] = self.packet_counter;
|
||||
self.packet_counter = (self.packet_counter + 1) & 0x0F;
|
||||
out_packet.copy_from_slice(&click_packet);
|
||||
|
||||
self.last_send_us = Some(now_us);
|
||||
self.last_write_us = Some(now_us);
|
||||
if self.is_bluetooth && !self.settings.sync_bluetooth {
|
||||
self.bt_tokens -= 1.0;
|
||||
}
|
||||
self.last_packet.copy_from_slice(&click_packet);
|
||||
self.has_last = true;
|
||||
self.last_was_click = true;
|
||||
|
||||
if self.latest_l.is_silent() && self.latest_r.is_silent() {
|
||||
self.peak_l = HdSample::default();
|
||||
self.peak_r = HdSample::default();
|
||||
self.dirty = false;
|
||||
} else {
|
||||
self.peak_l = self.latest_l;
|
||||
self.peak_r = self.latest_r;
|
||||
self.dirty = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
click.count_refused();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut out_l = send_l;
|
||||
let mut out_r = send_r;
|
||||
let mut accented = false;
|
||||
|
||||
if self.settings.bt_crisp_notes
|
||||
&& !self.bt_level.send_latest
|
||||
&& self.is_bluetooth
|
||||
&& !self.settings.sync_bluetooth
|
||||
{
|
||||
accented = self.bt_crisp_shape(&mut out_l, 2);
|
||||
accented |= self.bt_crisp_shape(&mut out_r, 6);
|
||||
}
|
||||
|
||||
let mut candidate_packet = [0u8; 10];
|
||||
candidate_packet[0] = 0x10;
|
||||
candidate_packet[1] = self.packet_counter;
|
||||
let mut side_l = [0u8; 4];
|
||||
let mut side_r = [0u8; 4];
|
||||
hd_encode_side(
|
||||
&mut side_l,
|
||||
out_l.amp_low,
|
||||
out_l.freq_low,
|
||||
out_l.amp_high,
|
||||
out_l.freq_high,
|
||||
);
|
||||
hd_encode_side(
|
||||
&mut side_r,
|
||||
out_r.amp_low,
|
||||
out_r.freq_low,
|
||||
out_r.amp_high,
|
||||
out_r.freq_high,
|
||||
);
|
||||
candidate_packet[2..6].copy_from_slice(&side_l);
|
||||
candidate_packet[6..10].copy_from_slice(&side_r);
|
||||
|
||||
// Level 4 keep-alive when the game keeps pushing identical samples: wait until resend_due, then send as new.
|
||||
let mut is_resend = false;
|
||||
if self.is_bluetooth
|
||||
&& self.bt_level.resend_ms > 0
|
||||
&& self.has_last
|
||||
&& !self.last_was_click
|
||||
&& candidate_packet[2..10] == self.last_packet[2..10]
|
||||
&& !hd_is_silent_packet(&candidate_packet)
|
||||
{
|
||||
if !self.resend_due(now_us) {
|
||||
return false;
|
||||
}
|
||||
is_resend = true;
|
||||
}
|
||||
|
||||
// Same packet, or a small change on Bluetooth: not written, but like Ryuhdr's HdSendPacket (which returns true)
|
||||
// it still uses up the spacing and the Bluetooth token.
|
||||
let skipped = !is_resend
|
||||
&& !self.last_was_click
|
||||
&& self.has_last
|
||||
&& (candidate_packet[2..10] == self.last_packet[2..10]
|
||||
|| (self.is_bluetooth
|
||||
&& !self.settings.sync_bluetooth
|
||||
&& hd_is_small_change(&self.last_packet, &candidate_packet, &self.bt_level)));
|
||||
|
||||
if !skipped {
|
||||
self.packet_counter = (self.packet_counter + 1) & 0x0F;
|
||||
out_packet.copy_from_slice(&candidate_packet);
|
||||
self.last_packet.copy_from_slice(&candidate_packet);
|
||||
self.has_last = true;
|
||||
self.last_was_click = false;
|
||||
self.last_write_us = Some(now_us);
|
||||
}
|
||||
|
||||
self.last_send_us = Some(now_us);
|
||||
self.bt_crisp_fresh = false;
|
||||
self.bt_crisp_restore_at_us = if accented {
|
||||
now_us + (2 * interval_ms as i64 * 1000)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
if self.is_bluetooth && !self.settings.sync_bluetooth {
|
||||
self.bt_tokens -= 1.0;
|
||||
}
|
||||
|
||||
if accented || !send_l.same_as(&self.latest_l) || !send_r.same_as(&self.latest_r) {
|
||||
self.peak_l = self.latest_l;
|
||||
self.peak_r = self.latest_r;
|
||||
self.dirty = true;
|
||||
} else {
|
||||
self.peak_l = HdSample::default();
|
||||
self.peak_r = HdSample::default();
|
||||
self.dirty = false;
|
||||
}
|
||||
|
||||
!skipped
|
||||
}
|
||||
|
||||
fn bt_crisp_shape(&self, s: &mut HdSample, side_offset: usize) -> bool {
|
||||
let not_neutral = match self.last_packet[side_offset..side_offset + 4].try_into() {
|
||||
Ok(b) => !hd_is_neutral(b),
|
||||
Err(_) => false,
|
||||
};
|
||||
if s.is_silent() || (self.has_last && !self.last_was_click && not_neutral) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let raw = HdSideSample::new(s.amp_low, s.freq_low, s.amp_high, s.freq_high);
|
||||
let (shaped, _capped) = HdCrispNotes::apply(&raw, HdCrispNotes::ACCENT_GAIN);
|
||||
s.amp_low = shaped.amp_low;
|
||||
s.amp_high = shaped.amp_high;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_bluetooth_sync_profile_constants() {
|
||||
assert!(BT_SYNC_MIN_GAP_MS >= 60);
|
||||
assert!(BT_SYNC_MAX_GAP_MS > BT_SYNC_MIN_GAP_MS);
|
||||
assert!(BT_SYNC_MAX_GAP_MS <= 150);
|
||||
assert!(BT_SYNC_SKIP_AMP >= 2);
|
||||
assert!(BT_SYNC_SKIP_HIGH_FREQ >= 16);
|
||||
assert!(BT_SYNC_SKIP_LOW_FREQ >= 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_usb_spacing_and_peak_hold() {
|
||||
let mut engine = NintendoHdEngine::new(false, true);
|
||||
let mut out = [0u8; 10];
|
||||
|
||||
// Push a short pulse at t = 0 ms
|
||||
engine.push_sample(0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
let sent = engine.tick(0, &mut out);
|
||||
assert!(sent);
|
||||
assert_eq!(out[0], 0x10);
|
||||
|
||||
// Immediate subsequent sample at t = 5 ms (shorter than 15 ms spacing) is not sent yet
|
||||
engine.push_sample(5_000, 0.8, 160.0, 0.0, 320.0, 0.8, 160.0, 0.0, 320.0);
|
||||
let sent_early = engine.tick(5_000, &mut out);
|
||||
assert!(!sent_early);
|
||||
|
||||
// At t = 15 ms, the peak sample (0.8) goes out
|
||||
let sent_spaced = engine.tick(15_000, &mut out);
|
||||
assert!(sent_spaced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_send_latest_knob_sends_newest_not_peak() {
|
||||
let run = |latest: bool| {
|
||||
let mut engine = NintendoHdEngine::new(false, true);
|
||||
engine.send_latest = latest;
|
||||
let mut out = [0u8; 10];
|
||||
engine.push_sample(0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
engine.tick(0, &mut out);
|
||||
engine.push_sample(5_000, 0.8, 160.0, 0.0, 320.0, 0.8, 160.0, 0.0, 320.0);
|
||||
engine.push_sample(10_000, 0.2, 160.0, 0.0, 320.0, 0.2, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(15_000, &mut out));
|
||||
out
|
||||
};
|
||||
assert_ne!(run(true), run(false));
|
||||
}
|
||||
|
||||
fn level4_engine() -> NintendoHdEngine {
|
||||
let mut settings = HdRumbleSettings::default();
|
||||
settings.bluetooth_level = 4;
|
||||
settings.bt_fast = false;
|
||||
let mut engine = NintendoHdEngine::new(true, true);
|
||||
engine.apply_settings(&settings);
|
||||
engine
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level4_sends_newest_sample() {
|
||||
let mut e = level4_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
e.push_sample(t0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(e.tick(t0, &mut out));
|
||||
e.push_sample(t0 + 5_000, 0.9, 160.0, 0.0, 320.0, 0.9, 160.0, 0.0, 320.0);
|
||||
e.push_sample(t0 + 10_000, 0.2, 160.0, 0.0, 320.0, 0.2, 160.0, 0.0, 320.0);
|
||||
assert!(e.tick(t0 + 32_000, &mut out));
|
||||
let mut want = [0u8; 4];
|
||||
hd_encode_side(&mut want, 0.2, 160.0, 0.0, 320.0);
|
||||
assert_eq!(out[2..6], want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level4_resends_every_40ms_but_not_silence() {
|
||||
let mut e = level4_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
e.push_sample(t0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(e.tick(t0, &mut out));
|
||||
assert!(!e.tick(t0 + 39_000, &mut out));
|
||||
assert!(e.tick(t0 + 40_000, &mut out));
|
||||
assert!(!hd_is_silent_packet(&out));
|
||||
// silence goes out once, then is never re-sent
|
||||
e.push_sample(t0 + 80_000, 0.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.0, 320.0);
|
||||
assert!(e.tick(t0 + 80_000, &mut out));
|
||||
assert!(hd_is_silent_packet(&out));
|
||||
assert!(!e.tick(t0 + 200_000, &mut out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level4_blocks_sends_closer_than_32ms() {
|
||||
let mut e = level4_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
e.push_sample(t0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(e.tick(t0, &mut out));
|
||||
e.push_sample(t0 + 10_000, 0.9, 160.0, 0.0, 320.0, 0.9, 160.0, 0.0, 320.0);
|
||||
assert!(!e.tick(t0 + 31_000, &mut out));
|
||||
assert!(e.tick(t0 + 32_000, &mut out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level4_resends_while_game_keeps_pushing() {
|
||||
let mut e = level4_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
let mut times = Vec::new();
|
||||
|
||||
for ms in 0..=400 {
|
||||
let now = t0 + ms * 1_000;
|
||||
if ms % 5 == 0 {
|
||||
e.push_sample(now, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
}
|
||||
if e.tick(now, &mut out) {
|
||||
assert!(!hd_is_silent_packet(&out));
|
||||
times.push(ms);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(times.len(), 11);
|
||||
assert_eq!(times[0], 0);
|
||||
for w in times.windows(2) {
|
||||
assert_eq!(w[1] - w[0], 40);
|
||||
}
|
||||
|
||||
// Stop rumbling: exactly one silent packet goes out, then nothing more
|
||||
let mut silent_sends = 0;
|
||||
for ms in 401..=520 {
|
||||
let now = t0 + ms * 1_000;
|
||||
if ms % 5 == 0 {
|
||||
e.push_sample(now, 0.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.0, 320.0);
|
||||
}
|
||||
if e.tick(now, &mut out) {
|
||||
assert!(hd_is_silent_packet(&out));
|
||||
silent_sends += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(silent_sends, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level3_does_not_resend_while_game_keeps_pushing() {
|
||||
let mut settings = HdRumbleSettings::default();
|
||||
settings.bluetooth_level = 3;
|
||||
settings.bt_fast = false;
|
||||
let mut e = NintendoHdEngine::new(true, true);
|
||||
e.apply_settings(&settings);
|
||||
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
let mut sent_count = 0;
|
||||
|
||||
for ms in 0..=400 {
|
||||
let now = t0 + ms * 1_000;
|
||||
if ms % 5 == 0 {
|
||||
e.push_sample(now, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
}
|
||||
if e.tick(now, &mut out) {
|
||||
sent_count += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(sent_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_neutral_packet_on_silence() {
|
||||
let mut engine = NintendoHdEngine::new(false, true);
|
||||
let mut out = [0u8; 10];
|
||||
|
||||
// Start rumble
|
||||
engine.push_sample(0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(0, &mut out));
|
||||
|
||||
// Silence arrives at t = 15 ms
|
||||
engine.push_sample(15_000, 0.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.0, 320.0);
|
||||
let sent_silence = engine.tick(15_000, &mut out);
|
||||
assert!(sent_silence);
|
||||
assert!(hd_is_silent_packet(&out));
|
||||
|
||||
// Next tick with no new samples is idle
|
||||
let sent_idle = engine.tick(30_000, &mut out);
|
||||
assert!(!sent_idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bluetooth_token_bucket_limits_rate() {
|
||||
let mut engine = NintendoHdEngine::new(true, true);
|
||||
let mut out = [0u8; 10];
|
||||
|
||||
// Burst is 2.0 on Level 1.
|
||||
// First packet at t = 0
|
||||
engine.push_sample(0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(0, &mut out));
|
||||
|
||||
// Second packet at t = 60 ms
|
||||
engine.push_sample(60_000, 0.9, 160.0, 0.0, 320.0, 0.9, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(60_000, &mut out));
|
||||
|
||||
// Third packet at t = 120 ms (tokens depleted, needs refill of 100 ms)
|
||||
engine.push_sample(120_000, 0.3, 160.0, 0.0, 320.0, 0.3, 160.0, 0.0, 320.0);
|
||||
let throttled = engine.tick(120_000, &mut out);
|
||||
assert!(!throttled);
|
||||
|
||||
// At t = 200 ms (elapsed 140 ms since t=60ms -> tokens refilled >= 1.0)
|
||||
let refilled = engine.tick(200_000, &mut out);
|
||||
assert!(refilled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_5ms_planner_needs_idle_gated_writes() {
|
||||
// Like Ryuhdr HdApplyEnvelope: wired = card 3 + USB no-queue, Bluetooth = card B3 only.
|
||||
let mut settings = HdRumbleSettings::default();
|
||||
settings.envelope_5ms = true;
|
||||
settings.usb_no_queue = true;
|
||||
|
||||
let mut bt = NintendoHdEngine::new(true, true);
|
||||
bt.apply_settings(&settings);
|
||||
assert!(bt.amfm_planner.is_none());
|
||||
settings.bt_fast = true;
|
||||
for level in [2, 4] {
|
||||
settings.bluetooth_level = level;
|
||||
bt.apply_settings(&settings);
|
||||
assert!(bt.amfm_planner.is_some());
|
||||
}
|
||||
settings.bt_fast = false;
|
||||
bt.apply_settings(&settings);
|
||||
assert!(bt.amfm_planner.is_none());
|
||||
settings.bt_fast = true;
|
||||
bt.apply_settings(&settings);
|
||||
|
||||
let mut usb = NintendoHdEngine::new(false, true);
|
||||
usb.apply_settings(&settings);
|
||||
assert!(usb.amfm_planner.is_some());
|
||||
settings.usb_no_queue = false;
|
||||
usb.apply_settings(&settings);
|
||||
assert!(usb.amfm_planner.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_usb_auto_slow_off_while_no_queue_runs() {
|
||||
let mut settings = HdRumbleSettings::default();
|
||||
settings.usb_auto_slow = true;
|
||||
|
||||
let mut usb = NintendoHdEngine::new(false, true);
|
||||
usb.apply_settings(&settings);
|
||||
assert!(usb.usb_auto_slow());
|
||||
settings.usb_no_queue = true;
|
||||
usb.apply_settings(&settings);
|
||||
assert!(!usb.usb_auto_slow());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bluetooth_skip_uses_spacing_and_token_like_ryuhdr() {
|
||||
// Level 1: 60 ms spacing, burst 2, refill 100 ms. Start at 1 s (Ryuhdr's Stopwatch clock is never 0).
|
||||
let mut engine = NintendoHdEngine::new(true, true);
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
|
||||
engine.push_sample(t0, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(t0, &mut out)); // tokens 2 -> 1
|
||||
|
||||
// Same value again at +60 ms: skipped, but the spacing restarts and a token is spent (1.6 -> 0.6).
|
||||
engine.push_sample(t0 + 60_000, 0.5, 160.0, 0.0, 320.0, 0.5, 160.0, 0.0, 320.0);
|
||||
assert!(!engine.tick(t0 + 60_000, &mut out));
|
||||
|
||||
// A real change at +61 ms waits for the spacing from the skip (+120 ms), then goes out (tokens 1.2).
|
||||
engine.push_sample(t0 + 61_000, 0.9, 160.0, 0.0, 320.0, 0.9, 160.0, 0.0, 320.0);
|
||||
assert!(!engine.tick(t0 + 61_000, &mut out));
|
||||
assert!(!engine.tick(t0 + 119_000, &mut out));
|
||||
assert!(engine.tick(t0 + 120_000, &mut out));
|
||||
}
|
||||
|
||||
fn wired_envelope_engine() -> NintendoHdEngine {
|
||||
let mut settings = HdRumbleSettings::default();
|
||||
settings.envelope_5ms = true;
|
||||
settings.usb_no_queue = true;
|
||||
let mut engine = NintendoHdEngine::new(false, true);
|
||||
engine.apply_settings(&settings);
|
||||
engine
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_5ms_planner_sends_the_ended_window_before_a_late_sample() {
|
||||
// Ryuhdr Push: HdAmFmSend, then Add. A sample after the window end belongs to the next window.
|
||||
let mut engine = wired_envelope_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
|
||||
engine.push_sample(t0, 0.45, 160.0, 0.0, 320.0, 0.45, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(t0 + 15_000, &mut out)); // steady, the planner now knows 160 / 320 Hz
|
||||
|
||||
// No tick at the end of the second window (t0 + 30 ms): the stop arrives 1 ms late
|
||||
engine.push_sample(t0 + 31_000, 0.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.0, 320.0);
|
||||
// The second window is the unchanged steady value: nothing to send (late, it would be a three-sample side ending in 0)
|
||||
assert!(!engine.tick(t0 + 31_000, &mut out));
|
||||
// The stop is the third window
|
||||
assert!(!engine.tick(t0 + 44_000, &mut out));
|
||||
assert!(engine.tick(t0 + 45_000, &mut out));
|
||||
assert!(hd_is_silent_packet(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_5ms_planner_has_no_keep_alive_of_its_own() {
|
||||
// SDL restates a running two-wave packet (Ryuhdr HdAmFmSend sends only what the planner built)
|
||||
let mut engine = wired_envelope_engine();
|
||||
let mut out = [0u8; 10];
|
||||
let t0 = 1_000_000;
|
||||
|
||||
engine.push_sample(t0, 0.45, 160.0, 0.0, 320.0, 0.45, 160.0, 0.0, 320.0);
|
||||
assert!(engine.tick(t0 + 15_000, &mut out));
|
||||
for ms in (30..=400).step_by(15) {
|
||||
assert!(!engine.tick(t0 + ms * 1_000, &mut out));
|
||||
}
|
||||
}
|
||||
}
|
||||
411
third_party/renhdrum/src/detectors/click_detector.rs
vendored
Normal file
411
third_party/renhdrum/src/detectors/click_detector.rs
vendored
Normal file
@@ -0,0 +1,411 @@
|
||||
/// Finds short vibration pulses in the game's sample stream (0.2.4.7, experimental).
|
||||
/// A pulse is "short" when it starts from silence and is silent again within [`max_pulse_ms`];
|
||||
/// the backend then sends one controller MCU click packet instead of the peak-hold two-wave packet plus the stop packet.
|
||||
/// One detector covers both sides: a packet is one pulse for the pair.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClickDetectorState {
|
||||
Idle,
|
||||
Candidate,
|
||||
Long,
|
||||
ClickReady,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HdClickDetector {
|
||||
state: ClickDetectorState,
|
||||
start_ms: i64,
|
||||
ready_since_ms: i64,
|
||||
peak_l: f32,
|
||||
peak_r: f32,
|
||||
max_pulse_ms: i64,
|
||||
dropped: i32,
|
||||
}
|
||||
|
||||
impl Default for HdClickDetector {
|
||||
fn default() -> Self {
|
||||
Self::new(Self::DEFAULT_MAX_PULSE_MS)
|
||||
}
|
||||
}
|
||||
|
||||
impl HdClickDetector {
|
||||
pub const DEFAULT_MAX_PULSE_MS: i64 = 20;
|
||||
pub const MAX_READY_WAIT_MS: i64 = 40;
|
||||
|
||||
pub fn new(max_pulse_ms: i64) -> Self {
|
||||
Self {
|
||||
state: ClickDetectorState::Idle,
|
||||
start_ms: 0,
|
||||
ready_since_ms: 0,
|
||||
peak_l: 0.0,
|
||||
peak_r: 0.0,
|
||||
max_pulse_ms,
|
||||
dropped: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn max_pulse_ms(&self) -> i64 {
|
||||
self.max_pulse_ms
|
||||
}
|
||||
|
||||
pub fn dropped(&self) -> i32 {
|
||||
self.dropped
|
||||
}
|
||||
|
||||
pub fn state(&self) -> ClickDetectorState {
|
||||
self.state
|
||||
}
|
||||
|
||||
/// True while the backend must not send the two-wave packet: a pulse of unknown length is running, or a click waits to be sent.
|
||||
pub fn holds_normal_send(&self) -> bool {
|
||||
matches!(
|
||||
self.state,
|
||||
ClickDetectorState::Candidate | ClickDetectorState::ClickReady
|
||||
)
|
||||
}
|
||||
|
||||
pub fn has_click_ready(&self) -> bool {
|
||||
self.state == ClickDetectorState::ClickReady
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.state = ClickDetectorState::Idle;
|
||||
self.peak_l = 0.0;
|
||||
self.peak_r = 0.0;
|
||||
}
|
||||
|
||||
/// Counts a click that was taken but could not be built (too weak): the normal path sends the peak.
|
||||
pub fn count_refused(&mut self) {
|
||||
self.dropped += 1;
|
||||
}
|
||||
|
||||
/// One sample from the game. `silent` = both sides encode to silence; amplitudes are 0..1 per side.
|
||||
pub fn on_sample(&mut self, now_ms: i64, silent: bool, amp_l: f32, amp_r: f32) {
|
||||
match self.state {
|
||||
ClickDetectorState::Idle => {
|
||||
if !silent {
|
||||
self.state = ClickDetectorState::Candidate;
|
||||
self.start_ms = now_ms;
|
||||
self.peak_l = amp_l;
|
||||
self.peak_r = amp_r;
|
||||
}
|
||||
}
|
||||
ClickDetectorState::Candidate => {
|
||||
if !silent {
|
||||
self.peak_l = self.peak_l.max(amp_l);
|
||||
self.peak_r = self.peak_r.max(amp_r);
|
||||
|
||||
if now_ms - self.start_ms > self.max_pulse_ms {
|
||||
self.state = ClickDetectorState::Long;
|
||||
}
|
||||
} else if now_ms - self.start_ms <= self.max_pulse_ms {
|
||||
self.state = ClickDetectorState::ClickReady;
|
||||
self.ready_since_ms = now_ms;
|
||||
} else {
|
||||
// Too long but not yet cut by Poll: the normal path sends the peak.
|
||||
self.state = ClickDetectorState::Idle;
|
||||
}
|
||||
}
|
||||
ClickDetectorState::Long => {
|
||||
if silent {
|
||||
self.state = ClickDetectorState::Idle;
|
||||
}
|
||||
}
|
||||
ClickDetectorState::ClickReady => {
|
||||
if !silent {
|
||||
// A new pulse came in before the click was sent: the normal path sends the gathered peak, as without the option.
|
||||
self.state = ClickDetectorState::Long;
|
||||
self.dropped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expires a pulse that never ended (the game stopped pushing) and a click that could not be sent in time.
|
||||
pub fn poll(&mut self, now_ms: i64) {
|
||||
if self.state == ClickDetectorState::Candidate && now_ms - self.start_ms > self.max_pulse_ms
|
||||
{
|
||||
self.state = ClickDetectorState::Long;
|
||||
} else if self.state == ClickDetectorState::ClickReady
|
||||
&& now_ms - self.ready_since_ms > Self::MAX_READY_WAIT_MS
|
||||
{
|
||||
self.state = ClickDetectorState::Long;
|
||||
self.dropped += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the click: returns the peak of each side and goes back to Idle.
|
||||
pub fn try_take_click(&mut self, amp_l: &mut f32, amp_r: &mut f32) -> bool {
|
||||
if self.state != ClickDetectorState::ClickReady {
|
||||
*amp_l = 0.0;
|
||||
*amp_r = 0.0;
|
||||
return false;
|
||||
}
|
||||
|
||||
*amp_l = self.peak_l;
|
||||
*amp_r = self.peak_r;
|
||||
self.state = ClickDetectorState::Idle;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn take_click(&mut self) -> Option<(f32, f32)> {
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
if self.try_take_click(&mut l, &mut r) {
|
||||
Some((l, r))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend could not use the click (too small, refused): the normal path sends the peak as before.
|
||||
pub fn on_click_dropped(&mut self) {
|
||||
if self.state == ClickDetectorState::ClickReady {
|
||||
self.state = ClickDetectorState::Long;
|
||||
self.dropped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::encoding::click::HdClickEncoding;
|
||||
|
||||
#[test]
|
||||
fn test_pulse_in_one_update_is_a_click_with_peaks() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(100, false, 0.3, 0.1);
|
||||
assert!(d.holds_normal_send());
|
||||
d.on_sample(100, false, 0.5, 0.05);
|
||||
d.on_sample(100, true, 0.0, 0.0);
|
||||
|
||||
assert!(d.holds_normal_send()); // click waits to be sent
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(d.try_take_click(&mut l, &mut r));
|
||||
assert_eq!(l, 0.5);
|
||||
assert_eq!(r, 0.1);
|
||||
assert!(!d.holds_normal_send());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pulse_ending_within_max_is_a_click() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(15, true, 0.0, 0.0);
|
||||
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pulse_ending_after_max_is_not_a_click() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(10, false, 0.5, 0.5);
|
||||
d.on_sample(25, false, 0.5, 0.5); // longer than 20 ms -> Long
|
||||
assert!(!d.holds_normal_send());
|
||||
d.on_sample(30, true, 0.0, 0.0);
|
||||
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_silent_sample_after_max_without_poll_goes_idle() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(25, true, 0.0, 0.0);
|
||||
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
assert!(!d.holds_normal_send());
|
||||
|
||||
// Back to Idle: the next short pulse is a click again.
|
||||
d.on_sample(100, false, 0.5, 0.5);
|
||||
d.on_sample(100, true, 0.0, 0.0);
|
||||
assert!(d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_poll_cuts_a_candidate_that_never_ends() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.poll(15);
|
||||
assert!(d.holds_normal_send());
|
||||
d.poll(21);
|
||||
assert!(!d.holds_normal_send());
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_poll_drops_a_click_that_waits_too_long() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(0, true, 0.0, 0.0);
|
||||
d.poll(HdClickDetector::MAX_READY_WAIT_MS);
|
||||
assert!(d.has_click_ready());
|
||||
d.poll(HdClickDetector::MAX_READY_WAIT_MS + 1);
|
||||
|
||||
assert!(!d.has_click_ready());
|
||||
assert!(!d.holds_normal_send());
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_next_pulse_after_long_one_is_not_a_click_until_silence() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.poll(30); // Long
|
||||
d.on_sample(40, false, 0.4, 0.4);
|
||||
d.on_sample(41, true, 0.0, 0.0); // silence -> Idle
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
|
||||
// A second silent sample while Idle changes nothing, a pulse after it is a click.
|
||||
d.on_sample(50, true, 0.0, 0.0);
|
||||
d.on_sample(60, false, 0.4, 0.4);
|
||||
d.on_sample(60, true, 0.0, 0.0);
|
||||
assert!(d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sample_while_long_without_silence_stays_long() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.poll(30);
|
||||
d.on_sample(35, false, 0.5, 0.5);
|
||||
|
||||
assert!(!d.holds_normal_send());
|
||||
assert!(!d.has_click_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_pulse_before_the_click_is_sent_falls_back_to_the_normal_path() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(0, true, 0.0, 0.0);
|
||||
d.on_sample(5, false, 0.6, 0.6);
|
||||
|
||||
assert!(!d.has_click_ready());
|
||||
assert!(!d.holds_normal_send());
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_on_click_dropped_hands_back_to_the_normal_path() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(0, true, 0.0, 0.0);
|
||||
d.on_click_dropped();
|
||||
|
||||
assert!(!d.holds_normal_send());
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(!d.try_take_click(&mut l, &mut r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dropped_counts_clicks_that_were_not_sent() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
d.on_sample(0, true, 0.0, 0.0);
|
||||
d.on_click_dropped(); // 1
|
||||
d.on_sample(10, true, 0.0, 0.0);
|
||||
|
||||
d.on_sample(20, false, 0.5, 0.5);
|
||||
d.on_sample(20, true, 0.0, 0.0);
|
||||
d.poll(20 + HdClickDetector::MAX_READY_WAIT_MS + 1); // 2
|
||||
d.on_sample(100, true, 0.0, 0.0);
|
||||
|
||||
d.on_sample(110, false, 0.5, 0.5);
|
||||
d.on_sample(110, true, 0.0, 0.0);
|
||||
d.on_sample(112, false, 0.5, 0.5); // 3 (new pulse first)
|
||||
|
||||
assert_eq!(d.dropped(), 3);
|
||||
|
||||
d.on_sample(120, true, 0.0, 0.0);
|
||||
d.on_sample(130, false, 0.5, 0.5);
|
||||
d.on_sample(130, true, 0.0, 0.0);
|
||||
let mut l = 0.0;
|
||||
let mut r = 0.0;
|
||||
assert!(d.try_take_click(&mut l, &mut r));
|
||||
assert_eq!(d.dropped(), 3, "a sent click is not a drop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_holds_normal_send_per_state() {
|
||||
let mut d = HdClickDetector::default();
|
||||
|
||||
assert!(!d.holds_normal_send()); // Idle
|
||||
d.on_sample(0, true, 0.0, 0.0);
|
||||
assert!(!d.holds_normal_send());
|
||||
d.on_sample(0, false, 0.5, 0.5);
|
||||
assert!(d.holds_normal_send()); // Candidate
|
||||
d.on_sample(1, true, 0.0, 0.0);
|
||||
assert!(d.holds_normal_send()); // ClickReady
|
||||
d.on_click_dropped();
|
||||
assert!(!d.holds_normal_send()); // Long
|
||||
d.reset();
|
||||
assert!(!d.holds_normal_send());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_click_packet_half_amplitude_matches_the_test_log() {
|
||||
let mut p = [0u8; 10];
|
||||
assert!(HdClickEncoding::build_click_packet(&mut p, 0.5, 0.5));
|
||||
assert_eq!(
|
||||
p,
|
||||
[0x10, 0x00, 0x00, 0x10, 0x0E, 0x00, 0x00, 0x10, 0x0E, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_click_packet_quiet_side_stays_neutral() {
|
||||
let mut p = [0u8; 10];
|
||||
assert!(HdClickEncoding::build_click_packet(&mut p, 0.5, 0.0));
|
||||
assert_eq!(&p[6..10], &[0x00, 0x01, 0x40, 0x40]);
|
||||
assert_eq!(&p[2..6], &[0x00, 0x10, 0x0E, 0x00]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_click_packet_too_weak_is_refused() {
|
||||
let mut p = [0u8; 10];
|
||||
assert!(!HdClickEncoding::build_click_packet(&mut p, 0.01, 0.01));
|
||||
assert!(!HdClickEncoding::build_click_packet(&mut p, 0.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_click_packet_full_amplitude_uses_code_2_never_code_1() {
|
||||
let mut p = [0u8; 10];
|
||||
assert!(HdClickEncoding::build_click_packet(&mut p, 1.0, 2.0));
|
||||
let side_l: [u8; 4] = p[2..6].try_into().unwrap();
|
||||
let side_r: [u8; 4] = p[6..10].try_into().unwrap();
|
||||
let l = HdClickEncoding::try_decode_side_click(&side_l).unwrap();
|
||||
let r = HdClickEncoding::try_decode_side_click(&side_r).unwrap();
|
||||
assert_eq!(l.pulse1_code, 2);
|
||||
assert_eq!(r.pulse1_code, 2);
|
||||
assert!(HdClickEncoding::is_click_packet(&p));
|
||||
}
|
||||
}
|
||||
255
third_party/renhdrum/src/detectors/dense.rs
vendored
Normal file
255
third_party/renhdrum/src/detectors/dense.rs
vendored
Normal file
@@ -0,0 +1,255 @@
|
||||
use crate::status::Entry;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Detects a dense vibration stream on USB HD Rumble. High-density sample streams can reach ~140-155 samples/s;
|
||||
/// at 15 ms spacing the packets may go out at an uneven 15-23 ms rhythm and peak-hold jumps between notes, which
|
||||
/// feels erratic, while 30 ms pacing restores smoothness. Moderate workloads peaking around ~43 samples/s never trigger this.
|
||||
/// The rate is counted in fixed 250 ms windows: two windows in a row at >= 90 samples/s enter the dense state, one
|
||||
/// second below 60 samples/s (or no samples) leaves it. Pure logic on a millisecond clock, unit-tested.
|
||||
#[derive(Clone)]
|
||||
pub struct HdDenseDetector {
|
||||
window_start_ms: i64,
|
||||
count: i32,
|
||||
dense_windows: i32,
|
||||
quiet_windows: i32,
|
||||
dense: bool,
|
||||
status_entry: Option<Arc<Entry>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for HdDenseDetector {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("HdDenseDetector")
|
||||
.field("window_start_ms", &self.window_start_ms)
|
||||
.field("count", &self.count)
|
||||
.field("dense_windows", &self.dense_windows)
|
||||
.field("quiet_windows", &self.quiet_windows)
|
||||
.field("dense", &self.dense)
|
||||
.field("has_status", &self.status_entry.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for HdDenseDetector {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
window_start_ms: -1,
|
||||
count: 0,
|
||||
dense_windows: 0,
|
||||
quiet_windows: 0,
|
||||
dense: false,
|
||||
status_entry: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HdDenseDetector {
|
||||
pub const WINDOW_MS: i32 = 250;
|
||||
pub const ENTER_SAMPLES_PER_SECOND: i32 = 90;
|
||||
pub const EXIT_SAMPLES_PER_SECOND: i32 = 60;
|
||||
pub const ENTER_WINDOWS: i32 = 2;
|
||||
pub const EXIT_WINDOWS: i32 = 4;
|
||||
pub const DENSE_SPACING_MS: i32 = 30;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_status(status_entry: Arc<Entry>) -> Self {
|
||||
Self {
|
||||
status_entry: Some(status_entry),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_status(&mut self, status_entry: Option<Arc<Entry>>) {
|
||||
self.status_entry = status_entry;
|
||||
}
|
||||
|
||||
pub fn dense(&self) -> bool {
|
||||
self.dense
|
||||
}
|
||||
|
||||
/// USB spacing to use: the configured one, raised to [`DENSE_SPACING_MS`] while the stream is dense.
|
||||
pub fn spacing(configured_ms: i32, dense: bool) -> i32 {
|
||||
if dense {
|
||||
configured_ms.max(Self::DENSE_SPACING_MS)
|
||||
} else {
|
||||
configured_ms
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts one vibration sample from the game. Returns true when `dense` changed.
|
||||
pub fn add_sample(&mut self, now_ms: i64) -> bool {
|
||||
let changed = self.update(now_ms);
|
||||
self.count += 1;
|
||||
changed
|
||||
}
|
||||
|
||||
/// Closes the windows that ended before `now_ms`; also called without samples so the dense
|
||||
/// state ends when the game goes quiet. Returns true when `dense` changed.
|
||||
pub fn update(&mut self, now_ms: i64) -> bool {
|
||||
if self.window_start_ms < 0 {
|
||||
self.window_start_ms = now_ms;
|
||||
return false;
|
||||
}
|
||||
|
||||
let was_dense = self.dense;
|
||||
|
||||
while now_ms - self.window_start_ms >= Self::WINDOW_MS as i64 {
|
||||
self.close_window();
|
||||
|
||||
self.window_start_ms += Self::WINDOW_MS as i64;
|
||||
|
||||
if now_ms - self.window_start_ms >= (Self::WINDOW_MS * Self::EXIT_WINDOWS) as i64 {
|
||||
// A long gap without samples: everything after the window just closed is quiet.
|
||||
self.dense = false;
|
||||
self.dense_windows = 0;
|
||||
self.quiet_windows = 0;
|
||||
self.window_start_ms = now_ms;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
self.dense != was_dense
|
||||
}
|
||||
|
||||
fn close_window(&mut self) {
|
||||
let rate = self.count * 1000 / Self::WINDOW_MS;
|
||||
self.count = 0;
|
||||
|
||||
if rate > 0 {
|
||||
if let Some(ref entry) = self.status_entry {
|
||||
entry.report_window_rate(rate);
|
||||
}
|
||||
}
|
||||
|
||||
if rate >= Self::ENTER_SAMPLES_PER_SECOND {
|
||||
self.quiet_windows = 0;
|
||||
|
||||
if !self.dense {
|
||||
self.dense_windows += 1;
|
||||
if self.dense_windows >= Self::ENTER_WINDOWS {
|
||||
self.dense = true;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self.dense_windows = 0;
|
||||
|
||||
if !self.dense {
|
||||
return;
|
||||
}
|
||||
|
||||
if rate < Self::EXIT_SAMPLES_PER_SECOND {
|
||||
self.quiet_windows += 1;
|
||||
if self.quiet_windows >= Self::EXIT_WINDOWS {
|
||||
self.dense = false;
|
||||
self.quiet_windows = 0;
|
||||
}
|
||||
} else {
|
||||
self.quiet_windows = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn feed(
|
||||
detector: &mut HdDenseDetector,
|
||||
start_ms: i64,
|
||||
duration_ms: i32,
|
||||
samples_per_second: i32,
|
||||
) -> i64 {
|
||||
let step_ms = 1000.0 / samples_per_second as f64;
|
||||
let count = (duration_ms as f64 / step_ms) as i32;
|
||||
|
||||
for i in 0..count {
|
||||
detector.add_sample(start_ms + (i as f64 * step_ms) as i64);
|
||||
}
|
||||
|
||||
start_ms + duration_ms as i64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_spacing_raised_only_when_dense_and_below_30_ms() {
|
||||
assert_eq!(HdDenseDetector::spacing(15, false), 15);
|
||||
assert_eq!(HdDenseDetector::spacing(15, true), 30);
|
||||
assert_eq!(HdDenseDetector::spacing(20, true), 30);
|
||||
assert_eq!(HdDenseDetector::spacing(30, true), 30);
|
||||
assert_eq!(HdDenseDetector::spacing(50, true), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_moderate_rates_never_enter_dense() {
|
||||
let mut detector = HdDenseDetector::new();
|
||||
|
||||
let now = feed(&mut detector, 1000, 10_000, 43);
|
||||
detector.update(now + 1);
|
||||
|
||||
assert!(!detector.dense());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_high_density_notes_enter_dense_within_half_a_second() {
|
||||
let mut detector = HdDenseDetector::new();
|
||||
|
||||
feed(&mut detector, 1000, 400, 150);
|
||||
assert!(!detector.dense(), "one window is not enough");
|
||||
|
||||
let now = feed(&mut detector, 1400, 400, 150);
|
||||
detector.update(now);
|
||||
|
||||
assert!(detector.dense());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_short_burst_does_not_enter_dense() {
|
||||
let mut detector = HdDenseDetector::new();
|
||||
|
||||
// ~200 ms burst inside a calm stream: at most one dense window.
|
||||
let mut now = feed(&mut detector, 1000, 1000, 20);
|
||||
now = feed(&mut detector, now, 200, 150);
|
||||
now = feed(&mut detector, now, 2000, 20);
|
||||
detector.update(now);
|
||||
|
||||
assert!(!detector.dense());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_leaves_dense_after_one_calm_second() {
|
||||
let mut detector = HdDenseDetector::new();
|
||||
|
||||
let mut now = feed(&mut detector, 1000, 2000, 150);
|
||||
detector.update(now);
|
||||
assert!(detector.dense());
|
||||
|
||||
// Still dense at 80/s (between the exit and enter rates).
|
||||
now = feed(&mut detector, now, 2000, 80);
|
||||
detector.update(now);
|
||||
assert!(detector.dense());
|
||||
|
||||
now = feed(&mut detector, now, 600, 20);
|
||||
detector.update(now);
|
||||
assert!(detector.dense(), "less than a second of calm");
|
||||
|
||||
now = feed(&mut detector, now, 800, 20);
|
||||
detector.update(now);
|
||||
assert!(!detector.dense());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_silence_ends_dense_without_samples() {
|
||||
let mut detector = HdDenseDetector::new();
|
||||
|
||||
let now = feed(&mut detector, 1000, 2000, 150);
|
||||
detector.update(now);
|
||||
assert!(detector.dense());
|
||||
|
||||
assert!(detector.update(now + 1500), "Update reports the change");
|
||||
assert!(!detector.dense());
|
||||
}
|
||||
}
|
||||
7
third_party/renhdrum/src/detectors/mod.rs
vendored
Normal file
7
third_party/renhdrum/src/detectors/mod.rs
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
pub mod click_detector;
|
||||
pub mod dense;
|
||||
pub mod short_pulse;
|
||||
|
||||
pub use click_detector::{ClickDetectorState, HdClickDetector};
|
||||
pub use dense::HdDenseDetector;
|
||||
pub use short_pulse::HdShortPulseCounter;
|
||||
180
third_party/renhdrum/src/detectors/short_pulse.rs
vendored
Normal file
180
third_party/renhdrum/src/detectors/short_pulse.rs
vendored
Normal file
@@ -0,0 +1,180 @@
|
||||
/// Counts the game's short vibration pulses on a Bluetooth pad (0.2.5.10, count only, nothing sent differently),
|
||||
/// to judge card B3 (one three-sample packet that carries a short pulse and its stop).
|
||||
/// A pulse starts from silence; it is "short" when it is silent again within [`MAX_PULSE_MS`].
|
||||
/// "Frequency held": every sounding band of the pulse's first sample has the frequency the pad still holds
|
||||
/// from the last two-wave packet, so 5-bit three-sample codes could carry it without setting a frequency.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct HdShortPulseCounter {
|
||||
in_pulse: bool,
|
||||
start_ms: i64,
|
||||
start_held: bool,
|
||||
pulses: i64,
|
||||
short_pulses: i64,
|
||||
short_pulses_held: i64,
|
||||
}
|
||||
|
||||
impl HdShortPulseCounter {
|
||||
/// Longest pulse that still counts as short (same limit as the click detector, 20 ms).
|
||||
pub const MAX_PULSE_MS: i64 = 20;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Pulses that ended (silent again), short or not.
|
||||
pub fn pulses(&self) -> i64 {
|
||||
self.pulses
|
||||
}
|
||||
|
||||
pub fn short_pulses(&self) -> i64 {
|
||||
self.short_pulses
|
||||
}
|
||||
|
||||
/// Short pulses whose first sample had the frequency the pad holds.
|
||||
pub fn short_pulses_held(&self) -> i64 {
|
||||
self.short_pulses_held
|
||||
}
|
||||
|
||||
/// True while a pulse runs; the caller only works out `frequency_held` when this is false and the sample is not silent.
|
||||
pub fn in_pulse(&self) -> bool {
|
||||
self.in_pulse
|
||||
}
|
||||
|
||||
pub fn on_sample(&mut self, now_ms: i64, silent: bool, frequency_held: bool) {
|
||||
if silent {
|
||||
if self.in_pulse {
|
||||
self.in_pulse = false;
|
||||
self.pulses += 1;
|
||||
|
||||
if now_ms - self.start_ms <= Self::MAX_PULSE_MS {
|
||||
self.short_pulses += 1;
|
||||
|
||||
if self.start_held {
|
||||
self.short_pulses_held += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if !self.in_pulse {
|
||||
self.in_pulse = true;
|
||||
self.start_ms = now_ms;
|
||||
self.start_held = frequency_held;
|
||||
}
|
||||
}
|
||||
|
||||
/// True when every sounding band of `side` (two-wave bytes) has the frequency encoded in `held_side`
|
||||
/// (the side of the last two-wave packet; a neutral side holds the default 160 / 320 Hz).
|
||||
/// A silent side always fits.
|
||||
pub fn frequency_held(held_side: &[u8; 4], side: &[u8; 4]) -> bool {
|
||||
let high_amp = side[1] >> 1;
|
||||
let low_amp = if side[3] < 0x40 {
|
||||
0
|
||||
} else {
|
||||
((side[3] - 0x40) << 1) | (side[2] >> 7)
|
||||
};
|
||||
|
||||
let side_high_freq = (side[0] as u16) | (((side[1] & 1) as u16) << 8);
|
||||
let held_high_freq = (held_side[0] as u16) | (((held_side[1] & 1) as u16) << 8);
|
||||
|
||||
if high_amp > 0 && side_high_freq != held_high_freq {
|
||||
return false;
|
||||
}
|
||||
|
||||
low_amp == 0 || (side[2] & 0x7F) == (held_side[2] & 0x7F)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const NEUTRAL: [u8; 4] = [0x00, 0x01, 0x40, 0x40];
|
||||
|
||||
fn encode(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> [u8; 4] {
|
||||
let mut side = [0u8; 4];
|
||||
crate::encoding::standard::hd_encode_side(
|
||||
&mut side, amp_low, freq_low, amp_high, freq_high,
|
||||
);
|
||||
side
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_short_and_long_pulses() {
|
||||
let mut counter = HdShortPulseCounter::new();
|
||||
|
||||
counter.on_sample(0, true, false); // silence: nothing
|
||||
counter.on_sample(100, false, true); // short pulse, frequency held
|
||||
counter.on_sample(105, false, false); // still the same pulse: the start decides
|
||||
counter.on_sample(118, true, false);
|
||||
counter.on_sample(200, false, false); // short pulse, frequency not held
|
||||
counter.on_sample(220, true, false); // exactly 20 ms = short
|
||||
counter.on_sample(300, false, true); // long pulse
|
||||
counter.on_sample(321, true, false);
|
||||
counter.on_sample(400, true, false); // silence again: nothing
|
||||
|
||||
assert_eq!(counter.pulses(), 3);
|
||||
assert_eq!(counter.short_pulses(), 2);
|
||||
assert_eq!(counter.short_pulses_held(), 1);
|
||||
assert!(!counter.in_pulse());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_running_pulse_is_not_counted() {
|
||||
let mut counter = HdShortPulseCounter::new();
|
||||
|
||||
counter.on_sample(0, false, true);
|
||||
|
||||
assert!(counter.in_pulse());
|
||||
assert_eq!(counter.pulses(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_frequencies_are_held_after_a_neutral_packet() {
|
||||
// A neutral side holds 160 Hz (low) / 320 Hz (high): a pulse at those frequencies fits, others do not.
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&NEUTRAL,
|
||||
&encode(0.5, 160.0, 0.0, 0.0)
|
||||
));
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&NEUTRAL,
|
||||
&encode(0.0, 0.0, 0.5, 320.0)
|
||||
));
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&NEUTRAL,
|
||||
&encode(0.3, 160.0, 0.3, 320.0)
|
||||
));
|
||||
assert!(!HdShortPulseCounter::frequency_held(
|
||||
&NEUTRAL,
|
||||
&encode(0.5, 100.0, 0.0, 0.0)
|
||||
));
|
||||
assert!(!HdShortPulseCounter::frequency_held(
|
||||
&NEUTRAL,
|
||||
&encode(0.0, 0.0, 0.5, 640.0)
|
||||
));
|
||||
assert!(HdShortPulseCounter::frequency_held(&NEUTRAL, &NEUTRAL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_silent_band_ignored() {
|
||||
let held = encode(0.4, 120.0, 0.4, 500.0);
|
||||
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&held,
|
||||
&encode(0.8, 120.0, 0.0, 900.0)
|
||||
));
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&held,
|
||||
&encode(0.0, 60.0, 0.2, 500.0)
|
||||
));
|
||||
assert!(HdShortPulseCounter::frequency_held(
|
||||
&held,
|
||||
&encode(0.8, 121.0, 0.0, 0.0)
|
||||
));
|
||||
assert!(!HdShortPulseCounter::frequency_held(
|
||||
&held,
|
||||
&encode(0.8, 130.0, 0.0, 0.0)
|
||||
));
|
||||
}
|
||||
}
|
||||
474
third_party/renhdrum/src/dualsense/bt_haptics.rs
vendored
Normal file
474
third_party/renhdrum/src/dualsense/bt_haptics.rs
vendored
Normal file
@@ -0,0 +1,474 @@
|
||||
//! DualSense voice-coil haptics over Bluetooth: HID output report 0x32.
|
||||
//! Report layout from egormanga's SAxense (https://apps.sdore.me/SAxense, MPL-2.0),
|
||||
//! reimplemented here; no SAxense code is copied.
|
||||
|
||||
use super::haptics::{
|
||||
DualSenseHapticsDsp, DS5_EFFECTS_STATE_SIZE, DUALSENSE_CHANNELS, DUALSENSE_LEFT_CHANNEL,
|
||||
DUALSENSE_RIGHT_CHANNEL,
|
||||
};
|
||||
use super::opus_codec::{BtOpusEncoder, BT_OPUS_PACKET_SIZE, BT_SPEAKER_SOURCE_TICK_SAMPLES};
|
||||
|
||||
pub const DS5_BT_HAPTICS_REPORT_ID: u8 = 0x32;
|
||||
pub const DS5_BT_HAPTICS_REPORT_SIZE: usize = 142;
|
||||
/// Stereo frames per report at 3 kHz (64 PCM bytes).
|
||||
pub const DS5_BT_HAPTICS_FRAMES: usize = 32;
|
||||
/// 48 kHz DSP frames averaged into one 3 kHz frame.
|
||||
pub const DS5_BT_HAPTICS_DECIMATION: usize = 16;
|
||||
/// 32 frames at 3 kHz = 10.667 ms between reports.
|
||||
pub const DS5_BT_HAPTICS_PERIOD_NS: u64 = 1_000_000_000 * DS5_BT_HAPTICS_FRAMES as u64 / 3000;
|
||||
/// Packet 0x11 byte 5 (report byte 9). SAxense uses 0xFF; tune on hardware if latency shows.
|
||||
pub const DS5_BT_BUFFER_LENGTH_DEFAULT: u8 = 0xFF;
|
||||
|
||||
/// Combined report 0x36: sub-packets 0x11 (state), 0x10 (63-byte SetState: triggers), 0x12 (haptics).
|
||||
/// Layout after Enhanced-PS5-DualSense-Haptics-Bridge (MIT, ragnarok179), `bluetooth_audio_packets.go`.
|
||||
pub const DS5_BT36_REPORT_ID: u8 = 0x36;
|
||||
pub const DS5_BT36_REPORT_SIZE: usize = 398;
|
||||
/// 2 s of 10.667 ms blocks.
|
||||
pub const DS5_BT36_IDLE_BLOCKS: u32 = 188;
|
||||
|
||||
const CRC_OFFSET: usize = DS5_BT_HAPTICS_REPORT_SIZE - 4;
|
||||
const PCM_OFFSET: usize = 13;
|
||||
const DSP_FRAMES: usize = DS5_BT_HAPTICS_FRAMES * DS5_BT_HAPTICS_DECIMATION;
|
||||
const _: () = assert!(DSP_FRAMES == BT_SPEAKER_SOURCE_TICK_SAMPLES);
|
||||
|
||||
/// CRC32 (0xEDB88320) of a Sony Bluetooth output report, seeded with the 0xA2 HID header byte.
|
||||
pub fn ds5_bt_crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in core::iter::once(&0xA2u8).chain(data) {
|
||||
crc ^= b as u32;
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & (crc & 1).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// Keeps the report sequence, packet 0x11 counter, and embedded Opus encoder across reports.
|
||||
pub struct DualSenseBtPacker {
|
||||
seq: u8,
|
||||
counter: u8,
|
||||
pcm: [f32; DSP_FRAMES * DUALSENSE_CHANNELS],
|
||||
idle_blocks: u32,
|
||||
opus: BtOpusEncoder,
|
||||
}
|
||||
|
||||
impl Default for DualSenseBtPacker {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
seq: 0,
|
||||
counter: 0,
|
||||
pcm: [0.0; DSP_FRAMES * DUALSENSE_CHANNELS],
|
||||
idle_blocks: 0,
|
||||
opus: BtOpusEncoder::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DualSenseBtPacker {
|
||||
/// Averages the pulled 48 kHz block down to 32 stereo int8 frames. True when not silent.
|
||||
fn downsample(&self, pcm64: &mut [u8; DS5_BT_HAPTICS_FRAMES * 2]) -> bool {
|
||||
let mut signal = false;
|
||||
let (blocks, _) = self
|
||||
.pcm
|
||||
.as_chunks::<{ DS5_BT_HAPTICS_DECIMATION * DUALSENSE_CHANNELS }>();
|
||||
for (frame, block) in blocks.iter().enumerate() {
|
||||
let (frames, _) = block.as_chunks::<DUALSENSE_CHANNELS>();
|
||||
for (side, channel) in [(0, DUALSENSE_LEFT_CHANNEL), (1, DUALSENSE_RIGHT_CHANNEL)] {
|
||||
let mean = frames.iter().map(|f| f[channel]).sum::<f32>()
|
||||
/ DS5_BT_HAPTICS_DECIMATION as f32;
|
||||
let sample = (mean * 127.0).round().clamp(-128.0, 127.0) as i8;
|
||||
pcm64[frame * 2 + side] = sample as u8;
|
||||
signal |= sample != 0;
|
||||
}
|
||||
}
|
||||
signal
|
||||
}
|
||||
|
||||
/// Pulls 10.667 ms from the DSP and writes one combined report 0x36 (rumble + triggers,
|
||||
/// plus speaker Opus sub-packet `0x93` when `dsp.speaker_enabled()`).
|
||||
pub fn build36(
|
||||
&mut self,
|
||||
dsp: &mut DualSenseHapticsDsp,
|
||||
state47: Option<&[u8; DS5_EFFECTS_STATE_SIZE]>,
|
||||
out: &mut [u8; DS5_BT36_REPORT_SIZE],
|
||||
) -> u8 {
|
||||
let allow_speaker = dsp.speaker_enabled();
|
||||
self.build36_with_speaker(dsp, state47, allow_speaker, out)
|
||||
}
|
||||
|
||||
/// Pulls 10.667 ms from the DSP and writes one combined report 0x36.
|
||||
/// `allow_speaker` lets callers suppress `0x93` / `0x90` speaker routing (e.g. when HD Haptics is off).
|
||||
/// Returns 0 (nothing written, DSP still advanced) after 2 s of silence with idle triggers,
|
||||
/// 1 when `out` holds a report to send, 2 when it also carries vibration.
|
||||
pub fn build36_with_speaker(
|
||||
&mut self,
|
||||
dsp: &mut DualSenseHapticsDsp,
|
||||
state47: Option<&[u8; DS5_EFFECTS_STATE_SIZE]>,
|
||||
allow_speaker: bool,
|
||||
out: &mut [u8; DS5_BT36_REPORT_SIZE],
|
||||
) -> u8 {
|
||||
dsp.fill_interleaved_f32(&mut self.pcm);
|
||||
let mut pcm64 = [0u8; DS5_BT_HAPTICS_FRAMES * 2];
|
||||
let signal = self.downsample(&mut pcm64);
|
||||
|
||||
let speaker_on = allow_speaker && dsp.speaker_enabled();
|
||||
let mut opus200 = [0u8; BT_OPUS_PACKET_SIZE];
|
||||
let speaker_active = if speaker_on {
|
||||
let mut mono512 = [0.0f32; BT_SPEAKER_SOURCE_TICK_SAMPLES];
|
||||
for (i, sample) in mono512.iter_mut().enumerate() {
|
||||
*sample = self.pcm[i * DUALSENSE_CHANNELS + 1];
|
||||
}
|
||||
self.opus.encode_source_tick(&mono512, &mut opus200)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
// A trigger effect other than Off {0x05, ...} or unset {0x00, ...} counts as activity.
|
||||
let trigger_active = state47.is_some_and(|s| {
|
||||
s[0] & 0x0C != 0
|
||||
&& [s[10], s[21]]
|
||||
.iter()
|
||||
.any(|&mode| mode != 0x05 && mode != 0x00)
|
||||
});
|
||||
if signal || speaker_active || trigger_active {
|
||||
self.idle_blocks = 0;
|
||||
} else {
|
||||
self.idle_blocks = self.idle_blocks.saturating_add(1);
|
||||
if self.idle_blocks > DS5_BT36_IDLE_BLOCKS {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
out.fill(0);
|
||||
out[0] = DS5_BT36_REPORT_ID;
|
||||
out[1] = self.seq << 4;
|
||||
out[2] = 0x11 | 0x80;
|
||||
out[3] = 7;
|
||||
out[4] = 0xFE; // haptics/speaker path on, microphone streaming off
|
||||
out[5..10].fill(64); // audio buffer length, same value in all five fields (bridge)
|
||||
out[10] = self.counter;
|
||||
out[11] = 0x10 | 0x80;
|
||||
out[12] = 63;
|
||||
if let Some(s) = state47 {
|
||||
// Trigger enable bits only (0x04 R2, 0x08 L2); speaker flags added below when enabled.
|
||||
out[13] = s[0] & 0x0C;
|
||||
out[13 + 10..13 + 32].copy_from_slice(&s[10..32]);
|
||||
}
|
||||
if speaker_on {
|
||||
out[13] |= 0xA0; // SPEAKER_VOLUME_ENABLE (0x20) | AUDIO_CONTROL_ENABLE (0x80)
|
||||
out[13 + 1] |= 0x80; // AUDIO_CONTROL2_ENABLE
|
||||
out[13 + 5] = 100; // internal speaker volume
|
||||
out[13 + 7] = 0x30; // audio output path -> speaker
|
||||
out[13 + 37] = 0x02; // speaker preamp config
|
||||
}
|
||||
out[76] = 0x12 | 0x80;
|
||||
out[77] = (DS5_BT_HAPTICS_FRAMES * 2) as u8;
|
||||
out[78..142].copy_from_slice(&pcm64);
|
||||
if speaker_on {
|
||||
out[142] = 0x93;
|
||||
out[143] = BT_OPUS_PACKET_SIZE as u8;
|
||||
out[144..144 + BT_OPUS_PACKET_SIZE].copy_from_slice(&opus200);
|
||||
}
|
||||
|
||||
let crc = ds5_bt_crc32(&out[..DS5_BT36_REPORT_SIZE - 4]);
|
||||
out[DS5_BT36_REPORT_SIZE - 4..].copy_from_slice(&crc.to_le_bytes());
|
||||
self.seq = (self.seq + 1) & 0x0F;
|
||||
self.counter = self.counter.wrapping_add(1);
|
||||
1 + u8::from(signal)
|
||||
}
|
||||
|
||||
/// Pulls 10.667 ms (512 frames) from the DSP and writes one report 0x32 into `out`.
|
||||
/// Returns true when the PCM block is not silent.
|
||||
pub fn build(
|
||||
&mut self,
|
||||
dsp: &mut DualSenseHapticsDsp,
|
||||
buffer_length: u8,
|
||||
out: &mut [u8; DS5_BT_HAPTICS_REPORT_SIZE],
|
||||
) -> bool {
|
||||
dsp.fill_interleaved_f32(&mut self.pcm);
|
||||
|
||||
out.fill(0);
|
||||
out[0] = DS5_BT_HAPTICS_REPORT_ID;
|
||||
out[1] = self.seq << 4;
|
||||
out[2] = 0x11 | 0x80; // packet 0x11, sized
|
||||
out[3] = 7;
|
||||
out[4] = 0xFE; // microphone session closed
|
||||
out[9] = buffer_length;
|
||||
out[10] = self.counter;
|
||||
out[11] = 0x12 | 0x80; // packet 0x12, sized
|
||||
out[12] = (DS5_BT_HAPTICS_FRAMES * 2) as u8;
|
||||
|
||||
let mut pcm64 = [0u8; DS5_BT_HAPTICS_FRAMES * 2];
|
||||
let signal = self.downsample(&mut pcm64);
|
||||
out[PCM_OFFSET..PCM_OFFSET + 64].copy_from_slice(&pcm64);
|
||||
|
||||
let crc = ds5_bt_crc32(&out[..CRC_OFFSET]);
|
||||
out[CRC_OFFSET..].copy_from_slice(&crc.to_le_bytes());
|
||||
self.seq = (self.seq + 1) & 0x0F;
|
||||
self.counter = self.counter.wrapping_add(1);
|
||||
signal
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_silent_report_matches_known_crc() {
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT_HAPTICS_REPORT_SIZE];
|
||||
let signal = packer.build(&mut dsp, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut out);
|
||||
assert!(!signal);
|
||||
assert_eq!(out[0], DS5_BT_HAPTICS_REPORT_ID);
|
||||
assert_eq!(out[1], 0);
|
||||
assert_eq!(out[2], 0x11 | 0x80);
|
||||
assert_eq!(out[3], 7);
|
||||
assert_eq!(out[4], 0xFE);
|
||||
assert_eq!(&out[5..9], &[0, 0, 0, 0]);
|
||||
assert_eq!(out[9], 0xFF);
|
||||
assert_eq!(out[10], 0);
|
||||
assert_eq!(out[11], 0x12 | 0x80);
|
||||
assert_eq!(out[12], 64);
|
||||
assert_eq!(&out[13..77], &[0u8; 64]);
|
||||
assert_eq!(&out[77..138], &[0u8; 61]);
|
||||
let crc = u32::from_le_bytes(out[138..142].try_into().unwrap());
|
||||
assert_eq!(crc, 0x26E2_0C96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequence_and_counter_advance() {
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT_HAPTICS_REPORT_SIZE];
|
||||
for k in 0..17u32 {
|
||||
packer.build(&mut dsp, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut out);
|
||||
assert_eq!(out[1], ((k % 16) as u8) << 4);
|
||||
assert_eq!(out[10], k as u8);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pcm_is_block_mean_of_dsp() {
|
||||
let mut dsp_a = DualSenseHapticsDsp::new(100, true);
|
||||
let mut dsp_b = DualSenseHapticsDsp::new(100, true);
|
||||
dsp_a.set_target(1.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.5, 320.0);
|
||||
dsp_b.set_target(1.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.5, 320.0);
|
||||
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut reports = [[0u8; DS5_BT_HAPTICS_REPORT_SIZE]; 2];
|
||||
packer.build(&mut dsp_a, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut reports[0]);
|
||||
packer.build(&mut dsp_a, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut reports[1]);
|
||||
|
||||
let mut b_pcm = [0.0f32; 1024 * DUALSENSE_CHANNELS];
|
||||
dsp_b.fill_interleaved_f32(&mut b_pcm);
|
||||
|
||||
for r in 0..2 {
|
||||
let offset_frames = r * DSP_FRAMES;
|
||||
for frame in 0..DS5_BT_HAPTICS_FRAMES {
|
||||
let start_f = offset_frames + frame * DS5_BT_HAPTICS_DECIMATION;
|
||||
for (side, ch) in [(0, DUALSENSE_LEFT_CHANNEL), (1, DUALSENSE_RIGHT_CHANNEL)] {
|
||||
let mut sum = 0.0f32;
|
||||
for dec in 0..DS5_BT_HAPTICS_DECIMATION {
|
||||
sum += b_pcm[(start_f + dec) * DUALSENSE_CHANNELS + ch];
|
||||
}
|
||||
let mean = sum / DS5_BT_HAPTICS_DECIMATION as f32;
|
||||
let expected = (mean * 127.0).round().clamp(-128.0, 127.0) as i8 as u8;
|
||||
assert_eq!(
|
||||
reports[r][PCM_OFFSET + frame * 2 + side],
|
||||
expected,
|
||||
"Mismatch at report {r}, frame {frame}, side {side}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_signal_stays_under_ceiling() {
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_target(1.0, 160.0, 1.0, 320.0, 1.0, 160.0, 1.0, 320.0);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT_HAPTICS_REPORT_SIZE];
|
||||
let mut had_signal = false;
|
||||
for _ in 0..20 {
|
||||
let signal = packer.build(&mut dsp, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut out);
|
||||
had_signal |= signal;
|
||||
for &b in &out[PCM_OFFSET..PCM_OFFSET + DS5_BT_HAPTICS_FRAMES * 2] {
|
||||
let s = b as i8;
|
||||
assert!(s.abs() <= 102, "sample {s} exceeds ceiling 102");
|
||||
}
|
||||
}
|
||||
assert!(had_signal, "expected at least one report to have signal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bt36_layout_crc_and_same_pcm_as_0x32() {
|
||||
let mut dsp_a = DualSenseHapticsDsp::new(100, true);
|
||||
let mut dsp_b = DualSenseHapticsDsp::new(100, true);
|
||||
dsp_a.set_target(1.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.5, 320.0);
|
||||
dsp_b.set_target(1.0, 160.0, 0.0, 320.0, 0.0, 160.0, 0.5, 320.0);
|
||||
let mut pa = DualSenseBtPacker::default();
|
||||
let mut pb = DualSenseBtPacker::default();
|
||||
let mut r32 = [0u8; DS5_BT_HAPTICS_REPORT_SIZE];
|
||||
let mut r36 = [0u8; DS5_BT36_REPORT_SIZE];
|
||||
pa.build(&mut dsp_a, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut r32);
|
||||
let mut state = [0u8; DS5_EFFECTS_STATE_SIZE];
|
||||
super::super::haptics::hd_haptics_trigger_block(
|
||||
true,
|
||||
Some(&[0x21, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
|
||||
&mut state,
|
||||
);
|
||||
assert_eq!(pb.build36(&mut dsp_b, Some(&state), &mut r36), 2);
|
||||
assert_eq!(r36.len(), 398);
|
||||
assert_eq!(&r36[..5], &[0x36, 0, 0x91, 7, 0xFE]);
|
||||
assert_eq!(&r36[5..10], &[64; 5]);
|
||||
assert_eq!(r36[10], 0);
|
||||
assert_eq!(&r36[11..13], &[0x90, 63]);
|
||||
assert_eq!(r36[13], 0x04);
|
||||
assert_eq!(
|
||||
&r36[13 + 10..13 + 21],
|
||||
&[0x21, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
);
|
||||
assert_eq!(&r36[13 + 21..13 + 32], &[0u8; 11]);
|
||||
assert_eq!(&r36[76..78], &[0x92, 64]);
|
||||
assert_eq!(&r36[78..142], &r32[PCM_OFFSET..PCM_OFFSET + 64]);
|
||||
assert_eq!(&r36[142..394], &[0u8; 252]);
|
||||
let crc = u32::from_le_bytes(r36[394..398].try_into().unwrap());
|
||||
assert_eq!(crc, ds5_bt_crc32(&r36[..394]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bt36_idle_rest_after_2s_and_wakes() {
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT36_REPORT_SIZE];
|
||||
let mut sent = 0;
|
||||
for _ in 0..300 {
|
||||
if packer.build36(&mut dsp, None, &mut out) != 0 {
|
||||
sent += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(sent, DS5_BT36_IDLE_BLOCKS as usize);
|
||||
// An active trigger wakes it at once.
|
||||
let mut state = [0u8; DS5_EFFECTS_STATE_SIZE];
|
||||
super::super::haptics::hd_haptics_trigger_block(
|
||||
false,
|
||||
Some(&[0x26, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
|
||||
&mut state,
|
||||
);
|
||||
assert_eq!(packer.build36(&mut dsp, Some(&state), &mut out), 1);
|
||||
// Off triggers alone do not keep it awake.
|
||||
let mut off = [0u8; DS5_EFFECTS_STATE_SIZE];
|
||||
super::super::haptics::hd_haptics_trigger_block(false, None, &mut off);
|
||||
for _ in 0..DS5_BT36_IDLE_BLOCKS {
|
||||
assert_ne!(packer.build36(&mut dsp, Some(&off), &mut out), 0);
|
||||
}
|
||||
assert_eq!(packer.build36(&mut dsp, Some(&off), &mut out), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_crc_covers_payload() {
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_target(1.0, 160.0, 1.0, 320.0, 1.0, 160.0, 1.0, 320.0);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT_HAPTICS_REPORT_SIZE];
|
||||
packer.build(&mut dsp, DS5_BT_BUFFER_LENGTH_DEFAULT, &mut out);
|
||||
let original_crc = u32::from_le_bytes(out[CRC_OFFSET..].try_into().unwrap());
|
||||
out[PCM_OFFSET] ^= 0x01;
|
||||
let modified_crc = ds5_bt_crc32(&out[..CRC_OFFSET]);
|
||||
assert_ne!(original_crc, modified_crc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bt36_speaker_silent_writes_0x93_silence_and_0x90_flags() {
|
||||
use super::super::opus_codec::{BT_OPUS_PACKET_SIZE, SPEAKER_OPUS_SILENCE};
|
||||
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_speaker(60);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut out = [0u8; DS5_BT36_REPORT_SIZE];
|
||||
|
||||
assert_eq!(packer.build36(&mut dsp, None, &mut out), 1);
|
||||
assert_eq!(out[13], 0xA0);
|
||||
assert_eq!(out[14], 0x80);
|
||||
assert_eq!(out[18], 100);
|
||||
assert_eq!(out[20], 0x30);
|
||||
assert_eq!(out[50], 0x02);
|
||||
assert_eq!(&out[142..144], &[0x93, BT_OPUS_PACKET_SIZE as u8]);
|
||||
assert_eq!(&out[144..344], &SPEAKER_OPUS_SILENCE);
|
||||
assert_eq!(&out[344..394], &[0u8; 50]);
|
||||
let crc = u32::from_le_bytes(out[394..398].try_into().unwrap());
|
||||
assert_eq!(crc, ds5_bt_crc32(&out[..394]));
|
||||
|
||||
// Trigger block flags merge cleanly without losing speaker flags.
|
||||
let mut state = [0u8; DS5_EFFECTS_STATE_SIZE];
|
||||
super::super::haptics::hd_haptics_trigger_block(
|
||||
true,
|
||||
Some(&[0x21, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
|
||||
&mut state,
|
||||
);
|
||||
assert_eq!(packer.build36(&mut dsp, Some(&state), &mut out), 1);
|
||||
assert_eq!(out[13], 0xA4);
|
||||
assert_eq!(&out[23..34], &[0x21, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bt36_speaker_grain_roundtrips_1200_3400_hz_energy() {
|
||||
use super::super::opus_codec::test_decoder::BtOpusDecoder;
|
||||
use super::super::opus_codec::{
|
||||
BT_OPUS_CHANNELS, BT_OPUS_FRAME_SAMPLES, BT_OPUS_PACKET_SIZE, SPEAKER_OPUS_SILENCE,
|
||||
};
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_speaker(60);
|
||||
let mut packer = DualSenseBtPacker::default();
|
||||
let mut decoder = BtOpusDecoder::new();
|
||||
let mut out = [0u8; DS5_BT36_REPORT_SIZE];
|
||||
|
||||
// Prime one silent block so onset detection triggers cleanly.
|
||||
assert_eq!(packer.build36(&mut dsp, None, &mut out), 1);
|
||||
dsp.set_target(0.0, 160.0, 0.8, 300.0, 0.0, 160.0, 0.8, 300.0);
|
||||
|
||||
let mut saw_non_silent_opus = false;
|
||||
let mut band_energy = 0.0f64;
|
||||
let mut low_energy = 0.0f64;
|
||||
let mut decoded = [0.0f32; BT_OPUS_FRAME_SAMPLES * BT_OPUS_CHANNELS];
|
||||
|
||||
for _ in 0..4 {
|
||||
assert_ne!(packer.build36(&mut dsp, None, &mut out), 0);
|
||||
assert_eq!(&out[142..144], &[0x93, BT_OPUS_PACKET_SIZE as u8]);
|
||||
let frame: &[u8; BT_OPUS_PACKET_SIZE] = out[144..344].try_into().unwrap();
|
||||
assert_eq!(frame[0], 0xF4);
|
||||
if frame != &SPEAKER_OPUS_SILENCE {
|
||||
saw_non_silent_opus = true;
|
||||
}
|
||||
let n = decoder.decode_frame(frame, &mut decoded);
|
||||
assert_eq!(n, BT_OPUS_FRAME_SAMPLES);
|
||||
// Bin k at 48 kHz / 480 samples = k * 100 Hz: bins 12..=34 cover 1200..3400 Hz.
|
||||
for k in 1..=34usize {
|
||||
let mut re = 0.0f64;
|
||||
let mut im = 0.0f64;
|
||||
for idx in 0..BT_OPUS_FRAME_SAMPLES {
|
||||
let mono = 0.5 * (decoded[idx * 2] as f64 + decoded[idx * 2 + 1] as f64);
|
||||
let angle = TAU * (k as f64) * (idx as f64) / (BT_OPUS_FRAME_SAMPLES as f64);
|
||||
re += mono * angle.cos();
|
||||
im -= mono * angle.sin();
|
||||
}
|
||||
let p = (re * re + im * im) / (BT_OPUS_FRAME_SAMPLES as f64);
|
||||
if k >= 12 {
|
||||
band_energy += p;
|
||||
} else {
|
||||
low_energy += p;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(saw_non_silent_opus, "expected active Opus speaker frame");
|
||||
assert!(
|
||||
band_energy > 0.01 && band_energy > low_energy,
|
||||
"expected speaker grain energy in 1.2-3.4 kHz (band={band_energy}, low={low_energy})"
|
||||
);
|
||||
}
|
||||
}
|
||||
1060
third_party/renhdrum/src/dualsense/haptics.rs
vendored
Normal file
1060
third_party/renhdrum/src/dualsense/haptics.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
37
third_party/renhdrum/src/dualsense/mod.rs
vendored
Normal file
37
third_party/renhdrum/src/dualsense/mod.rs
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
pub mod bt_haptics;
|
||||
pub mod haptics;
|
||||
mod motor;
|
||||
#[cfg(test)]
|
||||
mod motor_replay;
|
||||
mod opus_codec;
|
||||
pub mod settings;
|
||||
mod speaker;
|
||||
#[cfg(test)]
|
||||
mod speaker_replay;
|
||||
#[cfg(test)]
|
||||
mod tri_replay;
|
||||
pub mod tri_trigger;
|
||||
pub mod trigger_effect;
|
||||
pub mod trigger_profile;
|
||||
|
||||
pub use bt_haptics::{
|
||||
ds5_bt_crc32, DualSenseBtPacker, DS5_BT36_IDLE_BLOCKS, DS5_BT36_REPORT_ID,
|
||||
DS5_BT36_REPORT_SIZE, DS5_BT_BUFFER_LENGTH_DEFAULT, DS5_BT_HAPTICS_PERIOD_NS,
|
||||
DS5_BT_HAPTICS_REPORT_SIZE,
|
||||
};
|
||||
pub use haptics::{
|
||||
crisp_side, curve, hd_haptics_speaker_block, hd_haptics_trigger_block, make_side,
|
||||
DualSenseHapticsDsp, DualSenseSide, DualSenseVoice, DS5_EFFECTS_STATE_SIZE,
|
||||
DUALSENSE_AMPLITUDE_EXPONENT, DUALSENSE_BUFFER_FRAMES, DUALSENSE_CHANNELS,
|
||||
DUALSENSE_DEFAULT_HIGH_FREQUENCY, DUALSENSE_DEFAULT_LOW_FREQUENCY, DUALSENSE_LEFT_CHANNEL,
|
||||
DUALSENSE_MAX_FREQUENCY, DUALSENSE_MIN_FREQUENCY, DUALSENSE_OUTPUT_CEILING,
|
||||
DUALSENSE_RIGHT_CHANNEL, DUALSENSE_SAMPLE_RATE, DUALSENSE_SMOOTHING_MS,
|
||||
HD_HAPTICS_SPEAKER_PERCENT,
|
||||
};
|
||||
pub use settings::{DualSenseSettings, DualSenseSettingsFull};
|
||||
pub use tri_trigger::TriTrigger;
|
||||
pub use trigger_effect::DualSenseTriggerEffect;
|
||||
pub use trigger_profile::{
|
||||
pack_ds5_effects_state, DualSenseTriggerInput, DualSenseTriggerProfile,
|
||||
DualSenseTriggerProfileConfig,
|
||||
};
|
||||
1021
third_party/renhdrum/src/dualsense/motor.rs
vendored
Normal file
1021
third_party/renhdrum/src/dualsense/motor.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
341
third_party/renhdrum/src/dualsense/motor_replay.rs
vendored
Normal file
341
third_party/renhdrum/src/dualsense/motor_replay.rs
vendored
Normal file
@@ -0,0 +1,341 @@
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::haptics::{
|
||||
DualSenseHapticsDsp, DUALSENSE_BUFFER_FRAMES, DUALSENSE_CHANNELS, DUALSENSE_LEFT_CHANNEL,
|
||||
DUALSENSE_RIGHT_CHANNEL, DUALSENSE_SAMPLE_RATE, HD_HAPTICS_SPEAKER_PERCENT,
|
||||
};
|
||||
use super::speaker_replay::{load_type_a, load_type_b, TraceEvent};
|
||||
|
||||
const ACTIVE_RUMBLE_THRESHOLD: f32 = 0.01;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MotorTraceMetrics {
|
||||
#[allow(dead_code)]
|
||||
dur_s: f64,
|
||||
rumble_slots_l: u64,
|
||||
rumble_slots_r: u64,
|
||||
heavy_hits: u32,
|
||||
boom_events: u32,
|
||||
w_one_slots: u64,
|
||||
w_pos_slots: u64,
|
||||
shifted_gt220_slots: u64,
|
||||
fl_out_w1_sum: f64,
|
||||
fl_out_w1_count: u64,
|
||||
peak_ch23: f32,
|
||||
}
|
||||
|
||||
impl MotorTraceMetrics {
|
||||
fn new(dur_s: f64) -> Self {
|
||||
Self {
|
||||
dur_s: dur_s.max(0.001),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, other: &Self) {
|
||||
self.dur_s += other.dur_s;
|
||||
self.rumble_slots_l += other.rumble_slots_l;
|
||||
self.rumble_slots_r += other.rumble_slots_r;
|
||||
self.heavy_hits += other.heavy_hits;
|
||||
self.boom_events += other.boom_events;
|
||||
self.w_one_slots += other.w_one_slots;
|
||||
self.w_pos_slots += other.w_pos_slots;
|
||||
self.shifted_gt220_slots += other.shifted_gt220_slots;
|
||||
self.fl_out_w1_sum += other.fl_out_w1_sum;
|
||||
self.fl_out_w1_count += other.fl_out_w1_count;
|
||||
self.peak_ch23 = self.peak_ch23.max(other.peak_ch23);
|
||||
}
|
||||
|
||||
fn rumble_sec_avg(&self) -> f64 {
|
||||
(self.rumble_slots_l + self.rumble_slots_r) as f64 * DUALSENSE_BUFFER_FRAMES as f64
|
||||
/ DUALSENSE_SAMPLE_RATE as f64
|
||||
/ 2.0
|
||||
}
|
||||
|
||||
fn heavy_per_min(&self) -> f64 {
|
||||
let mins = self.rumble_sec_avg() / 60.0;
|
||||
if mins > 1e-9 {
|
||||
(self.heavy_hits as f64 / 2.0) / mins
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn w_one_pct(&self) -> f64 {
|
||||
let tot = self.rumble_slots_l + self.rumble_slots_r;
|
||||
if tot > 0 {
|
||||
100.0 * self.w_one_slots as f64 / tot as f64
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn w_pos_pct(&self) -> f64 {
|
||||
let tot = self.rumble_slots_l + self.rumble_slots_r;
|
||||
if tot > 0 {
|
||||
100.0 * self.w_pos_slots as f64 / tot as f64
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn avg_fl_out_w1(&self) -> Option<f64> {
|
||||
if self.fl_out_w1_count > 0 {
|
||||
Some(self.fl_out_w1_sum / self.fl_out_w1_count as f64)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ReportRow {
|
||||
name: String,
|
||||
metrics: Option<MotorTraceMetrics>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
fn replay_events(events: &[TraceEvent], nx2_mode: i32) -> MotorTraceMetrics {
|
||||
if events.is_empty() {
|
||||
return MotorTraceMetrics::default();
|
||||
}
|
||||
crate::nx2::set_nx2_mode(nx2_mode);
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_speaker(HD_HAPTICS_SPEAKER_PERCENT);
|
||||
|
||||
let start_us = events[0].t_us;
|
||||
let end_us = events.last().map_or(start_us, |e| e.t_us);
|
||||
let mut metrics = MotorTraceMetrics::new((end_us - start_us) as f64 / 1_000_000.0);
|
||||
|
||||
let mut idx = 0usize;
|
||||
let mut slot_idx = 0u64;
|
||||
let mut latest_sum = [0.0f32; 2];
|
||||
let mut buf = [0.0f32; DUALSENSE_BUFFER_FRAMES * DUALSENSE_CHANNELS];
|
||||
|
||||
loop {
|
||||
let slot_t_us = start_us
|
||||
+ ((slot_idx as i128 * DUALSENSE_BUFFER_FRAMES as i128 * 1_000_000)
|
||||
/ DUALSENSE_SAMPLE_RATE as i128) as i64;
|
||||
if slot_t_us > end_us + 50_000 {
|
||||
break;
|
||||
}
|
||||
while idx < events.len() && events[idx].t_us <= slot_t_us {
|
||||
let ev = events[idx];
|
||||
dsp.set_half_target(ev.is_right, ev.al, ev.fl, ev.ah, ev.fh);
|
||||
latest_sum[usize::from(ev.is_right)] = ev.al + ev.ah;
|
||||
idx += 1;
|
||||
}
|
||||
dsp.fill_interleaved_f32(&mut buf);
|
||||
|
||||
for frame in buf.as_chunks::<DUALSENSE_CHANNELS>().0 {
|
||||
metrics.peak_ch23 = metrics
|
||||
.peak_ch23
|
||||
.max(frame[DUALSENSE_LEFT_CHANNEL].abs())
|
||||
.max(frame[DUALSENSE_RIGHT_CHANNEL].abs());
|
||||
}
|
||||
|
||||
let (mot_l, mot_r) = dsp.motor_sides();
|
||||
for m in [mot_l, mot_r] {
|
||||
if m.effective_shift_w() > 0.0 && m.last_raw_fl > 220.0 {
|
||||
metrics.shifted_gt220_slots += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if slot_t_us <= end_us {
|
||||
if dsp.boom_fired() {
|
||||
metrics.boom_events += 1;
|
||||
}
|
||||
let active_l = latest_sum[0] > ACTIVE_RUMBLE_THRESHOLD;
|
||||
let active_r = latest_sum[1] > ACTIVE_RUMBLE_THRESHOLD;
|
||||
if active_l {
|
||||
metrics.rumble_slots_l += 1;
|
||||
}
|
||||
if active_r {
|
||||
metrics.rumble_slots_r += 1;
|
||||
}
|
||||
for (m, active) in [(mot_l, active_l), (mot_r, active_r)] {
|
||||
if m.last_fired_heavy {
|
||||
metrics.heavy_hits += 1;
|
||||
}
|
||||
if active && m.effective_w() > 0.0 {
|
||||
metrics.w_pos_slots += 1;
|
||||
}
|
||||
if active && m.effective_w() >= 0.999 {
|
||||
metrics.w_one_slots += 1;
|
||||
}
|
||||
if m.effective_w() >= 0.999 {
|
||||
metrics.fl_out_w1_sum += m.last_out_fl as f64;
|
||||
metrics.fl_out_w1_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
slot_idx += 1;
|
||||
}
|
||||
|
||||
metrics
|
||||
}
|
||||
|
||||
fn push_row(out: &mut String, row: &ReportRow) {
|
||||
match (&row.metrics, &row.note) {
|
||||
(Some(m), note) => {
|
||||
let extra = note.as_deref().unwrap_or("");
|
||||
let avg_fl = m.avg_fl_out_w1().unwrap_or(0.0);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {:.1} | {} | {:.1} | {} | {:.2}% | {:.2}% | {} | {:.1} | {:.3} | {} |",
|
||||
row.name,
|
||||
m.rumble_sec_avg(),
|
||||
m.heavy_hits,
|
||||
m.heavy_per_min(),
|
||||
m.boom_events,
|
||||
m.w_one_pct(),
|
||||
m.w_pos_pct(),
|
||||
m.shifted_gt220_slots,
|
||||
avg_fl,
|
||||
m.peak_ch23,
|
||||
extra
|
||||
);
|
||||
}
|
||||
(None, note) => {
|
||||
let txt = note.as_deref().unwrap_or("thiếu");
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | - | - | - | - | - | - | - | - | - |",
|
||||
row.name, txt
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn motor_replay_report() {
|
||||
let _guard = crate::nx2::NX2_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
let label = env::var("RENHDRUM_MOTOR_LABEL")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "goc".to_string());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let sw1_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/xbox_traces");
|
||||
for name in [
|
||||
"wonder.csv",
|
||||
"wonder2.csv",
|
||||
"wonder3.csv",
|
||||
"totk.csv",
|
||||
"totk2.csv",
|
||||
"totk3.csv",
|
||||
"odyssey.csv",
|
||||
"metroid.csv",
|
||||
] {
|
||||
let p = sw1_dir.join(name);
|
||||
if let Some(evs) = load_type_b(&p) {
|
||||
let m = replay_events(&evs, 0);
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: Some(m),
|
||||
note: None,
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (name, path) in [
|
||||
(
|
||||
"bananza-trace.csv",
|
||||
Path::new(r"D:\AGY\scratch\118-buoc6\bananza-trace.csv"),
|
||||
),
|
||||
(
|
||||
"mkw-trace.csv",
|
||||
Path::new(r"D:\AGY\scratch\118-buoc6\mkw-trace.csv"),
|
||||
),
|
||||
] {
|
||||
if let Some((evs, mode)) = load_type_a(path) {
|
||||
let m = replay_events(&evs, mode);
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: Some(m),
|
||||
note: Some(format!("mode {mode}")),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let oot_dir = Path::new(r"D:\do-096\fritchii\build\bin\Release");
|
||||
let mut oot_files: Vec<PathBuf> = fs::read_dir(oot_dir)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok().map(|x| x.path()))
|
||||
.filter(|p| {
|
||||
p.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(|s| s.starts_with("hdrumble_trace-dualsense-") && s.ends_with(".csv"))
|
||||
})
|
||||
.collect();
|
||||
oot_files.sort();
|
||||
if oot_files.is_empty() {
|
||||
rows.push(ReportRow {
|
||||
name: "OoT (hdrumble_trace-dualsense-*)".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
} else {
|
||||
let mut agg: Option<MotorTraceMetrics> = None;
|
||||
let mut used = 0usize;
|
||||
for p in &oot_files {
|
||||
if let Some(evs) = load_type_b(p) {
|
||||
let m = replay_events(&evs, 0);
|
||||
used += 1;
|
||||
match agg.as_mut() {
|
||||
Some(a) => a.merge_from(&m),
|
||||
None => agg = Some(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.push(ReportRow {
|
||||
name: format!("OoT ({used} file)"),
|
||||
metrics: agg,
|
||||
note: Some("Switch 1 / Fritchii".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
crate::nx2::set_nx2_mode(0);
|
||||
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Báo cáo đo mô-tơ DualSense — nhãn `{label}`\n");
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Cấu hình: `set_speaker({HD_HAPTICS_SPEAKER_PERCENT})`, mỗi khối 256 mẫu (48 kHz = 5,333 ms). Ngưỡng rung: `al + ah > {ACTIVE_RUMBLE_THRESHOLD}`.\n"
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"| Trace | Rung (s) | Va chạm nặng (cú) | Cú/phút | Nổ (lần) | % rung w=1 | % rung w>0 | Khe dịch f_L>220 | f_L ra TB (w=1) | Đỉnh kênh 2–3 | Ghi chú |"
|
||||
);
|
||||
let _ = writeln!(md, "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|");
|
||||
for r in &rows {
|
||||
push_row(&mut md, r);
|
||||
}
|
||||
|
||||
let out_dir = Path::new(r"D:\AGY\scratch\122-motor");
|
||||
fs::create_dir_all(out_dir).expect("create D:\\AGY\\scratch\\122-motor");
|
||||
let out_path = out_dir.join(format!("bao-cao-{label}.md"));
|
||||
fs::write(&out_path, &md).expect("write report markdown");
|
||||
println!("{md}");
|
||||
println!("Wrote {}", out_path.display());
|
||||
}
|
||||
223
third_party/renhdrum/src/dualsense/opus_codec.rs
vendored
Normal file
223
third_party/renhdrum/src/dualsense/opus_codec.rs
vendored
Normal file
@@ -0,0 +1,223 @@
|
||||
//! Embedded libopus wrapper for DualSense Bluetooth speaker packets (`0x36` sub-packet `0x93`).
|
||||
//! Encoding parameters match Enhanced-PS5-DualSense-Haptics-Bridge (MIT):
|
||||
//! 48 kHz stereo, 10 ms (480 samples/channel), hard CBR 160 kb/s -> 200 bytes/frame.
|
||||
|
||||
use std::ffi::{c_int, c_void};
|
||||
|
||||
pub const BT_OPUS_SAMPLE_RATE: i32 = 48_000;
|
||||
pub const BT_OPUS_CHANNELS: usize = 2;
|
||||
pub const BT_OPUS_FRAME_SAMPLES: usize = 480;
|
||||
pub const BT_OPUS_BITRATE: i32 = 160_000;
|
||||
pub const BT_OPUS_PACKET_SIZE: usize = 200;
|
||||
pub const BT_SPEAKER_SOURCE_TICK_SAMPLES: usize = 512;
|
||||
|
||||
/// Prebuilt 200-byte Opus 10 ms stereo CBR silence frame (TOC 0xF4).
|
||||
pub const SPEAKER_OPUS_SILENCE: [u8; BT_OPUS_PACKET_SIZE] = {
|
||||
let mut frame = [0u8; BT_OPUS_PACKET_SIZE];
|
||||
frame[0] = 0xF4;
|
||||
frame[1] = 0xFF;
|
||||
frame[2] = 0xFE;
|
||||
frame
|
||||
};
|
||||
|
||||
const OPUS_OK: c_int = 0;
|
||||
const OPUS_APPLICATION_AUDIO: c_int = 2049;
|
||||
const OPUS_SET_BITRATE_REQUEST: c_int = 4002;
|
||||
const OPUS_SET_VBR_REQUEST: c_int = 4006;
|
||||
const OPUS_RESET_STATE: c_int = 4028;
|
||||
const OPUS_SET_EXPERT_FRAME_DURATION_REQUEST: c_int = 4040;
|
||||
const OPUS_FRAMESIZE_10_MS: c_int = 5003;
|
||||
|
||||
const ENCODER_STATE_WORDS: usize = 6400; // 51,200 bytes, >= opus_encoder_get_size(2) (48,492 B on x64)
|
||||
|
||||
extern "C" {
|
||||
fn opus_encoder_get_size(channels: c_int) -> c_int;
|
||||
fn opus_encoder_init(st: *mut c_void, fs: i32, channels: c_int, application: c_int) -> c_int;
|
||||
fn opus_encode_float(
|
||||
st: *mut c_void,
|
||||
pcm: *const f32,
|
||||
frame_size: c_int,
|
||||
data: *mut u8,
|
||||
max_data_bytes: i32,
|
||||
) -> i32;
|
||||
fn opus_encoder_ctl(st: *mut c_void, request: c_int, ...) -> c_int;
|
||||
}
|
||||
|
||||
/// Fixed-storage, zero-heap-allocation Opus encoder for Bluetooth speaker frames.
|
||||
pub struct BtOpusEncoder {
|
||||
state: [u64; ENCODER_STATE_WORDS],
|
||||
was_active: bool,
|
||||
}
|
||||
|
||||
impl Default for BtOpusEncoder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl BtOpusEncoder {
|
||||
pub fn new() -> Self {
|
||||
let mut enc = Self {
|
||||
state: [0u64; ENCODER_STATE_WORDS],
|
||||
was_active: false,
|
||||
};
|
||||
unsafe {
|
||||
let needed = opus_encoder_get_size(BT_OPUS_CHANNELS as c_int);
|
||||
assert!(
|
||||
needed > 0 && (needed as usize) <= std::mem::size_of_val(&enc.state),
|
||||
"libopus encoder state size {needed} exceeds fixed buffer {}",
|
||||
std::mem::size_of_val(&enc.state)
|
||||
);
|
||||
let st = enc.state.as_mut_ptr() as *mut c_void;
|
||||
let rc = opus_encoder_init(
|
||||
st,
|
||||
BT_OPUS_SAMPLE_RATE,
|
||||
BT_OPUS_CHANNELS as c_int,
|
||||
OPUS_APPLICATION_AUDIO,
|
||||
);
|
||||
assert_eq!(rc, OPUS_OK, "opus_encoder_init failed: {rc}");
|
||||
assert_eq!(
|
||||
opus_encoder_ctl(st, OPUS_SET_BITRATE_REQUEST, BT_OPUS_BITRATE),
|
||||
OPUS_OK
|
||||
);
|
||||
assert_eq!(
|
||||
opus_encoder_ctl(st, OPUS_SET_VBR_REQUEST, 0 as c_int),
|
||||
OPUS_OK
|
||||
);
|
||||
assert_eq!(
|
||||
opus_encoder_ctl(
|
||||
st,
|
||||
OPUS_SET_EXPERT_FRAME_DURATION_REQUEST,
|
||||
OPUS_FRAMESIZE_10_MS
|
||||
),
|
||||
OPUS_OK
|
||||
);
|
||||
}
|
||||
enc
|
||||
}
|
||||
|
||||
/// Time-compresses 512 mono 48 kHz samples (10.667 ms) into 480 stereo samples (10 ms)
|
||||
/// and encodes one 200-byte CBR 160 kb/s Opus packet. Returns `true` when non-silent.
|
||||
pub fn encode_source_tick(
|
||||
&mut self,
|
||||
mono512: &[f32; BT_SPEAKER_SOURCE_TICK_SAMPLES],
|
||||
out200: &mut [u8; BT_OPUS_PACKET_SIZE],
|
||||
) -> bool {
|
||||
let silent = mono512.iter().all(|&s| !s.is_finite() || s.abs() <= 1e-6);
|
||||
if silent {
|
||||
if self.was_active {
|
||||
unsafe {
|
||||
let _ =
|
||||
opus_encoder_ctl(self.state.as_mut_ptr() as *mut c_void, OPUS_RESET_STATE);
|
||||
}
|
||||
self.was_active = false;
|
||||
}
|
||||
*out200 = SPEAKER_OPUS_SILENCE;
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut stereo = [0.0f32; BT_OPUS_FRAME_SAMPLES * BT_OPUS_CHANNELS];
|
||||
for i in 0..BT_OPUS_FRAME_SAMPLES {
|
||||
let pos = (i as f64) * ((BT_SPEAKER_SOURCE_TICK_SAMPLES - 1) as f64)
|
||||
/ ((BT_OPUS_FRAME_SAMPLES - 1) as f64);
|
||||
let lo = pos as usize;
|
||||
let hi = (lo + 1).min(BT_SPEAKER_SOURCE_TICK_SAMPLES - 1);
|
||||
let frac = (pos - lo as f64) as f32;
|
||||
let a = if mono512[lo].is_finite() {
|
||||
mono512[lo]
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let b = if mono512[hi].is_finite() {
|
||||
mono512[hi]
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let v = (a * (1.0 - frac) + b * frac).clamp(-0.99, 0.99);
|
||||
stereo[i * 2] = v;
|
||||
stereo[i * 2 + 1] = v;
|
||||
}
|
||||
|
||||
let encoded = unsafe {
|
||||
opus_encode_float(
|
||||
self.state.as_mut_ptr() as *mut c_void,
|
||||
stereo.as_ptr(),
|
||||
BT_OPUS_FRAME_SAMPLES as c_int,
|
||||
out200.as_mut_ptr(),
|
||||
BT_OPUS_PACKET_SIZE as i32,
|
||||
)
|
||||
};
|
||||
if encoded != BT_OPUS_PACKET_SIZE as i32 {
|
||||
*out200 = SPEAKER_OPUS_SILENCE;
|
||||
return false;
|
||||
}
|
||||
self.was_active = true;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod test_decoder {
|
||||
use super::*;
|
||||
|
||||
const DECODER_STATE_WORDS: usize = 4096; // 32,768 bytes
|
||||
|
||||
extern "C" {
|
||||
fn opus_decoder_get_size(channels: c_int) -> c_int;
|
||||
fn opus_decoder_init(st: *mut c_void, fs: i32, channels: c_int) -> c_int;
|
||||
fn opus_decode_float(
|
||||
st: *mut c_void,
|
||||
data: *const u8,
|
||||
len: i32,
|
||||
pcm: *mut f32,
|
||||
frame_size: c_int,
|
||||
decode_fec: c_int,
|
||||
) -> c_int;
|
||||
}
|
||||
|
||||
pub struct BtOpusDecoder {
|
||||
state: [u64; DECODER_STATE_WORDS],
|
||||
}
|
||||
|
||||
impl BtOpusDecoder {
|
||||
pub fn new() -> Self {
|
||||
let mut dec = Self {
|
||||
state: [0u64; DECODER_STATE_WORDS],
|
||||
};
|
||||
unsafe {
|
||||
let needed = opus_decoder_get_size(BT_OPUS_CHANNELS as c_int);
|
||||
assert!(
|
||||
needed > 0 && (needed as usize) <= std::mem::size_of_val(&dec.state),
|
||||
"libopus decoder state size {needed} exceeds fixed buffer {}",
|
||||
std::mem::size_of_val(&dec.state)
|
||||
);
|
||||
let rc = opus_decoder_init(
|
||||
dec.state.as_mut_ptr() as *mut c_void,
|
||||
BT_OPUS_SAMPLE_RATE,
|
||||
BT_OPUS_CHANNELS as c_int,
|
||||
);
|
||||
assert_eq!(rc, OPUS_OK, "opus_decoder_init failed: {rc}");
|
||||
}
|
||||
dec
|
||||
}
|
||||
|
||||
pub fn decode_frame(
|
||||
&mut self,
|
||||
packet: &[u8; BT_OPUS_PACKET_SIZE],
|
||||
out_stereo: &mut [f32; BT_OPUS_FRAME_SAMPLES * BT_OPUS_CHANNELS],
|
||||
) -> usize {
|
||||
let decoded = unsafe {
|
||||
opus_decode_float(
|
||||
self.state.as_mut_ptr() as *mut c_void,
|
||||
packet.as_ptr(),
|
||||
packet.len() as i32,
|
||||
out_stereo.as_mut_ptr(),
|
||||
BT_OPUS_FRAME_SAMPLES as c_int,
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert!(decoded >= 0, "opus_decode_float failed: {decoded}");
|
||||
decoded as usize
|
||||
}
|
||||
}
|
||||
}
|
||||
207
third_party/renhdrum/src/dualsense/settings.rs
vendored
Normal file
207
third_party/renhdrum/src/dualsense/settings.rs
vendored
Normal file
@@ -0,0 +1,207 @@
|
||||
use crate::settings::RumbleConfigController;
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Effective DualSense settings of one controller.
|
||||
/// Triggers are always disabled since 0.2.6.1 ("removed in 0.2.6.1").
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DualSenseSettings {
|
||||
pub triggers_enabled: bool,
|
||||
pub haptics_enabled: bool,
|
||||
pub haptics_volume: i32,
|
||||
pub crisp_notes: bool,
|
||||
}
|
||||
|
||||
impl Default for DualSenseSettings {
|
||||
fn default() -> Self {
|
||||
Self::resolve(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DualSenseSettingsFull {
|
||||
pub triggers_enabled: bool,
|
||||
pub triggers_source: String,
|
||||
pub haptics_enabled: bool,
|
||||
pub haptics_source: String,
|
||||
pub haptics_volume: i32,
|
||||
pub haptics_volume_source: String,
|
||||
pub crisp_notes: bool,
|
||||
}
|
||||
|
||||
impl DualSenseSettings {
|
||||
pub const TRIGGERS_OFF_FLAG_FILE: &'static str = "dualsense_triggers_off";
|
||||
pub const HAPTICS_OFF_FLAG_FILE: &'static str = "dualsense_haptics_off";
|
||||
pub const HAPTICS_VOLUME_FLAG_FILE: &'static str = "dualsense_haptics_volume.txt";
|
||||
|
||||
pub const MIN_HAPTICS_VOLUME: i32 = 10;
|
||||
pub const MAX_HAPTICS_VOLUME: i32 = 100;
|
||||
|
||||
pub const SOURCE_CONFIG: &'static str = "config";
|
||||
pub const SOURCE_DEFAULT: &'static str = "default";
|
||||
pub const SOURCE_REMOVED: &'static str = "removed in 0.2.6.1";
|
||||
|
||||
pub fn resolve(config: Option<&RumbleConfigController>) -> Self {
|
||||
let full = Self::resolve_full_with_dir(config, None);
|
||||
Self {
|
||||
triggers_enabled: full.triggers_enabled,
|
||||
haptics_enabled: full.haptics_enabled,
|
||||
haptics_volume: full.haptics_volume,
|
||||
crisp_notes: full.crisp_notes,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve_full(config: Option<&RumbleConfigController>) -> DualSenseSettingsFull {
|
||||
Self::resolve_full_with_dir(config, None)
|
||||
}
|
||||
|
||||
pub fn resolve_full_with_dir(
|
||||
config: Option<&RumbleConfigController>,
|
||||
base_dir: Option<&Path>,
|
||||
) -> DualSenseSettingsFull {
|
||||
let config_source = if config.is_some() {
|
||||
Self::SOURCE_CONFIG
|
||||
} else {
|
||||
Self::SOURCE_DEFAULT
|
||||
};
|
||||
|
||||
let triggers = false;
|
||||
let triggers_source = Self::SOURCE_REMOVED.to_string();
|
||||
|
||||
let mut haptics = config.map(|c| c.enable_dualsense_haptics).unwrap_or(true);
|
||||
let mut haptics_source = config_source.to_string();
|
||||
|
||||
if flag_file_exists(Self::HAPTICS_OFF_FLAG_FILE, base_dir) {
|
||||
haptics = false;
|
||||
haptics_source = format!("flag file {}", Self::HAPTICS_OFF_FLAG_FILE);
|
||||
}
|
||||
|
||||
let mut volume = config
|
||||
.map(|c| c.dualsense_haptics_volume)
|
||||
.unwrap_or(RumbleConfigController::DEFAULT_DUALSENSE_HAPTICS_VOLUME);
|
||||
let mut volume_source = config_source.to_string();
|
||||
|
||||
if !(Self::MIN_HAPTICS_VOLUME..=Self::MAX_HAPTICS_VOLUME).contains(&volume) {
|
||||
volume = volume.clamp(Self::MIN_HAPTICS_VOLUME, Self::MAX_HAPTICS_VOLUME);
|
||||
volume_source = format!("{}, clamped", config_source);
|
||||
}
|
||||
|
||||
if let Some(flag_volume) = try_read_flag_int(Self::HAPTICS_VOLUME_FLAG_FILE, base_dir) {
|
||||
volume = flag_volume.clamp(Self::MIN_HAPTICS_VOLUME, Self::MAX_HAPTICS_VOLUME);
|
||||
volume_source = format!("flag file {}", Self::HAPTICS_VOLUME_FLAG_FILE);
|
||||
}
|
||||
|
||||
let crisp = config.map(|c| c.dualsense_crisp_notes).unwrap_or(false);
|
||||
|
||||
DualSenseSettingsFull {
|
||||
triggers_enabled: triggers,
|
||||
triggers_source,
|
||||
haptics_enabled: haptics,
|
||||
haptics_source,
|
||||
haptics_volume: volume,
|
||||
haptics_volume_source: volume_source,
|
||||
crisp_notes: crisp,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn existing_flag_files(base_dir: Option<&Path>) -> Vec<&'static str> {
|
||||
let mut files = Vec::new();
|
||||
for &name in &[Self::HAPTICS_OFF_FLAG_FILE, Self::HAPTICS_VOLUME_FLAG_FILE] {
|
||||
if flag_file_exists(name, base_dir) {
|
||||
files.push(name);
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DualSenseSettingsFull {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"adaptive triggers {} ({}), haptics {} ({}), volume {}% ({}), crisp notes {}",
|
||||
if self.triggers_enabled { "on" } else { "off" },
|
||||
self.triggers_source,
|
||||
if self.haptics_enabled { "on" } else { "off" },
|
||||
self.haptics_source,
|
||||
self.haptics_volume,
|
||||
self.haptics_volume_source,
|
||||
if self.crisp_notes { "on" } else { "off" }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn flag_file_exists(name: &str, base_dir: Option<&Path>) -> bool {
|
||||
let path = if let Some(dir) = base_dir {
|
||||
dir.join(name)
|
||||
} else {
|
||||
match std::env::current_exe() {
|
||||
Ok(exe) => exe.parent().unwrap_or(Path::new(".")).join(name),
|
||||
Err(_) => PathBuf::from(name),
|
||||
}
|
||||
};
|
||||
path.is_file()
|
||||
}
|
||||
|
||||
fn try_read_flag_int(name: &str, base_dir: Option<&Path>) -> Option<i32> {
|
||||
let path = if let Some(dir) = base_dir {
|
||||
dir.join(name)
|
||||
} else {
|
||||
match std::env::current_exe() {
|
||||
Ok(exe) => exe.parent().unwrap_or(Path::new(".")).join(name),
|
||||
Err(_) => PathBuf::from(name),
|
||||
}
|
||||
};
|
||||
if let Ok(content) = std::fs::read_to_string(path) {
|
||||
content.trim().parse::<i32>().ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_dualsense_settings_defaults() {
|
||||
let settings = DualSenseSettings::resolve(None);
|
||||
assert!(!settings.triggers_enabled);
|
||||
assert!(settings.haptics_enabled);
|
||||
assert_eq!(settings.haptics_volume, 100);
|
||||
assert!(!settings.crisp_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dualsense_settings_configured() {
|
||||
let config = RumbleConfigController {
|
||||
enable_adaptive_triggers: true,
|
||||
enable_dualsense_haptics: false,
|
||||
dualsense_haptics_volume: 75,
|
||||
dualsense_crisp_notes: true,
|
||||
..RumbleConfigController::default()
|
||||
};
|
||||
let settings = DualSenseSettings::resolve(Some(&config));
|
||||
assert!(!settings.triggers_enabled); // always false in 0.2.6.1
|
||||
assert!(!settings.haptics_enabled);
|
||||
assert_eq!(settings.haptics_volume, 75);
|
||||
assert!(settings.crisp_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dualsense_settings_volume_clamp() {
|
||||
let config_low = RumbleConfigController {
|
||||
dualsense_haptics_volume: 5,
|
||||
..RumbleConfigController::default()
|
||||
};
|
||||
let settings_low = DualSenseSettings::resolve(Some(&config_low));
|
||||
assert_eq!(settings_low.haptics_volume, 10);
|
||||
|
||||
let config_high = RumbleConfigController {
|
||||
dualsense_haptics_volume: 150,
|
||||
..RumbleConfigController::default()
|
||||
};
|
||||
let settings_high = DualSenseSettings::resolve(Some(&config_high));
|
||||
assert_eq!(settings_high.haptics_volume, 100);
|
||||
}
|
||||
}
|
||||
1130
third_party/renhdrum/src/dualsense/speaker.rs
vendored
Normal file
1130
third_party/renhdrum/src/dualsense/speaker.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
602
third_party/renhdrum/src/dualsense/speaker_replay.rs
vendored
Normal file
602
third_party/renhdrum/src/dualsense/speaker_replay.rs
vendored
Normal file
@@ -0,0 +1,602 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::haptics::{
|
||||
DualSenseHapticsDsp, DUALSENSE_BUFFER_FRAMES, DUALSENSE_CHANNELS, DUALSENSE_SAMPLE_RATE,
|
||||
HD_HAPTICS_SPEAKER_PERCENT,
|
||||
};
|
||||
use super::speaker::SpeakerSide;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct TraceEvent {
|
||||
pub(super) t_us: i64,
|
||||
pub(super) is_right: bool,
|
||||
pub(super) al: f32,
|
||||
pub(super) fl: f32,
|
||||
pub(super) ah: f32,
|
||||
pub(super) fh: f32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SideStats {
|
||||
grains_by_kind: [u32; 4],
|
||||
max_1s: u32,
|
||||
noise_slots: u64,
|
||||
note_slots: u64,
|
||||
rumble_slots: u64,
|
||||
variant_repeats: u32,
|
||||
rapid_hits: u32,
|
||||
footstep_hits: u32,
|
||||
footstep_muted: u32,
|
||||
window: VecDeque<i64>,
|
||||
}
|
||||
|
||||
impl SideStats {
|
||||
fn record_slot(
|
||||
&mut self,
|
||||
t_us: i64,
|
||||
spk: &SpeakerSide,
|
||||
rumble_active: bool,
|
||||
repeats_delta: u32,
|
||||
) {
|
||||
let kind = spk.last_fired_kind;
|
||||
if kind != 0 && (kind as usize) < self.grains_by_kind.len() {
|
||||
self.grains_by_kind[kind as usize] += 1;
|
||||
self.window.push_back(t_us);
|
||||
while let Some(&front) = self.window.front() {
|
||||
if t_us - front >= 1_000_000 {
|
||||
self.window.pop_front();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let cur = self.window.len() as u32;
|
||||
if cur > self.max_1s {
|
||||
self.max_1s = cur;
|
||||
}
|
||||
}
|
||||
if spk.noise_active() {
|
||||
self.noise_slots += 1;
|
||||
}
|
||||
if spk.note_active() {
|
||||
self.note_slots += 1;
|
||||
}
|
||||
if rumble_active {
|
||||
self.rumble_slots += 1;
|
||||
}
|
||||
if spk.last_fired_rapid {
|
||||
self.rapid_hits += 1;
|
||||
}
|
||||
if spk.last_fired_footstep {
|
||||
self.footstep_hits += 1;
|
||||
}
|
||||
if spk.last_fired_footstep_muted {
|
||||
self.footstep_muted += 1;
|
||||
}
|
||||
self.variant_repeats += repeats_delta;
|
||||
}
|
||||
|
||||
fn total_grains(&self) -> u32 {
|
||||
self.grains_by_kind[1] + self.grains_by_kind[2] + self.grains_by_kind[3]
|
||||
}
|
||||
|
||||
fn noise_sec(&self) -> f64 {
|
||||
self.noise_slots as f64 * DUALSENSE_BUFFER_FRAMES as f64 / DUALSENSE_SAMPLE_RATE as f64
|
||||
}
|
||||
|
||||
fn note_sec(&self) -> f64 {
|
||||
self.note_slots as f64 * DUALSENSE_BUFFER_FRAMES as f64 / DUALSENSE_SAMPLE_RATE as f64
|
||||
}
|
||||
|
||||
fn note_pct(&self) -> f64 {
|
||||
if self.rumble_slots == 0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * self.note_slots as f64 / self.rumble_slots as f64
|
||||
}
|
||||
}
|
||||
|
||||
fn rumble_sec(&self) -> f64 {
|
||||
self.rumble_slots as f64 * DUALSENSE_BUFFER_FRAMES as f64 / DUALSENSE_SAMPLE_RATE as f64
|
||||
}
|
||||
}
|
||||
|
||||
struct TraceMetrics {
|
||||
dur_s: f64,
|
||||
left: SideStats,
|
||||
right: SideStats,
|
||||
}
|
||||
|
||||
impl TraceMetrics {
|
||||
fn new(dur_s: f64) -> Self {
|
||||
Self {
|
||||
dur_s: dur_s.max(0.001),
|
||||
left: SideStats::default(),
|
||||
right: SideStats::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_from(&mut self, other: &Self) {
|
||||
self.dur_s += other.dur_s;
|
||||
for (dst, src) in [
|
||||
(&mut self.left, &other.left),
|
||||
(&mut self.right, &other.right),
|
||||
] {
|
||||
for k in 1..4 {
|
||||
dst.grains_by_kind[k] += src.grains_by_kind[k];
|
||||
}
|
||||
dst.max_1s = dst.max_1s.max(src.max_1s);
|
||||
dst.noise_slots += src.noise_slots;
|
||||
dst.note_slots += src.note_slots;
|
||||
dst.rumble_slots += src.rumble_slots;
|
||||
dst.variant_repeats += src.variant_repeats;
|
||||
dst.rapid_hits += src.rapid_hits;
|
||||
dst.footstep_hits += src.footstep_hits;
|
||||
dst.footstep_muted += src.footstep_muted;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ReportRow {
|
||||
name: String,
|
||||
metrics: Option<TraceMetrics>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn load_type_b(path: &Path) -> Option<Vec<TraceEvent>> {
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
let mut events = Vec::new();
|
||||
for line in text.lines() {
|
||||
let mut parts = line.split(',');
|
||||
if parts.next() != Some("G") {
|
||||
continue;
|
||||
}
|
||||
let Ok(t_us) = parts.next().unwrap_or("").trim().parse::<i64>() else {
|
||||
continue;
|
||||
};
|
||||
let is_right = match parts.next().unwrap_or("").trim() {
|
||||
"R" => true,
|
||||
"L" => false,
|
||||
_ => continue,
|
||||
};
|
||||
let Ok(al) = parts.next().unwrap_or("").trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(fl) = parts.next().unwrap_or("").trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(ah) = parts.next().unwrap_or("").trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(fh) = parts.next().unwrap_or("").trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
events.push(TraceEvent {
|
||||
t_us,
|
||||
is_right,
|
||||
al,
|
||||
fl,
|
||||
ah,
|
||||
fh,
|
||||
});
|
||||
}
|
||||
if events.is_empty() {
|
||||
None
|
||||
} else {
|
||||
events.sort_by_key(|e| e.t_us);
|
||||
Some(events)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load_type_a(path: &Path) -> Option<(Vec<TraceEvent>, i32)> {
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
let mut lines = text.lines();
|
||||
let header = lines.next()?;
|
||||
let cols: Vec<&str> = header.split(',').map(|s| s.trim()).collect();
|
||||
let col_idx = |name: &str| cols.iter().position(|&c| c == name);
|
||||
let i_ms = col_idx("ms")?;
|
||||
let i_mode = col_idx("mode")?;
|
||||
let i_dev = col_idx("device_index")?;
|
||||
let i_al = col_idx("low_amp")?;
|
||||
let i_fl = col_idx("low_freq")?;
|
||||
let i_ah = col_idx("high_amp")?;
|
||||
let i_fh = col_idx("high_freq")?;
|
||||
|
||||
let mut events = Vec::new();
|
||||
let mut mode = 2;
|
||||
for line in lines {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = trimmed.split(',').collect();
|
||||
if parts.len() <= i_fh {
|
||||
continue;
|
||||
}
|
||||
let Ok(ms) = parts[i_ms].trim().parse::<f64>() else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(m) = parts[i_mode].trim().parse::<i32>() {
|
||||
mode = m;
|
||||
}
|
||||
let Ok(dev) = parts[i_dev].trim().parse::<i32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(al) = parts[i_al].trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(fl) = parts[i_fl].trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(ah) = parts[i_ah].trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(fh) = parts[i_fh].trim().parse::<f32>() else {
|
||||
continue;
|
||||
};
|
||||
events.push(TraceEvent {
|
||||
t_us: (ms * 1000.0).round() as i64,
|
||||
is_right: dev != 0,
|
||||
al,
|
||||
fl,
|
||||
ah,
|
||||
fh,
|
||||
});
|
||||
}
|
||||
if events.is_empty() {
|
||||
None
|
||||
} else {
|
||||
events.sort_by_key(|e| e.t_us);
|
||||
Some((events, mode))
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches `scratch/118-buoc6/phan-tich-trace.py` Q1 Group 1 definition (44 MKW menu clicks).
|
||||
fn extract_mkw_menu_clicks(events: &[TraceEvent]) -> Vec<(i64, i64)> {
|
||||
let left: Vec<TraceEvent> = events.iter().copied().filter(|e| !e.is_right).collect();
|
||||
let mut pulses: Vec<(f64, f64, f32)> = Vec::new();
|
||||
let mut in_p = false;
|
||||
let mut p_start = 0.0f64;
|
||||
let mut max_ah = 0.0f32;
|
||||
|
||||
for (i, ev) in left.iter().enumerate() {
|
||||
let t_ms = ev.t_us as f64 / 1000.0;
|
||||
let act = (ev.al + ev.ah) > 0.001;
|
||||
if i > 0 {
|
||||
let prev_ms = left[i - 1].t_us as f64 / 1000.0;
|
||||
if t_ms - prev_ms > 500.0 && in_p {
|
||||
let dur = prev_ms + 5.0 - p_start;
|
||||
pulses.push((p_start, dur, max_ah));
|
||||
in_p = false;
|
||||
max_ah = 0.0;
|
||||
}
|
||||
}
|
||||
if act && !in_p {
|
||||
in_p = true;
|
||||
p_start = t_ms;
|
||||
max_ah = ev.ah;
|
||||
} else if act && in_p {
|
||||
if ev.ah > max_ah {
|
||||
max_ah = ev.ah;
|
||||
}
|
||||
} else if !act && in_p {
|
||||
let dur = t_ms - p_start;
|
||||
pulses.push((p_start, dur, max_ah));
|
||||
in_p = false;
|
||||
max_ah = 0.0;
|
||||
}
|
||||
}
|
||||
if in_p {
|
||||
if let Some(last) = left.last() {
|
||||
let dur = last.t_us as f64 / 1000.0 + 5.0 - p_start;
|
||||
pulses.push((p_start, dur, max_ah));
|
||||
}
|
||||
}
|
||||
|
||||
pulses
|
||||
.into_iter()
|
||||
.filter(|&(_, dur, mah)| (4.5..20.5).contains(&dur) && mah >= 0.005)
|
||||
.map(|(st_ms, dur, _)| {
|
||||
let st_us = ((st_ms - 1.0) * 1000.0).round() as i64;
|
||||
let en_us = ((st_ms + dur + 10.0) * 1000.0).round() as i64;
|
||||
(st_us, en_us)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn replay_events(
|
||||
events: &[TraceEvent],
|
||||
nx2_mode: i32,
|
||||
sub_win_us: Option<(i64, i64)>,
|
||||
menu_windows: &[(i64, i64)],
|
||||
) -> (TraceMetrics, Option<TraceMetrics>, (usize, usize)) {
|
||||
crate::nx2::set_nx2_mode(nx2_mode);
|
||||
let mut dsp = DualSenseHapticsDsp::new(100, true);
|
||||
dsp.set_speaker(HD_HAPTICS_SPEAKER_PERCENT);
|
||||
|
||||
let start_us = events[0].t_us;
|
||||
let end_us = events.last().map_or(start_us, |e| e.t_us);
|
||||
let mut full = TraceMetrics::new((end_us - start_us) as f64 / 1_000_000.0);
|
||||
let mut sub = sub_win_us.map(|(ws, we)| TraceMetrics::new((we - ws) as f64 / 1_000_000.0));
|
||||
let mut menu_hit_l = vec![false; menu_windows.len()];
|
||||
let mut menu_hit_r = vec![false; menu_windows.len()];
|
||||
|
||||
let mut idx = 0usize;
|
||||
let mut slot_idx = 0u64;
|
||||
let mut latest_sum = [0.0f32; 2];
|
||||
let mut prev_rep_l = 0u32;
|
||||
let mut prev_rep_r = 0u32;
|
||||
let mut buf = [0.0f32; DUALSENSE_BUFFER_FRAMES * DUALSENSE_CHANNELS];
|
||||
|
||||
loop {
|
||||
let slot_t_us = start_us
|
||||
+ ((slot_idx as i128 * DUALSENSE_BUFFER_FRAMES as i128 * 1_000_000)
|
||||
/ DUALSENSE_SAMPLE_RATE as i128) as i64;
|
||||
if slot_t_us > end_us + 50_000 {
|
||||
break;
|
||||
}
|
||||
while idx < events.len() && events[idx].t_us <= slot_t_us {
|
||||
let ev = events[idx];
|
||||
dsp.set_half_target(ev.is_right, ev.al, ev.fl, ev.ah, ev.fh);
|
||||
latest_sum[usize::from(ev.is_right)] = ev.al + ev.ah;
|
||||
idx += 1;
|
||||
}
|
||||
dsp.fill_interleaved_f32(&mut buf);
|
||||
|
||||
let (spk_l, spk_r): (&SpeakerSide, &SpeakerSide) = dsp.spk_sides();
|
||||
let kind_l = spk_l.last_fired_kind;
|
||||
let kind_r = spk_r.last_fired_kind;
|
||||
let rep_dl = spk_l.variant_repeats - prev_rep_l;
|
||||
let rep_dr = spk_r.variant_repeats - prev_rep_r;
|
||||
prev_rep_l = spk_l.variant_repeats;
|
||||
prev_rep_r = spk_r.variant_repeats;
|
||||
let rumble_l = latest_sum[0] > 0.001;
|
||||
let rumble_r = latest_sum[1] > 0.001;
|
||||
|
||||
if slot_t_us <= end_us {
|
||||
full.left.record_slot(slot_t_us, spk_l, rumble_l, rep_dl);
|
||||
full.right.record_slot(slot_t_us, spk_r, rumble_r, rep_dr);
|
||||
}
|
||||
if let (Some((ws, we)), Some(sub_m)) = (sub_win_us, sub.as_mut()) {
|
||||
if slot_t_us >= ws && slot_t_us <= we {
|
||||
sub_m.left.record_slot(slot_t_us, spk_l, rumble_l, rep_dl);
|
||||
sub_m.right.record_slot(slot_t_us, spk_r, rumble_r, rep_dr);
|
||||
}
|
||||
}
|
||||
if kind_l != 0 || kind_r != 0 {
|
||||
for (ci, &(cs, ce)) in menu_windows.iter().enumerate() {
|
||||
if slot_t_us >= cs && slot_t_us <= ce {
|
||||
if kind_l != 0 {
|
||||
menu_hit_l[ci] = true;
|
||||
}
|
||||
if kind_r != 0 {
|
||||
menu_hit_r[ci] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
slot_idx += 1;
|
||||
}
|
||||
|
||||
let hit_l = menu_hit_l.iter().filter(|&&h| h).count();
|
||||
let hit_r = menu_hit_r.iter().filter(|&&h| h).count();
|
||||
(full, sub, (hit_l, hit_r))
|
||||
}
|
||||
|
||||
fn push_row(out: &mut String, row: &ReportRow) {
|
||||
match (&row.metrics, &row.note) {
|
||||
(Some(m), note) => {
|
||||
let l = &m.left;
|
||||
let r = &m.right;
|
||||
let tl = l.total_grains();
|
||||
let tr = r.total_grains();
|
||||
let avg_l = tl as f64 / m.dur_s;
|
||||
let avg_r = tr as f64 / m.dur_s;
|
||||
let extra = note.as_deref().unwrap_or("");
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {:.1} | {:.1} / {:.1} | {} / {} | {} / {} | {} / {} | {} / {} | {:.2} / {:.2} | {} / {} | {:.1} / {:.1} | {:.2} / {:.2} | {:.2}% / {:.2}% | {} / {} | {}/{} L, {}/{} R | {} / {} | {} |",
|
||||
row.name,
|
||||
m.dur_s,
|
||||
l.rumble_sec(),
|
||||
r.rumble_sec(),
|
||||
l.grains_by_kind[1],
|
||||
r.grains_by_kind[1],
|
||||
l.grains_by_kind[2],
|
||||
r.grains_by_kind[2],
|
||||
l.grains_by_kind[3],
|
||||
r.grains_by_kind[3],
|
||||
tl,
|
||||
tr,
|
||||
avg_l,
|
||||
avg_r,
|
||||
l.max_1s,
|
||||
r.max_1s,
|
||||
l.noise_sec(),
|
||||
r.noise_sec(),
|
||||
l.note_sec(),
|
||||
r.note_sec(),
|
||||
l.note_pct(),
|
||||
r.note_pct(),
|
||||
l.rapid_hits,
|
||||
r.rapid_hits,
|
||||
l.footstep_hits,
|
||||
l.footstep_muted,
|
||||
r.footstep_hits,
|
||||
r.footstep_muted,
|
||||
l.variant_repeats,
|
||||
r.variant_repeats,
|
||||
extra
|
||||
);
|
||||
}
|
||||
(None, note) => {
|
||||
let txt = note.as_deref().unwrap_or("thiếu");
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | - | - | - | - | - | - | - | - | - | - | - | - | - | - |",
|
||||
row.name, txt
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn speaker_replay_report() {
|
||||
let _guard = crate::nx2::NX2_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
let label = env::var("RENHDRUM_SPK_LABEL")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "goc".to_string());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let sw1_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/xbox_traces");
|
||||
for name in [
|
||||
"wonder.csv",
|
||||
"wonder2.csv",
|
||||
"wonder3.csv",
|
||||
"totk.csv",
|
||||
"totk2.csv",
|
||||
"totk3.csv",
|
||||
"odyssey.csv",
|
||||
"metroid.csv",
|
||||
] {
|
||||
let p = sw1_dir.join(name);
|
||||
if let Some(evs) = load_type_b(&p) {
|
||||
let (m, _, _) = replay_events(&evs, 0, None, &[]);
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: Some(m),
|
||||
note: None,
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let bananza_path = Path::new(r"D:\AGY\scratch\118-buoc6\bananza-trace.csv");
|
||||
if let Some((evs, mode)) = load_type_a(bananza_path) {
|
||||
let (full, sub, _) = replay_events(&evs, mode, Some((210_000_000, 270_000_000)), &[]);
|
||||
rows.push(ReportRow {
|
||||
name: "bananza-trace.csv".to_string(),
|
||||
metrics: Some(full),
|
||||
note: Some(format!("mode {mode}")),
|
||||
});
|
||||
rows.push(ReportRow {
|
||||
name: "bananza 210-270s (lốc xoáy)".to_string(),
|
||||
metrics: sub,
|
||||
note: Some("cửa sổ 60 s".to_string()),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: "bananza-trace.csv".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let mkw_path = Path::new(r"D:\AGY\scratch\118-buoc6\mkw-trace.csv");
|
||||
let mut mkw_menu_summary = None;
|
||||
if let Some((evs, mode)) = load_type_a(mkw_path) {
|
||||
let clicks = extract_mkw_menu_clicks(&evs);
|
||||
let (full, _, (hit_l, hit_r)) = replay_events(&evs, mode, None, &clicks);
|
||||
mkw_menu_summary = Some((hit_l, hit_r, clicks.len()));
|
||||
rows.push(ReportRow {
|
||||
name: "mkw-trace.csv".to_string(),
|
||||
metrics: Some(full),
|
||||
note: Some(format!(
|
||||
"mode {mode}; menu {hit_l}/{} L, {hit_r}/{} R",
|
||||
clicks.len(),
|
||||
clicks.len()
|
||||
)),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: "mkw-trace.csv".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let oot_dir = Path::new(r"D:\do-096\fritchii\build\bin\Release");
|
||||
let mut oot_files: Vec<PathBuf> = fs::read_dir(oot_dir)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok().map(|x| x.path()))
|
||||
.filter(|p| {
|
||||
p.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(|s| s.starts_with("hdrumble_trace-dualsense-") && s.ends_with(".csv"))
|
||||
})
|
||||
.collect();
|
||||
oot_files.sort();
|
||||
if oot_files.is_empty() {
|
||||
rows.push(ReportRow {
|
||||
name: "OoT (hdrumble_trace-dualsense-*)".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
} else {
|
||||
let mut agg: Option<TraceMetrics> = None;
|
||||
let mut used = 0usize;
|
||||
for p in &oot_files {
|
||||
if let Some(evs) = load_type_b(p) {
|
||||
let (m, _, _) = replay_events(&evs, 0, None, &[]);
|
||||
used += 1;
|
||||
match agg.as_mut() {
|
||||
Some(a) => a.merge_from(&m),
|
||||
None => agg = Some(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.push(ReportRow {
|
||||
name: format!("OoT ({used} file)"),
|
||||
metrics: agg,
|
||||
note: Some("Switch 1 / Fritchii".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
crate::nx2::set_nx2_mode(0);
|
||||
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Báo cáo đo loa DualSense — nhãn `{label}`\n");
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Cấu hình: `set_speaker({HD_HAPTICS_SPEAKER_PERCENT})`, mỗi khối 256 mẫu (48 kHz = 5,333 ms). Số ghi dạng `Trái / Phải`.\n"
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"| Trace | Thời lượng (s) | Rung (s) L/R | G1 L/R | G2 L/R | G3 L/R | Tổng L/R | Hạt/s TB L/R | Max 1s L/R | Nhiễu (s) L/R | Nốt (s) L/R | Nốt % rung L/R | LT L/R | BC kêu/im | Trùng biến thể L/R | Ghi chú |"
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|---:|---|"
|
||||
);
|
||||
for r in &rows {
|
||||
push_row(&mut md, r);
|
||||
}
|
||||
if let Some((hl, hr, total)) = mkw_menu_summary {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"\n- **MKW {total} nhấp menu:** L kêu **{hl}/{total}**, R kêu **{hr}/{total}**."
|
||||
);
|
||||
}
|
||||
|
||||
let out_dir = Path::new(r"D:\AGY\scratch\121-loa");
|
||||
fs::create_dir_all(out_dir).expect("create D:\\AGY\\scratch\\121-loa");
|
||||
let out_path = out_dir.join(format!("bao-cao-{label}.md"));
|
||||
fs::write(&out_path, &md).expect("write report markdown");
|
||||
println!("{md}");
|
||||
println!("Wrote {}", out_path.display());
|
||||
}
|
||||
296
third_party/renhdrum/src/dualsense/tri_replay.rs
vendored
Normal file
296
third_party/renhdrum/src/dualsense/tri_replay.rs
vendored
Normal file
@@ -0,0 +1,296 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::speaker_replay::{load_type_a, load_type_b, TraceEvent};
|
||||
use super::tri_trigger::{PulseKind, TriTrigger};
|
||||
use super::trigger_effect::DualSenseTriggerEffect;
|
||||
|
||||
const ACTIVE_RUMBLE_THRESHOLD: f32 = 0.01;
|
||||
const REPLAY_TRIGGER_DEPTH: u8 = 200;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TriTraceMetrics {
|
||||
rumble_ms: u64,
|
||||
total_pulses: u32,
|
||||
sac: u32,
|
||||
nang: u32,
|
||||
no: u32,
|
||||
max_changes_1s: u32,
|
||||
}
|
||||
|
||||
impl TriTraceMetrics {
|
||||
fn merge_from(&mut self, other: &Self) {
|
||||
self.rumble_ms += other.rumble_ms;
|
||||
self.total_pulses += other.total_pulses;
|
||||
self.sac += other.sac;
|
||||
self.nang += other.nang;
|
||||
self.no += other.no;
|
||||
self.max_changes_1s = self.max_changes_1s.max(other.max_changes_1s);
|
||||
}
|
||||
|
||||
fn rumble_sec(&self) -> f64 {
|
||||
self.rumble_ms as f64 / 1000.0
|
||||
}
|
||||
}
|
||||
|
||||
struct ReportRow {
|
||||
name: String,
|
||||
metrics: Option<TriTraceMetrics>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
fn replay_events(events: &[TraceEvent]) -> TriTraceMetrics {
|
||||
if events.is_empty() {
|
||||
return TriTraceMetrics::default();
|
||||
}
|
||||
|
||||
let mut triggers = [TriTrigger::new(), TriTrigger::new()];
|
||||
let mut latest = [(0.0f32, 160.0f32, 0.0f32, 320.0f32); 2];
|
||||
let mut prev_eff = [DualSenseTriggerEffect::off().data; 2];
|
||||
let mut windows = [VecDeque::<i64>::new(), VecDeque::<i64>::new()];
|
||||
|
||||
let start_us = events[0].t_us;
|
||||
let end_us = events.last().map_or(start_us, |e| e.t_us);
|
||||
let total_ms = (end_us - start_us + 999).max(0) / 1000;
|
||||
|
||||
let mut metrics = TriTraceMetrics::default();
|
||||
let mut idx = 0usize;
|
||||
|
||||
for t_ms in 0..=total_ms {
|
||||
let slot_t_us = start_us + t_ms * 1000;
|
||||
let mut fresh = [false; 2];
|
||||
|
||||
while idx < events.len() && events[idx].t_us <= slot_t_us {
|
||||
let ev = events[idx];
|
||||
let side = usize::from(ev.is_right);
|
||||
latest[side] = (ev.al, ev.fl, ev.ah, ev.fh);
|
||||
fresh[side] = true;
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
if latest[0].0 + latest[0].2 > ACTIVE_RUMBLE_THRESHOLD
|
||||
|| latest[1].0 + latest[1].2 > ACTIVE_RUMBLE_THRESHOLD
|
||||
{
|
||||
metrics.rumble_ms += 1;
|
||||
}
|
||||
|
||||
for side in 0..2 {
|
||||
let mut out = [0u8; DualSenseTriggerEffect::SIZE];
|
||||
let changed = triggers[side].update(
|
||||
t_ms as u32,
|
||||
REPLAY_TRIGGER_DEPTH,
|
||||
latest[side],
|
||||
fresh[side],
|
||||
&mut out,
|
||||
);
|
||||
// Ignore Off reminder repeats (0x05 -> 0x05): they are not effect changes.
|
||||
if changed && out != prev_eff[side] {
|
||||
prev_eff[side] = out;
|
||||
let win = &mut windows[side];
|
||||
win.push_back(t_ms);
|
||||
while let Some(&front) = win.front() {
|
||||
if t_ms - front >= 1000 {
|
||||
win.pop_front();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
metrics.max_changes_1s = metrics.max_changes_1s.max(win.len() as u32);
|
||||
|
||||
if out[0] == DualSenseTriggerEffect::MODE_VIBRATION {
|
||||
metrics.total_pulses += 1;
|
||||
match triggers[side].active_pulse_kind() {
|
||||
Some(PulseKind::Sharp) => metrics.sac += 1,
|
||||
Some(PulseKind::Heavy) => metrics.nang += 1,
|
||||
Some(PulseKind::Boom) => metrics.no += 1,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
metrics
|
||||
}
|
||||
|
||||
fn push_row(out: &mut String, row: &ReportRow) {
|
||||
match (&row.metrics, &row.note) {
|
||||
(Some(m), note) => {
|
||||
let extra = note.as_deref().unwrap_or("");
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {:.1} | {} | {} | {} | {} | {} | {} |",
|
||||
row.name,
|
||||
m.rumble_sec(),
|
||||
m.total_pulses,
|
||||
m.sac,
|
||||
m.nang,
|
||||
m.no,
|
||||
m.max_changes_1s,
|
||||
extra
|
||||
);
|
||||
}
|
||||
(None, note) => {
|
||||
let txt = note.as_deref().unwrap_or("thiếu");
|
||||
let _ = writeln!(out, "| {} | {} | - | - | - | - | - | - |", row.name, txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn tri_replay_report() {
|
||||
let label = env::var("RENHDRUM_TRI_LABEL")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "goc".to_string());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let sw1_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/xbox_traces");
|
||||
for name in [
|
||||
"wonder.csv",
|
||||
"wonder2.csv",
|
||||
"wonder3.csv",
|
||||
"totk.csv",
|
||||
"totk2.csv",
|
||||
"totk3.csv",
|
||||
"odyssey.csv",
|
||||
"metroid.csv",
|
||||
] {
|
||||
let p = sw1_dir.join(name);
|
||||
if let Some(evs) = load_type_b(&p) {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: Some(replay_events(&evs)),
|
||||
note: None,
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (name, path) in [
|
||||
(
|
||||
"bananza-trace.csv",
|
||||
Path::new(r"D:\AGY\scratch\118-buoc6\bananza-trace.csv"),
|
||||
),
|
||||
(
|
||||
"mkw-trace.csv",
|
||||
Path::new(r"D:\AGY\scratch\118-buoc6\mkw-trace.csv"),
|
||||
),
|
||||
] {
|
||||
if let Some((evs, _mode)) = load_type_a(path) {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: Some(replay_events(&evs)),
|
||||
note: Some("Switch 2".to_string()),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: name.to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let oot_dir = Path::new(r"D:\do-096\fritchii\build\bin\Release");
|
||||
let mut oot_files: Vec<PathBuf> = fs::read_dir(oot_dir)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok().map(|x| x.path()))
|
||||
.filter(|p| {
|
||||
p.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(|s| s.starts_with("hdrumble_trace-dualsense-") && s.ends_with(".csv"))
|
||||
})
|
||||
.collect();
|
||||
oot_files.sort();
|
||||
if oot_files.is_empty() {
|
||||
rows.push(ReportRow {
|
||||
name: "OoT (hdrumble_trace-dualsense-*)".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
} else {
|
||||
let mut agg: Option<TriTraceMetrics> = None;
|
||||
let mut used = 0usize;
|
||||
for p in &oot_files {
|
||||
if let Some(evs) = load_type_b(p) {
|
||||
let m = replay_events(&evs);
|
||||
used += 1;
|
||||
match agg.as_mut() {
|
||||
Some(a) => a.merge_from(&m),
|
||||
None => agg = Some(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.push(ReportRow {
|
||||
name: format!("OoT ({used} file)"),
|
||||
metrics: agg,
|
||||
note: Some("Switch 1 / Fritchii".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let khien_path = Path::new(r"D:\AGY\scratch\122-motor\oot-do-khien-2026-11-19.csv");
|
||||
if let Some(evs) = load_type_b(khien_path) {
|
||||
rows.push(ReportRow {
|
||||
name: "oot-do-khien-2026-11-19.csv".to_string(),
|
||||
metrics: Some(replay_events(&evs)),
|
||||
note: Some("OoT đỡ khiên".to_string()),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: "oot-do-khien-2026-11-19.csv".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let thu_tay_path = Path::new(
|
||||
r"D:\AGY\scratch\122-co\thu-tay-1911\hdrumble_trace-dualsense-1795090194-14804-0.csv",
|
||||
);
|
||||
if let Some(evs) = load_type_b(thu_tay_path) {
|
||||
rows.push(ReportRow {
|
||||
name: "thu-tay-1911".to_string(),
|
||||
metrics: Some(replay_events(&evs)),
|
||||
note: Some("Thử tay 19/11".to_string()),
|
||||
});
|
||||
} else {
|
||||
rows.push(ReportRow {
|
||||
name: "thu-tay-1911".to_string(),
|
||||
metrics: None,
|
||||
note: Some("thiếu".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Báo cáo đo cò DualSense — nhãn `{label}`\n");
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Phát lại từng 1 ms từ mẫu đầu tới mẫu cuối, giữ cò (`depth = {REPLAY_TRIGGER_DEPTH}`), không gọi `note_action`. Ngưỡng rung: `al + ah > {ACTIVE_RUMBLE_THRESHOLD}`.\n"
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"| Trace | Rung (s) | Tổng | Sắc | Nặng (20 Hz) | Nổ (15 Hz) | Đổi tối đa / 1 s | Ghi chú |"
|
||||
);
|
||||
let _ = writeln!(md, "|---|---:|---:|---:|---:|---:|---:|---|");
|
||||
for r in &rows {
|
||||
push_row(&mut md, r);
|
||||
}
|
||||
|
||||
let out_dir = Path::new(r"D:\AGY\scratch\122-co");
|
||||
fs::create_dir_all(out_dir).expect("create D:\\AGY\\scratch\\122-co");
|
||||
let out_path = out_dir.join(format!("bao-cao-{label}.md"));
|
||||
fs::write(&out_path, &md).expect("write report markdown");
|
||||
println!("{md}");
|
||||
println!("Wrote {}", out_path.display());
|
||||
}
|
||||
998
third_party/renhdrum/src/dualsense/tri_trigger.rs
vendored
Normal file
998
third_party/renhdrum/src/dualsense/tri_trigger.rs
vendored
Normal file
@@ -0,0 +1,998 @@
|
||||
//! Vibration-reactive adaptive trigger (plan 118, extended by plan 122B). Pure logic, no I/O.
|
||||
//!
|
||||
//! One state machine per trigger. While the trigger is held, rumble on that side is
|
||||
//! classified into three tactile effects (sharp/parry, heavy hit, explosion) while
|
||||
//! ignoring music notes, footsteps, and steady background rumble.
|
||||
//! The host calls `update` and, when it returns `true`, sends the 11 bytes.
|
||||
|
||||
use super::trigger_effect::DualSenseTriggerEffect;
|
||||
|
||||
/// Trigger counts as held above this depth (0..255).
|
||||
pub const TRI_HOLD_ON: u8 = 12;
|
||||
/// ...and as released below this depth.
|
||||
pub const TRI_HOLD_OFF: u8 = 4;
|
||||
/// Rumble intensity (`amp_low + amp_high`) that must be crossed upwards to fire a sharp pulse.
|
||||
pub const TRI_IMPACT_THRESHOLD: f32 = 0.25;
|
||||
/// A sharp hit: intensity crosses this level...
|
||||
pub const TRI_SHARP_LEVEL: f32 = 0.14;
|
||||
/// ...with at least this step from the previous sample.
|
||||
pub const TRI_SHARP_STEP: f32 = 0.08;
|
||||
/// Off is repeated at these delays after the first Off (a lost HID write is swallowed by SDL).
|
||||
const TRI_OFF_REMIND_MS: [u32; 2] = [100, 250];
|
||||
/// How long a sharp pulse is held before returning to Off (kept for public compatibility).
|
||||
pub const TRI_PULSE_MS: u32 = 70;
|
||||
/// Minimum time between two pulse starts (ms).
|
||||
pub const TRI_MIN_GAP_MS: u32 = 100;
|
||||
/// No fresh rumble sample for this long: back to Off (ms).
|
||||
pub const TRI_STALE_MS: u32 = 350;
|
||||
/// Mute tail after the last `note_action` call of an action streak (ms).
|
||||
pub const TRI_ACTION_MUTE_MS: u32 = 500;
|
||||
/// Gap between `note_action` calls that starts a new button-press streak (ms).
|
||||
// ponytail: if a stance button is already held before the trigger pull and a second button is
|
||||
// pressed, the core cannot see it (the host only sends "a button is down"), so the trigger does
|
||||
// not mute for the second button. Fix needs the host to send press edges.
|
||||
pub const TRI_ACTION_RELEASE_GAP_MS: u32 = 30;
|
||||
|
||||
/// Music / dense note cutoff on low band when low band dominates (Hz).
|
||||
pub const TRI_MUSIC_FL: f32 = 220.0;
|
||||
/// Music / click cutoff on high band when high band dominates (Hz).
|
||||
pub const TRI_MUSIC_FH: f32 = 350.0;
|
||||
/// Sharp / parry pulse base amplitude (1..8, used when `amp_low + amp_high < TRI_SHARP_STRONG_INTENSITY`).
|
||||
pub const TRI_SHARP_AMP_LOW: i32 = 2;
|
||||
/// Sharp / parry pulse strong amplitude (1..8, used when `amp_low + amp_high >= TRI_SHARP_STRONG_INTENSITY`).
|
||||
pub const TRI_SHARP_AMP_HIGH: i32 = 3;
|
||||
/// Intensity threshold (`amp_low + amp_high`) that promotes sharp pulse amplitude from 2 to 3.
|
||||
pub const TRI_SHARP_STRONG_INTENSITY: f32 = 0.6;
|
||||
/// Sharp / parry pulse frequency scale applied to `freq_low` (Hz out per Hz in).
|
||||
pub const TRI_SHARP_FREQ_SCALE: f32 = 0.25;
|
||||
/// Sharp / parry pulse minimum frequency (Hz).
|
||||
pub const TRI_SHARP_FREQ_MIN: f32 = 12.0;
|
||||
/// Sharp / parry pulse maximum frequency (Hz).
|
||||
pub const TRI_SHARP_FREQ_MAX: f32 = 36.0;
|
||||
/// Sharp / parry pulse duration (ms).
|
||||
pub const TRI_SHARP_PULSE_MS: u32 = TRI_PULSE_MS;
|
||||
/// Heavy hit minimum low-band amplitude.
|
||||
pub const TRI_HEAVY_AL: f32 = 0.30;
|
||||
/// Heavy hit minimum low-band rise over `TRI_HEAVY_RISE_MS`.
|
||||
pub const TRI_HEAVY_RISE: f32 = 0.12;
|
||||
/// Lookback window for heavy hit low-band rise (ms).
|
||||
pub const TRI_HEAVY_RISE_MS: u32 = 10;
|
||||
/// Heavy hit upper bound on high-band share `a_H / (a_L + a_H)`.
|
||||
pub const TRI_HEAVY_HIGH_RATIO: f32 = 0.4;
|
||||
/// Heavy hit maximum low-band frequency (Hz).
|
||||
pub const TRI_HEAVY_MAX_FL: f32 = 220.0;
|
||||
/// Heavy hit pulse amplitude (1..8).
|
||||
pub const TRI_HEAVY_AMP: i32 = 3;
|
||||
/// Heavy hit pulse frequency (Hz).
|
||||
pub const TRI_HEAVY_FREQ: i32 = 20;
|
||||
/// Heavy hit pulse duration (ms).
|
||||
pub const TRI_HEAVY_PULSE_MS: u32 = 100;
|
||||
/// Boom trigger minimum low-band amplitude.
|
||||
pub const TRI_BOOM_AL: f32 = 0.70;
|
||||
/// Boom trigger maximum low-band frequency (Hz).
|
||||
pub const TRI_BOOM_FL: f32 = 200.0;
|
||||
/// Continuous low-band rumble duration required to trigger a boom (ms).
|
||||
pub const TRI_BOOM_MS: u32 = 200;
|
||||
/// Boom vibration amplitude (1..8).
|
||||
pub const TRI_BOOM_AMP: i32 = 4;
|
||||
/// Boom vibration frequency (Hz).
|
||||
pub const TRI_BOOM_FREQ: i32 = 15;
|
||||
/// Boom stops and rearms once low-band amplitude falls below this.
|
||||
pub const TRI_BOOM_RELEASE_AL: f32 = 0.20;
|
||||
/// Maximum duration of one boom vibration before forcing Off (ms).
|
||||
pub const TRI_BOOM_MAX_MS: u32 = 1500;
|
||||
|
||||
/// Fixed ring-buffer capacity for recent `(timestamp_ms, amp_low)` samples (no heap allocation).
|
||||
const TRI_AL_HIST_LEN: usize = 32;
|
||||
const TRI_START_ZONE: i32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum PulseKind {
|
||||
Sharp,
|
||||
Heavy,
|
||||
Boom,
|
||||
}
|
||||
|
||||
impl PulseKind {
|
||||
fn duration_ms(self) -> u32 {
|
||||
match self {
|
||||
Self::Sharp => TRI_SHARP_PULSE_MS,
|
||||
Self::Heavy => TRI_HEAVY_PULSE_MS,
|
||||
Self::Boom => TRI_BOOM_MAX_MS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TriTrigger {
|
||||
held: bool,
|
||||
held_since_ms: Option<u32>,
|
||||
prev_intensity: f32,
|
||||
last_fresh_ms: Option<u32>,
|
||||
last_pulse_start_ms: Option<u32>,
|
||||
active_pulse: Option<(PulseKind, u32)>,
|
||||
al_hist: [(u32, f32); TRI_AL_HIST_LEN],
|
||||
al_hist_next: usize,
|
||||
al_hist_len: usize,
|
||||
boom_ms: u32,
|
||||
boom_done: bool,
|
||||
prev_boom_cond: bool,
|
||||
/// What the host was last told (the effect currently on the trigger).
|
||||
last_returned: [u8; DualSenseTriggerEffect::SIZE],
|
||||
now_ms: u32,
|
||||
last_seen_ms: Option<u32>,
|
||||
off_since_ms: u32,
|
||||
off_reminders: u8,
|
||||
action_start_ms: Option<u32>,
|
||||
action_last_ms: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for TriTrigger {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TriTrigger {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
held: false,
|
||||
held_since_ms: None,
|
||||
prev_intensity: 0.0,
|
||||
last_fresh_ms: None,
|
||||
last_pulse_start_ms: None,
|
||||
active_pulse: None,
|
||||
al_hist: [(0, 0.0); TRI_AL_HIST_LEN],
|
||||
al_hist_next: 0,
|
||||
al_hist_len: 0,
|
||||
boom_ms: 0,
|
||||
boom_done: false,
|
||||
prev_boom_cond: false,
|
||||
last_returned: DualSenseTriggerEffect::off().data,
|
||||
now_ms: 0,
|
||||
last_seen_ms: None,
|
||||
off_since_ms: 0,
|
||||
off_reminders: 0,
|
||||
action_start_ms: None,
|
||||
action_last_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn active_pulse_kind(&self) -> Option<PulseKind> {
|
||||
self.active_pulse.map(|(kind, _)| kind)
|
||||
}
|
||||
|
||||
/// Never-backwards clock shared by `update` and `note_action`.
|
||||
/// No max(): u32 ms wraps after ~49 days.
|
||||
fn tick_clock(&mut self, now_ms: u32) -> u32 {
|
||||
let now_ms = match self.last_seen_ms {
|
||||
Some(p) if (now_ms.wrapping_sub(p) as i32) < 0 => p,
|
||||
_ => now_ms,
|
||||
};
|
||||
self.last_seen_ms = Some(now_ms);
|
||||
self.now_ms = now_ms;
|
||||
now_ms
|
||||
}
|
||||
|
||||
/// The player is pressing another button (call every tick while held, before `update`, same clock):
|
||||
/// a streak started strictly before this trigger was held counts as a posture and does not mute;
|
||||
/// a streak started with or after trigger hold (gap > `TRI_ACTION_RELEASE_GAP_MS` starts a new
|
||||
/// streak) mutes new pulses while held and for `TRI_ACTION_MUTE_MS` after the last call.
|
||||
pub fn note_action(&mut self, now_ms: u32) {
|
||||
let now = self.tick_clock(now_ms);
|
||||
let new_streak = match self.action_last_ms {
|
||||
Some(last) => now.wrapping_sub(last) > TRI_ACTION_RELEASE_GAP_MS,
|
||||
None => true,
|
||||
};
|
||||
if new_streak {
|
||||
self.action_start_ms = Some(now);
|
||||
}
|
||||
self.action_last_ms = Some(now);
|
||||
}
|
||||
|
||||
/// Returns `a_L` of the newest stored sample with `ts <= now - TRI_HEAVY_RISE_MS`, or `0.0`.
|
||||
fn lookup_al_10ms_ago(&self, now_ms: u32) -> f32 {
|
||||
for age_idx in 1..=self.al_hist_len {
|
||||
let slot = (self.al_hist_next + TRI_AL_HIST_LEN - age_idx) % TRI_AL_HIST_LEN;
|
||||
let (ts, prev_al) = self.al_hist[slot];
|
||||
if now_ms.wrapping_sub(ts) >= TRI_HEAVY_RISE_MS {
|
||||
return prev_al;
|
||||
}
|
||||
}
|
||||
0.0
|
||||
}
|
||||
|
||||
fn push_al_hist(&mut self, now_ms: u32, al: f32) {
|
||||
self.al_hist[self.al_hist_next] = (now_ms, al);
|
||||
self.al_hist_next = (self.al_hist_next + 1) % TRI_AL_HIST_LEN;
|
||||
self.al_hist_len = (self.al_hist_len + 1).min(TRI_AL_HIST_LEN);
|
||||
}
|
||||
|
||||
/// Advances the machine.
|
||||
///
|
||||
/// * `now_ms`: monotonic time in ms (wrapping is tolerated).
|
||||
/// * `depth`: trigger depth 0..255.
|
||||
/// * `sample`: latest raw rumble of this side `(amp_low, freq_low, amp_high, freq_high)`.
|
||||
/// * `fresh`: true when `sample` is new since the previous call.
|
||||
///
|
||||
/// Returns `true` and writes `out` only when the effect differs from the last one returned.
|
||||
pub fn update(
|
||||
&mut self,
|
||||
now_ms: u32,
|
||||
depth: u8,
|
||||
sample: (f32, f32, f32, f32),
|
||||
fresh: bool,
|
||||
out: &mut [u8; DualSenseTriggerEffect::SIZE],
|
||||
) -> bool {
|
||||
// The clock never runs backwards (another thread may call with an older stamp).
|
||||
let now_ms = self.tick_clock(now_ms);
|
||||
|
||||
if self.held {
|
||||
if depth < TRI_HOLD_OFF {
|
||||
self.held = false;
|
||||
self.held_since_ms = None;
|
||||
}
|
||||
} else if depth > TRI_HOLD_ON {
|
||||
self.held = true;
|
||||
self.held_since_ms = Some(now_ms);
|
||||
}
|
||||
|
||||
let mut want: Option<[u8; DualSenseTriggerEffect::SIZE]> = None;
|
||||
|
||||
if fresh {
|
||||
let (dt_ms, dt_stale) = match self.last_fresh_ms {
|
||||
Some(prev_t) => {
|
||||
let d = now_ms.wrapping_sub(prev_t);
|
||||
(d, d > TRI_STALE_MS)
|
||||
}
|
||||
None => (0, false),
|
||||
};
|
||||
self.last_fresh_ms = Some(now_ms);
|
||||
|
||||
if dt_stale {
|
||||
self.boom_ms = 0;
|
||||
self.boom_done = false;
|
||||
self.prev_boom_cond = false;
|
||||
self.al_hist_len = 0;
|
||||
self.al_hist_next = 0;
|
||||
self.active_pulse = None;
|
||||
}
|
||||
|
||||
let al = if sample.0.is_finite() {
|
||||
sample.0.max(0.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let fl = if sample.1.is_finite() { sample.1 } else { 0.0 };
|
||||
let ah = if sample.2.is_finite() {
|
||||
sample.2.max(0.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let fh = if sample.3.is_finite() { sample.3 } else { 0.0 };
|
||||
let intensity = al + ah;
|
||||
|
||||
// 1. Low-band history for 10 ms rise detection.
|
||||
let al_ref = self.lookup_al_10ms_ago(now_ms);
|
||||
let rise_10ms = al - al_ref;
|
||||
self.push_al_hist(now_ms, al);
|
||||
|
||||
// 2. Boom duration counter (tracks signal even while trigger is released).
|
||||
let boom_cond = al >= TRI_BOOM_AL && fl <= TRI_BOOM_FL;
|
||||
if al < TRI_BOOM_RELEASE_AL {
|
||||
self.boom_ms = 0;
|
||||
self.boom_done = false;
|
||||
} else if boom_cond && self.prev_boom_cond {
|
||||
self.boom_ms = self.boom_ms.saturating_add(dt_ms);
|
||||
}
|
||||
self.prev_boom_cond = boom_cond;
|
||||
|
||||
// 3. If currently booming, stop once low-band releases or max duration elapses.
|
||||
if let Some((PulseKind::Boom, start)) = self.active_pulse {
|
||||
if al < TRI_BOOM_RELEASE_AL || now_ms.wrapping_sub(start) >= TRI_BOOM_MAX_MS {
|
||||
self.active_pulse = None;
|
||||
want = Some(DualSenseTriggerEffect::off().data);
|
||||
}
|
||||
}
|
||||
|
||||
let muted = match (
|
||||
self.held_since_ms,
|
||||
self.action_start_ms,
|
||||
self.action_last_ms,
|
||||
) {
|
||||
(Some(held_since), Some(start), Some(last)) => {
|
||||
let started_with_or_after_hold = (start.wrapping_sub(held_since) as i32) >= 0;
|
||||
let since_last = now_ms.wrapping_sub(last);
|
||||
started_with_or_after_hold && since_last < TRI_ACTION_MUTE_MS
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let is_booming = matches!(self.active_pulse, Some((PulseKind::Boom, _)));
|
||||
|
||||
// 4. Priority 1: boom (not blocked by TRI_MIN_GAP_MS, but respects TRI_ACTION_MUTE_MS).
|
||||
if want.is_none()
|
||||
&& !is_booming
|
||||
&& self.held
|
||||
&& !muted
|
||||
&& self.boom_ms >= TRI_BOOM_MS
|
||||
&& !self.boom_done
|
||||
{
|
||||
let eff = DualSenseTriggerEffect::vibration(
|
||||
"boom",
|
||||
TRI_START_ZONE,
|
||||
TRI_BOOM_AMP,
|
||||
TRI_BOOM_FREQ,
|
||||
);
|
||||
self.active_pulse = Some((PulseKind::Boom, now_ms));
|
||||
self.last_pulse_start_ms = Some(now_ms);
|
||||
self.boom_done = true;
|
||||
want = Some(eff.data);
|
||||
}
|
||||
|
||||
// 5. Priority 2 & 3: heavy hit > sharp hit, subject to gap, mute, and music filter.
|
||||
let gap_ok = match self.last_pulse_start_ms {
|
||||
Some(t) => now_ms.wrapping_sub(t) >= TRI_MIN_GAP_MS,
|
||||
None => true,
|
||||
};
|
||||
let is_music = (fl > TRI_MUSIC_FL && al >= ah) || (ah > al && fh > TRI_MUSIC_FH);
|
||||
|
||||
if want.is_none() && !is_booming && self.held && !muted && gap_ok && !is_music {
|
||||
let heavy = al >= TRI_HEAVY_AL
|
||||
&& rise_10ms >= TRI_HEAVY_RISE
|
||||
&& fl <= TRI_HEAVY_MAX_FL
|
||||
&& intensity > 0.0
|
||||
&& (ah / intensity) < TRI_HEAVY_HIGH_RATIO;
|
||||
let prev = self.prev_intensity;
|
||||
let sharp_edge = prev < TRI_SHARP_LEVEL
|
||||
&& intensity >= TRI_SHARP_LEVEL
|
||||
&& intensity - prev >= TRI_SHARP_STEP;
|
||||
let rising = sharp_edge
|
||||
|| (prev < TRI_IMPACT_THRESHOLD && intensity >= TRI_IMPACT_THRESHOLD);
|
||||
|
||||
if heavy {
|
||||
let eff = DualSenseTriggerEffect::vibration(
|
||||
"heavy",
|
||||
TRI_START_ZONE,
|
||||
TRI_HEAVY_AMP,
|
||||
TRI_HEAVY_FREQ,
|
||||
);
|
||||
self.active_pulse = Some((PulseKind::Heavy, now_ms));
|
||||
self.last_pulse_start_ms = Some(now_ms);
|
||||
want = Some(eff.data);
|
||||
} else if rising {
|
||||
let amp = if intensity >= TRI_SHARP_STRONG_INTENSITY {
|
||||
TRI_SHARP_AMP_HIGH
|
||||
} else {
|
||||
TRI_SHARP_AMP_LOW
|
||||
};
|
||||
let freq = (fl * TRI_SHARP_FREQ_SCALE)
|
||||
.clamp(TRI_SHARP_FREQ_MIN, TRI_SHARP_FREQ_MAX)
|
||||
.round() as i32;
|
||||
let eff = DualSenseTriggerEffect::vibration("sharp", TRI_START_ZONE, amp, freq);
|
||||
self.active_pulse = Some((PulseKind::Sharp, now_ms));
|
||||
self.last_pulse_start_ms = Some(now_ms);
|
||||
want = Some(eff.data);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Update previous intensity.
|
||||
self.prev_intensity = intensity;
|
||||
}
|
||||
|
||||
if want.is_none() {
|
||||
let pulse_over = match self.active_pulse {
|
||||
Some((kind, start)) => now_ms.wrapping_sub(start) >= kind.duration_ms(),
|
||||
None => true,
|
||||
};
|
||||
let stale = match self.last_fresh_ms {
|
||||
Some(t) => now_ms.wrapping_sub(t) > TRI_STALE_MS,
|
||||
None => true,
|
||||
};
|
||||
if pulse_over || stale || !self.held {
|
||||
self.active_pulse = None;
|
||||
if stale {
|
||||
self.boom_ms = 0;
|
||||
self.boom_done = false;
|
||||
self.prev_boom_cond = false;
|
||||
}
|
||||
want = Some(DualSenseTriggerEffect::off().data);
|
||||
}
|
||||
}
|
||||
|
||||
match want {
|
||||
Some(w) if w != self.last_returned => {
|
||||
self.last_returned = w;
|
||||
if w == DualSenseTriggerEffect::off().data {
|
||||
self.off_since_ms = now_ms;
|
||||
self.off_reminders = TRI_OFF_REMIND_MS.len() as u8;
|
||||
} else {
|
||||
self.off_reminders = 0;
|
||||
}
|
||||
*out = w;
|
||||
true
|
||||
}
|
||||
Some(w) if self.off_reminders > 0 && w == DualSenseTriggerEffect::off().data => {
|
||||
let due = TRI_OFF_REMIND_MS[TRI_OFF_REMIND_MS.len() - self.off_reminders as usize];
|
||||
if now_ms.wrapping_sub(self.off_since_ms) >= due {
|
||||
self.off_reminders -= 1;
|
||||
*out = w;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Back to the initial state (host should send Off itself on shutdown).
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::new();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const QUIET: (f32, f32, f32, f32) = (0.0, 160.0, 0.0, 320.0);
|
||||
const SHARP: (f32, f32, f32, f32) = (0.20, 180.0, 0.01, 250.0);
|
||||
const HIT: (f32, f32, f32, f32) = (0.5, 160.0, 0.3, 320.0);
|
||||
|
||||
fn step(t: &mut TriTrigger, ms: u32, depth: u8, s: (f32, f32, f32, f32)) -> Option<[u8; 11]> {
|
||||
let mut out = [0u8; 11];
|
||||
t.update(ms, depth, s, true, &mut out).then_some(out)
|
||||
}
|
||||
|
||||
fn is_vib(e: &[u8; 11]) -> bool {
|
||||
e[0] == DualSenseTriggerEffect::MODE_VIBRATION
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn released_trigger_never_vibrates() {
|
||||
let mut t = TriTrigger::new();
|
||||
for i in 0..50u32 {
|
||||
let s = if i % 2 == 0 { QUIET } else { HIT };
|
||||
assert_eq!(step(&mut t, i * 20, 0, s), None);
|
||||
}
|
||||
// below hold-on threshold too
|
||||
assert_eq!(step(&mut t, 2000, 10, QUIET), None);
|
||||
assert_eq!(step(&mut t, 2020, 10, HIT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharp_hit_while_held_pulses_then_off_after_70ms() {
|
||||
let mut t = TriTrigger::new();
|
||||
assert_eq!(step(&mut t, 0, 200, QUIET), None);
|
||||
let e = step(&mut t, 20, 200, SHARP).expect("sharp pulse");
|
||||
assert!(is_vib(&e));
|
||||
assert_eq!(
|
||||
e,
|
||||
DualSenseTriggerEffect::vibration("s", TRI_START_ZONE, TRI_SHARP_AMP_LOW, 36).data
|
||||
);
|
||||
assert_eq!(e[9], 36);
|
||||
assert_eq!(t.active_pulse_kind(), Some(PulseKind::Sharp));
|
||||
// still on at +50 ms
|
||||
assert_eq!(step(&mut t, 70, 200, SHARP), None);
|
||||
// off at +70 ms
|
||||
let off = step(&mut t, 90, 200, SHARP).expect("off");
|
||||
assert_eq!(off, DualSenseTriggerEffect::off().data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_hits_50ms_apart_change_once() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
let mut changes = 0;
|
||||
for (ms, s) in [(10, HIT), (30, QUIET), (60, HIT), (65, QUIET)] {
|
||||
if step(&mut t, ms, 200, s).is_some() {
|
||||
changes += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(changes, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hits_respect_100ms_gap() {
|
||||
let mut t = TriTrigger::new();
|
||||
let off_data = DualSenseTriggerEffect::off().data;
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, SHARP).is_some());
|
||||
step(&mut t, 20, 200, QUIET);
|
||||
assert_eq!(step(&mut t, 80, 200, QUIET), Some(off_data)); // Off after 70 ms sharp pulse
|
||||
assert!(step(&mut t, 100, 200, SHARP).is_none()); // 90 ms since start (< 100)
|
||||
step(&mut t, 105, 200, QUIET);
|
||||
assert!(step(&mut t, 115, 200, SHARP).is_some()); // 105 ms since start (>= 100)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_during_pulse_goes_off() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, HIT).is_some());
|
||||
let off = step(&mut t, 30, 0, HIT).expect("off on release");
|
||||
assert_eq!(off, DualSenseTriggerEffect::off().data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hysteresis_between_4_and_12() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 13, QUIET);
|
||||
// depth 8 keeps it held
|
||||
step(&mut t, 20, 8, QUIET);
|
||||
assert!(step(&mut t, 40, 8, HIT).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_signal_goes_off() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, SHARP).is_some());
|
||||
let mut out = [0u8; 11];
|
||||
// no fresh samples; first non-fresh call after the 70 ms pulse time returns Off
|
||||
assert!(t.update(100, 200, SHARP, false, &mut out));
|
||||
assert_eq!(out, DualSenseTriggerEffect::off().data);
|
||||
// the two Off reminders follow (>= +100 and >= +250 ms after the Off), then silence
|
||||
assert!(!t.update(150, 200, SHARP, false, &mut out));
|
||||
assert!(t.update(200, 200, SHARP, false, &mut out));
|
||||
assert!(t.update(500, 200, SHARP, false, &mut out));
|
||||
assert!(!t.update(900, 200, SHARP, false, &mut out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_without_pulse_end_forces_off() {
|
||||
// Pulse lasting nothing special: stale path also yields Off.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, HIT).is_some());
|
||||
let mut out = [0u8; 11];
|
||||
assert!(t.update(400, 200, HIT, false, &mut out));
|
||||
assert_eq!(out[0], DualSenseTriggerEffect::MODE_OFF);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_emits_forbidden_mode_bytes() {
|
||||
let mut t = TriTrigger::new();
|
||||
let mut out = [0u8; 11];
|
||||
let mut ms = 0u32;
|
||||
for i in 0..2000u32 {
|
||||
ms += 7 + (i % 5) * 13;
|
||||
let depth = ((i * 37) % 256) as u8;
|
||||
let a = ((i * 29) % 100) as f32 / 40.0;
|
||||
let f = ((i * 53) % 1400) as f32;
|
||||
let fresh = i % 3 != 0;
|
||||
if t.update(ms, depth, (a, f, a * 0.5, f), fresh, &mut out) {
|
||||
assert!(
|
||||
!(0xFC..=0xFE).contains(&out[0]),
|
||||
"forbidden byte {:#x}",
|
||||
out[0]
|
||||
);
|
||||
assert!(out[0] == 0x05 || out[0] == 0x26);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heavy_and_sharp_use_expected_amplitude_and_freq() {
|
||||
let heavy = {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
step(&mut t, 10, 200, (0.6, 170.0, 0.2, 320.0)).unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
heavy,
|
||||
DualSenseTriggerEffect::vibration("h", TRI_START_ZONE, TRI_HEAVY_AMP, TRI_HEAVY_FREQ)
|
||||
.data
|
||||
);
|
||||
assert_eq!(heavy[9], 20);
|
||||
let sharp_strong = {
|
||||
let mut t2 = TriTrigger::new();
|
||||
step(&mut t2, 0, 200, QUIET);
|
||||
step(&mut t2, 10, 200, (0.25, 1000.0, 0.40, 320.0)).unwrap()
|
||||
};
|
||||
assert_eq!(sharp_strong[9], 36);
|
||||
let sharp_weak = {
|
||||
let mut t3 = TriTrigger::new();
|
||||
step(&mut t3, 0, 200, QUIET);
|
||||
step(&mut t3, 10, 200, (0.1, 10.0, 0.2, 320.0)).unwrap()
|
||||
};
|
||||
assert_eq!(sharp_weak[9], 12);
|
||||
assert_ne!(sharp_strong[3], sharp_weak[3]); // different amplitude packing (3 vs 2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backwards_clock_does_not_end_pulse_early() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 900, 200, QUIET);
|
||||
assert!(step(&mut t, 1000, 200, SHARP).is_some());
|
||||
assert_eq!(step(&mut t, 999, 200, SHARP), None);
|
||||
assert_eq!(step(&mut t, 1000, 200, SHARP), None);
|
||||
assert_eq!(step(&mut t, 1050, 200, SHARP), None);
|
||||
assert!(step(&mut t, 1070, 200, SHARP).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharp_hit_needs_level_and_step() {
|
||||
let mk = |a: f32| (a, 160.0, 0.0, 320.0);
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, mk(0.02));
|
||||
assert!(step(&mut t, 10, 200, mk(0.16)).is_some());
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, mk(0.09));
|
||||
assert!(step(&mut t, 10, 200, mk(0.16)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_is_reminded_twice_then_silent() {
|
||||
let mut t = TriTrigger::new();
|
||||
let mut out = [0u8; 11];
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, SHARP).is_some());
|
||||
assert!(t.update(80, 200, SHARP, true, &mut out)); // Off at +70
|
||||
let mut times = vec![];
|
||||
for ms in (81..2000).step_by(1) {
|
||||
if t.update(ms, 200, SHARP, false, &mut out) {
|
||||
assert_eq!(out, DualSenseTriggerEffect::off().data);
|
||||
times.push(ms);
|
||||
}
|
||||
}
|
||||
assert_eq!(times.len(), 2, "{times:?}");
|
||||
assert!(times[0] >= 180 && times[1] >= 330, "{times:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_fired_never_reminds() {
|
||||
let mut t = TriTrigger::new();
|
||||
let mut out = [0u8; 11];
|
||||
for ms in 0..2000 {
|
||||
assert!(!t.update(ms, 0, QUIET, ms % 7 == 0, &mut out));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_wrap_still_ends_pulse() {
|
||||
let mut t = TriTrigger::new();
|
||||
let base = u32::MAX - 30;
|
||||
step(&mut t, base.wrapping_sub(10), 200, QUIET);
|
||||
assert!(step(&mut t, base, 200, SHARP).is_some());
|
||||
assert_eq!(step(&mut t, base.wrapping_add(50), 200, SHARP), None);
|
||||
assert!(step(&mut t, base.wrapping_add(70), 200, SHARP).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_button_mutes_pulses_for_500ms() {
|
||||
// (a)
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
t.note_action(1000);
|
||||
assert_eq!(step(&mut t, 1100, 200, HIT), None);
|
||||
step(&mut t, 1200, 200, QUIET);
|
||||
assert!(step(&mut t, 1600, 200, HIT).is_some());
|
||||
// note_action with an older stamp does not rewind the clock
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
step(&mut t, 5000, 200, QUIET);
|
||||
t.note_action(4000);
|
||||
assert_eq!(step(&mut t, 5200, 200, HIT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn action_mute_survives_clock_wrap() {
|
||||
let mut t = TriTrigger::new();
|
||||
let base = u32::MAX - 50;
|
||||
step(&mut t, base.wrapping_sub(10), 200, QUIET);
|
||||
t.note_action(base);
|
||||
assert_eq!(step(&mut t, base.wrapping_add(300), 200, QUIET), None);
|
||||
assert_eq!(step(&mut t, base.wrapping_add(400), 200, HIT), None);
|
||||
step(&mut t, base.wrapping_add(450), 200, QUIET);
|
||||
assert!(step(&mut t, base.wrapping_add(560), 200, HIT).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn i_action_after_hold_mutes_through_hold_and_500ms_after() {
|
||||
// Short 100 ms press after holding trigger from 0: mutes at 1300, fires at 1650.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
for ms in 1000..1100 {
|
||||
t.note_action(ms);
|
||||
}
|
||||
step(&mut t, 1290, 200, QUIET);
|
||||
assert_eq!(step(&mut t, 1300, 200, HIT), None);
|
||||
step(&mut t, 1640, 200, QUIET);
|
||||
let e = step(&mut t, 1650, 200, HIT).expect("pulse at 1650");
|
||||
assert!(is_vib(&e));
|
||||
|
||||
// Long 2000 ms button press started after holding trigger from 0: stays muted through hold!
|
||||
let mut t2 = TriTrigger::new();
|
||||
step(&mut t2, 0, 200, QUIET);
|
||||
for ms in 1000..=3000 {
|
||||
t2.note_action(ms);
|
||||
if ms == 2490 {
|
||||
step(&mut t2, 2490, 200, QUIET);
|
||||
}
|
||||
if ms == 2500 {
|
||||
assert_eq!(step(&mut t2, 2500, 200, HIT), None);
|
||||
}
|
||||
}
|
||||
step(&mut t2, 3540, 200, QUIET);
|
||||
let e2 = step(&mut t2, 3550, 200, HIT).expect("pulse at 3550 after 500 ms release tail");
|
||||
assert!(is_vib(&e2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ii_action_started_before_hold_is_posture() {
|
||||
let mut t = TriTrigger::new();
|
||||
for ms in (0..=600).step_by(10) {
|
||||
t.note_action(ms);
|
||||
let depth = if ms >= 500 { 200 } else { 0 };
|
||||
let sample = match ms {
|
||||
590 => QUIET,
|
||||
600 => HIT,
|
||||
_ => QUIET,
|
||||
};
|
||||
let res = step(&mut t, ms, depth, sample);
|
||||
if ms == 600 {
|
||||
let e = res.expect("posture started before trigger hold must not mute at 600");
|
||||
assert!(is_vib(&e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iii_release_and_rehold_while_posture_active_still_fires() {
|
||||
let mut t = TriTrigger::new();
|
||||
for ms in (0..=1300).step_by(10) {
|
||||
t.note_action(ms);
|
||||
let depth = if (500..1000).contains(&ms) || ms >= 1200 {
|
||||
200
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let sample = if ms == 1300 { HIT } else { QUIET };
|
||||
let res = step(&mut t, ms, depth, sample);
|
||||
if ms == 1300 {
|
||||
let e = res.expect("re-held trigger while posture stays active must still fire");
|
||||
assert!(is_vib(&e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iv_boom_0_47_does_not_boom_and_1_0_booms_amp4_15hz() {
|
||||
// 0.47 @ 100 Hz for 400 ms must never enter Boom.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
for ms in (10..=400).step_by(10) {
|
||||
let _ = step(&mut t, ms, 200, (0.47, 100.0, 0.0, 320.0));
|
||||
assert_ne!(t.active_pulse_kind(), Some(PulseKind::Boom), "ms={ms}");
|
||||
}
|
||||
|
||||
// 1.0 @ 70 Hz for 700 ms triggers Boom with amp 4 and 15 Hz.
|
||||
let mut t2 = TriTrigger::new();
|
||||
let expected_boom =
|
||||
DualSenseTriggerEffect::vibration("boom", TRI_START_ZONE, TRI_BOOM_AMP, TRI_BOOM_FREQ)
|
||||
.data;
|
||||
assert_eq!(TRI_BOOM_AMP, 4);
|
||||
assert_eq!(TRI_BOOM_FREQ, 15);
|
||||
step(&mut t2, 0, 200, QUIET);
|
||||
let mut saw_boom = false;
|
||||
for ms in (10..=700).step_by(10) {
|
||||
if let Some(eff) = step(&mut t2, ms, 200, (1.0, 70.0, 0.0, 320.0)) {
|
||||
if eff[9] == 15 {
|
||||
assert_eq!(eff, expected_boom);
|
||||
assert_eq!(t2.active_pulse_kind(), Some(PulseKind::Boom));
|
||||
saw_boom = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(saw_boom, "expected boom at 1.0 @ 70 Hz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_oot_shield_parry_repeats_identically_10_times() {
|
||||
let mut t = TriTrigger::new();
|
||||
let parry = (0.19, 182.0, 0.01, 257.0);
|
||||
let expected =
|
||||
DualSenseTriggerEffect::vibration("sharp", TRI_START_ZONE, TRI_SHARP_AMP_LOW, 36).data;
|
||||
let off_data = DualSenseTriggerEffect::off().data;
|
||||
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
for k in 0..10u32 {
|
||||
let t0 = 1000 + k * 2000;
|
||||
// Quiet sample before parry (mirroring real host cadence).
|
||||
assert_eq!(step(&mut t, t0 - 10, 200, QUIET), None);
|
||||
let pulse = step(&mut t, t0, 200, parry).expect("parry pulse");
|
||||
assert_eq!(pulse, expected, "parry #{k}");
|
||||
assert_eq!(pulse[9], 36);
|
||||
assert_eq!(t.active_pulse_kind(), Some(PulseKind::Sharp));
|
||||
// 10 ms pulse drops back to quiet, trigger stays active until +70 ms.
|
||||
assert_eq!(step(&mut t, t0 + 10, 200, QUIET), None);
|
||||
assert_eq!(step(&mut t, t0 + 60, 200, QUIET), None);
|
||||
let off = step(&mut t, t0 + 70, 200, QUIET).expect("parry off at +70 ms");
|
||||
assert_eq!(off, off_data);
|
||||
// Drain the two Off reminders (+100 and +250 ms) as the host ticks.
|
||||
assert_eq!(step(&mut t, t0 + 170, 200, QUIET), Some(off_data));
|
||||
assert_eq!(step(&mut t, t0 + 320, 200, QUIET), Some(off_data));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn b_sharp_fires_above_0_12_background() {
|
||||
// Without the 40 ms quiet gate, a steady 0.12 background still permits a sharp edge.
|
||||
let mut t = TriTrigger::new();
|
||||
let bg = (0.12, 160.0, 0.0, 320.0);
|
||||
step(&mut t, 0, 200, bg);
|
||||
step(&mut t, 10, 200, bg);
|
||||
step(&mut t, 30, 200, bg);
|
||||
let e = step(&mut t, 40, 200, SHARP).expect("sharp above 0.12 background");
|
||||
assert_eq!(t.active_pulse_kind(), Some(PulseKind::Sharp));
|
||||
assert_eq!(e[9], 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_music_and_high_freq_clicks_stay_silent() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert_eq!(step(&mut t, 100, 200, (0.15, 443.0, 0.15, 443.0)), None);
|
||||
step(&mut t, 500, 200, QUIET);
|
||||
assert_eq!(step(&mut t, 600, 200, (0.0, 160.0, 0.48, 795.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn d_heavy_hit_fires_20hz_for_100ms() {
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
let e = step(&mut t, 10, 200, (0.45, 170.0, 0.02, 320.0)).expect("heavy pulse");
|
||||
assert_eq!(
|
||||
e,
|
||||
DualSenseTriggerEffect::vibration(
|
||||
"heavy",
|
||||
TRI_START_ZONE,
|
||||
TRI_HEAVY_AMP,
|
||||
TRI_HEAVY_FREQ
|
||||
)
|
||||
.data
|
||||
);
|
||||
assert_eq!(e[9], 20);
|
||||
// Still active at +90 ms.
|
||||
assert_eq!(step(&mut t, 100, 200, (0.20, 170.0, 0.0, 320.0)), None);
|
||||
// Off at +100 ms.
|
||||
let off = step(&mut t, 110, 200, QUIET).expect("heavy off at +100 ms");
|
||||
assert_eq!(off, DualSenseTriggerEffect::off().data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn e_boom_fires_at_200ms_releases_below_0_20_and_caps_at_1500ms() {
|
||||
let boom_sample = (0.80, 110.0, 0.0, 320.0);
|
||||
let expected =
|
||||
DualSenseTriggerEffect::vibration("boom", TRI_START_ZONE, TRI_BOOM_AMP, TRI_BOOM_FREQ)
|
||||
.data;
|
||||
let off_data = DualSenseTriggerEffect::off().data;
|
||||
|
||||
// Pre-arm at 0.65 while released, then engage hold at 0.70 (rise 0.05 < 0.12) to isolate boom onset.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 0, (0.65, 110.0, 0.0, 320.0));
|
||||
assert_eq!(step(&mut t, 10, 200, (0.70, 110.0, 0.0, 320.0)), None);
|
||||
for ms in (20..210).step_by(10) {
|
||||
assert_eq!(step(&mut t, ms, 200, boom_sample), None, "ms={ms}");
|
||||
}
|
||||
let b = step(&mut t, 210, 200, boom_sample).expect("boom at 200 ms");
|
||||
assert_eq!(b, expected);
|
||||
assert_eq!(b[9], 15);
|
||||
for ms in (220..=610).step_by(10) {
|
||||
assert_eq!(step(&mut t, ms, 200, boom_sample), None);
|
||||
}
|
||||
let off = step(&mut t, 620, 200, (0.10, 110.0, 0.0, 320.0)).expect("boom release off");
|
||||
assert_eq!(off, off_data);
|
||||
|
||||
// Held for 3 seconds: caps Off at 1500 ms and does not retrigger until a_L < 0.20.
|
||||
let mut t2 = TriTrigger::new();
|
||||
step(&mut t2, 0, 0, (0.65, 110.0, 0.0, 320.0));
|
||||
step(&mut t2, 10, 200, (0.70, 110.0, 0.0, 320.0));
|
||||
for ms in (20..210).step_by(10) {
|
||||
step(&mut t2, ms, 200, boom_sample);
|
||||
}
|
||||
assert_eq!(step(&mut t2, 210, 200, boom_sample), Some(expected));
|
||||
for ms in (220..1710).step_by(10) {
|
||||
assert_eq!(step(&mut t2, ms, 200, boom_sample), None, "ms={ms}");
|
||||
}
|
||||
assert_eq!(step(&mut t2, 1710, 200, boom_sample), Some(off_data));
|
||||
assert_eq!(step(&mut t2, 1810, 200, boom_sample), Some(off_data)); // Off reminder #1
|
||||
assert_eq!(step(&mut t2, 1960, 200, boom_sample), Some(off_data)); // Off reminder #2
|
||||
for ms in (1720..3000).step_by(10) {
|
||||
if ms == 1810 || ms == 1960 {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
step(&mut t2, ms, 200, boom_sample),
|
||||
None,
|
||||
"no retrigger ms={ms}"
|
||||
);
|
||||
}
|
||||
// Dropping below 0.20 rearms boom for the next explosion.
|
||||
step(&mut t2, 3010, 200, (0.10, 110.0, 0.0, 320.0));
|
||||
step(&mut t2, 3050, 200, (0.65, 110.0, 0.0, 320.0));
|
||||
step(&mut t2, 3060, 200, (0.70, 110.0, 0.0, 320.0));
|
||||
for ms in (3070..3260).step_by(10) {
|
||||
step(&mut t2, ms, 200, boom_sample);
|
||||
}
|
||||
assert_eq!(step(&mut t2, 3260, 200, boom_sample), Some(expected));
|
||||
|
||||
// note_action started after trigger hold mutes boom too (row 12).
|
||||
let mut t3 = TriTrigger::new();
|
||||
step(&mut t3, 0, 0, (0.65, 110.0, 0.0, 320.0));
|
||||
step(&mut t3, 10, 200, (0.65, 110.0, 0.0, 320.0));
|
||||
t3.note_action(100);
|
||||
step(&mut t3, 110, 200, (0.70, 110.0, 0.0, 320.0));
|
||||
for ms in (120..=320).step_by(10) {
|
||||
assert_eq!(step(&mut t3, ms, 200, boom_sample), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f_sharp_gap_80ms_blocked_110ms_allowed() {
|
||||
let off_data = DualSenseTriggerEffect::off().data;
|
||||
// Two sharp hits 80 ms apart -> only one pulse.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 200, QUIET);
|
||||
assert!(step(&mut t, 10, 200, SHARP).is_some());
|
||||
step(&mut t, 20, 200, QUIET);
|
||||
assert_eq!(step(&mut t, 80, 200, QUIET), Some(off_data));
|
||||
assert_eq!(step(&mut t, 90, 200, SHARP), None);
|
||||
|
||||
// Two sharp hits 110 ms apart -> both pulse.
|
||||
let mut t2 = TriTrigger::new();
|
||||
step(&mut t2, 0, 200, QUIET);
|
||||
assert!(step(&mut t2, 10, 200, SHARP).is_some());
|
||||
step(&mut t2, 20, 200, QUIET);
|
||||
assert_eq!(step(&mut t2, 80, 200, QUIET), Some(off_data));
|
||||
step(&mut t2, 100, 200, QUIET);
|
||||
let second = step(&mut t2, 120, 200, SHARP).expect("second sharp after 110 ms");
|
||||
assert_eq!(second[9], 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn g_during_boom_sharp_and_heavy_do_not_change_effect() {
|
||||
let mut t = TriTrigger::new();
|
||||
let boom_sample = (0.80, 110.0, 0.0, 320.0);
|
||||
step(&mut t, 0, 0, (0.65, 110.0, 0.0, 320.0));
|
||||
step(&mut t, 10, 200, (0.70, 110.0, 0.0, 320.0));
|
||||
for ms in (20..210).step_by(10) {
|
||||
step(&mut t, ms, 200, boom_sample);
|
||||
}
|
||||
assert_eq!(step(&mut t, 210, 200, boom_sample).unwrap()[9], 15);
|
||||
// Keep boom stream alive (< 350 ms stale timeout), then inject heavy & sharp candidates.
|
||||
for ms in [310, 410, 510] {
|
||||
assert_eq!(step(&mut t, ms, 200, boom_sample), None);
|
||||
}
|
||||
assert_eq!(step(&mut t, 600, 200, (0.95, 150.0, 0.05, 300.0)), None);
|
||||
for ms in [700, 800, 900] {
|
||||
assert_eq!(step(&mut t, ms, 200, boom_sample), None);
|
||||
}
|
||||
assert_eq!(step(&mut t, 950, 200, (0.25, 180.0, 0.50, 200.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn h_boom_when_released_stays_off_and_release_during_boom_stops_immediately() {
|
||||
let boom_sample = (0.80, 110.0, 0.0, 320.0);
|
||||
let off_data = DualSenseTriggerEffect::off().data;
|
||||
|
||||
// Released during entire boom buildup -> never fires.
|
||||
let mut t = TriTrigger::new();
|
||||
step(&mut t, 0, 0, QUIET);
|
||||
for ms in (10..=400).step_by(10) {
|
||||
assert_eq!(step(&mut t, ms, 0, boom_sample), None);
|
||||
}
|
||||
|
||||
// Active boom -> releasing trigger yields Off immediately.
|
||||
let mut t2 = TriTrigger::new();
|
||||
step(&mut t2, 0, 0, (0.65, 110.0, 0.0, 320.0));
|
||||
step(&mut t2, 10, 200, (0.70, 110.0, 0.0, 320.0));
|
||||
for ms in (20..210).step_by(10) {
|
||||
step(&mut t2, ms, 200, boom_sample);
|
||||
}
|
||||
assert_eq!(step(&mut t2, 210, 200, boom_sample).unwrap()[9], 15);
|
||||
assert_eq!(step(&mut t2, 220, 0, boom_sample), Some(off_data));
|
||||
}
|
||||
}
|
||||
214
third_party/renhdrum/src/dualsense/trigger_effect.rs
vendored
Normal file
214
third_party/renhdrum/src/dualsense/trigger_effect.rs
vendored
Normal file
@@ -0,0 +1,214 @@
|
||||
/// One DualSense adaptive trigger effect: the 11 bytes SDL copies into DS5EffectsState_t.
|
||||
/// Encodings follow the controller's "zone" effects (10 zones over the trigger travel, 3-bit strength per zone).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DualSenseTriggerEffect {
|
||||
pub name: String,
|
||||
pub data: [u8; Self::SIZE],
|
||||
}
|
||||
|
||||
impl DualSenseTriggerEffect {
|
||||
pub const SIZE: usize = 11;
|
||||
pub const ZONES: usize = 10;
|
||||
|
||||
pub const MODE_OFF: u8 = 0x05;
|
||||
pub const MODE_FEEDBACK: u8 = 0x21;
|
||||
pub const MODE_WEAPON: u8 = 0x25;
|
||||
pub const MODE_VIBRATION: u8 = 0x26;
|
||||
|
||||
pub fn new(name: &str, data: [u8; Self::SIZE]) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Free trigger, no resistance.
|
||||
pub fn off() -> Self {
|
||||
Self {
|
||||
name: "off".to_string(),
|
||||
data: [Self::MODE_OFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Resistance from `start_zone` (0-9) to the end of the travel, strength 1-8.
|
||||
pub fn feedback(name: &str, start_zone: i32, strength: i32) -> Self {
|
||||
let mut strengths = [0i32; Self::ZONES];
|
||||
let clamped_start = start_zone.clamp(0, (Self::ZONES - 1) as i32) as usize;
|
||||
|
||||
for s in strengths[clamped_start..Self::ZONES].iter_mut() {
|
||||
*s = strength;
|
||||
}
|
||||
|
||||
Self::zone_feedback(name, &strengths)
|
||||
}
|
||||
|
||||
/// Resistance per zone (0 = free, 1-8), e.g. growing with the pull.
|
||||
pub fn zone_feedback(name: &str, strengths: &[i32]) -> Self {
|
||||
let (active, force) = Self::pack_zones(strengths);
|
||||
let mut data = [0u8; Self::SIZE];
|
||||
data[0] = Self::MODE_FEEDBACK;
|
||||
Self::write_zones(&mut data, active, force);
|
||||
Self::new(name, data)
|
||||
}
|
||||
|
||||
/// Resistance between `start_zone` (2-7) and `end_zone` (start+1 - 8) that
|
||||
/// "breaks" when pulled past the end, like a gun trigger. Strength 1-8.
|
||||
pub fn weapon(name: &str, start_zone: i32, end_zone: i32, strength: i32) -> Self {
|
||||
let start = start_zone.clamp(2, 7);
|
||||
let end = end_zone.clamp(start + 1, 8);
|
||||
|
||||
let zones: u16 = (1 << start) | (1 << end);
|
||||
|
||||
let mut data = [0u8; Self::SIZE];
|
||||
data[0] = Self::MODE_WEAPON;
|
||||
data[1] = (zones & 0xFF) as u8;
|
||||
data[2] = (zones >> 8) as u8;
|
||||
data[3] = (strength.clamp(1, 8) - 1) as u8;
|
||||
|
||||
Self::new(name, data)
|
||||
}
|
||||
|
||||
/// Vibration inside the trigger from `start_zone` (0-9) on, amplitude 1-8, frequency in Hz (1-255).
|
||||
pub fn vibration(name: &str, start_zone: i32, amplitude: i32, frequency: i32) -> Self {
|
||||
let mut strengths = [0i32; Self::ZONES];
|
||||
let clamped_start = start_zone.clamp(0, (Self::ZONES - 1) as i32) as usize;
|
||||
|
||||
for s in strengths[clamped_start..Self::ZONES].iter_mut() {
|
||||
*s = amplitude;
|
||||
}
|
||||
|
||||
let (active, amplitudes) = Self::pack_zones(&strengths);
|
||||
|
||||
let mut data = [0u8; Self::SIZE];
|
||||
data[0] = Self::MODE_VIBRATION;
|
||||
Self::write_zones(&mut data, active, amplitudes);
|
||||
data[9] = frequency.clamp(1, 255) as u8;
|
||||
|
||||
Self::new(name, data)
|
||||
}
|
||||
|
||||
pub fn pack_zones(strengths: &[i32]) -> (u16, u32) {
|
||||
let mut active: u16 = 0;
|
||||
let mut values: u32 = 0;
|
||||
|
||||
for (zone, &strength) in strengths.iter().take(Self::ZONES).enumerate() {
|
||||
if strength <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
active |= 1 << zone;
|
||||
values |= (((strength.min(8) - 1) & 7) as u32) << (3 * zone);
|
||||
}
|
||||
|
||||
(active, values)
|
||||
}
|
||||
|
||||
pub fn write_zones(data: &mut [u8; Self::SIZE], active: u16, values: u32) {
|
||||
data[1] = (active & 0xFF) as u8;
|
||||
data[2] = (active >> 8) as u8;
|
||||
data[3] = (values & 0xFF) as u8;
|
||||
data[4] = ((values >> 8) & 0xFF) as u8;
|
||||
data[5] = ((values >> 16) & 0xFF) as u8;
|
||||
data[6] = ((values >> 24) & 0xFF) as u8;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn data(&self) -> &[u8; Self::SIZE] {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_off() {
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::off().data,
|
||||
[0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_effects_are_eleven_bytes() {
|
||||
assert_eq!(DualSenseTriggerEffect::SIZE, 11);
|
||||
assert_eq!(DualSenseTriggerEffect::off().data.len(), 11);
|
||||
assert_eq!(DualSenseTriggerEffect::feedback("t", 0, 1).data.len(), 11);
|
||||
assert_eq!(DualSenseTriggerEffect::weapon("t", 2, 5, 1).data.len(), 11);
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::vibration("t", 0, 1, 1).data.len(),
|
||||
11
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_feedback() {
|
||||
// Shield feedback: position 2, strength 2
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::feedback("test", 2, 2).data,
|
||||
[0x21, 0xFC, 0x03, 0x40, 0x92, 0x24, 0x09, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::feedback("test", 0, 8).data,
|
||||
[0x21, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::feedback("test", 9, 1).data,
|
||||
[0x21, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zone_feedback() {
|
||||
let bow = [0, 1, 2, 3, 4, 5, 6, 7, 8, 8];
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::zone_feedback("test", &bow).data,
|
||||
[0x21, 0xFE, 0x03, 0x40, 0x34, 0xD6, 0x3F, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zone_feedback_with_equal_zones_is_feedback() {
|
||||
let even = [0, 0, 0, 5, 5, 5, 5, 5, 5, 5];
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::zone_feedback("a", &even).data,
|
||||
DualSenseTriggerEffect::feedback("b", 3, 5).data
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_weapon() {
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::weapon("test", 2, 5, 8).data,
|
||||
[0x25, 0x24, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::weapon("test", 4, 8, 3).data,
|
||||
[0x25, 0x10, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vibration() {
|
||||
// Shot pulse: position 0, amp 8, freq 35
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::vibration("test", 0, 8, 35).data,
|
||||
[0x26, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x23, 0x00]
|
||||
);
|
||||
|
||||
// Continuous held device: position 0, amp 3, freq 25
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::vibration("test", 0, 3, 25).data,
|
||||
[0x26, 0xFF, 0x03, 0x92, 0x24, 0x49, 0x12, 0x00, 0x00, 0x19, 0x00]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
DualSenseTriggerEffect::vibration("test", 3, 5, 200).data,
|
||||
[0x26, 0xF8, 0x03, 0x00, 0x48, 0x92, 0x24, 0x00, 0x00, 0xC8, 0x00]
|
||||
);
|
||||
}
|
||||
}
|
||||
452
third_party/renhdrum/src/dualsense/trigger_profile.rs
vendored
Normal file
452
third_party/renhdrum/src/dualsense/trigger_profile.rs
vendored
Normal file
@@ -0,0 +1,452 @@
|
||||
use super::trigger_effect::DualSenseTriggerEffect;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What the game is doing, as far as the triggers care.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DualSenseTriggerInput {
|
||||
pub zl_held: bool,
|
||||
pub zr_held: bool,
|
||||
pub rumble_on: bool,
|
||||
pub rumble_on_ms: i64,
|
||||
pub pulse_age_ms: i64,
|
||||
}
|
||||
|
||||
impl DualSenseTriggerInput {
|
||||
pub fn new(
|
||||
zl_held: bool,
|
||||
zr_held: bool,
|
||||
rumble_on: bool,
|
||||
rumble_on_ms: i64,
|
||||
pulse_age_ms: i64,
|
||||
) -> Self {
|
||||
Self {
|
||||
zl_held,
|
||||
zr_held,
|
||||
rumble_on,
|
||||
rumble_on_ms,
|
||||
pulse_age_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DualSense adaptive trigger profile config of one game (title id).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DualSenseTriggerProfileConfig {
|
||||
pub title_id: u64,
|
||||
pub name: String,
|
||||
pub arm_triggers: bool,
|
||||
pub bow_enabled: bool,
|
||||
pub bow_strength: i32,
|
||||
pub shield_enabled: bool,
|
||||
pub shield_start_zone: i32,
|
||||
pub shield_strength: i32,
|
||||
pub shot_enabled: bool,
|
||||
pub shot_amplitude: i32,
|
||||
pub shot_frequency: i32,
|
||||
pub shot_min_pulse_ms: i32,
|
||||
pub sustained_enabled: bool,
|
||||
pub sustained_amplitude: i32,
|
||||
pub sustained_frequency: i32,
|
||||
pub sustained_min_rumble_ms: i32,
|
||||
}
|
||||
|
||||
impl DualSenseTriggerProfileConfig {
|
||||
pub const BOW_DRAW_TITLE_ID: u64 = 0x0100F2C0115B6000;
|
||||
|
||||
pub const MIN_STRENGTH: i32 = 1;
|
||||
pub const MAX_STRENGTH: i32 = 8;
|
||||
pub const MAX_START_ZONE: i32 = 9;
|
||||
pub const MIN_FREQUENCY: i32 = 1;
|
||||
pub const MAX_FREQUENCY: i32 = 255;
|
||||
|
||||
pub fn create_bow_draw() -> Self {
|
||||
Self {
|
||||
title_id: Self::BOW_DRAW_TITLE_ID,
|
||||
name: "BOW_DRAW".to_string(),
|
||||
arm_triggers: true,
|
||||
bow_enabled: true,
|
||||
bow_strength: 8,
|
||||
shield_enabled: true,
|
||||
shield_start_zone: 2,
|
||||
shield_strength: 2,
|
||||
shot_enabled: true,
|
||||
shot_amplitude: 8,
|
||||
shot_frequency: 35,
|
||||
shot_min_pulse_ms: 90,
|
||||
sustained_enabled: true,
|
||||
sustained_amplitude: 3,
|
||||
sustained_frequency: 25,
|
||||
sustained_min_rumble_ms: 450,
|
||||
}
|
||||
}
|
||||
|
||||
/// Public API alias kept for external crates (e.g. `Brontide-App`) until migrated.
|
||||
pub fn create_totk() -> Self {
|
||||
Self::create_bow_draw()
|
||||
}
|
||||
|
||||
pub fn create_defaults() -> Vec<Self> {
|
||||
vec![Self::create_bow_draw()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-game trigger profile built from a `DualSenseTriggerProfileConfig`.
|
||||
pub struct DualSenseTriggerProfile {
|
||||
pub title_id: u64,
|
||||
pub name: String,
|
||||
pub armed: bool,
|
||||
|
||||
bow: Option<DualSenseTriggerEffect>,
|
||||
shield: Option<DualSenseTriggerEffect>,
|
||||
shot: Option<DualSenseTriggerEffect>,
|
||||
held: Option<DualSenseTriggerEffect>,
|
||||
min_pulse_ms: i64,
|
||||
sustained_rumble_ms: i64,
|
||||
|
||||
off_effect: DualSenseTriggerEffect,
|
||||
}
|
||||
|
||||
impl DualSenseTriggerProfile {
|
||||
pub fn new(config: &DualSenseTriggerProfileConfig) -> Self {
|
||||
let bow_strength = config.bow_strength.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_STRENGTH,
|
||||
DualSenseTriggerProfileConfig::MAX_STRENGTH,
|
||||
);
|
||||
let bow_start = 1.max((bow_strength + 2) / 4);
|
||||
|
||||
let mut bow_zones = [0i32; DualSenseTriggerEffect::ZONES];
|
||||
for (zone, z) in bow_zones.iter_mut().enumerate() {
|
||||
*z = bow_start + ((bow_strength - bow_start) * zone.min(8) as i32 + 4) / 8;
|
||||
}
|
||||
|
||||
let bow = if config.bow_enabled {
|
||||
Some(DualSenseTriggerEffect::zone_feedback(
|
||||
&format!("bow feedback (progressive, {})", bow_strength),
|
||||
&bow_zones,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let shield_zone = config
|
||||
.shield_start_zone
|
||||
.clamp(0, DualSenseTriggerProfileConfig::MAX_START_ZONE);
|
||||
let shield_strength = config.shield_strength.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_STRENGTH,
|
||||
DualSenseTriggerProfileConfig::MAX_STRENGTH,
|
||||
);
|
||||
|
||||
let shield = if config.shield_enabled {
|
||||
Some(DualSenseTriggerEffect::feedback(
|
||||
&format!(
|
||||
"shield feedback (zone {}, {})",
|
||||
shield_zone, shield_strength
|
||||
),
|
||||
shield_zone,
|
||||
shield_strength,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let shot_amp = config.shot_amplitude.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_STRENGTH,
|
||||
DualSenseTriggerProfileConfig::MAX_STRENGTH,
|
||||
);
|
||||
let shot_freq = config.shot_frequency.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_FREQUENCY,
|
||||
DualSenseTriggerProfileConfig::MAX_FREQUENCY,
|
||||
);
|
||||
|
||||
let shot = if config.shot_enabled {
|
||||
Some(DualSenseTriggerEffect::vibration(
|
||||
&format!("shot vibration (pulse, {} / {} Hz)", shot_amp, shot_freq),
|
||||
0,
|
||||
shot_amp,
|
||||
shot_freq,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let sus_amp = config.sustained_amplitude.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_STRENGTH,
|
||||
DualSenseTriggerProfileConfig::MAX_STRENGTH,
|
||||
);
|
||||
let sus_freq = config.sustained_frequency.clamp(
|
||||
DualSenseTriggerProfileConfig::MIN_FREQUENCY,
|
||||
DualSenseTriggerProfileConfig::MAX_FREQUENCY,
|
||||
);
|
||||
|
||||
let held = if config.sustained_enabled {
|
||||
Some(DualSenseTriggerEffect::vibration(
|
||||
&format!(
|
||||
"device vibration (continuous, {} / {} Hz)",
|
||||
sus_amp, sus_freq
|
||||
),
|
||||
0,
|
||||
sus_amp,
|
||||
sus_freq,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Self {
|
||||
title_id: config.title_id,
|
||||
name: if config.name.trim().is_empty() {
|
||||
format!("{:016x}", config.title_id)
|
||||
} else {
|
||||
config.name.trim().to_string()
|
||||
},
|
||||
armed: config.arm_triggers,
|
||||
bow,
|
||||
shield,
|
||||
shot,
|
||||
held,
|
||||
min_pulse_ms: config.shot_min_pulse_ms.clamp(0, 5000) as i64,
|
||||
sustained_rumble_ms: config.sustained_min_rumble_ms.clamp(50, 10000) as i64,
|
||||
off_effect: DualSenseTriggerEffect::off(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(
|
||||
configs: Option<&[DualSenseTriggerProfileConfig]>,
|
||||
) -> HashMap<u64, DualSenseTriggerProfile> {
|
||||
let mut map = HashMap::new();
|
||||
let default_list = DualSenseTriggerProfileConfig::create_defaults();
|
||||
let list = configs.unwrap_or(&default_list);
|
||||
|
||||
for cfg in list {
|
||||
if cfg.title_id != 0 && !map.contains_key(&cfg.title_id) {
|
||||
map.insert(cfg.title_id, DualSenseTriggerProfile::new(cfg));
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
pub fn test_effects(&self) -> (&DualSenseTriggerEffect, &DualSenseTriggerEffect) {
|
||||
let left = self
|
||||
.shield
|
||||
.as_ref()
|
||||
.or(self.shot.as_ref())
|
||||
.or(self.held.as_ref())
|
||||
.unwrap_or(&self.off_effect);
|
||||
let right = self.bow.as_ref().unwrap_or(&self.off_effect);
|
||||
(left, right)
|
||||
}
|
||||
|
||||
pub fn evaluate<'a>(
|
||||
&'a self,
|
||||
input: &DualSenseTriggerInput,
|
||||
) -> (&'a DualSenseTriggerEffect, &'a DualSenseTriggerEffect) {
|
||||
let right = if input.zr_held || self.armed {
|
||||
self.bow.as_ref().unwrap_or(&self.off_effect)
|
||||
} else {
|
||||
&self.off_effect
|
||||
};
|
||||
|
||||
let mut left = if self.armed {
|
||||
self.shield.as_ref().unwrap_or(&self.off_effect)
|
||||
} else {
|
||||
&self.off_effect
|
||||
};
|
||||
|
||||
if input.zl_held {
|
||||
if let Some(held) = self.held.as_ref() {
|
||||
if input.rumble_on && input.rumble_on_ms >= self.sustained_rumble_ms {
|
||||
left = held;
|
||||
} else if let Some(shot) = self.shot.as_ref() {
|
||||
if input.rumble_on || input.pulse_age_ms < self.min_pulse_ms {
|
||||
left = shot;
|
||||
} else if let Some(shield) = self.shield.as_ref() {
|
||||
left = shield;
|
||||
}
|
||||
} else if let Some(shield) = self.shield.as_ref() {
|
||||
left = shield;
|
||||
}
|
||||
} else if let Some(shot) = self.shot.as_ref() {
|
||||
if input.rumble_on || input.pulse_age_ms < self.min_pulse_ms {
|
||||
left = shot;
|
||||
} else if let Some(shield) = self.shield.as_ref() {
|
||||
left = shield;
|
||||
}
|
||||
} else if let Some(shield) = self.shield.as_ref() {
|
||||
left = shield;
|
||||
}
|
||||
}
|
||||
|
||||
(left, right)
|
||||
}
|
||||
}
|
||||
|
||||
/// Packs the 11-byte Left and Right trigger effects into a 47-byte DS5EffectsState_t packet.
|
||||
pub fn pack_ds5_effects_state(left: &[u8; 11], right: &[u8; 11], out47: &mut [u8; 47]) {
|
||||
out47.fill(0);
|
||||
// ucEnableBits1: EnableRightTrigger (0x04) | EnableLeftTrigger (0x08) = 0x0C
|
||||
out47[0] = 0x04 | 0x08;
|
||||
out47[10..21].copy_from_slice(right);
|
||||
out47[21..32].copy_from_slice(left);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const BOW_DRAW_TITLE_ID: u64 = 0x0100F2C0115B6000;
|
||||
|
||||
const OFF: [u8; 11] = [
|
||||
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
const BOW: [u8; 11] = [
|
||||
0x21, 0xFF, 0x03, 0xD1, 0xC6, 0xDA, 0x3F, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
const SHIELD: [u8; 11] = [
|
||||
0x21, 0xFC, 0x03, 0x40, 0x92, 0x24, 0x09, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
const SHOT: [u8; 11] = [
|
||||
0x26, 0xFF, 0x03, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x23, 0x00,
|
||||
];
|
||||
const HELD: [u8; 11] = [
|
||||
0x26, 0xFF, 0x03, 0x92, 0x24, 0x49, 0x12, 0x00, 0x00, 0x19, 0x00,
|
||||
];
|
||||
|
||||
fn bow_draw_profile(
|
||||
configs: Option<&[DualSenseTriggerProfileConfig]>,
|
||||
) -> DualSenseTriggerProfile {
|
||||
let profiles = DualSenseTriggerProfile::build(configs);
|
||||
let profile = profiles
|
||||
.get(&BOW_DRAW_TITLE_ID)
|
||||
.expect("bow_draw profile missing");
|
||||
DualSenseTriggerProfile::new(&DualSenseTriggerProfileConfig {
|
||||
title_id: profile.title_id,
|
||||
name: profile.name.clone(),
|
||||
arm_triggers: profile.armed,
|
||||
bow_enabled: profile.bow.is_some(),
|
||||
bow_strength: 8,
|
||||
shield_enabled: profile.shield.is_some(),
|
||||
shield_start_zone: 2,
|
||||
shield_strength: 2,
|
||||
shot_enabled: profile.shot.is_some(),
|
||||
shot_amplitude: 8,
|
||||
shot_frequency: 35,
|
||||
shot_min_pulse_ms: 90,
|
||||
sustained_enabled: profile.held.is_some(),
|
||||
sustained_amplitude: 3,
|
||||
sustained_frequency: 25,
|
||||
sustained_min_rumble_ms: 450,
|
||||
})
|
||||
}
|
||||
|
||||
fn eval(
|
||||
profile: &DualSenseTriggerProfile,
|
||||
zl: bool,
|
||||
zr: bool,
|
||||
rumble_on: bool,
|
||||
rumble_on_ms: i64,
|
||||
pulse_age_ms: i64,
|
||||
) -> ([u8; 11], [u8; 11]) {
|
||||
let input = DualSenseTriggerInput::new(zl, zr, rumble_on, rumble_on_ms, pulse_age_ms);
|
||||
let (left, right) = profile.evaluate(&input);
|
||||
(left.data, right.data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_defaults_are_bow_draw_only() {
|
||||
let profiles = DualSenseTriggerProfile::build(None);
|
||||
assert_eq!(profiles.len(), 1);
|
||||
assert!(profiles.contains_key(&BOW_DRAW_TITLE_ID));
|
||||
assert_eq!(profiles[&BOW_DRAW_TITLE_ID].name, "BOW_DRAW");
|
||||
assert!(!profiles.contains_key(&0x01006A800016E000));
|
||||
assert!(!profiles.contains_key(&0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_defaults_match_0194_values() {
|
||||
let config = DualSenseTriggerProfileConfig::create_bow_draw();
|
||||
assert_eq!(config.title_id, BOW_DRAW_TITLE_ID);
|
||||
assert!(config.arm_triggers);
|
||||
assert!(
|
||||
config.bow_enabled
|
||||
&& config.shield_enabled
|
||||
&& config.shot_enabled
|
||||
&& config.sustained_enabled
|
||||
);
|
||||
assert_eq!(config.bow_strength, 8);
|
||||
assert_eq!(config.shield_start_zone, 2);
|
||||
assert_eq!(config.shield_strength, 2);
|
||||
assert_eq!(config.shot_amplitude, 8);
|
||||
assert_eq!(config.shot_frequency, 35);
|
||||
assert_eq!(config.shot_min_pulse_ms, 90);
|
||||
assert_eq!(config.sustained_amplitude, 3);
|
||||
assert_eq!(config.sustained_frequency, 25);
|
||||
assert_eq!(config.sustained_min_rumble_ms, 450);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_bow_draw_profile_gives_0194_effects() {
|
||||
let t = bow_draw_profile(None);
|
||||
assert!(t.armed);
|
||||
|
||||
// Nothing held: bow and shield already loaded (arm_triggers), even while game rumbles
|
||||
assert_eq!(eval(&t, false, false, false, 0, i64::MAX), (SHIELD, BOW));
|
||||
assert_eq!(eval(&t, false, false, true, 1000, 0), (SHIELD, BOW));
|
||||
|
||||
// ZR held: bow on R2
|
||||
assert_eq!(eval(&t, false, true, false, 0, i64::MAX), (SHIELD, BOW));
|
||||
|
||||
// ZL held, no rumble: shield on L2
|
||||
assert_eq!(eval(&t, true, false, false, 0, i64::MAX), (SHIELD, BOW));
|
||||
|
||||
// ZL held + rumble pulse: shot; lasts at least 90 ms after rumble stopped
|
||||
assert_eq!(eval(&t, true, false, true, 10, 0), (SHOT, BOW));
|
||||
assert_eq!(eval(&t, true, false, false, 0, 89), (SHOT, BOW));
|
||||
assert_eq!(eval(&t, true, false, false, 0, 90), (SHIELD, BOW));
|
||||
|
||||
// ZL held + rumble lasting 450 ms: held device
|
||||
assert_eq!(eval(&t, true, false, true, 449, 0), (SHOT, BOW));
|
||||
assert_eq!(eval(&t, true, false, true, 450, 0), (HELD, BOW));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_arm_triggers_off_frees_released_triggers() {
|
||||
let mut config = DualSenseTriggerProfileConfig::create_bow_draw();
|
||||
config.arm_triggers = false;
|
||||
let t = DualSenseTriggerProfile::new(&config);
|
||||
|
||||
assert!(!t.armed);
|
||||
assert_eq!(eval(&t, false, false, true, 1000, 0), (OFF, OFF));
|
||||
assert_eq!(eval(&t, false, true, false, 0, i64::MAX), (OFF, BOW));
|
||||
assert_eq!(eval(&t, true, false, false, 0, i64::MAX), (SHIELD, OFF));
|
||||
assert_eq!(eval(&t, true, false, true, 10, 0), (SHOT, OFF));
|
||||
assert_eq!(eval(&t, true, false, true, 450, 0), (HELD, OFF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disabled_situations_fall_through() {
|
||||
let mut config = DualSenseTriggerProfileConfig::create_bow_draw();
|
||||
config.sustained_enabled = false;
|
||||
config.bow_enabled = false;
|
||||
let t = DualSenseTriggerProfile::new(&config);
|
||||
|
||||
// Long rumble without held-device situation: still shot; no bow: R2 free
|
||||
assert_eq!(eval(&t, true, true, true, 1000, 0), (SHOT, OFF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_test_button_effects() {
|
||||
let t = bow_draw_profile(None);
|
||||
let (left, right) = t.test_effects();
|
||||
assert_eq!(left.data, SHIELD);
|
||||
assert_eq!(right.data, BOW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pack_ds5_effects_state() {
|
||||
let mut out = [0u8; 47];
|
||||
pack_ds5_effects_state(&SHIELD, &BOW, &mut out);
|
||||
assert_eq!(out[0], 0x0C);
|
||||
assert_eq!(&out[10..21], &BOW);
|
||||
assert_eq!(&out[21..32], &SHIELD);
|
||||
}
|
||||
}
|
||||
760
third_party/renhdrum/src/encoding/amfm.rs
vendored
Normal file
760
third_party/renhdrum/src/encoding/amfm.rs
vendored
Normal file
@@ -0,0 +1,760 @@
|
||||
use crate::encoding::standard::hd_encode_side;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ArgumentOutOfRange(pub String);
|
||||
|
||||
impl std::fmt::Display for ArgumentOutOfRange {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "ArgumentOutOfRange: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ArgumentOutOfRange {}
|
||||
|
||||
pub struct HdAmFmEncoding;
|
||||
|
||||
impl HdAmFmEncoding {
|
||||
pub const CODE5_GAME_SCALE: f32 = 1.7947091;
|
||||
pub const MIN_CODE: i32 = 3;
|
||||
pub const MAX_CODE: i32 = 11;
|
||||
pub const HOLD: i32 = 24;
|
||||
pub const SILENT_BELOW: f32 = 0.04;
|
||||
pub const MAX_AMP7: i32 = 100;
|
||||
pub const DEFAULT_FREQ7: i32 = 64;
|
||||
pub const PRESET_FIRST: i32 = 12;
|
||||
pub const PRESET_STEPS: [i32; 5] = [-12, -6, 0, 6, 12];
|
||||
pub const STEP_UP: i32 = 23;
|
||||
pub const STEP_DOWN: i32 = 25;
|
||||
|
||||
pub fn game_amplitude(code: i32) -> Result<f32, ArgumentOutOfRange> {
|
||||
if code == 0 {
|
||||
return Ok(0.0);
|
||||
}
|
||||
|
||||
if !(Self::MIN_CODE..=Self::MAX_CODE).contains(&code) {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"Only 0 and 3..11 have a known amplitude: code {code}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(Self::CODE5_GAME_SCALE * 2.0f32.powf(-0.5 * (code - 1) as f32))
|
||||
}
|
||||
|
||||
pub fn code(game_amplitude: f32) -> i32 {
|
||||
if !(game_amplitude >= Self::SILENT_BELOW) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let code_val = 1.0 + 2.0 * (Self::CODE5_GAME_SCALE / game_amplitude).log2();
|
||||
let rounded = code_val.round_ties_even() as i32;
|
||||
|
||||
rounded.clamp(Self::MIN_CODE, Self::MAX_CODE)
|
||||
}
|
||||
|
||||
pub fn pack_three(
|
||||
lo0: i32,
|
||||
hi0: i32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
lo2: i32,
|
||||
hi2: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
Self::check_sample(lo0, hi0)?;
|
||||
Self::check_sample(lo1, hi1)?;
|
||||
Self::check_sample(lo2, hi2)?;
|
||||
|
||||
Self::pack_three_raw(lo0, hi0, lo1, hi1, lo2, hi2)
|
||||
}
|
||||
|
||||
pub fn pack_three_raw(
|
||||
lo0: i32,
|
||||
hi0: i32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
lo2: i32,
|
||||
hi2: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
for &code in &[lo0, hi0, lo1, hi1, lo2, hi2] {
|
||||
if !(0..=31).contains(&code) {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"A 5-bit code is 0..31: code {code}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok((3u32 << 30)
|
||||
| ((lo0 as u32) << 25)
|
||||
| ((hi0 as u32) << 20)
|
||||
| ((lo1 as u32) << 15)
|
||||
| ((hi1 as u32) << 10)
|
||||
| ((lo2 as u32) << 5)
|
||||
| (hi2 as u32))
|
||||
}
|
||||
|
||||
pub fn freq7(high: bool, freq: f32) -> i32 {
|
||||
let v = Self::two_wave(
|
||||
if high { 0.0 } else { 0.5 },
|
||||
if high { 160.0 } else { freq },
|
||||
if high { 0.5 } else { 0.0 },
|
||||
if high { freq } else { 320.0 },
|
||||
);
|
||||
|
||||
(if high { v >> 2 } else { v >> 16 } & 0x7F) as i32
|
||||
}
|
||||
|
||||
pub fn amp7(game_amplitude: f32) -> i32 {
|
||||
let v = Self::two_wave(game_amplitude, 160.0, 0.0, 320.0);
|
||||
((v >> 23) & 0x7F) as i32
|
||||
}
|
||||
|
||||
pub fn pack_three_7bit(
|
||||
high: bool,
|
||||
is_fm: bool,
|
||||
value7: i32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
lo2: i32,
|
||||
hi2: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
Self::check_value7(is_fm, value7)?;
|
||||
Self::check_sample(lo1, hi1)?;
|
||||
Self::check_sample(lo2, hi2)?;
|
||||
|
||||
Ok((1u32 << 30)
|
||||
| ((value7 as u32) << 23)
|
||||
| ((lo1 as u32) << 18)
|
||||
| ((hi1 as u32) << 13)
|
||||
| ((lo2 as u32) << 8)
|
||||
| ((hi2 as u32) << 3)
|
||||
| (if is_fm { 4u32 } else { 0u32 })
|
||||
| 2u32
|
||||
| (if high { 1u32 } else { 0u32 }))
|
||||
}
|
||||
|
||||
pub fn pack_two_14bit(
|
||||
high: bool,
|
||||
freq7: i32,
|
||||
amp7: i32,
|
||||
other0: i32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
Self::check_value7(true, freq7)?;
|
||||
Self::check_value7(false, amp7)?;
|
||||
|
||||
if other0 != 0 && other0 != Self::HOLD {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"The other band's first sample must be 0 or 24 (hold): {other0}"
|
||||
)));
|
||||
}
|
||||
|
||||
Self::check_sample(lo1, hi1)?;
|
||||
|
||||
Ok(Self::two_14bit_raw(high, freq7, amp7, other0, lo1, hi1))
|
||||
}
|
||||
|
||||
pub fn pack_two_14bit_level(
|
||||
high: bool,
|
||||
freq7: i32,
|
||||
game_amplitude: f32,
|
||||
other0: i32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
Self::check_value7(true, freq7)?;
|
||||
|
||||
if !Self::is_allowed(other0) {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"Codes must be 0, 3..11 or 24 (hold): {other0}"
|
||||
)));
|
||||
}
|
||||
|
||||
if (Self::MIN_CODE..=Self::MAX_CODE).contains(&other0) {
|
||||
let other_amp = Self::game_amplitude(other0)?;
|
||||
if game_amplitude + other_amp > 1.0 + 1e-4 {
|
||||
return Err(ArgumentOutOfRange(
|
||||
"Low + high band above game amplitude 1.0".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Self::check_sample(lo1, hi1)?;
|
||||
|
||||
Ok(Self::two_14bit_raw(
|
||||
high,
|
||||
freq7,
|
||||
Self::amp7(game_amplitude),
|
||||
other0,
|
||||
lo1,
|
||||
hi1,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn preset_code(high: bool, freq7: i32) -> i32 {
|
||||
let diff = freq7 - Self::DEFAULT_FREQ7;
|
||||
let index = Self::PRESET_STEPS.iter().position(|&s| s == diff);
|
||||
|
||||
match index {
|
||||
Some(idx) => {
|
||||
if high && idx == 1 {
|
||||
-1
|
||||
} else {
|
||||
Self::PRESET_FIRST + idx as i32
|
||||
}
|
||||
}
|
||||
None => -1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_preset(code: i32) -> bool {
|
||||
(Self::PRESET_FIRST..Self::PRESET_FIRST + Self::PRESET_STEPS.len() as i32).contains(&code)
|
||||
}
|
||||
|
||||
pub fn pack_two_14bit_reach(
|
||||
high: bool,
|
||||
freq7: i32,
|
||||
game_amplitude: f32,
|
||||
reach_code: i32,
|
||||
other_amplitude: f32,
|
||||
lo1: i32,
|
||||
hi1: i32,
|
||||
) -> Result<u32, ArgumentOutOfRange> {
|
||||
Self::check_value7(true, freq7)?;
|
||||
|
||||
if !Self::is_preset(reach_code)
|
||||
&& reach_code != Self::STEP_UP
|
||||
&& reach_code != Self::STEP_DOWN
|
||||
{
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"The other band's first sample must be a preset 12..16 or a step 23 / 25: {reach_code}"
|
||||
)));
|
||||
}
|
||||
|
||||
if game_amplitude + other_amplitude > 1.0 + 1e-4 {
|
||||
return Err(ArgumentOutOfRange(
|
||||
"Low + high band above game amplitude 1.0".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Self::check_sample(lo1, hi1)?;
|
||||
|
||||
Ok(Self::two_14bit_raw(
|
||||
high,
|
||||
freq7,
|
||||
Self::amp7(game_amplitude),
|
||||
reach_code,
|
||||
lo1,
|
||||
hi1,
|
||||
))
|
||||
}
|
||||
|
||||
fn two_14bit_raw(high: bool, freq7: i32, amp7: i32, other0: i32, lo1: i32, hi1: i32) -> u32 {
|
||||
(2u32 << 30)
|
||||
| ((amp7 as u32) << 23)
|
||||
| ((other0 as u32) << 18)
|
||||
| ((lo1 as u32) << 13)
|
||||
| ((hi1 as u32) << 8)
|
||||
| ((freq7 as u32) << 1)
|
||||
| (if high { 1u32 } else { 0u32 })
|
||||
}
|
||||
|
||||
pub fn write_side(dst4: &mut [u8], v: u32) {
|
||||
dst4[0..4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
pub fn is_three_sample_side(side: &[u8]) -> bool {
|
||||
if side.len() < 4 {
|
||||
false
|
||||
} else {
|
||||
(side[3] >> 6) == 3
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(v: u32) -> String {
|
||||
format!(
|
||||
"3x5bit lo {}/{}/{} hi {}/{}/{}",
|
||||
(v >> 25) & 31,
|
||||
(v >> 15) & 31,
|
||||
(v >> 5) & 31,
|
||||
(v >> 20) & 31,
|
||||
(v >> 10) & 31,
|
||||
v & 31
|
||||
)
|
||||
}
|
||||
|
||||
fn is_allowed(code: i32) -> bool {
|
||||
code == 0 || code == Self::HOLD || (Self::MIN_CODE..=Self::MAX_CODE).contains(&code)
|
||||
}
|
||||
|
||||
fn check_value7(is_frequency: bool, value7: i32) -> Result<(), ArgumentOutOfRange> {
|
||||
let valid = if is_frequency {
|
||||
(1..=127).contains(&value7)
|
||||
} else {
|
||||
(0..=Self::MAX_AMP7).contains(&value7)
|
||||
};
|
||||
|
||||
if !valid {
|
||||
Err(ArgumentOutOfRange(format!(
|
||||
"{}: {value7}",
|
||||
if is_frequency {
|
||||
"A 7-bit frequency is 1..127"
|
||||
} else {
|
||||
"A 7-bit amplitude is 0..100"
|
||||
}
|
||||
)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn two_wave(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> u32 {
|
||||
let mut side = [0u8; 4];
|
||||
hd_encode_side(&mut side, amp_low, freq_low, amp_high, freq_high);
|
||||
u32::from_le_bytes(side)
|
||||
}
|
||||
|
||||
fn check_sample(lo: i32, hi: i32) -> Result<(), ArgumentOutOfRange> {
|
||||
if !Self::is_allowed(lo) || !Self::is_allowed(hi) {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"Codes must be 0, 3..11 or 24 (hold): {lo}/{hi}"
|
||||
)));
|
||||
}
|
||||
|
||||
let lo_set = (Self::MIN_CODE..=Self::MAX_CODE).contains(&lo);
|
||||
let hi_set = (Self::MIN_CODE..=Self::MAX_CODE).contains(&hi);
|
||||
|
||||
if lo_set && hi_set && Self::game_amplitude(lo)? + Self::game_amplitude(hi)? > 1.0 {
|
||||
return Err(ArgumentOutOfRange(format!(
|
||||
"Low + high band above game amplitude 1.0: {lo}/{hi}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn steam_tick_matches_reference() {
|
||||
let v = HdAmFmEncoding::pack_three_raw(0, 0, 10, 0, 0, 0).unwrap();
|
||||
let mut dst = [0u8; 4];
|
||||
HdAmFmEncoding::write_side(&mut dst, v);
|
||||
|
||||
assert_eq!(dst, [0x00, 0x00, 0x05, 0xC0]);
|
||||
assert_eq!(HdAmFmEncoding::describe(v), "3x5bit lo 0/10/0 hi 0/0/0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_raw_pack() {
|
||||
let mut seed: u64 = 1234;
|
||||
let mut next_rand = || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
((seed >> 33) % 32) as i32
|
||||
};
|
||||
|
||||
for _ in 0..1000 {
|
||||
let lo0 = next_rand();
|
||||
let hi0 = next_rand();
|
||||
let lo1 = next_rand();
|
||||
let hi1 = next_rand();
|
||||
let lo2 = next_rand();
|
||||
let hi2 = next_rand();
|
||||
|
||||
let v = HdAmFmEncoding::pack_three_raw(lo0, hi0, lo1, hi1, lo2, hi2).unwrap();
|
||||
|
||||
assert_eq!(v >> 30, 3);
|
||||
assert_eq!(((v >> 25) & 31) as i32, lo0);
|
||||
assert_eq!(((v >> 20) & 31) as i32, hi0);
|
||||
assert_eq!(((v >> 15) & 31) as i32, lo1);
|
||||
assert_eq!(((v >> 10) & 31) as i32, hi1);
|
||||
assert_eq!(((v >> 5) & 31) as i32, lo2);
|
||||
assert_eq!((v & 31) as i32, hi2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_maps_game_amplitude() {
|
||||
for c in HdAmFmEncoding::MIN_CODE..=HdAmFmEncoding::MAX_CODE {
|
||||
assert_eq!(
|
||||
HdAmFmEncoding::code(HdAmFmEncoding::game_amplitude(c).unwrap()),
|
||||
c
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(HdAmFmEncoding::code(0.03), 0);
|
||||
assert_eq!(HdAmFmEncoding::code(f32::NAN), 0);
|
||||
assert_eq!(HdAmFmEncoding::code(1.0), 3);
|
||||
assert_eq!(HdAmFmEncoding::code(0.45), 5);
|
||||
assert_eq!(HdAmFmEncoding::code(0.06), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn game_amplitude_validation() {
|
||||
assert!(HdAmFmEncoding::game_amplitude(3).unwrap() < 1.0);
|
||||
assert_eq!(HdAmFmEncoding::game_amplitude(0).unwrap(), 0.0);
|
||||
assert!(HdAmFmEncoding::game_amplitude(1).is_err());
|
||||
assert!(HdAmFmEncoding::game_amplitude(12).is_err());
|
||||
assert!(HdAmFmEncoding::game_amplitude(24).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pack_three_invalid_codes_throw() {
|
||||
let invalid_codes = [1, 2, 12, 23, 25, 31, -1, 32];
|
||||
|
||||
for &bad in &invalid_codes {
|
||||
assert!(HdAmFmEncoding::pack_three(bad, 0, 0, 0, 0, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(0, bad, 0, 0, 0, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(0, 0, bad, 0, 0, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(0, 0, 0, bad, 0, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(0, 0, 0, 0, bad, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(0, 0, 0, 0, 0, bad).is_err());
|
||||
}
|
||||
|
||||
assert!(HdAmFmEncoding::pack_three(24, 24, 0, 0, 5, 0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motor_protection() {
|
||||
assert!(HdAmFmEncoding::pack_three(3, 3, 0, 0, 0, 0).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three(4, 5, 0, 0, 0, 0).is_err());
|
||||
|
||||
assert!(HdAmFmEncoding::pack_three(5, 5, 0, 0, 5, 5).is_ok());
|
||||
assert!(HdAmFmEncoding::pack_three(4, 6, 0, 0, 0, 0).is_ok());
|
||||
assert!(HdAmFmEncoding::pack_three(3, 0, 3, 0, 3, 0).is_ok());
|
||||
assert!(HdAmFmEncoding::pack_three(3, 24, 0, 0, 0, 0).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_sides_are_not_dual_wave() {
|
||||
let valid_packs = [
|
||||
HdAmFmEncoding::pack_three(0, 0, 0, 0, 0, 0).unwrap(),
|
||||
HdAmFmEncoding::pack_three(5, 5, 0, 0, 5, 5).unwrap(),
|
||||
HdAmFmEncoding::pack_three(3, 0, 3, 0, 3, 0).unwrap(),
|
||||
HdAmFmEncoding::pack_three(24, 24, 0, 0, 5, 0).unwrap(),
|
||||
HdAmFmEncoding::pack_three(11, 11, 11, 11, 11, 11).unwrap(),
|
||||
];
|
||||
|
||||
let mut b = [0u8; 4];
|
||||
for pack in valid_packs {
|
||||
HdAmFmEncoding::write_side(&mut b, pack);
|
||||
let is_dual_wave = (b[0] & 3) == 0 && (b[3] & 0xC0) == 0x40;
|
||||
assert!(!is_dual_wave);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_three_sample_side_identifies_correctly() {
|
||||
let mut side = [0u8; 4];
|
||||
HdAmFmEncoding::write_side(
|
||||
&mut side,
|
||||
HdAmFmEncoding::pack_three(5, 5, 0, 0, 5, 5).unwrap(),
|
||||
);
|
||||
assert!(HdAmFmEncoding::is_three_sample_side(&side));
|
||||
|
||||
let neutral = [0x00, 0x01, 0x40, 0x40];
|
||||
assert!(!HdAmFmEncoding::is_three_sample_side(&neutral));
|
||||
|
||||
let mut two_wave = [0u8; 4];
|
||||
hd_encode_side(&mut two_wave, 0.45, 160.0, 0.45, 320.0);
|
||||
assert!(!HdAmFmEncoding::is_three_sample_side(&two_wave));
|
||||
}
|
||||
|
||||
// Decoder for testing frequency forms
|
||||
fn both(freq: i32, amp: i32) -> i32 {
|
||||
0x8080 | (freq << 8) | amp
|
||||
}
|
||||
fn freq_only(freq: i32) -> i32 {
|
||||
0x8000 | (freq << 8)
|
||||
}
|
||||
fn amp_only(amp: i32) -> i32 {
|
||||
0x80 | amp
|
||||
}
|
||||
|
||||
fn decode(v: u32) -> Vec<(i32, i32)> {
|
||||
let bits =
|
||||
|v: u32, shift: usize, count: usize| ((v >> shift) & ((1u32 << count) - 1)) as i32;
|
||||
|
||||
let mut samples = Vec::new();
|
||||
match v >> 30 {
|
||||
1 if bits(v, 0, 20) == 0 => {
|
||||
samples.push((bits(v, 25, 5), bits(v, 20, 5)));
|
||||
}
|
||||
1 if bits(v, 0, 2) == 0 => {
|
||||
samples.push((
|
||||
both(bits(v, 16, 7), bits(v, 23, 7)),
|
||||
both(bits(v, 2, 7), bits(v, 9, 7)),
|
||||
));
|
||||
}
|
||||
1 => {
|
||||
let value = bits(v, 23, 7);
|
||||
let selected = if bits(v, 2, 1) == 1 {
|
||||
freq_only(value)
|
||||
} else {
|
||||
amp_only(value)
|
||||
};
|
||||
samples.push(if bits(v, 0, 1) == 1 {
|
||||
(HdAmFmEncoding::HOLD, selected)
|
||||
} else {
|
||||
(selected, HdAmFmEncoding::HOLD)
|
||||
});
|
||||
samples.push((bits(v, 18, 5), bits(v, 13, 5)));
|
||||
samples.push((bits(v, 8, 5), bits(v, 3, 5)));
|
||||
}
|
||||
2 if bits(v, 0, 10) == 0 => {
|
||||
samples.push((bits(v, 25, 5), bits(v, 20, 5)));
|
||||
samples.push((bits(v, 15, 5), bits(v, 10, 5)));
|
||||
}
|
||||
2 => {
|
||||
let channel = both(bits(v, 1, 7), bits(v, 23, 7));
|
||||
let other = bits(v, 18, 5);
|
||||
samples.push(if bits(v, 0, 1) == 1 {
|
||||
(other, channel)
|
||||
} else {
|
||||
(channel, other)
|
||||
});
|
||||
samples.push((bits(v, 13, 5), bits(v, 8, 5)));
|
||||
samples.push((HdAmFmEncoding::HOLD, HdAmFmEncoding::HOLD));
|
||||
}
|
||||
3 => {
|
||||
samples.push((bits(v, 25, 5), bits(v, 20, 5)));
|
||||
samples.push((bits(v, 15, 5), bits(v, 10, 5)));
|
||||
samples.push((bits(v, 5, 5), bits(v, 0, 5)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
samples
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_decoder_reads_nintendos_own_packet() {
|
||||
let v = u32::from_le_bytes([0xC2, 0xC8, 0x03, 0x72]);
|
||||
assert_eq!(
|
||||
decode(v),
|
||||
vec![
|
||||
(amp_only(100), HdAmFmEncoding::HOLD),
|
||||
(0, 30),
|
||||
(8, HdAmFmEncoding::HOLD)
|
||||
]
|
||||
);
|
||||
|
||||
let steam_v = u32::from_le_bytes([0x00, 0x00, 0x05, 0xC0]);
|
||||
assert_eq!(decode(steam_v), vec![(0, 0), (10, 0), (0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seven_bit_fields_match_the_two_wave_encoder() {
|
||||
assert_eq!(HdAmFmEncoding::freq7(false, 160.0), 64);
|
||||
assert_eq!(HdAmFmEncoding::freq7(true, 320.0), 64);
|
||||
assert_eq!(HdAmFmEncoding::amp7(0.0), 0);
|
||||
assert_eq!(HdAmFmEncoding::amp7(1.0), HdAmFmEncoding::MAX_AMP7);
|
||||
|
||||
for &freq in &[41.0f32, 80.0, 160.0, 200.0, 320.0, 626.0] {
|
||||
for & in &[0.05f32, 0.224, 0.45, 0.6] {
|
||||
let v = HdAmFmEncoding::two_wave(amp, freq, amp / 2.0, freq * 2.0);
|
||||
let s = decode(v);
|
||||
|
||||
assert_eq!(
|
||||
s[0].0,
|
||||
both(
|
||||
HdAmFmEncoding::freq7(false, freq),
|
||||
HdAmFmEncoding::amp7(amp)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
s[0].1,
|
||||
both(
|
||||
HdAmFmEncoding::freq7(true, freq * 2.0),
|
||||
HdAmFmEncoding::amp7(amp / 2.0)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_7bit_decodes_as_packed() {
|
||||
let f80 = HdAmFmEncoding::freq7(false, 80.0);
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
|
||||
assert_eq!(
|
||||
decode(
|
||||
HdAmFmEncoding::pack_three_7bit(false, true, f80, hold, hold, hold, hold).unwrap()
|
||||
),
|
||||
vec![(freq_only(f80), hold), (hold, hold), (hold, hold)]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_three_7bit(false, false, 37, 5, 0, 7, hold).unwrap()),
|
||||
vec![(amp_only(37), hold), (5, 0), (7, hold)]
|
||||
);
|
||||
|
||||
let f640 = HdAmFmEncoding::freq7(true, 640.0);
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_three_7bit(true, true, f640, 0, 5, hold, 9).unwrap()),
|
||||
vec![(hold, freq_only(f640)), (0, 5), (hold, 9)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_14bit_decodes_as_packed() {
|
||||
let f80 = HdAmFmEncoding::freq7(false, 80.0);
|
||||
let amp = HdAmFmEncoding::amp7(0.45);
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_two_14bit(false, f80, amp, hold, 0, hold).unwrap()),
|
||||
vec![(both(f80, amp), hold), (0, hold), (hold, hold)]
|
||||
);
|
||||
|
||||
let f640 = HdAmFmEncoding::freq7(true, 640.0);
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_two_14bit(true, f640, amp, 0, 5, 7).unwrap()),
|
||||
vec![(0, both(f640, amp)), (5, 7), (hold, hold)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_14bit_never_reads_as_two_plain_samples() {
|
||||
let v = HdAmFmEncoding::pack_two_14bit(false, 1, 0, 0, 0, 0).unwrap();
|
||||
assert_eq!(v >> 30, 2);
|
||||
assert_ne!(v & 0x3FF, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_forms_are_neither_two_wave_nor_three_sample() {
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
let mut side = [0u8; 4];
|
||||
|
||||
for &v in &[
|
||||
HdAmFmEncoding::pack_three_7bit(false, true, 50, hold, hold, hold, hold).unwrap(),
|
||||
HdAmFmEncoding::pack_three_7bit(true, false, 0, 0, 0, 0, 0).unwrap(),
|
||||
HdAmFmEncoding::pack_two_14bit(false, 50, 40, hold, hold, hold).unwrap(),
|
||||
HdAmFmEncoding::pack_two_14bit(true, 1, 0, 0, 0, 0).unwrap(),
|
||||
] {
|
||||
HdAmFmEncoding::write_side(&mut side, v);
|
||||
let two_wave = (side[0] & 3) == 0 && (side[3] & 0xC0) == 0x40;
|
||||
assert!(!two_wave);
|
||||
assert!(!HdAmFmEncoding::is_three_sample_side(&side));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_values_throw() {
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
assert!(HdAmFmEncoding::pack_three_7bit(false, true, 0, hold, hold, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three_7bit(false, true, 128, hold, hold, hold, hold).is_err());
|
||||
assert!(
|
||||
HdAmFmEncoding::pack_three_7bit(false, false, 101, hold, hold, hold, hold).is_err()
|
||||
);
|
||||
assert!(HdAmFmEncoding::pack_three_7bit(false, false, 50, 1, hold, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_three_7bit(false, false, 50, 3, 3, hold, hold).is_err());
|
||||
|
||||
assert!(HdAmFmEncoding::pack_two_14bit(false, 0, 50, hold, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit(false, 50, 101, hold, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit(false, 50, 50, 5, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit(false, 50, 50, hold, 12, hold).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_14bit_level_allows_the_other_band_within_full_scale() {
|
||||
let f80 = HdAmFmEncoding::freq7(false, 80.0);
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_two_14bit_level(false, f80, 0.45, 5, 7, 7).unwrap()),
|
||||
vec![
|
||||
(both(f80, HdAmFmEncoding::amp7(0.45)), 5),
|
||||
(7, 7),
|
||||
(hold, hold)
|
||||
]
|
||||
);
|
||||
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_level(false, f80, 0.9, 5, hold, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_level(false, f80, 0.4, 13, hold, hold).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_sit_around_both_defaults() {
|
||||
assert_eq!(
|
||||
HdAmFmEncoding::freq7(false, 160.0),
|
||||
HdAmFmEncoding::DEFAULT_FREQ7
|
||||
);
|
||||
assert_eq!(
|
||||
HdAmFmEncoding::freq7(true, 320.0),
|
||||
HdAmFmEncoding::DEFAULT_FREQ7
|
||||
);
|
||||
|
||||
let low = [121.0f32, 138.0, 158.0, 180.0, 204.0];
|
||||
let high = [243.0f32, 276.0, 316.0, 359.0, 409.0];
|
||||
|
||||
for i in 0..5 {
|
||||
let low7 = HdAmFmEncoding::freq7(false, low[i] / 0.987);
|
||||
let high7 = HdAmFmEncoding::freq7(true, high[i] / 0.987);
|
||||
|
||||
assert_eq!(
|
||||
low7,
|
||||
HdAmFmEncoding::DEFAULT_FREQ7 + HdAmFmEncoding::PRESET_STEPS[i]
|
||||
);
|
||||
assert_eq!(high7, low7);
|
||||
assert_eq!(HdAmFmEncoding::preset_code(false, low7), 12 + i as i32);
|
||||
assert_eq!(
|
||||
HdAmFmEncoding::preset_code(true, high7),
|
||||
if i == 1 { -1 } else { 12 + i as i32 }
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
HdAmFmEncoding::preset_code(false, HdAmFmEncoding::DEFAULT_FREQ7 + 1),
|
||||
-1
|
||||
);
|
||||
assert!(!HdAmFmEncoding::is_preset(11));
|
||||
assert!(!HdAmFmEncoding::is_preset(17));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_14bit_reach_decodes_as_packed() {
|
||||
let f640 = HdAmFmEncoding::freq7(true, 640.0);
|
||||
let f80 = HdAmFmEncoding::freq7(false, 80.0);
|
||||
let hold = HdAmFmEncoding::HOLD;
|
||||
|
||||
assert_eq!(
|
||||
decode(
|
||||
HdAmFmEncoding::pack_two_14bit_reach(
|
||||
true,
|
||||
f640,
|
||||
0.5,
|
||||
HdAmFmEncoding::STEP_UP,
|
||||
0.3,
|
||||
6,
|
||||
7
|
||||
)
|
||||
.unwrap()
|
||||
),
|
||||
vec![
|
||||
(23, both(f640, HdAmFmEncoding::amp7(0.5))),
|
||||
(6, 7),
|
||||
(hold, hold)
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decode(HdAmFmEncoding::pack_two_14bit_reach(false, f80, 0.6, 16, 0.3, 6, 6).unwrap()),
|
||||
vec![
|
||||
(both(f80, HdAmFmEncoding::amp7(0.6)), 16),
|
||||
(6, 6),
|
||||
(hold, hold)
|
||||
]
|
||||
);
|
||||
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_reach(true, f640, 0.5, hold, 0.3, 6, 7).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_reach(true, f640, 0.5, 5, 0.3, 6, 7).is_err());
|
||||
assert!(
|
||||
HdAmFmEncoding::pack_two_14bit_reach(true, f640, 0.8, 25, 0.3, hold, hold).is_err()
|
||||
);
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_reach(true, f640, 0.5, 25, 0.3, 23, hold).is_err());
|
||||
assert!(HdAmFmEncoding::pack_two_14bit_reach(true, 0, 0.5, 25, 0.3, hold, hold).is_err());
|
||||
}
|
||||
}
|
||||
590
third_party/renhdrum/src/encoding/click.rs
vendored
Normal file
590
third_party/renhdrum/src/encoding/click.rs
vendored
Normal file
@@ -0,0 +1,590 @@
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HdClickKind {
|
||||
DualResonance3Pulse = 0,
|
||||
SingleWaveResonance = 1,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HdClickSide {
|
||||
pub kind: HdClickKind,
|
||||
pub res_high_code: i32,
|
||||
pub res_low_code: i32,
|
||||
pub pulse1_code: i32,
|
||||
pub pulse2_code: i32,
|
||||
pub res_high_off: bool,
|
||||
pub res_low_off: bool,
|
||||
pub pulse1_off: bool,
|
||||
pub pulse2_off: bool,
|
||||
pub amp7: i32,
|
||||
pub freq7: i32,
|
||||
pub freq_is_high: bool,
|
||||
}
|
||||
|
||||
impl HdClickSide {
|
||||
pub fn silent(kind: HdClickKind) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
res_high_code: 0,
|
||||
res_low_code: 0,
|
||||
pulse1_code: 0,
|
||||
pulse2_code: 0,
|
||||
res_high_off: true,
|
||||
res_low_off: true,
|
||||
pulse1_off: true,
|
||||
pulse2_off: true,
|
||||
amp7: 0,
|
||||
freq7: 0,
|
||||
freq_is_high: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pulse3(amplitude: f32) -> Self {
|
||||
let mut s = Self::silent(HdClickKind::DualResonance3Pulse);
|
||||
s.amp7 = HdClickEncoding::amp7(amplitude);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn pulse1(amplitude: f32) -> Self {
|
||||
let mut s = Self::silent(HdClickKind::DualResonance3Pulse);
|
||||
s.pulse1_code = HdClickEncoding::amp4(amplitude);
|
||||
s.pulse1_off = false;
|
||||
s
|
||||
}
|
||||
|
||||
pub fn pulse2(amplitude: f32) -> Self {
|
||||
let mut s = Self::silent(HdClickKind::DualResonance3Pulse);
|
||||
s.pulse2_code = HdClickEncoding::amp4(amplitude);
|
||||
s.pulse2_off = false;
|
||||
s
|
||||
}
|
||||
|
||||
pub fn x0_pulse1(amplitude: f32) -> Self {
|
||||
let mut s = Self::silent(HdClickKind::SingleWaveResonance);
|
||||
s.pulse1_code = HdClickEncoding::amp4(amplitude);
|
||||
s.pulse1_off = false;
|
||||
s
|
||||
}
|
||||
|
||||
pub fn x0_pulse2(amplitude: f32) -> Self {
|
||||
let mut s = Self::silent(HdClickKind::SingleWaveResonance);
|
||||
s.amp7 = HdClickEncoding::amp7(amplitude);
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HdClickEncoding;
|
||||
|
||||
impl HdClickEncoding {
|
||||
pub const MAX_AMP7: i32 = 100;
|
||||
pub const MIN_CODE4: i32 = 2;
|
||||
pub const MAX_CODE4: i32 = 11;
|
||||
|
||||
pub const AMP4: [f64; 16] = [
|
||||
0.0,
|
||||
1.0,
|
||||
0.713429339,
|
||||
0.510491764,
|
||||
0.364076932,
|
||||
0.263212876,
|
||||
0.187285343,
|
||||
0.128740086,
|
||||
0.096642284,
|
||||
0.065562582,
|
||||
0.047502641,
|
||||
0.035863824,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
];
|
||||
|
||||
pub fn amp4_value(code: i32) -> f64 {
|
||||
Self::AMP4[(code & 0xF) as usize]
|
||||
}
|
||||
|
||||
pub fn amp4(amplitude: f32) -> i32 {
|
||||
if !(amplitude > 0.0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (amplitude as f64) < Self::AMP4[Self::MAX_CODE4 as usize] / 2.0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let mut best = Self::MIN_CODE4;
|
||||
let mut best_diff = f64::MAX;
|
||||
|
||||
for code in Self::MIN_CODE4..=Self::MAX_CODE4 {
|
||||
let diff = (Self::AMP4[code as usize] - amplitude as f64).abs();
|
||||
if diff < best_diff {
|
||||
best = code;
|
||||
best_diff = diff;
|
||||
}
|
||||
}
|
||||
|
||||
best
|
||||
}
|
||||
|
||||
pub fn amp7(amplitude: f32) -> i32 {
|
||||
if !(amplitude > 0.0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let raw = (amplitude.min(1.0) * 127.0).round_ties_even() as i32;
|
||||
raw.clamp(0, Self::MAX_AMP7)
|
||||
}
|
||||
|
||||
pub fn is_dual_wave_side(side: &[u8]) -> bool {
|
||||
if side.len() < 4 {
|
||||
false
|
||||
} else {
|
||||
(side[0] & 0x03) == 0 && (side[3] & 0xC0) == 0x40
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_click_packet(packet: &[u8]) -> bool {
|
||||
if packet.len() < 10 {
|
||||
false
|
||||
} else {
|
||||
!Self::is_dual_wave_side(&packet[2..6]) || !Self::is_dual_wave_side(&packet[6..10])
|
||||
}
|
||||
}
|
||||
|
||||
fn code4(code: i32, off: bool) -> i32 {
|
||||
if off {
|
||||
code & 0xF
|
||||
} else if code <= 0 {
|
||||
0
|
||||
} else {
|
||||
code.clamp(Self::MIN_CODE4, Self::MAX_CODE4)
|
||||
}
|
||||
}
|
||||
|
||||
fn active(code: i32, off: bool) -> bool {
|
||||
!off && code > 0
|
||||
}
|
||||
|
||||
pub fn hd_encode_side_click(dst: &mut [u8], side: &HdClickSide) {
|
||||
if dst.len() < 4 {
|
||||
return;
|
||||
}
|
||||
|
||||
let amp7 = side.amp7.clamp(0, Self::MAX_AMP7);
|
||||
|
||||
let mut any_active = Self::active(side.res_high_code, side.res_high_off)
|
||||
|| Self::active(side.res_low_code, side.res_low_off)
|
||||
|| Self::active(side.pulse1_code, side.pulse1_off)
|
||||
|| amp7 > 0;
|
||||
|
||||
if side.kind == HdClickKind::DualResonance3Pulse {
|
||||
any_active |= Self::active(side.pulse2_code, side.pulse2_off);
|
||||
}
|
||||
|
||||
if !any_active {
|
||||
dst[0] = 0x00;
|
||||
dst[1] = 0x01;
|
||||
dst[2] = 0x40;
|
||||
dst[3] = 0x40;
|
||||
return;
|
||||
}
|
||||
|
||||
let v: u32 = if side.kind == HdClickKind::DualResonance3Pulse {
|
||||
let a = Self::code4(side.res_high_code, side.res_high_off) as u32;
|
||||
let c = Self::code4(side.res_low_code, side.res_low_off) as u32;
|
||||
let e = Self::code4(side.pulse1_code, side.pulse1_off) as u32;
|
||||
let g = Self::code4(side.pulse2_code, side.pulse2_off) as u32;
|
||||
|
||||
0x2u32
|
||||
| (a << 3)
|
||||
| (if side.res_high_off { 1u32 } else { 0u32 } << 7)
|
||||
| (c << 8)
|
||||
| (if side.res_low_off { 1u32 } else { 0u32 } << 12)
|
||||
| ((e & 7u32) << 13)
|
||||
| ((e >> 3) << 16)
|
||||
| (if side.pulse1_off { 1u32 } else { 0u32 } << 17)
|
||||
| (g << 18)
|
||||
| (if side.pulse2_off { 1u32 } else { 0u32 } << 22)
|
||||
| (((amp7 as u32) & 1u32) << 23)
|
||||
| (((amp7 as u32) >> 1) << 24)
|
||||
| (1u32 << 30)
|
||||
} else {
|
||||
let c = Self::code4(side.res_high_code, side.res_high_off) as u32;
|
||||
let e = Self::code4(side.res_low_code, side.res_low_off) as u32;
|
||||
let g = Self::code4(side.pulse1_code, side.pulse1_off) as u32;
|
||||
|
||||
(if side.freq_is_high { 1u32 } else { 0u32 })
|
||||
| ((side.freq7.clamp(0, 127) as u32) << 1)
|
||||
| (c << 8)
|
||||
| (if side.res_high_off { 1u32 } else { 0u32 } << 12)
|
||||
| ((e & 7u32) << 13)
|
||||
| ((e >> 3) << 16)
|
||||
| (if side.res_low_off { 1u32 } else { 0u32 } << 17)
|
||||
| (g << 18)
|
||||
| (if side.pulse1_off { 1u32 } else { 0u32 } << 22)
|
||||
| (((amp7 as u32) & 1u32) << 23)
|
||||
| (((amp7 as u32) >> 1) << 24)
|
||||
};
|
||||
|
||||
dst[0] = (v & 0xFF) as u8;
|
||||
dst[1] = ((v >> 8) & 0xFF) as u8;
|
||||
dst[2] = ((v >> 16) & 0xFF) as u8;
|
||||
dst[3] = ((v >> 24) & 0xFF) as u8;
|
||||
}
|
||||
|
||||
pub fn build_click_packet(packet: &mut [u8], amp_l: f32, amp_r: f32) -> bool {
|
||||
if packet.len() < 10 {
|
||||
return false;
|
||||
}
|
||||
|
||||
packet[0] = 0x10;
|
||||
packet[1] = 0x00;
|
||||
|
||||
let mut any = false;
|
||||
|
||||
for i in 0..2 {
|
||||
let amp = if i == 0 { amp_l } else { amp_r };
|
||||
let side_slice = &mut packet[2 + i * 4..6 + i * 4];
|
||||
|
||||
if Self::amp4(amp) != 0 {
|
||||
Self::hd_encode_side_click(side_slice, &HdClickSide::x0_pulse1(amp));
|
||||
any = true;
|
||||
} else {
|
||||
side_slice[0] = 0x00;
|
||||
side_slice[1] = 0x01;
|
||||
side_slice[2] = 0x40;
|
||||
side_slice[3] = 0x40;
|
||||
}
|
||||
}
|
||||
|
||||
any
|
||||
}
|
||||
|
||||
pub fn try_decode_side_click(side: &[u8]) -> Option<HdClickSide> {
|
||||
if side.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let v = side[0] as u32
|
||||
| ((side[1] as u32) << 8)
|
||||
| ((side[2] as u32) << 16)
|
||||
| ((side[3] as u32) << 24);
|
||||
let top = v >> 30;
|
||||
|
||||
let x0 = (top & 1) == 0;
|
||||
let dual10 = top == 1 && (v & 3) == 2;
|
||||
|
||||
if !x0 && !dual10 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let e = (((v >> 13) & 7u32) | (((v >> 16) & 1u32) << 3)) as i32;
|
||||
let amp7 = (((v >> 23) & 1u32) | (((v >> 24) & 0x3Fu32) << 1)) as i32;
|
||||
|
||||
if dual10 {
|
||||
Some(HdClickSide {
|
||||
kind: HdClickKind::DualResonance3Pulse,
|
||||
res_high_code: ((v >> 3) & 0xF) as i32,
|
||||
res_high_off: ((v >> 7) & 1) != 0,
|
||||
res_low_code: ((v >> 8) & 0xF) as i32,
|
||||
res_low_off: ((v >> 12) & 1) != 0,
|
||||
pulse1_code: e,
|
||||
pulse1_off: ((v >> 17) & 1) != 0,
|
||||
pulse2_code: ((v >> 18) & 0xF) as i32,
|
||||
pulse2_off: ((v >> 22) & 1) != 0,
|
||||
amp7,
|
||||
freq7: 0,
|
||||
freq_is_high: false,
|
||||
})
|
||||
} else {
|
||||
Some(HdClickSide {
|
||||
kind: HdClickKind::SingleWaveResonance,
|
||||
res_high_code: ((v >> 8) & 0xF) as i32,
|
||||
res_high_off: ((v >> 12) & 1) != 0,
|
||||
res_low_code: e,
|
||||
res_low_off: ((v >> 17) & 1) != 0,
|
||||
pulse1_code: ((v >> 18) & 0xF) as i32,
|
||||
pulse1_off: ((v >> 22) & 1) != 0,
|
||||
pulse2_code: 0,
|
||||
pulse2_off: false,
|
||||
amp7,
|
||||
freq7: ((v >> 1) & 0x7F) as i32,
|
||||
freq_is_high: (v & 1) != 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(s: &HdClickSide) -> String {
|
||||
let part = |name: &str, code: i32, off: bool| {
|
||||
if off || code == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {name}={code}")
|
||||
}
|
||||
};
|
||||
|
||||
if s.kind == HdClickKind::DualResonance3Pulse {
|
||||
format!(
|
||||
"01-10{}{}{}{}{}",
|
||||
part("res320", s.res_high_code, s.res_high_off),
|
||||
part("res160", s.res_low_code, s.res_low_off),
|
||||
part("pulse1", s.pulse1_code, s.pulse1_off),
|
||||
part("pulse2", s.pulse2_code, s.pulse2_off),
|
||||
if s.amp7 > 0 {
|
||||
format!(" pulse3={}", s.amp7)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"X0 {}Freq={}{}{}{}{}",
|
||||
if s.freq_is_high { "high" } else { "low" },
|
||||
s.freq7,
|
||||
part("resHigh", s.res_high_code, s.res_high_off),
|
||||
part("resLow", s.res_low_code, s.res_low_off),
|
||||
part("pulse1", s.pulse1_code, s.pulse1_off),
|
||||
if s.amp7 > 0 {
|
||||
format!(" pulse2={}", s.amp7)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::encoding::standard::hd_encode_side;
|
||||
|
||||
fn encode(side: &HdClickSide) -> [u8; 4] {
|
||||
let mut dst = [0u8; 4];
|
||||
HdClickEncoding::hd_encode_side_click(&mut dst, side);
|
||||
dst
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reproduces_nintendo_packet_byte_for_byte() {
|
||||
let side = HdClickSide {
|
||||
kind: HdClickKind::DualResonance3Pulse,
|
||||
res_high_code: 8,
|
||||
res_high_off: true,
|
||||
res_low_code: 8,
|
||||
res_low_off: false,
|
||||
pulse1_code: 14,
|
||||
pulse1_off: true,
|
||||
pulse2_code: 0,
|
||||
pulse2_off: false,
|
||||
amp7: 100,
|
||||
freq7: 0,
|
||||
freq_is_high: false,
|
||||
};
|
||||
|
||||
assert_eq!(encode(&side), [0xC2, 0xC8, 0x03, 0x72]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_nintendo_packet() {
|
||||
let decoded = HdClickEncoding::try_decode_side_click(&[0xC2, 0xC8, 0x03, 0x72]).unwrap();
|
||||
assert_eq!(decoded.kind, HdClickKind::DualResonance3Pulse);
|
||||
assert!(decoded.res_high_off);
|
||||
assert!(!decoded.res_low_off);
|
||||
assert_eq!(decoded.res_low_code, 8);
|
||||
assert_eq!(decoded.pulse1_code, 14);
|
||||
assert!(decoded.pulse1_off);
|
||||
assert_eq!(decoded.pulse2_code, 0);
|
||||
assert_eq!(decoded.amp7, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_nintendo_packet_is_not_a_modelled_type() {
|
||||
let raw = [0xC3, 0xC8, 0x60, 0x64];
|
||||
assert!(HdClickEncoding::try_decode_side_click(&raw).is_none());
|
||||
assert!(!HdClickEncoding::is_dual_wave_side(&raw));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_is_neutral_packet() {
|
||||
let neutral = [0x00, 0x01, 0x40, 0x40];
|
||||
|
||||
assert_eq!(encode(&HdClickSide::pulse3(0.0)), neutral);
|
||||
assert_eq!(encode(&HdClickSide::pulse1(0.0)), neutral);
|
||||
assert_eq!(encode(&HdClickSide::pulse2(-1.0)), neutral);
|
||||
assert_eq!(encode(&HdClickSide::x0_pulse1(f32::NAN)), neutral);
|
||||
assert_eq!(encode(&HdClickSide::x0_pulse2(0.0)), neutral);
|
||||
assert!(HdClickEncoding::is_dual_wave_side(&neutral));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amplitudes_are_clamped_to_the_safe_range() {
|
||||
assert_eq!(HdClickEncoding::amp7(1.0), HdClickEncoding::MAX_AMP7);
|
||||
assert_eq!(HdClickEncoding::amp7(50.0), HdClickEncoding::MAX_AMP7);
|
||||
|
||||
let mut a = 0.0f32;
|
||||
while a <= 2.0 {
|
||||
let code = HdClickEncoding::amp4(a);
|
||||
assert!(
|
||||
code == 0
|
||||
|| (code >= HdClickEncoding::MIN_CODE4 && code <= HdClickEncoding::MAX_CODE4)
|
||||
);
|
||||
assert_ne!(code, 1);
|
||||
a += 0.01;
|
||||
}
|
||||
|
||||
let mut side = HdClickSide::pulse3(1.0);
|
||||
side.amp7 = 127;
|
||||
side.res_low_off = false;
|
||||
side.res_low_code = 1;
|
||||
let bytes = encode(&side);
|
||||
|
||||
let back = HdClickEncoding::try_decode_side_click(&bytes).unwrap();
|
||||
assert_eq!(back.amp7, HdClickEncoding::MAX_AMP7);
|
||||
assert_eq!(back.res_low_code, HdClickEncoding::MIN_CODE4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_bit_code_is_nearest_table_entry() {
|
||||
let cases = [
|
||||
(0.713429339f32, 2),
|
||||
(0.5, 3),
|
||||
(0.1, 8),
|
||||
(0.036, 11),
|
||||
(0.01, 0),
|
||||
];
|
||||
|
||||
for (amplitude, code) in cases {
|
||||
assert_eq!(HdClickEncoding::amp4(amplitude), code);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_field() {
|
||||
let mut pulse3 = 0;
|
||||
while pulse3 <= HdClickEncoding::MAX_AMP7 {
|
||||
for code in HdClickEncoding::MIN_CODE4..=HdClickEncoding::MAX_CODE4 {
|
||||
let mut side = HdClickSide {
|
||||
kind: HdClickKind::DualResonance3Pulse,
|
||||
res_high_code: code,
|
||||
res_low_code: 13 - code,
|
||||
pulse1_code: code,
|
||||
pulse2_code: 12 - code,
|
||||
res_high_off: false,
|
||||
res_low_off: false,
|
||||
pulse1_off: false,
|
||||
pulse2_off: code % 2 == 0,
|
||||
amp7: pulse3,
|
||||
freq7: 0,
|
||||
freq_is_high: false,
|
||||
};
|
||||
side.res_low_code = side.res_low_code.clamp(2, 11);
|
||||
side.pulse2_code = side.pulse2_code.clamp(2, 11);
|
||||
|
||||
let back = HdClickEncoding::try_decode_side_click(&encode(&side)).unwrap();
|
||||
assert_eq!(back.res_high_code, side.res_high_code);
|
||||
assert_eq!(back.res_low_code, side.res_low_code);
|
||||
assert_eq!(back.pulse1_code, side.pulse1_code);
|
||||
assert_eq!(back.pulse2_code, side.pulse2_code);
|
||||
assert_eq!(back.pulse2_off, side.pulse2_off);
|
||||
assert_eq!(back.amp7, side.amp7);
|
||||
}
|
||||
pulse3 += 7;
|
||||
}
|
||||
|
||||
let x0 = HdClickSide {
|
||||
kind: HdClickKind::SingleWaveResonance,
|
||||
freq_is_high: true,
|
||||
freq7: 0x55,
|
||||
res_high_code: 4,
|
||||
res_low_code: 9,
|
||||
pulse1_code: 7,
|
||||
pulse2_code: 0,
|
||||
res_high_off: false,
|
||||
res_low_off: true,
|
||||
pulse1_off: false,
|
||||
pulse2_off: false,
|
||||
amp7: 33,
|
||||
};
|
||||
|
||||
let bytes = encode(&x0);
|
||||
assert_eq!(bytes[3] & 0x40, 0);
|
||||
|
||||
let x0_back = HdClickEncoding::try_decode_side_click(&bytes).unwrap();
|
||||
assert_eq!(x0_back.kind, HdClickKind::SingleWaveResonance);
|
||||
assert!(x0_back.freq_is_high);
|
||||
assert_eq!(x0_back.freq7, 0x55);
|
||||
assert_eq!(x0_back.res_high_code, 4);
|
||||
assert_eq!(x0_back.res_low_code, 9);
|
||||
assert!(x0_back.res_low_off);
|
||||
assert_eq!(x0_back.pulse1_code, 7);
|
||||
assert_eq!(x0_back.amp7, 33);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_sides_are_never_taken_for_the_regular_encoding() {
|
||||
let sides = [
|
||||
HdClickSide::pulse1(0.5),
|
||||
HdClickSide::pulse2(0.5),
|
||||
HdClickSide::pulse3(0.5),
|
||||
HdClickSide::pulse3(1.0),
|
||||
HdClickSide::x0_pulse1(0.5),
|
||||
HdClickSide::x0_pulse2(0.5),
|
||||
HdClickSide::x0_pulse2(1.0),
|
||||
];
|
||||
|
||||
for side in &sides {
|
||||
assert!(!HdClickEncoding::is_dual_wave_side(&encode(side)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_regular_encoding_is_recognised_as_regular() {
|
||||
let mut dst = [0u8; 4];
|
||||
let amps = [
|
||||
0.0f32,
|
||||
0.001,
|
||||
0.01,
|
||||
0.05,
|
||||
0.1,
|
||||
0.2,
|
||||
0.3,
|
||||
0.5,
|
||||
0.7,
|
||||
0.9,
|
||||
1.0,
|
||||
1.5,
|
||||
f32::NAN,
|
||||
];
|
||||
let freqs = [
|
||||
0.0f32, 40.0, 80.0, 100.0, 160.0, 200.0, 320.0, 500.0, 800.0, 1252.0, 5000.0,
|
||||
];
|
||||
|
||||
for &_low in &s {
|
||||
for &_high in &s {
|
||||
for &freq_low in &freqs {
|
||||
for &freq_high in &freqs {
|
||||
hd_encode_side(&mut dst, amp_low, freq_low, amp_high, freq_high);
|
||||
assert!(HdClickEncoding::is_dual_wave_side(&dst));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_is_click_when_either_side_is() {
|
||||
let neutral = [0x00, 0x01, 0x40, 0x40];
|
||||
let click = encode(&HdClickSide::pulse3(0.5));
|
||||
let mut packet = [0u8; 10];
|
||||
packet[0] = 0x10;
|
||||
|
||||
packet[2..6].copy_from_slice(&neutral);
|
||||
packet[6..10].copy_from_slice(&neutral);
|
||||
assert!(!HdClickEncoding::is_click_packet(&packet));
|
||||
|
||||
packet[6..10].copy_from_slice(&click);
|
||||
assert!(HdClickEncoding::is_click_packet(&packet));
|
||||
}
|
||||
}
|
||||
199
third_party/renhdrum/src/encoding/crisp_notes.rs
vendored
Normal file
199
third_party/renhdrum/src/encoding/crisp_notes.rs
vendored
Normal file
@@ -0,0 +1,199 @@
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct HdSideSample {
|
||||
pub amp_low: f32,
|
||||
pub freq_low: f32,
|
||||
pub amp_high: f32,
|
||||
pub freq_high: f32,
|
||||
}
|
||||
|
||||
impl HdSideSample {
|
||||
pub const fn new(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> Self {
|
||||
Self {
|
||||
amp_low,
|
||||
freq_low,
|
||||
amp_high,
|
||||
freq_high,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn silent() -> Self {
|
||||
Self {
|
||||
amp_low: 0.0,
|
||||
freq_low: 160.0,
|
||||
amp_high: 0.0,
|
||||
freq_high: 320.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HdCrispNotes;
|
||||
|
||||
impl HdCrispNotes {
|
||||
/// Accent at a note's start: +3 dB = one 5-bit amplitude code.
|
||||
pub const ACCENT_GAIN: f32 = 1.41;
|
||||
|
||||
/// Dip right after the accent (wired only): -3 dB = one 5-bit amplitude code.
|
||||
pub const DIP_GAIN: f32 = 0.71;
|
||||
|
||||
/// Accent length on the wired path: 2 slots = 10 ms.
|
||||
pub const ACCENT_SLOTS: i32 = 2;
|
||||
|
||||
/// Dip length on the wired path: 6 slots = 30 ms; a longer vibration plays at the game's level afterwards.
|
||||
pub const DIP_SLOTS: i32 = 6;
|
||||
|
||||
/// Gain of the slot `slots_since_onset` slots after a note started (0 = the first sounding slot).
|
||||
pub fn slot_gain(slots_since_onset: i32) -> f32 {
|
||||
if slots_since_onset < 0 {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
if slots_since_onset < Self::ACCENT_SLOTS {
|
||||
return Self::ACCENT_GAIN;
|
||||
}
|
||||
|
||||
if slots_since_onset < Self::ACCENT_SLOTS + Self::DIP_SLOTS {
|
||||
Self::DIP_GAIN
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Both bands times `gain`. A boost is limited so low + high stays within max(1.0, the game's own sum) and each band
|
||||
/// within 1.0; `capped` is true when that limit took part of the boost. Frequencies are kept.
|
||||
pub fn apply(s: &HdSideSample, gain: f32) -> (HdSideSample, bool) {
|
||||
if gain == 1.0 {
|
||||
return (*s, false);
|
||||
}
|
||||
|
||||
let mut r = *s;
|
||||
r.amp_low = 1.0f32.min(s.amp_low * gain);
|
||||
r.amp_high = 1.0f32.min(s.amp_high * gain);
|
||||
|
||||
let mut capped = false;
|
||||
|
||||
if gain > 1.0 {
|
||||
let limit = 1.0f32.max(s.amp_low + s.amp_high);
|
||||
let sum = r.amp_low + r.amp_high;
|
||||
|
||||
if sum > limit {
|
||||
let scale = limit / sum;
|
||||
r.amp_low *= scale;
|
||||
r.amp_high *= scale;
|
||||
}
|
||||
|
||||
capped = r.amp_low < s.amp_low * gain || r.amp_high < s.amp_high * gain;
|
||||
}
|
||||
|
||||
(r, capped)
|
||||
}
|
||||
|
||||
/// Silent like the two-wave encoder sees it (amplitude index 0 on both bands).
|
||||
pub fn is_silent(s: &HdSideSample) -> bool {
|
||||
s.amp_low * 65535.0 < 1.0 && s.amp_high * 65535.0 < 1.0
|
||||
}
|
||||
|
||||
/// One slot of one side on the wired path: follows the note (`slots_since_onset`, -1 while silent) and returns the
|
||||
/// shaped value. `onset` is true for a note's first slot.
|
||||
pub fn shape_slot(slots_since_onset: &mut i32, s: &HdSideSample) -> (HdSideSample, bool, bool) {
|
||||
let mut onset = false;
|
||||
|
||||
if Self::is_silent(s) {
|
||||
*slots_since_onset = -1;
|
||||
return (*s, onset, false);
|
||||
}
|
||||
|
||||
if *slots_since_onset < 0 {
|
||||
*slots_since_onset = 0;
|
||||
onset = true;
|
||||
}
|
||||
|
||||
let gain = Self::slot_gain(*slots_since_onset);
|
||||
|
||||
if *slots_since_onset < Self::ACCENT_SLOTS + Self::DIP_SLOTS {
|
||||
*slots_since_onset += 1;
|
||||
}
|
||||
|
||||
let (shaped, capped) = Self::apply(s, gain);
|
||||
(shaped, onset, capped)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SILENT: HdSideSample = HdSideSample::new(0.0, 160.0, 0.0, 320.0);
|
||||
const LOW160: HdSideSample = HdSideSample::new(0.45, 160.0, 0.0, 320.0);
|
||||
|
||||
#[test]
|
||||
fn accent_and_dip_are_one_five_bit_code_each() {
|
||||
assert!((HdCrispNotes::ACCENT_GAIN - 2.0f32.sqrt()).abs() <= 0.01);
|
||||
assert!((HdCrispNotes::DIP_GAIN - (1.0 / 2.0f32.sqrt())).abs() <= 0.01);
|
||||
assert_eq!(HdCrispNotes::ACCENT_SLOTS * 5, 10);
|
||||
assert_eq!(HdCrispNotes::DIP_SLOTS * 5, 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slot_gain_is_accent_then_dip_then_the_game() {
|
||||
assert_eq!(HdCrispNotes::slot_gain(-1), 1.0);
|
||||
assert_eq!(HdCrispNotes::slot_gain(0), HdCrispNotes::ACCENT_GAIN);
|
||||
assert_eq!(HdCrispNotes::slot_gain(1), HdCrispNotes::ACCENT_GAIN);
|
||||
assert_eq!(HdCrispNotes::slot_gain(2), HdCrispNotes::DIP_GAIN);
|
||||
assert_eq!(HdCrispNotes::slot_gain(7), HdCrispNotes::DIP_GAIN);
|
||||
assert_eq!(HdCrispNotes::slot_gain(8), 1.0);
|
||||
assert_eq!(HdCrispNotes::slot_gain(1000), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accent_never_exceeds_the_motor_limit() {
|
||||
let loud = HdSideSample::new(0.6, 160.0, 0.3, 320.0);
|
||||
let (r, capped) = HdCrispNotes::apply(&loud, HdCrispNotes::ACCENT_GAIN);
|
||||
|
||||
assert!(capped);
|
||||
assert!(r.amp_low + r.amp_high <= 1.0 + 1e-6);
|
||||
assert!((r.amp_low / r.amp_high - 2.0).abs() <= 1e-4);
|
||||
assert_eq!(r.freq_low, 160.0);
|
||||
assert_eq!(r.freq_high, 320.0);
|
||||
|
||||
// Game sends more than 1.0 in total
|
||||
let over = HdSideSample::new(0.7, 160.0, 0.6, 320.0);
|
||||
let (r, capped) = HdCrispNotes::apply(&over, HdCrispNotes::ACCENT_GAIN);
|
||||
assert!(capped);
|
||||
assert!(r.amp_low + r.amp_high <= 1.3 + 1e-6);
|
||||
|
||||
let quiet = HdSideSample::new(0.2, 160.0, 0.1, 320.0);
|
||||
let (r, capped) = HdCrispNotes::apply(&quiet, HdCrispNotes::ACCENT_GAIN);
|
||||
assert!(!capped);
|
||||
assert!((r.amp_low - 0.2 * HdCrispNotes::ACCENT_GAIN).abs() <= 1e-6);
|
||||
|
||||
let (r, capped) = HdCrispNotes::apply(&loud, HdCrispNotes::DIP_GAIN);
|
||||
assert!(!capped);
|
||||
assert!((r.amp_low - 0.6 * HdCrispNotes::DIP_GAIN).abs() <= 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_slot_follows_a_note_and_resets_on_silence() {
|
||||
let mut slots = -1;
|
||||
|
||||
let (_, onset, _) = HdCrispNotes::shape_slot(&mut slots, &SILENT);
|
||||
assert!(!onset);
|
||||
assert_eq!(slots, -1);
|
||||
|
||||
let (first, onset, _) = HdCrispNotes::shape_slot(&mut slots, &LOW160);
|
||||
assert!(onset);
|
||||
assert!((first.amp_low - 0.45 * HdCrispNotes::ACCENT_GAIN).abs() <= 1e-6);
|
||||
|
||||
for _ in 1..(HdCrispNotes::ACCENT_SLOTS + HdCrispNotes::DIP_SLOTS) {
|
||||
let (_, onset, _) = HdCrispNotes::shape_slot(&mut slots, &LOW160);
|
||||
assert!(!onset);
|
||||
}
|
||||
|
||||
let (later, _, _) = HdCrispNotes::shape_slot(&mut slots, &LOW160);
|
||||
assert_eq!(later.amp_low, 0.45);
|
||||
|
||||
HdCrispNotes::shape_slot(&mut slots, &SILENT);
|
||||
let (_, onset, _) = HdCrispNotes::shape_slot(&mut slots, &LOW160);
|
||||
assert!(onset);
|
||||
}
|
||||
}
|
||||
4
third_party/renhdrum/src/encoding/mod.rs
vendored
Normal file
4
third_party/renhdrum/src/encoding/mod.rs
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
pub mod amfm;
|
||||
pub mod click;
|
||||
pub mod crisp_notes;
|
||||
pub mod standard;
|
||||
384
third_party/renhdrum/src/encoding/standard.rs
vendored
Normal file
384
third_party/renhdrum/src/encoding/standard.rs
vendored
Normal file
@@ -0,0 +1,384 @@
|
||||
/// Amplitude thresholds (0..65535) from dekuNukem's rumble data table, same as SDL's tables.
|
||||
pub const HD_AMP_THRESHOLDS: [u16; 101] = [
|
||||
0, 514, 775, 921, 1096, 1303, 1550, 1843, 2192, 2606, 3100, 3686, 4383, 5213, 6199, 7372, 7698,
|
||||
8039, 8395, 8767, 9155, 9560, 9984, 10426, 10887, 11369, 11873, 12398, 12947, 13520, 14119,
|
||||
14744, 15067, 15397, 15734, 16079, 16431, 16790, 17158, 17534, 17918, 18310, 18711, 19121,
|
||||
19540, 19967, 20405, 20851, 21308, 21775, 22251, 22739, 23236, 23745, 24265, 24797, 25340,
|
||||
25894, 26462, 27041, 27633, 28238, 28856, 29488, 30134, 30794, 31468, 32157, 32861, 33581,
|
||||
34316, 35068, 35836, 36620, 37422, 38242, 39079, 39935, 40809, 41703, 42616, 43549, 44503,
|
||||
45477, 46473, 47491, 48531, 49593, 50679, 51789, 52923, 54082, 55266, 56476, 57713, 58977,
|
||||
60268, 61588, 62936, 64315, 65535,
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct HdBtLevel {
|
||||
pub level: i32,
|
||||
pub name: &'static str,
|
||||
pub spacing_ms: i32,
|
||||
pub burst: f64,
|
||||
pub refill_ms: f64,
|
||||
pub amp_steps: i32,
|
||||
pub high_freq: i32,
|
||||
pub low_freq: i32,
|
||||
pub stop_priority: bool,
|
||||
/// Send the newest sample instead of the held peak (level 4).
|
||||
pub send_latest: bool,
|
||||
/// Re-send a still-rumbling packet after this many ms; 0 = never.
|
||||
pub resend_ms: i32,
|
||||
}
|
||||
|
||||
pub const HD_BT_LEVELS: [HdBtLevel; 4] = [
|
||||
HdBtLevel {
|
||||
level: 1,
|
||||
name: "Stable",
|
||||
spacing_ms: 60,
|
||||
burst: 2.0,
|
||||
refill_ms: 100.0,
|
||||
amp_steps: 2,
|
||||
high_freq: 16,
|
||||
low_freq: 4,
|
||||
stop_priority: false,
|
||||
send_latest: false,
|
||||
resend_ms: 0,
|
||||
},
|
||||
HdBtLevel {
|
||||
level: 2,
|
||||
name: "Balanced",
|
||||
spacing_ms: 45,
|
||||
burst: 3.0,
|
||||
refill_ms: 80.0,
|
||||
amp_steps: 1,
|
||||
high_freq: 8,
|
||||
low_freq: 2,
|
||||
stop_priority: true,
|
||||
send_latest: false,
|
||||
resend_ms: 0,
|
||||
},
|
||||
HdBtLevel {
|
||||
level: 3,
|
||||
name: "Quality",
|
||||
spacing_ms: 35,
|
||||
burst: 4.0,
|
||||
refill_ms: 65.0,
|
||||
amp_steps: 0,
|
||||
high_freq: 4,
|
||||
low_freq: 1,
|
||||
stop_priority: true,
|
||||
send_latest: false,
|
||||
resend_ms: 0,
|
||||
},
|
||||
// amp_steps / freq 0: any change counts as real (hd_is_small_change only skips diffs <= these).
|
||||
HdBtLevel {
|
||||
level: 4,
|
||||
name: "Compatible",
|
||||
spacing_ms: 32,
|
||||
burst: 1.0,
|
||||
refill_ms: 32.0,
|
||||
amp_steps: 0,
|
||||
high_freq: 0,
|
||||
low_freq: 0,
|
||||
stop_priority: true,
|
||||
send_latest: true,
|
||||
resend_ms: 40,
|
||||
},
|
||||
];
|
||||
|
||||
#[inline]
|
||||
pub fn hd_amp_index(amplitude: f32) -> usize {
|
||||
if !(amplitude > 0.0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let raw = (amplitude.min(1.0) * 65535.0) as u16;
|
||||
|
||||
HD_AMP_THRESHOLDS
|
||||
.partition_point(|&threshold| threshold < raw)
|
||||
.min(HD_AMP_THRESHOLDS.len() - 1)
|
||||
}
|
||||
|
||||
pub fn hd_encode_side(
|
||||
dst: &mut [u8; 4],
|
||||
mut amp_low: f32,
|
||||
mut freq_low: f32,
|
||||
mut amp_high: f32,
|
||||
mut freq_high: f32,
|
||||
) {
|
||||
// Motor protection: when both bands together exceed full scale, scale them down proportionally.
|
||||
if amp_low > 0.0 && amp_high > 0.0 && amp_low + amp_high > 1.0 {
|
||||
let scale = 1.0 / (amp_low + amp_high);
|
||||
amp_low *= scale;
|
||||
amp_high *= scale;
|
||||
}
|
||||
|
||||
let hi_idx = hd_amp_index(amp_high);
|
||||
let lo_idx = hd_amp_index(amp_low);
|
||||
|
||||
if hi_idx == 0 && lo_idx == 0 {
|
||||
// Neutral (no vibration)
|
||||
dst[0] = 0x00;
|
||||
dst[1] = 0x01;
|
||||
dst[2] = 0x40;
|
||||
dst[3] = 0x40;
|
||||
return;
|
||||
}
|
||||
|
||||
if !(freq_high > 0.0) {
|
||||
freq_high = 320.0;
|
||||
}
|
||||
|
||||
if !(freq_low > 0.0) {
|
||||
freq_low = 160.0;
|
||||
}
|
||||
|
||||
// Frequency encoding: round(log2(f / 10) * 32)
|
||||
// C# uses Math.Round(double) which is Round Ties to Even.
|
||||
let hf_round = ((freq_high as f64 / 10.0).log2() * 32.0).round_ties_even() as i32;
|
||||
let lf_round = ((freq_low as f64 / 10.0).log2() * 32.0).round_ties_even() as i32;
|
||||
|
||||
let hf = (hf_round - 0x60) * 4;
|
||||
let lf = lf_round - 0x40;
|
||||
|
||||
let hf = hf.clamp(0x00, 0x1FC);
|
||||
let lf = lf.clamp(0x01, 0x7F);
|
||||
|
||||
let hf_amp = (hi_idx * 2) as i32;
|
||||
let lf_amp = (if (lo_idx & 1) != 0 { 0x8000 } else { 0 }) | (0x40 + lo_idx / 2) as i32;
|
||||
|
||||
dst[0] = (hf & 0xFF) as u8;
|
||||
dst[1] = (hf_amp | ((hf >> 8) & 0x01)) as u8;
|
||||
dst[2] = (lf | ((lf_amp >> 8) & 0x80)) as u8;
|
||||
dst[3] = (lf_amp & 0xFF) as u8;
|
||||
}
|
||||
|
||||
pub fn hd_encode_packet(
|
||||
left_lf: f32,
|
||||
left_la: f32,
|
||||
left_hf: f32,
|
||||
left_ha: f32,
|
||||
right_lf: f32,
|
||||
right_la: f32,
|
||||
right_hf: f32,
|
||||
right_ha: f32,
|
||||
dst: &mut [u8; 8],
|
||||
) {
|
||||
let mut left_side = [0u8; 4];
|
||||
let mut right_side = [0u8; 4];
|
||||
hd_encode_side(&mut left_side, left_la, left_lf, left_ha, left_hf);
|
||||
hd_encode_side(&mut right_side, right_la, right_lf, right_ha, right_hf);
|
||||
dst[0..4].copy_from_slice(&left_side);
|
||||
dst[4..8].copy_from_slice(&right_side);
|
||||
}
|
||||
|
||||
pub fn hd_is_neutral(side: &[u8]) -> bool {
|
||||
if side.len() < 4 {
|
||||
return false;
|
||||
}
|
||||
(side[1] & 0xFE) == 0 && side[3] == 0x40 && (side[2] & 0x80) == 0
|
||||
}
|
||||
|
||||
pub fn hd_is_silent_packet(packet: &[u8]) -> bool {
|
||||
let offset = if packet.len() >= 10 { 2 } else { 0 };
|
||||
if packet.len() >= offset + 8 {
|
||||
hd_is_neutral(&packet[offset..offset + 4]) && hd_is_neutral(&packet[offset + 4..offset + 8])
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hd_is_small_change(old_packet: &[u8], new_packet: &[u8], level: &HdBtLevel) -> bool {
|
||||
let offset_start = if old_packet.len() >= 10 && new_packet.len() >= 10 {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if old_packet.len() < offset_start + 8 || new_packet.len() < offset_start + 8 {
|
||||
return false;
|
||||
}
|
||||
|
||||
for offset in (offset_start..=offset_start + 4).step_by(4) {
|
||||
let a = &old_packet[offset..offset + 4];
|
||||
let b = &new_packet[offset..offset + 4];
|
||||
|
||||
let a_neutral = hd_is_neutral(a);
|
||||
let b_neutral = hd_is_neutral(b);
|
||||
|
||||
if a_neutral != b_neutral {
|
||||
return false;
|
||||
}
|
||||
|
||||
if a_neutral {
|
||||
continue;
|
||||
}
|
||||
|
||||
let a_hf = a[0] as i32 | (((a[1] & 1) as i32) << 8);
|
||||
let b_hf = b[0] as i32 | (((b[1] & 1) as i32) << 8);
|
||||
let a_hf_amp = (a[1] >> 1) as i32;
|
||||
let b_hf_amp = (b[1] >> 1) as i32;
|
||||
let a_lf = (a[2] & 0x7F) as i32;
|
||||
let b_lf = (b[2] & 0x7F) as i32;
|
||||
let a_lf_amp = ((a[3] as i32 - 0x40) * 2) + if (a[2] & 0x80) != 0 { 1 } else { 0 };
|
||||
let b_lf_amp = ((b[3] as i32 - 0x40) * 2) + if (b[2] & 0x80) != 0 { 1 } else { 0 };
|
||||
|
||||
if (a_hf_amp - b_hf_amp).abs() > level.amp_steps
|
||||
|| (a_lf_amp - b_lf_amp).abs() > level.amp_steps
|
||||
|| (a_hf - b_hf).abs() > level.high_freq
|
||||
|| (a_lf - b_lf).abs() > level.low_freq
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> [u8; 4] {
|
||||
let mut dst = [0u8; 4];
|
||||
hd_encode_side(&mut dst, amp_low, freq_low, amp_high, freq_high);
|
||||
dst
|
||||
}
|
||||
|
||||
fn high_freq(side: &[u8; 4]) -> i32 {
|
||||
side[0] as i32 | (((side[1] & 0x01) as i32) << 8)
|
||||
}
|
||||
|
||||
fn high_amp(side: &[u8; 4]) -> i32 {
|
||||
(side[1] & 0xFE) as i32
|
||||
}
|
||||
|
||||
fn low_freq(side: &[u8; 4]) -> i32 {
|
||||
(side[2] & 0x7F) as i32
|
||||
}
|
||||
|
||||
fn low_amp(side: &[u8; 4]) -> i32 {
|
||||
(((side[2] & 0x80) as i32) << 8) | (side[3] as i32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_amplitude_is_neutral_packet() {
|
||||
assert_eq!(encode(0.0, 160.0, 0.0, 320.0), [0x00, 0x01, 0x40, 0x40]);
|
||||
assert_eq!(encode(0.0, 0.0, 0.0, 0.0), [0x00, 0x01, 0x40, 0x40]);
|
||||
assert_eq!(
|
||||
encode(-1.0, 160.0, f32::NAN, 320.0),
|
||||
[0x00, 0x01, 0x40, 0x40]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amplitude_matches_table() {
|
||||
let cases = [
|
||||
(0.0078f32, 0x02, 0x8040),
|
||||
(0.0118, 0x04, 0x0041),
|
||||
(0.1226, 0x22, 0x8048),
|
||||
(0.2562, 0x4A, 0x8052),
|
||||
(0.5014, 0x88, 0x0062),
|
||||
(0.9813, 0xC6, 0x8071),
|
||||
(1.0, 0xC8, 0x0072),
|
||||
];
|
||||
|
||||
for (amplitude, high_a, low_a) in cases {
|
||||
let high = encode(0.0, 160.0, amplitude, 320.0);
|
||||
assert_eq!(high_amp(&high), high_a, "high band for {amplitude}");
|
||||
assert_eq!(
|
||||
low_amp(&high),
|
||||
0x0040,
|
||||
"low band stays silent for {amplitude}"
|
||||
);
|
||||
|
||||
let low = encode(amplitude, 160.0, 0.0, 320.0);
|
||||
assert_eq!(low_amp(&low), low_a, "low band for {amplitude}");
|
||||
assert_eq!(high_amp(&low), 0, "high band stays silent for {amplitude}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amplitude_above_one_is_capped_at_table_max() {
|
||||
assert_eq!(high_amp(&encode(0.0, 160.0, 1.5, 320.0)), 0xC8);
|
||||
assert_eq!(low_amp(&encode(3.0, 160.0, 0.0, 320.0)), 0x0072);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_frequency_matches_table() {
|
||||
let cases = [
|
||||
(40.0f32, 0x01),
|
||||
(40.875885, 0x01),
|
||||
(80.0, 0x20),
|
||||
(160.0, 0x40),
|
||||
(320.0, 0x60),
|
||||
];
|
||||
|
||||
for (frequency, expected_low_f) in cases {
|
||||
assert_eq!(
|
||||
low_freq(&encode(0.5014, frequency, 0.0, 320.0)),
|
||||
expected_low_f
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_frequency_matches_table() {
|
||||
let cases = [
|
||||
(160.0f32, 0x0080),
|
||||
(320.0, 0x0100),
|
||||
(1252.0, 0x01FC),
|
||||
(1252.5723, 0x01FC),
|
||||
(3000.0, 0x01FC),
|
||||
];
|
||||
|
||||
for (frequency, expected_high_f) in cases {
|
||||
assert_eq!(
|
||||
high_freq(&encode(0.0, 160.0, 0.5014, frequency)),
|
||||
expected_high_f
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_side_combines_both_bands() {
|
||||
assert_eq!(
|
||||
encode(0.2562, 160.0, 0.5014, 320.0),
|
||||
[0x00, 0x89, 0xC0, 0x52]
|
||||
);
|
||||
assert_eq!(encode(1.0, 40.0, 0.0, 0.0), [0x00, 0x01, 0x01, 0x72]);
|
||||
assert_eq!(encode(0.0, 0.0, 1.0, 1252.0), [0xFC, 0xC9, 0x40, 0x40]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_frequency_falls_back_to_defaults() {
|
||||
assert_eq!(
|
||||
encode(0.5014, 0.0, 0.2562, 0.0),
|
||||
encode(0.5014, 160.0, 0.2562, 320.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_bands_are_clamped_to_full_scale() {
|
||||
let clamped = encode(0.8, 160.0, 0.8, 320.0);
|
||||
assert_eq!(clamped, encode(0.5, 160.0, 0.5, 320.0));
|
||||
assert_eq!(high_amp(&clamped), 0x88);
|
||||
assert_eq!(low_amp(&clamped), 0x0062);
|
||||
|
||||
assert_eq!(encode(0.6, 160.0, 0.6, 320.0), clamped);
|
||||
assert!(high_amp(&encode(0.0, 160.0, 0.6, 320.0)) > 0x88);
|
||||
|
||||
assert_eq!(
|
||||
encode(1.5, 160.0, 0.5, 320.0),
|
||||
encode(0.75, 160.0, 0.25, 320.0)
|
||||
);
|
||||
|
||||
assert_eq!(high_amp(&encode(0.4986, 160.0, 0.5014, 320.0)), 0x88);
|
||||
assert_eq!(
|
||||
low_amp(&encode(0.4986, 160.0, 0.5014, 320.0)),
|
||||
low_amp(&encode(0.4986, 160.0, 0.0, 320.0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_band_is_never_scaled() {
|
||||
assert_eq!(high_amp(&encode(0.0, 160.0, 1.0, 320.0)), 0xC8);
|
||||
assert_eq!(low_amp(&encode(1.0, 160.0, 0.0, 320.0)), 0x0072);
|
||||
}
|
||||
}
|
||||
2424
third_party/renhdrum/src/ffi.rs
vendored
Normal file
2424
third_party/renhdrum/src/ffi.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
822
third_party/renhdrum/src/ipc.rs
vendored
Normal file
822
third_party/renhdrum/src/ipc.rs
vendored
Normal file
@@ -0,0 +1,822 @@
|
||||
//! Shared-memory layout between Brontide-App (GUI) and `renhdrum.dll` (running inside the
|
||||
//! emulator), plus the reader side that lives in the DLL.
|
||||
//!
|
||||
//! The struct is exactly 4096 bytes (guardrail): new fields must come out of `_reserved`.
|
||||
//! Writer (App) publishes `config` with a seqlock on `config_sequence` (odd = writing).
|
||||
|
||||
use crate::ffi::RenHdcConfig;
|
||||
use crate::settings::RumbleConfigController;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{fence, AtomicU32, AtomicU64, Ordering};
|
||||
|
||||
pub const SHMEM_MAGIC: u32 = 0x5248444D; // "RHDM"
|
||||
pub const SHMEM_VERSION: u32 = 3;
|
||||
pub const SHMEM_NAME: &str = "Local\\RenHDrum_SharedState_v1";
|
||||
pub const HOOK_MODE_RENHDRUM: u32 = 4;
|
||||
pub const EMULATOR_EDEN: u32 = 1;
|
||||
|
||||
/// Live telemetry & diagnostics collected from injected hooks.
|
||||
#[repr(C)]
|
||||
pub struct DiagnosticTelemetry {
|
||||
pub samples_received: AtomicU64,
|
||||
pub packets_sent: AtomicU64,
|
||||
pub emu_rumble_suppressed: AtomicU64,
|
||||
pub last_sample_freq_hz: AtomicU32,
|
||||
pub last_sample_amp: AtomicU32,
|
||||
/// 0 = Idle, 1 = SDL3, 2 = WriteFile HID, 3 = Harmony, 4 = renhdrum.dll (eden-hdr)
|
||||
pub hook_mode: AtomicU32,
|
||||
pub error_count: AtomicU32,
|
||||
pub last_update_unix_ms: AtomicU64,
|
||||
pub _pad: [u8; 16],
|
||||
}
|
||||
|
||||
impl Default for DiagnosticTelemetry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl DiagnosticTelemetry {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
samples_received: AtomicU64::new(0),
|
||||
packets_sent: AtomicU64::new(0),
|
||||
emu_rumble_suppressed: AtomicU64::new(0),
|
||||
last_sample_freq_hz: AtomicU32::new(0),
|
||||
last_sample_amp: AtomicU32::new(0),
|
||||
hook_mode: AtomicU32::new(0),
|
||||
error_count: AtomicU32::new(0),
|
||||
last_update_unix_ms: AtomicU64::new(0),
|
||||
_pad: [0; 16],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: the App's copy derived serde Serialize/Deserialize here. RenHDrum has no
|
||||
// dependencies, so the derive is dropped; renhdrum-ipc must re-add it if it needs it.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct BlackboxSampleEntry {
|
||||
pub timestamp_ms: u32, // Sample arrival timestamp (ms since runtime start)
|
||||
pub dt_us: u32, // Elapsed time since preceding sample (microseconds)
|
||||
pub low_freq: f32, // Low-band frequency (Hz)
|
||||
pub low_amp: f32, // Low-band amplitude (0.0 - 1.0)
|
||||
pub high_freq: f32, // High-band frequency (Hz)
|
||||
pub high_amp: f32, // High-band amplitude (0.0 - 1.0)
|
||||
pub packet_head: [u8; 6], // First 6 bytes of encoded 0x10 packet dispatched to controller
|
||||
pub flags: u16, // bit 0: sent_to_hid, bit 1: is_fallback, bit 2: is_bt, bit 3: write_ok
|
||||
}
|
||||
|
||||
const _: () = assert!(std::mem::size_of::<BlackboxSampleEntry>() == 32);
|
||||
|
||||
/// 4096-byte Shared Memory structure mapped between GUI and Emulator hooks.
|
||||
#[repr(C)]
|
||||
pub struct RenHDrumSharedMemory {
|
||||
pub magic: u32,
|
||||
pub struct_version: u32,
|
||||
pub config_sequence: AtomicU32,
|
||||
pub override_emulator_rumble: bool,
|
||||
pub _pad1: [u8; 3],
|
||||
pub config: RenHdcConfig,
|
||||
pub active_emulator_pid: AtomicU32,
|
||||
pub _pad2: [u8; 4],
|
||||
pub active_title_id: AtomicU64,
|
||||
pub player1_status_utf8: [u8; 256],
|
||||
pub play_report_utf8: [u8; 512],
|
||||
pub telemetry: DiagnosticTelemetry,
|
||||
pub diag_emulator_type: AtomicU32, // 0 = None, 1 = Eden (C++/SDL3), 2 = Ryubing (.NET/Harmony)
|
||||
pub diag_controller_vid_pid: AtomicU32, // High byte = VID, Low byte = PID
|
||||
pub diag_hid_write_errors: AtomicU32, // Number of failed WriteFile / SDL calls
|
||||
pub diag_last_win32_error: AtomicU32, // Latest GetLastError()
|
||||
pub diag_min_interval_us: AtomicU32, // Minimum interval between packets
|
||||
pub diag_max_interval_us: AtomicU32, // Maximum interval between packets
|
||||
pub blackbox_write_idx: AtomicU32, // Ring-buffer write index
|
||||
pub _pad3: [u8; 4],
|
||||
pub blackbox_samples: [BlackboxSampleEntry; 32],
|
||||
pub _reserved: [u8; 4096
|
||||
- 16
|
||||
- std::mem::size_of::<RenHdcConfig>()
|
||||
- 4
|
||||
- 4
|
||||
- 8
|
||||
- 256
|
||||
- 512
|
||||
- std::mem::size_of::<DiagnosticTelemetry>()
|
||||
- 28
|
||||
- 4
|
||||
- (32 * std::mem::size_of::<BlackboxSampleEntry>())],
|
||||
}
|
||||
|
||||
// Compile-time assertion that the struct is exactly 4096 bytes and offsets are consistent
|
||||
const _: () = assert!(std::mem::size_of::<RenHDrumSharedMemory>() == 4096);
|
||||
const _: () = assert!(std::mem::offset_of!(RenHDrumSharedMemory, config) == 16);
|
||||
const _: () = assert!(std::mem::offset_of!(RenHDrumSharedMemory, active_emulator_pid) == 64);
|
||||
const _: () = assert!(std::mem::offset_of!(RenHDrumSharedMemory, telemetry) == 848);
|
||||
const _: () = assert!(std::mem::offset_of!(RenHDrumSharedMemory, diag_emulator_type) == 912);
|
||||
const _: () = assert!(std::mem::offset_of!(RenHDrumSharedMemory, blackbox_samples) == 944);
|
||||
|
||||
impl RenHDrumSharedMemory {
|
||||
pub fn init(&mut self) {
|
||||
self.magic = SHMEM_MAGIC;
|
||||
self.struct_version = SHMEM_VERSION;
|
||||
self.config_sequence = AtomicU32::new(0); // even = nobody is writing
|
||||
self.override_emulator_rumble = true;
|
||||
self._pad1 = [0; 3];
|
||||
self.config = RenHdcConfig::from(&RumbleConfigController::default());
|
||||
self.active_emulator_pid = AtomicU32::new(0);
|
||||
self._pad2 = [0; 4];
|
||||
self.active_title_id = AtomicU64::new(0);
|
||||
self.player1_status_utf8 = [0; 256];
|
||||
self.play_report_utf8 = [0; 512];
|
||||
self.telemetry = DiagnosticTelemetry::new();
|
||||
self.diag_emulator_type = AtomicU32::new(0);
|
||||
self.diag_controller_vid_pid = AtomicU32::new(0);
|
||||
self.diag_hid_write_errors = AtomicU32::new(0);
|
||||
self.diag_last_win32_error = AtomicU32::new(0);
|
||||
self.diag_min_interval_us = AtomicU32::new(u32::MAX);
|
||||
self.diag_max_interval_us = AtomicU32::new(0);
|
||||
self.blackbox_write_idx = AtomicU32::new(0);
|
||||
self._pad3 = [0; 4];
|
||||
self.blackbox_samples = [BlackboxSampleEntry::default(); 32];
|
||||
self._reserved = [0; _];
|
||||
}
|
||||
|
||||
/// Records a blackbox sample into the 32-entry circular buffer.
|
||||
pub fn record_blackbox_sample(&self, sample: BlackboxSampleEntry) {
|
||||
let idx = self.blackbox_write_idx.fetch_add(1, Ordering::Relaxed);
|
||||
let slot = (idx % 32) as usize;
|
||||
unsafe {
|
||||
let ptr = self.blackbox_samples.as_ptr() as *mut BlackboxSampleEntry;
|
||||
ptr.add(slot).write_volatile(sample);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads up to 32 blackbox samples from oldest to newest.
|
||||
pub fn get_blackbox_samples(&self) -> Vec<BlackboxSampleEntry> {
|
||||
let total_written = self.blackbox_write_idx.load(Ordering::Relaxed);
|
||||
let mut samples = Vec::with_capacity(32);
|
||||
let count = (total_written as usize).min(32);
|
||||
for i in 0..count {
|
||||
let idx = if total_written <= 32 {
|
||||
i
|
||||
} else {
|
||||
let start = (total_written as usize) - 32;
|
||||
(start + i) % 32
|
||||
};
|
||||
unsafe {
|
||||
let ptr = self.blackbox_samples.as_ptr();
|
||||
samples.push(ptr.add(idx).read_volatile());
|
||||
}
|
||||
}
|
||||
samples
|
||||
}
|
||||
|
||||
/// Sets the status string (null-terminated UTF-8).
|
||||
pub fn set_status(&mut self, status: &str) {
|
||||
let bytes = status.as_bytes();
|
||||
let copy_len = bytes.len().min(self.player1_status_utf8.len() - 1);
|
||||
self.player1_status_utf8[..copy_len].copy_from_slice(&bytes[..copy_len]);
|
||||
self.player1_status_utf8[copy_len] = 0;
|
||||
}
|
||||
|
||||
/// Reads the status string as a Rust String.
|
||||
pub fn get_status(&self) -> String {
|
||||
let len = self
|
||||
.player1_status_utf8
|
||||
.iter()
|
||||
.position(|&b| b == 0)
|
||||
.unwrap_or(self.player1_status_utf8.len());
|
||||
String::from_utf8_lossy(&self.player1_status_utf8[..len]).to_string()
|
||||
}
|
||||
|
||||
/// Sets the play report string (null-terminated UTF-8).
|
||||
pub fn set_play_report(&mut self, report: &str) {
|
||||
let bytes = report.as_bytes();
|
||||
let copy_len = bytes.len().min(self.play_report_utf8.len() - 1);
|
||||
self.play_report_utf8[..copy_len].copy_from_slice(&bytes[..copy_len]);
|
||||
self.play_report_utf8[copy_len] = 0;
|
||||
}
|
||||
|
||||
/// Reads the play report string as a Rust String.
|
||||
pub fn get_play_report(&self) -> String {
|
||||
let len = self
|
||||
.play_report_utf8
|
||||
.iter()
|
||||
.position(|&b| b == 0)
|
||||
.unwrap_or(self.play_report_utf8.len());
|
||||
String::from_utf8_lossy(&self.play_report_utf8[..len]).to_string()
|
||||
}
|
||||
|
||||
/// Publishes a new configuration (seqlock writer: odd while writing, even when done).
|
||||
pub fn update_config(&mut self, new_config: RenHdcConfig) {
|
||||
self.config_sequence.fetch_add(1, Ordering::AcqRel); // odd: writing
|
||||
fence(Ordering::Release);
|
||||
unsafe { std::ptr::write_volatile(&mut self.config, new_config) };
|
||||
self.config_sequence.fetch_add(1, Ordering::Release); // even: done
|
||||
}
|
||||
|
||||
/// Seqlock reader: returns a consistent copy of the config, or `None` if a writer
|
||||
/// kept interfering after a few attempts.
|
||||
pub fn read_config(&self) -> Option<RenHdcConfig> {
|
||||
for _ in 0..8 {
|
||||
let s1 = self.config_sequence.load(Ordering::Acquire);
|
||||
if s1 & 1 == 1 {
|
||||
std::hint::spin_loop();
|
||||
continue;
|
||||
}
|
||||
let c = unsafe { std::ptr::read_volatile(&self.config) };
|
||||
fence(Ordering::Acquire);
|
||||
if self.config_sequence.load(Ordering::Relaxed) == s1 {
|
||||
return Some(c);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reader side (inside renhdrum.dll, Windows only)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(windows)]
|
||||
mod win {
|
||||
use super::*;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::AtomicPtr;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
const FILE_MAP_ALL_ACCESS: u32 = 0xF001F;
|
||||
|
||||
extern "system" {
|
||||
fn OpenFileMappingW(access: u32, inherit: i32, name: *const u16) -> *mut c_void;
|
||||
fn MapViewOfFile(
|
||||
h: *mut c_void,
|
||||
access: u32,
|
||||
hi: u32,
|
||||
lo: u32,
|
||||
bytes: usize,
|
||||
) -> *mut c_void;
|
||||
fn UnmapViewOfFile(base: *const c_void) -> i32;
|
||||
fn CloseHandle(h: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
static SHARED: AtomicPtr<RenHDrumSharedMemory> = AtomicPtr::new(std::ptr::null_mut());
|
||||
static LAST_TRY_MS: AtomicU64 = AtomicU64::new(0);
|
||||
static LAST_SAMPLE_US: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Opens the named mapping and validates magic + version. `None` on any mismatch.
|
||||
pub(super) fn open_named(name: &str) -> Option<*mut RenHDrumSharedMemory> {
|
||||
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
unsafe {
|
||||
let h = OpenFileMappingW(FILE_MAP_ALL_ACCESS, 0, wide.as_ptr());
|
||||
if h.is_null() {
|
||||
return None;
|
||||
}
|
||||
let view = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 4096);
|
||||
if view.is_null() {
|
||||
CloseHandle(h);
|
||||
return None;
|
||||
}
|
||||
let p = view as *mut RenHDrumSharedMemory;
|
||||
if (*p).magic != SHMEM_MAGIC || (*p).struct_version != SHMEM_VERSION {
|
||||
UnmapViewOfFile(view);
|
||||
CloseHandle(h);
|
||||
return None;
|
||||
}
|
||||
// ponytail: mapping lives for the process; App restarts reuse it
|
||||
Some(p)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shared() -> Option<&'static RenHDrumSharedMemory> {
|
||||
// Unit tests must not read or write a real App running on this machine
|
||||
if cfg!(test) {
|
||||
return None;
|
||||
}
|
||||
let p = SHARED.load(Ordering::Acquire);
|
||||
if !p.is_null() {
|
||||
return Some(unsafe { &*p });
|
||||
}
|
||||
let now = now_ms();
|
||||
let last = LAST_TRY_MS.load(Ordering::Relaxed);
|
||||
if last != 0 && now.saturating_sub(last) < 1000 {
|
||||
return None;
|
||||
}
|
||||
LAST_TRY_MS.store(now, Ordering::Relaxed);
|
||||
let p = open_named(SHMEM_NAME)?;
|
||||
match SHARED.compare_exchange(std::ptr::null_mut(), p, Ordering::AcqRel, Ordering::Acquire)
|
||||
{
|
||||
Ok(_) => {
|
||||
let r = unsafe { &*p };
|
||||
r.active_emulator_pid
|
||||
.store(std::process::id(), Ordering::Relaxed);
|
||||
r.diag_emulator_type.store(EMULATOR_EDEN, Ordering::Relaxed);
|
||||
r.telemetry
|
||||
.hook_mode
|
||||
.store(HOOK_MODE_RENHDRUM, Ordering::Relaxed);
|
||||
Some(r)
|
||||
}
|
||||
Err(existing) => {
|
||||
// Lost the race: release our duplicate view (its handle stays open, harmless).
|
||||
unsafe { UnmapViewOfFile(p as *const c_void) };
|
||||
Some(unsafe { &*existing })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn note_sample(now_us: u64, al: f32, fl: f32, ah: f32, fh: f32) {
|
||||
let Some(s) = shared() else { return };
|
||||
s.telemetry.samples_received.fetch_add(1, Ordering::Relaxed);
|
||||
s.telemetry
|
||||
.last_sample_freq_hz
|
||||
.store(fl.max(fh) as u32, Ordering::Relaxed);
|
||||
s.telemetry
|
||||
.last_sample_amp
|
||||
.store((al.max(ah) * 100.0) as u32, Ordering::Relaxed);
|
||||
let prev = LAST_SAMPLE_US.swap(now_us, Ordering::Relaxed);
|
||||
let dt_us = if prev == 0 {
|
||||
0
|
||||
} else {
|
||||
now_us.saturating_sub(prev) as u32
|
||||
};
|
||||
s.record_blackbox_sample(BlackboxSampleEntry {
|
||||
timestamp_ms: (now_us / 1000) as u32,
|
||||
dt_us,
|
||||
low_freq: fl,
|
||||
low_amp: al,
|
||||
high_freq: fh,
|
||||
high_amp: ah,
|
||||
packet_head: [0; 6],
|
||||
flags: 0,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn note_packet(_packet: &[u8; 10]) {
|
||||
let Some(s) = shared() else { return };
|
||||
s.telemetry.packets_sent.fetch_add(1, Ordering::Relaxed);
|
||||
s.telemetry
|
||||
.last_update_unix_ms
|
||||
.store(now_ms(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn note_controller(is_bluetooth: bool, is_pro: bool) {
|
||||
if shared().is_none() {
|
||||
return;
|
||||
}
|
||||
let p = SHARED.load(Ordering::Acquire);
|
||||
if p.is_null() {
|
||||
return;
|
||||
}
|
||||
let status = match (is_pro, is_bluetooth) {
|
||||
(true, true) => "Pro Controller · Bluetooth",
|
||||
(true, false) => "Pro Controller · USB",
|
||||
(false, true) => "Joy-Con · Bluetooth",
|
||||
(false, false) => "Joy-Con · USB",
|
||||
};
|
||||
unsafe {
|
||||
(*p).set_status(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mapped App shared memory, if the App is running (retries at most once per second).
|
||||
#[cfg(windows)]
|
||||
pub fn shared() -> Option<&'static RenHDrumSharedMemory> {
|
||||
win::shared()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn shared() -> Option<&'static RenHDrumSharedMemory> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Path to the settings file read by renhdrum.dll when the App is closed:
|
||||
/// `%APPDATA%\RenHDrum\renhdrum-settings.txt`. Returns `None` if `APPDATA` is unset.
|
||||
pub fn settings_file_path() -> Option<PathBuf> {
|
||||
let appdata = std::env::var_os("APPDATA")?;
|
||||
let mut p = PathBuf::from(appdata);
|
||||
p.push("RenHDrum");
|
||||
p.push("renhdrum-settings.txt");
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// Serializes all 25 fields of `RenHdcConfig` to simple `key=value` text format.
|
||||
pub fn write_settings_text(c: &RenHdcConfig) -> String {
|
||||
let mut s = String::new();
|
||||
s.push_str("# Brontide-App settings, read by renhdrum.dll when the App is closed\n");
|
||||
s.push_str(&format!("enable_hd_rumble={}\n", c.enable_hd_rumble));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_usb_interval_ms={}\n",
|
||||
c.hd_rumble_usb_interval_ms
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_bluetooth_level={}\n",
|
||||
c.hd_rumble_bluetooth_level
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_usb_auto_slow={}\n",
|
||||
c.hd_rumble_usb_auto_slow
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_usb_no_queue={}\n",
|
||||
c.hd_rumble_experimental_usb_no_queue
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_envelope_5ms={}\n",
|
||||
c.hd_rumble_experimental_envelope_5ms
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_frequency_in_packet={}\n",
|
||||
c.hd_rumble_experimental_frequency_in_packet
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_frequency_both_bands={}\n",
|
||||
c.hd_rumble_experimental_frequency_both_bands
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_bt_after_input={}\n",
|
||||
c.hd_rumble_experimental_bt_after_input
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_bt_fast={}\n",
|
||||
c.hd_rumble_experimental_bt_fast
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_crisp_notes={}\n",
|
||||
c.hd_rumble_experimental_crisp_notes
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_bt_crisp_notes={}\n",
|
||||
c.hd_rumble_experimental_bt_crisp_notes
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_sync_to_input={}\n",
|
||||
c.hd_rumble_experimental_sync_to_input
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_click_pulse={}\n",
|
||||
c.hd_rumble_experimental_click_pulse
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_experimental_sync_bluetooth={}\n",
|
||||
c.hd_rumble_experimental_sync_bluetooth
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"hd_rumble_sync_auto_slow={}\n",
|
||||
c.hd_rumble_sync_auto_slow
|
||||
));
|
||||
s.push_str(&format!("strong_rumble={}\n", c.strong_rumble));
|
||||
s.push_str(&format!("weak_rumble={}\n", c.weak_rumble));
|
||||
s.push_str(&format!("enable_rumble={}\n", c.enable_rumble));
|
||||
s.push_str(&format!(
|
||||
"enable_adaptive_triggers={}\n",
|
||||
c.enable_adaptive_triggers
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"enable_dualsense_haptics={}\n",
|
||||
c.enable_dualsense_haptics
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"dualsense_haptics_volume={}\n",
|
||||
c.dualsense_haptics_volume
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"dualsense_crisp_notes={}\n",
|
||||
c.dualsense_crisp_notes
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"dualsense_bt_crisp_notes={}\n",
|
||||
c.dualsense_bt_crisp_notes
|
||||
));
|
||||
s.push_str(&format!(
|
||||
"dualsense_hd_haptics_off={}\n",
|
||||
c.dualsense_hd_haptics_off
|
||||
));
|
||||
s
|
||||
}
|
||||
|
||||
/// Parses settings text. Starts from defaults, overwriting each valid line.
|
||||
/// Returns `None` if the input contains zero valid lines.
|
||||
pub fn parse_settings_text(text: &str) -> Option<RenHdcConfig> {
|
||||
let mut cfg = RenHdcConfig::from(&RumbleConfigController::default());
|
||||
let mut valid_count = 0usize;
|
||||
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, val)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = key.trim();
|
||||
let val = val.trim();
|
||||
|
||||
let parsed_valid = match key {
|
||||
"enable_hd_rumble" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.enable_hd_rumble = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_usb_interval_ms" => val
|
||||
.parse::<i32>()
|
||||
.map(|v| cfg.hd_rumble_usb_interval_ms = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_bluetooth_level" => val
|
||||
.parse::<i32>()
|
||||
.map(|v| cfg.hd_rumble_bluetooth_level = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_usb_auto_slow" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_usb_auto_slow = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_usb_no_queue" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_usb_no_queue = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_envelope_5ms" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_envelope_5ms = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_frequency_in_packet" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_frequency_in_packet = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_frequency_both_bands" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_frequency_both_bands = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_bt_after_input" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_bt_after_input = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_bt_fast" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_bt_fast = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_crisp_notes" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_crisp_notes = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_bt_crisp_notes" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_bt_crisp_notes = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_sync_to_input" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_sync_to_input = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_click_pulse" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_click_pulse = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_experimental_sync_bluetooth" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_experimental_sync_bluetooth = v)
|
||||
.is_ok(),
|
||||
"hd_rumble_sync_auto_slow" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.hd_rumble_sync_auto_slow = v)
|
||||
.is_ok(),
|
||||
"strong_rumble" => val.parse::<f32>().map(|v| cfg.strong_rumble = v).is_ok(),
|
||||
"weak_rumble" => val.parse::<f32>().map(|v| cfg.weak_rumble = v).is_ok(),
|
||||
"enable_rumble" => val.parse::<bool>().map(|v| cfg.enable_rumble = v).is_ok(),
|
||||
"enable_adaptive_triggers" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.enable_adaptive_triggers = v)
|
||||
.is_ok(),
|
||||
"enable_dualsense_haptics" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.enable_dualsense_haptics = v)
|
||||
.is_ok(),
|
||||
"dualsense_haptics_volume" => val
|
||||
.parse::<i32>()
|
||||
.map(|v| cfg.dualsense_haptics_volume = v)
|
||||
.is_ok(),
|
||||
"dualsense_crisp_notes" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.dualsense_crisp_notes = v)
|
||||
.is_ok(),
|
||||
"dualsense_bt_crisp_notes" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.dualsense_bt_crisp_notes = v)
|
||||
.is_ok(),
|
||||
"dualsense_hd_haptics_off" => val
|
||||
.parse::<bool>()
|
||||
.map(|v| cfg.dualsense_hd_haptics_off = v)
|
||||
.is_ok(),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if parsed_valid {
|
||||
valid_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if valid_count == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves configuration to `%APPDATA%\RenHDrum\renhdrum-settings.txt` (creates directory if missing).
|
||||
pub fn save_settings_file(c: &RenHdcConfig) -> std::io::Result<()> {
|
||||
let path = settings_file_path().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"APPDATA environment variable not set",
|
||||
)
|
||||
})?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let text = write_settings_text(c);
|
||||
std::fs::write(&path, text)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn saved_config() -> Option<RenHdcConfig> {
|
||||
let path = settings_file_path()?;
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
parse_settings_text(&text)
|
||||
}
|
||||
|
||||
/// The active configuration for emulator hooks: shared memory first (if App is running),
|
||||
/// otherwise falls back to the saved settings file on disk (`renhdrum-settings.txt`).
|
||||
pub fn app_config() -> Option<RenHdcConfig> {
|
||||
// Unit tests must not depend on the settings file saved on this machine
|
||||
if cfg!(test) {
|
||||
return None;
|
||||
}
|
||||
shared().and_then(|s| s.read_config()).or_else(saved_config)
|
||||
}
|
||||
|
||||
/// Telemetry: one HD sample received from the emulator. No-op when the App is not running.
|
||||
pub fn note_sample(now_us: u64, al: f32, fl: f32, ah: f32, fh: f32) {
|
||||
#[cfg(windows)]
|
||||
win::note_sample(now_us, al, fl, ah, fh);
|
||||
#[cfg(not(windows))]
|
||||
let _ = (now_us, al, fl, ah, fh);
|
||||
}
|
||||
|
||||
/// Telemetry: one packet sent to the controller. No-op when the App is not running.
|
||||
pub fn note_packet(packet: &[u8; 10]) {
|
||||
#[cfg(windows)]
|
||||
win::note_packet(packet);
|
||||
#[cfg(not(windows))]
|
||||
let _ = packet;
|
||||
}
|
||||
|
||||
/// Telemetry: notes the active controller type and connection mode into shared memory.
|
||||
/// No-op when the App is not running.
|
||||
pub fn note_controller(is_bluetooth: bool, is_pro: bool) {
|
||||
#[cfg(windows)]
|
||||
win::note_controller(is_bluetooth, is_pro);
|
||||
#[cfg(not(windows))]
|
||||
let _ = (is_bluetooth, is_pro);
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::c_void;
|
||||
|
||||
extern "system" {
|
||||
fn CreateFileMappingW(
|
||||
file: *mut c_void,
|
||||
attrs: *const c_void,
|
||||
protect: u32,
|
||||
hi: u32,
|
||||
lo: u32,
|
||||
name: *const u16,
|
||||
) -> *mut c_void;
|
||||
}
|
||||
|
||||
/// Creates a named mapping (leaked on purpose) and returns the initialised block.
|
||||
fn create(name: &str) -> &'static mut RenHDrumSharedMemory {
|
||||
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
unsafe {
|
||||
let h = CreateFileMappingW(
|
||||
usize::MAX as *mut c_void,
|
||||
std::ptr::null(),
|
||||
0x04, // PAGE_READWRITE
|
||||
0,
|
||||
4096,
|
||||
wide.as_ptr(),
|
||||
);
|
||||
assert!(!h.is_null());
|
||||
let view = {
|
||||
extern "system" {
|
||||
fn MapViewOfFile(
|
||||
h: *mut c_void,
|
||||
a: u32,
|
||||
hi: u32,
|
||||
lo: u32,
|
||||
n: usize,
|
||||
) -> *mut c_void;
|
||||
}
|
||||
MapViewOfFile(h, 0xF001F, 0, 0, 4096)
|
||||
};
|
||||
assert!(!view.is_null());
|
||||
let p = view as *mut RenHDrumSharedMemory;
|
||||
(*p).init();
|
||||
&mut *p
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seqlock_roundtrip_and_validation() {
|
||||
let name = format!("Local\\RenHDrum_Test_{}", std::process::id());
|
||||
let owner = create(&name);
|
||||
|
||||
let mut cfg = RenHdcConfig::from(&RumbleConfigController::default());
|
||||
cfg.hd_rumble_bluetooth_level = 1;
|
||||
owner.update_config(cfg);
|
||||
assert_eq!(owner.config_sequence.load(Ordering::Relaxed) & 1, 0);
|
||||
|
||||
let reader = unsafe { &*win::open_named(&name).expect("open") };
|
||||
assert_eq!(reader.read_config().unwrap().hd_rumble_bluetooth_level, 1);
|
||||
|
||||
// odd sequence = writer in progress -> no consistent read
|
||||
owner.config_sequence.store(7, Ordering::Relaxed);
|
||||
assert!(reader.read_config().is_none());
|
||||
owner.config_sequence.store(8, Ordering::Relaxed);
|
||||
assert!(reader.read_config().is_some());
|
||||
|
||||
// wrong version is rejected
|
||||
owner.struct_version = 2;
|
||||
assert!(win::open_named(&name).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_text_roundtrip_and_validation() {
|
||||
let mut cfg = RenHdcConfig::from(&RumbleConfigController::default());
|
||||
cfg.hd_rumble_bluetooth_level = 1;
|
||||
cfg.hd_rumble_experimental_bt_crisp_notes = false;
|
||||
cfg.dualsense_haptics_volume = 70;
|
||||
cfg.dualsense_bt_crisp_notes = true;
|
||||
|
||||
let text = write_settings_text(&cfg);
|
||||
let parsed = parse_settings_text(&text).expect("roundtrip parse failed");
|
||||
assert_eq!(cfg, parsed);
|
||||
|
||||
// Garbage lines and unknown keys are ignored while valid lines are parsed
|
||||
let text_with_garbage = format!(
|
||||
"{}\nunknown_key=12345\ninvalid_line_without_equal\nhd_rumble_bluetooth_level=not_an_int\n",
|
||||
text
|
||||
);
|
||||
let parsed_garbage =
|
||||
parse_settings_text(&text_with_garbage).expect("parse with garbage failed");
|
||||
assert_eq!(parsed_garbage.hd_rumble_bluetooth_level, 1);
|
||||
assert!(!parsed_garbage.hd_rumble_experimental_bt_crisp_notes);
|
||||
assert_eq!(parsed_garbage.dualsense_haptics_volume, 70);
|
||||
|
||||
// Empty string returns None
|
||||
assert!(parse_settings_text("").is_none());
|
||||
|
||||
// Only comments and unknown lines return None
|
||||
assert!(parse_settings_text("# comment\nunknown=1\n").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_controller_without_shmem_does_not_panic() {
|
||||
note_controller(true, true);
|
||||
note_controller(true, false);
|
||||
note_controller(false, true);
|
||||
note_controller(false, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_file_hd_haptics_off_roundtrip_and_legacy_default() {
|
||||
let dir = std::env::temp_dir().join(format!("renhdrum_ipc_119_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("renhdrum-settings.txt");
|
||||
|
||||
// (c) roundtrip true and false through a settings file
|
||||
for expected in [true, false] {
|
||||
let mut cfg = RenHdcConfig::from(&RumbleConfigController::default());
|
||||
cfg.dualsense_hd_haptics_off = expected;
|
||||
std::fs::write(&path, write_settings_text(&cfg)).unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let parsed = parse_settings_text(&text).expect("roundtrip parse failed");
|
||||
assert_eq!(parsed.dualsense_hd_haptics_off, expected);
|
||||
}
|
||||
|
||||
// (d) legacy settings file without dualsense_hd_haptics_off defaults to false
|
||||
let legacy_text =
|
||||
"enable_hd_rumble=true\ndualsense_crisp_notes=true\ndualsense_bt_crisp_notes=false\n";
|
||||
std::fs::write(&path, legacy_text).unwrap();
|
||||
let read_legacy = std::fs::read_to_string(&path).unwrap();
|
||||
let parsed_legacy = parse_settings_text(&read_legacy).expect("legacy parse failed");
|
||||
assert!(!parsed_legacy.dualsense_hd_haptics_off);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
51
third_party/renhdrum/src/lib.rs
vendored
Normal file
51
third_party/renhdrum/src/lib.rs
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
#![allow(clippy::neg_cmp_op_on_partial_ord)]
|
||||
|
||||
pub mod backend;
|
||||
pub mod detectors;
|
||||
pub mod dualsense;
|
||||
pub mod encoding;
|
||||
pub mod ffi;
|
||||
pub mod ipc;
|
||||
pub mod nx2;
|
||||
pub mod options;
|
||||
pub mod planner;
|
||||
pub mod play_report;
|
||||
pub mod preset;
|
||||
pub mod settings;
|
||||
pub mod status;
|
||||
pub mod test_pattern;
|
||||
pub mod trace;
|
||||
pub mod valve;
|
||||
pub mod xbox;
|
||||
|
||||
pub use backend::{HdSample, NintendoHdEngine};
|
||||
pub use dualsense::{
|
||||
pack_ds5_effects_state, DualSenseHapticsDsp, DualSenseSettings, DualSenseSettingsFull,
|
||||
DualSenseSide, DualSenseTriggerEffect, DualSenseTriggerInput, DualSenseTriggerProfile,
|
||||
DualSenseTriggerProfileConfig, DualSenseVoice,
|
||||
};
|
||||
|
||||
pub use detectors::{ClickDetectorState, HdClickDetector, HdDenseDetector, HdShortPulseCounter};
|
||||
pub use encoding::amfm::HdAmFmEncoding;
|
||||
pub use encoding::click::{HdClickEncoding, HdClickKind, HdClickSide};
|
||||
pub use encoding::crisp_notes::{HdCrispNotes, HdSideSample};
|
||||
pub use encoding::standard::{
|
||||
hd_amp_index, hd_encode_packet, hd_encode_side, hd_is_neutral, hd_is_silent_packet,
|
||||
hd_is_small_change, HdBtLevel, HD_AMP_THRESHOLDS, HD_BT_LEVELS,
|
||||
};
|
||||
pub use ffi::*;
|
||||
pub use options::*;
|
||||
pub use planner::{
|
||||
am_fm_measure_changes_amplitude, am_fm_measure_codes, format_steps, hd_am_fm_measure_segments,
|
||||
AmFmSegment, HdAmFmFallbackKind, HdAmFmPlanner, HdAmFmSideKind, AM_FM_AMPLITUDE,
|
||||
AM_FM_MEASURE_LOW_CODES, AM_FM_MEASURE_MARKER_MS, AM_FM_MEASURE_PHASE_SLOTS,
|
||||
AM_FM_MEASURE_SEGMENT_MS, AM_FM_MEASURE_WEAK, AM_FM_PACKET_MS,
|
||||
};
|
||||
pub use preset::{HdRumblePreset, HdRumblePresetKind};
|
||||
pub use settings::{HdRumbleSettings, RumbleConfigController};
|
||||
pub use status::{
|
||||
DualSenseHapticsStatus, Entry, LinkCounters, PlayerIndex, RumbleBackendKind, RumbleStatus,
|
||||
RumbleTransport, SyncCounters,
|
||||
};
|
||||
pub use xbox::{XboxRumbleMapper, XboxRumbleTuning};
|
||||
370
third_party/renhdrum/src/nx2.rs
vendored
Normal file
370
third_party/renhdrum/src/nx2.rs
vendored
Normal file
@@ -0,0 +1,370 @@
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
|
||||
use crate::settings::HdRumbleSettings;
|
||||
|
||||
pub const LATEST_FLAG: &str = "hdrumble_latest.txt"; // ponytail: núm đo; plan 103 mức 4 dùng lại
|
||||
|
||||
const PRO_DEFAULT: [f32; 5] = [0.004, 0.048, 0.240, 0.640, 0.950];
|
||||
|
||||
pub(crate) fn flag_present_in(name: &str, dir: Option<&Path>) -> bool {
|
||||
HdRumbleSettings::flag_path(name, dir).is_file()
|
||||
}
|
||||
|
||||
fn map_curve(amp: f32, c: [f32; 5]) -> f32 {
|
||||
map_piecewise(amp, c[0], c[1], c[2], c[3], c[4])
|
||||
}
|
||||
|
||||
/// Switch 2 rumble mode state:
|
||||
/// 0 = Switch 1 default / no translation (100% untouched)
|
||||
/// 2 = Switch 2 Mode 2 translation active
|
||||
static NX2_MODE: AtomicI32 = AtomicI32::new(0);
|
||||
|
||||
pub fn set_nx2_mode(mode: i32) {
|
||||
NX2_MODE.store(mode, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn get_nx2_mode() -> i32 {
|
||||
NX2_MODE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Piecewise linear curve matching MapPiecewise / ApplyNx2MapExplicit:
|
||||
/// (t, p1) -> (0.10, p2) -> (0.50, p3) -> (1.00, p4)
|
||||
pub fn map_piecewise(amp: f32, t: f32, p1: f32, p2: f32, p3: f32, p4: f32) -> f32 {
|
||||
if !amp.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
if amp <= t {
|
||||
return 0.0;
|
||||
}
|
||||
if amp >= 1.0 {
|
||||
return p4.clamp(0.0, 1.0);
|
||||
}
|
||||
let val = if amp < 0.1 {
|
||||
if 0.1 <= t {
|
||||
p2
|
||||
} else {
|
||||
p1 + (amp - t) * (p2 - p1) / (0.1 - t)
|
||||
}
|
||||
} else if amp < 0.5 {
|
||||
p2 + (amp - 0.1) * (p3 - p2) / (0.5 - 0.1)
|
||||
} else {
|
||||
p3 + (amp - 0.5) * (p4 - p3) / (1.0 - 0.5)
|
||||
};
|
||||
val.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// DualSense Switch 2 Mode 2, stage 1 of the plan 104 L1 law: noise floor only, `a <= 0.001 -> 0`,
|
||||
/// the rest passes through unchanged. The amplitude law `min(1, 3.5 * a^0.75)` is applied once,
|
||||
/// later, in `dualsense::haptics::make_side`; applying it here too doubles it (plan 105 bug).
|
||||
/// When nx2_mode != 2, returns inputs verbatim (Switch 1 remains 100% untouched).
|
||||
pub fn apply_dualsense_nx2(amp_low: f32, amp_high: f32) -> (f32, f32) {
|
||||
if get_nx2_mode() != 2 {
|
||||
return (amp_low, amp_high);
|
||||
}
|
||||
// `!(a > T)` also zeroes NaN
|
||||
let gate = |a: f32| if !(a > 0.001) { 0.0 } else { a };
|
||||
(gate(amp_low), gate(amp_high))
|
||||
}
|
||||
|
||||
/// Xbox One S Switch 2 Mode 2 mapping: the Xbox translates the Pro 1 score, so it uses the same
|
||||
/// Pro curve (`PRO_DEFAULT`, follows Pro tuning) and then the Switch 1 Xbox mapper. No onset
|
||||
/// boost: the Xbox mapper has its own kick. When nx2_mode != 2, returns inputs verbatim.
|
||||
pub fn apply_xbox_nx2(amp_low: f32, amp_high: f32) -> (f32, f32) {
|
||||
if get_nx2_mode() != 2 {
|
||||
return (amp_low, amp_high);
|
||||
}
|
||||
(
|
||||
map_curve(amp_low, PRO_DEFAULT),
|
||||
map_curve(amp_high, PRO_DEFAULT),
|
||||
)
|
||||
}
|
||||
|
||||
/// State tracking for note onset boost on Nintendo Pro 1 actuators.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Nx2ProBoostState {
|
||||
pub low_active: bool,
|
||||
pub high_active: bool,
|
||||
pub low_until_us: u64,
|
||||
pub high_until_us: u64,
|
||||
}
|
||||
|
||||
fn apply_pro_band(amp: f32, freq: f32, now_us: u64, active: &mut bool, until_us: &mut u64) -> f32 {
|
||||
// Pro 1 way B: T = 0.004, P1 = 0.048, P2 = 0.240, P3 = 0.640, P4 = 0.950
|
||||
let c = PRO_DEFAULT;
|
||||
if amp <= c[0] {
|
||||
*active = false;
|
||||
*until_us = 0;
|
||||
return 0.0;
|
||||
}
|
||||
let mapped = map_curve(amp, c);
|
||||
if !*active {
|
||||
*active = true;
|
||||
*until_us = now_us.saturating_add(25_000);
|
||||
}
|
||||
if now_us < *until_us && freq < 150.0 {
|
||||
(mapped * 1.2).min(1.0)
|
||||
} else {
|
||||
mapped
|
||||
}
|
||||
}
|
||||
|
||||
impl Nx2ProBoostState {
|
||||
/// Nintendo Pro 1 Switch 2 Mode 2 mapping:
|
||||
/// Pro 1 way B curve + 1.2x boost for 25 ms on frequencies < 150 Hz.
|
||||
/// When nx2_mode != 2, returns inputs verbatim (Switch 1 remains 100% untouched).
|
||||
pub fn apply_pro_nx2(
|
||||
&mut self,
|
||||
amp_low: f32,
|
||||
freq_low: f32,
|
||||
amp_high: f32,
|
||||
freq_high: f32,
|
||||
now_us: u64,
|
||||
) -> (f32, f32) {
|
||||
if get_nx2_mode() != 2 {
|
||||
return (amp_low, amp_high);
|
||||
}
|
||||
let out_low = apply_pro_band(
|
||||
amp_low,
|
||||
freq_low,
|
||||
now_us,
|
||||
&mut self.low_active,
|
||||
&mut self.low_until_us,
|
||||
);
|
||||
let out_high = apply_pro_band(
|
||||
amp_high,
|
||||
freq_high,
|
||||
now_us,
|
||||
&mut self.high_active,
|
||||
&mut self.high_until_us,
|
||||
);
|
||||
(out_low, out_high)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) static NX2_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nx2_mode_0_keeps_switch1_unchanged() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(0);
|
||||
let mut state = Nx2ProBoostState::default();
|
||||
|
||||
// DualSense tests
|
||||
assert_eq!(apply_dualsense_nx2(0.02, 0.5), (0.02, 0.5));
|
||||
assert_eq!(apply_dualsense_nx2(0.0005, 0.8), (0.0005, 0.8));
|
||||
assert_eq!(apply_dualsense_nx2(0.0, 1.0), (0.0, 1.0));
|
||||
|
||||
// Pro 1 tests
|
||||
assert_eq!(
|
||||
state.apply_pro_nx2(0.02, 140.0, 0.5, 300.0, 10_000),
|
||||
(0.02, 0.5)
|
||||
);
|
||||
assert_eq!(
|
||||
state.apply_pro_nx2(0.0005, 100.0, 0.05, 120.0, 20_000),
|
||||
(0.0005, 0.05)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nx2_mode_2_dualsense_uses_l1_law() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
// T = 0.001, below threshold gives 0.0
|
||||
let (zero_l, zero_h) = apply_dualsense_nx2(0.0005, 0.001);
|
||||
assert_eq!(zero_l, 0.0);
|
||||
assert_eq!(zero_h, 0.0);
|
||||
|
||||
// Above the floor this stage passes the game's value through...
|
||||
assert_eq!(apply_dualsense_nx2(0.01, 0.3), (0.01, 0.3));
|
||||
assert_eq!(apply_dualsense_nx2(1.0, 0.5), (1.0, 0.5));
|
||||
|
||||
// ...and the whole chain (this stage + make_side, as ffi.rs runs it) applies the law ONCE:
|
||||
// 0.01 -> 3.5 * 0.01^0.75 ~ 0.1107, not 3.5 * 0.1107^0.75 ~ 0.67.
|
||||
let (al, ah) = apply_dualsense_nx2(0.01, 0.0);
|
||||
let side = crate::dualsense::haptics::make_side(al, 160.0, ah, 320.0);
|
||||
assert!(
|
||||
(side.amp_low - 0.1107).abs() < 0.001,
|
||||
"chain 0.01 -> {} expected ~0.1107",
|
||||
side.amp_low
|
||||
);
|
||||
|
||||
// Reset back to 0 for other tests
|
||||
set_nx2_mode(0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nx2_mode_2_pro_uses_preset_4_with_boost() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
let mut state = Nx2ProBoostState::default();
|
||||
|
||||
// 0.02 unboosted is ~0.0800. With 1.2x boost under 150 Hz it becomes ~0.0960.
|
||||
let now_us = 100_000;
|
||||
let (al1, ah1) = state.apply_pro_nx2(0.02, 140.0, 0.02, 200.0, now_us);
|
||||
assert!(
|
||||
(al1 - 0.0960).abs() < 0.001,
|
||||
"al1={al1} expected ~0.0960 with boost"
|
||||
);
|
||||
// ah1 freq is 200 Hz >= 150 Hz, so no boost: ~0.08005
|
||||
assert!(
|
||||
(ah1 - 0.0800).abs() < 0.001,
|
||||
"ah1={ah1} expected ~0.0800 unboosted"
|
||||
);
|
||||
|
||||
// 10 ms later (now_us + 10_000): still in 25 ms boost window
|
||||
let (al2, _) = state.apply_pro_nx2(0.02, 140.0, 0.02, 200.0, now_us + 10_000);
|
||||
assert!((al2 - 0.0960).abs() < 0.001, "al2={al2} still boosted");
|
||||
|
||||
// 30 ms later (now_us + 30_000): boost window expired (> 25 ms), drops to ~0.08005
|
||||
let (al3, _) = state.apply_pro_nx2(0.02, 140.0, 0.02, 200.0, now_us + 30_000);
|
||||
assert!(
|
||||
(al3 - 0.0800).abs() < 0.001,
|
||||
"al3={al3} unboosted after 25ms"
|
||||
);
|
||||
|
||||
// Reset back to 0
|
||||
set_nx2_mode(0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nx2_mode_2_nan_amplitude_returns_zero_and_no_boost() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
let mut state = Nx2ProBoostState::default();
|
||||
|
||||
// Mode 2, amp_low = NaN, 140 Hz in first 25 ms -> returns 0.0 (previously was 1.0 due to (NaN * 1.2).min(1.0))
|
||||
let (out_l, out_h) = state.apply_pro_nx2(f32::NAN, 140.0, 0.0, 320.0, 10_000);
|
||||
assert_eq!(out_l, 0.0);
|
||||
assert_eq!(out_h, 0.0);
|
||||
|
||||
set_nx2_mode(0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nx2_mode_2_curve_table_and_behavior() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
|
||||
// 1. Table check (tolerance 0.001):
|
||||
// raw | Pro [4] (no boost: freq >= 150) | DualSense stage 1 (floor only, passes through)
|
||||
let points = [
|
||||
(0.05f32, 0.1400f32, 0.05f32),
|
||||
(0.30f32, 0.4400f32, 0.30f32),
|
||||
(0.75f32, 0.7950f32, 0.75f32),
|
||||
];
|
||||
|
||||
for &(raw, expected_pro, expected_ds) in &points {
|
||||
let (ds_l, ds_h) = apply_dualsense_nx2(raw, raw);
|
||||
assert!(
|
||||
(ds_l - expected_ds).abs() < 0.001,
|
||||
"DS raw {raw}: expected {expected_ds}, got {ds_l}"
|
||||
);
|
||||
assert!(
|
||||
(ds_h - expected_ds).abs() < 0.001,
|
||||
"DS high raw {raw}: expected {expected_ds}, got {ds_h}"
|
||||
);
|
||||
|
||||
// Pro unboosted (using freq 200.0 >= 150.0)
|
||||
let mut state = Nx2ProBoostState::default();
|
||||
let (pro_l, pro_h) = state.apply_pro_nx2(raw, 200.0, raw, 200.0, 10_000);
|
||||
assert!(
|
||||
(pro_l - expected_pro).abs() < 0.001,
|
||||
"Pro raw {raw}: expected {expected_pro}, got {pro_l}"
|
||||
);
|
||||
assert!(
|
||||
(pro_h - expected_pro).abs() < 0.001,
|
||||
"Pro high raw {raw}: expected {expected_pro}, got {pro_h}"
|
||||
);
|
||||
}
|
||||
|
||||
// (a) DualSense 2 different bands stay independent: low 0.05 / high 0.3 pass through
|
||||
assert_eq!(apply_dualsense_nx2(0.05, 0.30), (0.05, 0.30));
|
||||
|
||||
// (b) Pro boost: 140 Hz, raw 0.3 -> at 24 ms gives 0.528, at 26 ms gives 0.440
|
||||
let mut pro_state = Nx2ProBoostState::default();
|
||||
let t0 = 100_000u64;
|
||||
let (pro_b1, _) = pro_state.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0);
|
||||
assert!(
|
||||
(pro_b1 - 0.528).abs() < 0.001,
|
||||
"Pro at start: expected 0.528, got {pro_b1}"
|
||||
);
|
||||
let (pro_b24, _) = pro_state.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0 + 24_000);
|
||||
assert!(
|
||||
(pro_b24 - 0.528).abs() < 0.001,
|
||||
"Pro at 24 ms: expected 0.528, got {pro_b24}"
|
||||
);
|
||||
let (pro_b26, _) = pro_state.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0 + 26_000);
|
||||
assert!(
|
||||
(pro_b26 - 0.440).abs() < 0.001,
|
||||
"Pro at 26 ms: expected 0.440, got {pro_b26}"
|
||||
);
|
||||
|
||||
// (c) 149 Hz is boosted, 151 Hz is not
|
||||
let mut state_149 = Nx2ProBoostState::default();
|
||||
let (pro_149, _) = state_149.apply_pro_nx2(0.30, 149.0, 0.0, 320.0, t0);
|
||||
assert!(
|
||||
(pro_149 - 0.528).abs() < 0.001,
|
||||
"149 Hz should be boosted to 0.528, got {pro_149}"
|
||||
);
|
||||
|
||||
let mut state_151 = Nx2ProBoostState::default();
|
||||
let (pro_151, _) = state_151.apply_pro_nx2(0.30, 151.0, 0.0, 320.0, t0);
|
||||
assert!(
|
||||
(pro_151 - 0.440).abs() < 0.001,
|
||||
"151 Hz should not be boosted (0.440), got {pro_151}"
|
||||
);
|
||||
|
||||
// (d) Off then on: send 0.0 then 0.3 -> re-triggered boost
|
||||
let mut state_retrigger = Nx2ProBoostState::default();
|
||||
let (on1, _) = state_retrigger.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0);
|
||||
assert!((on1 - 0.528).abs() < 0.001);
|
||||
// Advance past boost window
|
||||
let (expired, _) = state_retrigger.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0 + 30_000);
|
||||
assert!((expired - 0.440).abs() < 0.001);
|
||||
// Send 0.0 (turn off)
|
||||
let (off, _) = state_retrigger.apply_pro_nx2(0.0, 140.0, 0.0, 320.0, t0 + 35_000);
|
||||
assert_eq!(off, 0.0);
|
||||
// Send 0.3 again (turn on) -> should be boosted again!
|
||||
let (on2, _) = state_retrigger.apply_pro_nx2(0.30, 140.0, 0.0, 320.0, t0 + 40_000);
|
||||
assert!(
|
||||
(on2 - 0.528).abs() < 0.001,
|
||||
"Retriggered note should get boost 0.528, got {on2}"
|
||||
);
|
||||
|
||||
set_nx2_mode(0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_pro_t004_xbox_follows_pro() {
|
||||
assert_eq!(PRO_DEFAULT, [0.004, 0.048, 0.240, 0.640, 0.950]);
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
let mut state = Nx2ProBoostState::default();
|
||||
let (pro, _) = state.apply_pro_nx2(0.003, 200.0, 0.0, 320.0, 10_000);
|
||||
let (xbox, _) = apply_xbox_nx2(0.003, 0.0);
|
||||
// 0.3 at 200 Hz: no Pro boost, so Pro and Xbox must agree
|
||||
let (pro_mid, _) = state.apply_pro_nx2(0.3, 200.0, 0.0, 320.0, 50_000);
|
||||
let (xbox_mid, _) = apply_xbox_nx2(0.3, 0.0);
|
||||
set_nx2_mode(0);
|
||||
assert_eq!(pro, 0.0, "Pro T 0.004 cuts 0.003");
|
||||
assert_eq!(xbox, 0.0, "Xbox follows the Pro floor");
|
||||
assert_eq!(pro_mid, xbox_mid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xbox_nx2_curve_and_mode0_passthrough() {
|
||||
let _guard = NX2_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set_nx2_mode(2);
|
||||
let (lo, hi) = apply_xbox_nx2(0.05, 0.3);
|
||||
set_nx2_mode(0);
|
||||
assert!((lo - 0.1400).abs() < 0.001, "{lo}");
|
||||
assert!((hi - 0.4400).abs() < 0.001, "{hi}");
|
||||
assert_eq!(apply_xbox_nx2(0.05, 0.3), (0.05, 0.3));
|
||||
}
|
||||
}
|
||||
482
third_party/renhdrum/src/options.rs
vendored
Normal file
482
third_party/renhdrum/src/options.rs
vendored
Normal file
@@ -0,0 +1,482 @@
|
||||
//! Settings table + value store (plan 120). Hosts draw their settings page from `renhdrum_options`
|
||||
//! and keep values in a `RenHdcStore`; `renhdrum_store_to_config` turns them into `RenHdcConfig`.
|
||||
//! `RenHdcConfig` (48 bytes, IPC) is unchanged.
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::c_char;
|
||||
|
||||
use crate::ffi::{RenHdcConfig, RENHDRUM_ERR_INVALID_ARG, RENHDRUM_ERR_NULL_PTR, RENHDRUM_OK};
|
||||
use crate::preset::{HdRumblePreset, HdRumblePresetKind};
|
||||
use crate::settings::RumbleConfigController;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct RenHdcOption {
|
||||
pub key: *const c_char,
|
||||
pub label: *const c_char,
|
||||
pub help: *const c_char,
|
||||
pub choices: *const c_char,
|
||||
/// 0 BOOL, 1 PERCENT/INT, 2 CHOICE (value = index into `choices`)
|
||||
pub kind: i32,
|
||||
pub min: i32,
|
||||
pub max: i32,
|
||||
pub step: i32,
|
||||
pub def: i32,
|
||||
/// bit: 1 Switch, 2 DualSense, 4 Xbox, 8 Steam
|
||||
pub devices: u32,
|
||||
/// 0 Basic, 1 Advanced
|
||||
pub tier: i32,
|
||||
/// 0 any link, 1 USB only, 2 Bluetooth only
|
||||
pub link: i32,
|
||||
/// row index that must be non-zero for this row to matter, -1 = none
|
||||
pub requires: i32,
|
||||
}
|
||||
|
||||
// Only ever points at 'static NUL-terminated literals.
|
||||
unsafe impl Sync for RenHdcOption {}
|
||||
|
||||
macro_rules! s {
|
||||
($s:expr) => {
|
||||
concat!($s, "\0").as_ptr() as *const c_char
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! opt {
|
||||
($key:expr, $label:expr, $help:expr, $choices:expr, $kind:expr, $min:expr, $max:expr, $step:expr,
|
||||
$def:expr, $dev:expr, $tier:expr, $link:expr, $req:expr) => {
|
||||
RenHdcOption {
|
||||
key: s!($key),
|
||||
label: s!($label),
|
||||
help: s!($help),
|
||||
choices: s!($choices),
|
||||
kind: $kind,
|
||||
min: $min,
|
||||
max: $max,
|
||||
step: $step,
|
||||
def: $def,
|
||||
devices: $dev,
|
||||
tier: $tier,
|
||||
link: $link,
|
||||
requires: $req,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const BOOL: i32 = 0;
|
||||
const INT: i32 = 1;
|
||||
const CHOICE: i32 = 2;
|
||||
const SW: u32 = 1;
|
||||
const DS: u32 = 2;
|
||||
const XB: u32 = 4;
|
||||
const ALL: u32 = 15;
|
||||
|
||||
/// `usb_interval_ms` is a CHOICE: value = index into this list.
|
||||
const USB_INTERVALS_MS: [i32; 4] = [10, 15, 20, 30];
|
||||
|
||||
// Row indexes the table refers to (`requires`) and the code below reads by position.
|
||||
const I_ENABLE: usize = 0;
|
||||
const I_BT_MODE: usize = 1;
|
||||
const I_DS_HAPTICS: usize = 2;
|
||||
const I_DS_HD: usize = 3;
|
||||
const I_DS_VOLUME: usize = 4;
|
||||
const I_NO_QUEUE: usize = 8;
|
||||
const I_ENVELOPE: usize = 9;
|
||||
const I_FREQ_PACKET: usize = 10;
|
||||
const I_FREQ_BOTH: usize = 11;
|
||||
const I_CRISP: usize = 12;
|
||||
const I_USB_INTERVAL: usize = 13;
|
||||
const I_USB_AUTO_SLOW: usize = 14;
|
||||
const I_BT_AFTER_INPUT: usize = 15;
|
||||
const I_BT_CRISP: usize = 16;
|
||||
const I_DS_CRISP: usize = 17;
|
||||
|
||||
static OPTIONS: [RenHdcOption; 23] = [
|
||||
opt!("enable_hd_rumble", "HD Rumble", "Plays the game's HD Rumble in full detail. Off: the standard rumble.", "", BOOL, 0, 1, 1, 1, ALL, 0, 0, -1),
|
||||
opt!("switch_bt_mode", "Bluetooth mode", "Detailed (5 ms): every detail, like wired. Compatible: works on every Bluetooth adapter; used automatically when Detailed cannot run.", "Detailed (5 ms)|Compatible", CHOICE, 0, 1, 1, 0, SW, 0, 2, -1),
|
||||
opt!("dualsense_haptics", "Haptics", "Rumble through the two haptic voice coils. Off: the standard rumble.", "", BOOL, 0, 1, 1, 1, DS, 0, 0, -1),
|
||||
opt!("dualsense_hd_haptics", "HD Haptics", "HD Rumble upgraded for DualSense. The controller speaker and the L2/R2 triggers react to the rumble. Off = standard HD Rumble.", "", BOOL, 0, 1, 1, 1, DS, 0, 0, 2),
|
||||
opt!("dualsense_volume", "Strength", "Lower it if the rumble feels too strong.", "", INT, 10, 100, 5, RumbleConfigController::DEFAULT_DUALSENSE_HAPTICS_VOLUME, DS, 0, 0, 2),
|
||||
opt!("xbox_enabled", "HD Rumble on Xbox", "The game's HD Rumble translated for the Xbox motors. Off: the standard rumble.", "", BOOL, 0, 1, 1, 1, XB, 0, 0, -1),
|
||||
opt!("gain", "Intensity", "Overall rumble strength.", "", INT, 25, 1000, 5, 100, ALL, 1, 0, -1),
|
||||
opt!("low_boost", "Lift weak rumble", "Makes faint rumble easier to feel.", "", INT, 0, 100, 5, 0, ALL, 1, 0, -1),
|
||||
opt!("usb_no_queue", "Send rumble without queuing", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("envelope_5ms", "Detailed 5 ms rumble", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("frequency_in_packet", "Accurate pitch, low band", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("frequency_both_bands", "Accurate pitch, both bands", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("crisp_notes", "Accent each note", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("usb_interval_ms", "Send interval (when detailed rumble is off)", "Used only while Detailed 5 ms rumble is off.", "10 ms|15 ms|20 ms|30 ms", CHOICE, 0, 3, 1, 1, SW, 1, 1, -1),
|
||||
opt!("usb_auto_slow", "Slow down during heavy rumble", "", "", BOOL, 0, 1, 1, 1, SW, 1, 1, -1),
|
||||
opt!("bt_after_input", "Send rumble between button reads", "", "", BOOL, 0, 1, 1, 1, SW, 1, 2, -1),
|
||||
opt!("bt_crisp_notes", "Accent each note", "", "", BOOL, 0, 1, 1, 1, SW, 1, 2, -1),
|
||||
opt!("dualsense_crisp_notes", "Accent each note", "", "", BOOL, 0, 1, 1, 1, DS, 1, 0, -1),
|
||||
opt!("xbox_mode", "Mode", "", "RenHDrum|Direct", CHOICE, 0, 1, 1, 0, XB, 1, 0, -1),
|
||||
opt!("xbox_strength", "Motor strength", "100% = as the game sends it. Raise it if the rumble feels weak.", "", INT, 0, 1000, 10, 100, XB, 1, 0, 5),
|
||||
opt!("xbox_detail", "Detail on main motor", "", "", INT, 0, 100, 5, 50, XB, 1, 0, 18),
|
||||
opt!("xbox_accents", "Hit accents", "", "", INT, 0, 100, 5, 50, XB, 1, 0, 18),
|
||||
opt!("xbox_trigger_mix", "Trigger rumble", "", "", INT, 0, 100, 5, 20, XB, 1, 0, 18),
|
||||
];
|
||||
|
||||
pub struct RenHdcStore {
|
||||
values: [i32; OPTIONS.len()],
|
||||
}
|
||||
|
||||
fn index_of(k: &str) -> Option<usize> {
|
||||
OPTIONS
|
||||
.iter()
|
||||
.position(|o| unsafe { CStr::from_ptr(o.key) }.to_str() == Ok(k))
|
||||
}
|
||||
|
||||
fn find(key: *const c_char) -> Option<usize> {
|
||||
if key.is_null() {
|
||||
return None;
|
||||
}
|
||||
index_of(unsafe { CStr::from_ptr(key) }.to_str().ok()?)
|
||||
}
|
||||
|
||||
impl RenHdcStore {
|
||||
/// Value by key; unknown key = 0 (callers use fixed keys from the table).
|
||||
pub(crate) fn value(&self, key: &str) -> i32 {
|
||||
index_of(key).map_or(0, |i| self.values[i])
|
||||
}
|
||||
|
||||
fn new() -> Self {
|
||||
let mut values = [0; OPTIONS.len()];
|
||||
for (v, o) in values.iter_mut().zip(OPTIONS.iter()) {
|
||||
*v = o.def;
|
||||
}
|
||||
Self { values }
|
||||
}
|
||||
|
||||
fn is_recommended(&self) -> bool {
|
||||
self.values
|
||||
.iter()
|
||||
.zip(OPTIONS.iter())
|
||||
.all(|(v, o)| *v == o.def)
|
||||
&& HdRumblePreset::detect(&RumbleConfigController::from(&self.to_config()))
|
||||
== HdRumblePresetKind::Standard
|
||||
}
|
||||
|
||||
fn to_config(&self) -> RenHdcConfig {
|
||||
// Fields the core manages itself keep the Standard preset values.
|
||||
let mut c = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Standard, &mut c);
|
||||
let v = |i: usize| self.values[i];
|
||||
let b = |i: usize| self.values[i] != 0;
|
||||
c.enable_hd_rumble = b(I_ENABLE);
|
||||
c.hd_rumble_bluetooth_level = 4;
|
||||
c.hd_rumble_experimental_bt_fast = v(I_BT_MODE) == 0;
|
||||
c.enable_dualsense_haptics = b(I_DS_HAPTICS);
|
||||
c.dualsense_hd_haptics_off = !b(I_DS_HD);
|
||||
c.dualsense_haptics_volume = v(I_DS_VOLUME);
|
||||
c.hd_rumble_experimental_usb_no_queue = b(I_NO_QUEUE);
|
||||
c.hd_rumble_experimental_envelope_5ms = b(I_ENVELOPE);
|
||||
c.hd_rumble_experimental_frequency_in_packet = b(I_FREQ_PACKET);
|
||||
c.hd_rumble_experimental_frequency_both_bands = b(I_FREQ_BOTH);
|
||||
c.hd_rumble_experimental_crisp_notes = b(I_CRISP);
|
||||
c.hd_rumble_usb_interval_ms = USB_INTERVALS_MS[v(I_USB_INTERVAL) as usize];
|
||||
c.hd_rumble_usb_auto_slow = b(I_USB_AUTO_SLOW);
|
||||
c.hd_rumble_experimental_bt_after_input = b(I_BT_AFTER_INPUT);
|
||||
c.hd_rumble_experimental_bt_crisp_notes = b(I_BT_CRISP);
|
||||
c.dualsense_crisp_notes = b(I_DS_CRISP);
|
||||
RenHdcConfig::from(&c)
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_options(
|
||||
out_count: *mut i32,
|
||||
out_stride: *mut i32,
|
||||
) -> *const RenHdcOption {
|
||||
if !out_count.is_null() {
|
||||
*out_count = OPTIONS.len() as i32;
|
||||
}
|
||||
if !out_stride.is_null() {
|
||||
*out_stride = std::mem::size_of::<RenHdcOption>() as i32;
|
||||
}
|
||||
OPTIONS.as_ptr()
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn renhdrum_store_create() -> *mut RenHdcStore {
|
||||
Box::into_raw(Box::new(RenHdcStore::new()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_destroy(s: *mut RenHdcStore) {
|
||||
if !s.is_null() {
|
||||
drop(Box::from_raw(s));
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_get(
|
||||
s: *const RenHdcStore,
|
||||
key: *const c_char,
|
||||
out: *mut i32,
|
||||
) -> i32 {
|
||||
if s.is_null() || key.is_null() || out.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
match find(key) {
|
||||
Some(i) => {
|
||||
*out = (*s).values[i];
|
||||
RENHDRUM_OK
|
||||
}
|
||||
None => RENHDRUM_ERR_INVALID_ARG,
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_set(
|
||||
s: *mut RenHdcStore,
|
||||
key: *const c_char,
|
||||
value: i32,
|
||||
) -> i32 {
|
||||
if s.is_null() || key.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
match find(key) {
|
||||
Some(i) => {
|
||||
(*s).values[i] = value.clamp(OPTIONS[i].min, OPTIONS[i].max);
|
||||
RENHDRUM_OK
|
||||
}
|
||||
None => RENHDRUM_ERR_INVALID_ARG,
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_reset(s: *mut RenHdcStore) -> i32 {
|
||||
if s.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
*s = RenHdcStore::new();
|
||||
RENHDRUM_OK
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_is_recommended(
|
||||
s: *const RenHdcStore,
|
||||
out: *mut bool,
|
||||
) -> i32 {
|
||||
if s.is_null() || out.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
*out = (*s).is_recommended();
|
||||
RENHDRUM_OK
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_to_config(
|
||||
s: *const RenHdcStore,
|
||||
out: *mut RenHdcConfig,
|
||||
) -> i32 {
|
||||
if s.is_null() || out.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
*out = (*s).to_config();
|
||||
RENHDRUM_OK
|
||||
}
|
||||
|
||||
/// Intensity (`gain`), then a power curve lifting weak rumble (`low_boost`): exponent 1.0 at 0
|
||||
/// down to 0.4 at 100. Below a small knee the curve turns quadratic so near-silent values between
|
||||
/// hits do not become a constant buzz. Same formula as lichii `ShapeAmplitude`.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_store_shape_amplitude(
|
||||
s: *const RenHdcStore,
|
||||
amplitude: f32,
|
||||
) -> f32 {
|
||||
if s.is_null() {
|
||||
return amplitude;
|
||||
}
|
||||
let gain = (*s).value("gain") as f32;
|
||||
let boost = (*s).value("low_boost");
|
||||
let x = (amplitude * gain / 100.0).min(1.0);
|
||||
if x <= 0.0 || boost <= 0 {
|
||||
return x;
|
||||
}
|
||||
let exponent = 1.0 - 0.006 * boost as f32;
|
||||
const KNEE: f32 = 0.02;
|
||||
if x < KNEE {
|
||||
let r = x / KNEE;
|
||||
return KNEE.powf(exponent) * r * r;
|
||||
}
|
||||
x.powf(exponent)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::CString;
|
||||
|
||||
fn key(o: &RenHdcOption) -> String {
|
||||
unsafe { CStr::from_ptr(o.key) }
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn set(s: *mut RenHdcStore, k: &str, v: i32) -> i32 {
|
||||
let k = CString::new(k).unwrap();
|
||||
unsafe { renhdrum_store_set(s, k.as_ptr(), v) }
|
||||
}
|
||||
|
||||
fn get(s: *const RenHdcStore, k: &str) -> i32 {
|
||||
let k = CString::new(k).unwrap();
|
||||
let mut out = -999;
|
||||
assert_eq!(
|
||||
unsafe { renhdrum_store_get(s, k.as_ptr(), &mut out) },
|
||||
RENHDRUM_OK
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn recommended(s: *const RenHdcStore) -> bool {
|
||||
let mut r = false;
|
||||
unsafe { renhdrum_store_is_recommended(s, &mut r) };
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_unique_and_ranges_sane() {
|
||||
let (mut n, mut stride) = (0, 0);
|
||||
let base = unsafe { renhdrum_options(&mut n, &mut stride) };
|
||||
assert_eq!(stride as usize, std::mem::size_of::<RenHdcOption>());
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for i in 0..n as usize {
|
||||
let o =
|
||||
unsafe { &*((base as *const u8).add(i * stride as usize) as *const RenHdcOption) };
|
||||
assert!(seen.insert(key(o)), "duplicate key {}", key(o));
|
||||
assert!(o.min <= o.def && o.def <= o.max, "{}", key(o));
|
||||
if o.requires >= 0 {
|
||||
assert!((o.requires as usize) < n as usize);
|
||||
}
|
||||
}
|
||||
assert_eq!(USB_INTERVALS_MS[OPTIONS[I_USB_INTERVAL].def as usize], 15);
|
||||
assert_eq!(OPTIONS[18].max, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_store_is_recommended_standard() {
|
||||
let s = renhdrum_store_create();
|
||||
let mut cfg = unsafe { std::mem::zeroed::<RenHdcConfig>() };
|
||||
assert_eq!(
|
||||
unsafe { renhdrum_store_to_config(s, &mut cfg) },
|
||||
RENHDRUM_OK
|
||||
);
|
||||
let mut expected = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Standard, &mut expected);
|
||||
let mut expected = RenHdcConfig::from(&expected);
|
||||
expected.hd_rumble_experimental_bt_fast = true; // Detailed (5 ms) by default
|
||||
assert_eq!(cfg, expected);
|
||||
assert_eq!(
|
||||
HdRumblePreset::detect(&RumbleConfigController::from(&cfg)),
|
||||
HdRumblePresetKind::Standard
|
||||
);
|
||||
assert!(recommended(s));
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bluetooth_mode_compatible_is_custom_until_reset() {
|
||||
let s = renhdrum_store_create();
|
||||
assert_eq!(set(s, "switch_bt_mode", 1), RENHDRUM_OK);
|
||||
let mut cfg = unsafe { std::mem::zeroed::<RenHdcConfig>() };
|
||||
unsafe { renhdrum_store_to_config(s, &mut cfg) };
|
||||
assert_eq!(cfg.hd_rumble_bluetooth_level, 4);
|
||||
assert!(!cfg.hd_rumble_experimental_bt_fast);
|
||||
assert!(!recommended(s));
|
||||
unsafe { renhdrum_store_reset(s) };
|
||||
assert!(recommended(s));
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_key_errors_and_values_clamp() {
|
||||
let s = renhdrum_store_create();
|
||||
assert_eq!(set(s, "nope", 1), RENHDRUM_ERR_INVALID_ARG);
|
||||
let k = CString::new("nope").unwrap();
|
||||
let mut out = 0;
|
||||
assert_eq!(
|
||||
unsafe { renhdrum_store_get(s, k.as_ptr(), &mut out) },
|
||||
RENHDRUM_ERR_INVALID_ARG
|
||||
);
|
||||
set(s, "gain", 5000);
|
||||
assert_eq!(get(s, "gain"), 1000);
|
||||
set(s, "gain", -3);
|
||||
assert_eq!(get(s, "gain"), 25);
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_keys_reach_config() {
|
||||
let s = renhdrum_store_create();
|
||||
set(s, "dualsense_hd_haptics", 0);
|
||||
set(s, "usb_interval_ms", 3);
|
||||
set(s, "dualsense_volume", 40);
|
||||
let mut cfg = unsafe { std::mem::zeroed::<RenHdcConfig>() };
|
||||
unsafe { renhdrum_store_to_config(s, &mut cfg) };
|
||||
assert!(cfg.dualsense_hd_haptics_off);
|
||||
assert_eq!(cfg.hd_rumble_usb_interval_ms, 30);
|
||||
assert_eq!(cfg.dualsense_haptics_volume, 40);
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_covers_ui_guidelines_keys() {
|
||||
let md = std::fs::read_to_string(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/docs/integration/ui-guidelines.md"
|
||||
))
|
||||
.unwrap();
|
||||
let mut checked = 0;
|
||||
for line in md.lines().filter(|l| l.starts_with("| `")) {
|
||||
let first = line.split('|').nth(1).unwrap();
|
||||
for (i, part) in first.split('`').enumerate() {
|
||||
if i % 2 == 1 {
|
||||
assert!(
|
||||
find(CString::new(part).unwrap().as_ptr()).is_some(),
|
||||
"missing key {part}"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, OPTIONS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_amplitude_matches_cpp_formula() {
|
||||
let cases = [
|
||||
(100, 0, 0.3f64),
|
||||
(400, 0, 0.1),
|
||||
(100, 50, 0.01),
|
||||
(100, 50, 0.5),
|
||||
(1000, 100, 0.9),
|
||||
];
|
||||
for (gain, boost, a) in cases {
|
||||
let s = renhdrum_store_create();
|
||||
set(s, "gain", gain);
|
||||
set(s, "low_boost", boost);
|
||||
let got = unsafe { renhdrum_store_shape_amplitude(s, a as f32) } as f64;
|
||||
let x = (a * gain as f64 / 100.0).min(1.0);
|
||||
let want = if boost == 0 {
|
||||
x
|
||||
} else {
|
||||
let e = 1.0 - 0.006 * boost as f64;
|
||||
if x < 0.02 {
|
||||
0.02f64.powf(e) * (x / 0.02).powi(2)
|
||||
} else {
|
||||
x.powf(e)
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
(got - want).abs() < 1e-6,
|
||||
"({gain},{boost},{a}): {got} vs {want}"
|
||||
);
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
let s = renhdrum_store_create();
|
||||
assert_eq!(unsafe { renhdrum_store_shape_amplitude(s, 0.37) }, 0.37);
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
}
|
||||
455
third_party/renhdrum/src/planner/amfm_measure.rs
vendored
Normal file
455
third_party/renhdrum/src/planner/amfm_measure.rs
vendored
Normal file
@@ -0,0 +1,455 @@
|
||||
use crate::encoding::amfm::HdAmFmEncoding;
|
||||
use crate::encoding::standard::hd_encode_side;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const AM_FM_PACKET_MS: i32 = 15;
|
||||
pub const AM_FM_MEASURE_PHASE_SLOTS: i32 = 67;
|
||||
pub const AM_FM_MEASURE_SEGMENT_MS: i32 = 3 * AM_FM_MEASURE_PHASE_SLOTS * AM_FM_PACKET_MS; // 3015 ms
|
||||
pub const AM_FM_MEASURE_MARKER_MS: i32 = 900;
|
||||
pub const AM_FM_MEASURE_WEAK: f32 = 0.224;
|
||||
pub const AM_FM_AMPLITUDE: f32 = 0.45;
|
||||
|
||||
pub const AM_FM_MEASURE_LOW_CODES: [i32; 5] = [12, 13, 14, 15, 16];
|
||||
|
||||
pub fn am_fm_measure_codes() -> Vec<i32> {
|
||||
(12..=31).filter(|&c| c != HdAmFmEncoding::HOLD).collect()
|
||||
}
|
||||
|
||||
pub fn am_fm_measure_changes_amplitude(code: i32) -> bool {
|
||||
(17..=22).contains(&code) || code >= 26
|
||||
}
|
||||
|
||||
pub fn format_steps(now: &[i64; 5], logged: &[i64; 5]) -> String {
|
||||
let labels = ["1", "2-3", "4-7", "8-15", "16+"];
|
||||
labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, label)| format!("{}:{}", label, now[i] - logged[i]))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
pub struct AmFmSegment {
|
||||
pub name: String,
|
||||
pub ms: i32,
|
||||
side_at_fn: Arc<dyn Fn(i32) -> Option<[u8; 4]> + Send + Sync>,
|
||||
}
|
||||
|
||||
impl Clone for AmFmSegment {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
name: self.name.clone(),
|
||||
ms: self.ms,
|
||||
side_at_fn: Arc::clone(&self.side_at_fn),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AmFmSegment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AmFmSegment")
|
||||
.field("name", &self.name)
|
||||
.field("ms", &self.ms)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl AmFmSegment {
|
||||
pub fn side_at(&self, slot: i32) -> Option<[u8; 4]> {
|
||||
(self.side_at_fn)(slot)
|
||||
}
|
||||
}
|
||||
|
||||
fn am_fm_two_wave(amp_low: f32, freq_low: f32, amp_high: f32, freq_high: f32) -> [u8; 4] {
|
||||
let mut side = [0u8; 4];
|
||||
hd_encode_side(&mut side, amp_low, freq_low, amp_high, freq_high);
|
||||
side
|
||||
}
|
||||
|
||||
fn am_fm_side(v: u32) -> [u8; 4] {
|
||||
let mut side = [0u8; 4];
|
||||
HdAmFmEncoding::write_side(&mut side, v);
|
||||
side
|
||||
}
|
||||
|
||||
fn am_fm_measure_codes3(high: bool, c0: i32, c1: i32, c2: i32) -> [u8; 4] {
|
||||
const HOLD: i32 = HdAmFmEncoding::HOLD;
|
||||
if high {
|
||||
am_fm_side(HdAmFmEncoding::pack_three_raw(HOLD, c0, HOLD, c1, HOLD, c2).unwrap())
|
||||
} else {
|
||||
am_fm_side(HdAmFmEncoding::pack_three_raw(c0, HOLD, c1, HOLD, c2, HOLD).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
fn am_fm_measure_phases(
|
||||
name: &str,
|
||||
first: [u8; 4],
|
||||
second: [u8; 4],
|
||||
third: [u8; 4],
|
||||
) -> AmFmSegment {
|
||||
AmFmSegment {
|
||||
name: name.to_string(),
|
||||
ms: AM_FM_MEASURE_SEGMENT_MS,
|
||||
side_at_fn: Arc::new(move |s| {
|
||||
let phase = s / AM_FM_MEASURE_PHASE_SLOTS;
|
||||
match phase {
|
||||
0 => Some(first),
|
||||
1 => Some(second),
|
||||
_ => Some(third),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn am_fm_measure_code_segment(code: i32, high: bool) -> AmFmSegment {
|
||||
let amplitude = am_fm_measure_changes_amplitude(code);
|
||||
let start = if (17..=22).contains(&code) {
|
||||
AM_FM_MEASURE_WEAK
|
||||
} else {
|
||||
AM_FM_AMPLITUDE
|
||||
};
|
||||
|
||||
let reference = if high {
|
||||
am_fm_two_wave(0.0, 160.0, start, 640.0)
|
||||
} else {
|
||||
am_fm_two_wave(start, 160.0, 0.0, 320.0)
|
||||
};
|
||||
|
||||
let keep = if amplitude {
|
||||
HdAmFmEncoding::HOLD
|
||||
} else {
|
||||
HdAmFmEncoding::code(start)
|
||||
};
|
||||
|
||||
let once = am_fm_measure_codes3(high, code, keep, keep);
|
||||
let three = am_fm_measure_codes3(high, code, code, code);
|
||||
let rest = am_fm_measure_codes3(high, keep, keep, keep);
|
||||
let band = if high { "high 640" } else { "low 160" };
|
||||
let holds = if amplitude {
|
||||
"24".to_string()
|
||||
} else {
|
||||
format!("level {}", keep)
|
||||
};
|
||||
|
||||
let name = format!(
|
||||
"{}{} code {} on the {} Hz band at {:.3}: reference, then 1x, then 10x (holds {})",
|
||||
if high { "H" } else { "L" },
|
||||
code,
|
||||
code,
|
||||
band,
|
||||
start,
|
||||
holds
|
||||
);
|
||||
|
||||
AmFmSegment {
|
||||
name,
|
||||
ms: AM_FM_MEASURE_SEGMENT_MS,
|
||||
side_at_fn: Arc::new(move |s| {
|
||||
let phase = s / AM_FM_MEASURE_PHASE_SLOTS;
|
||||
let i = s % AM_FM_MEASURE_PHASE_SLOTS;
|
||||
match phase {
|
||||
0 => Some(reference),
|
||||
1 => Some(if i == 0 { once } else { rest }),
|
||||
_ => Some(if i < 3 { three } else { rest }),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hd_am_fm_measure_segments() -> Vec<AmFmSegment> {
|
||||
const HOLD: i32 = HdAmFmEncoding::HOLD;
|
||||
let neutral: [u8; 4] = [0x00, 0x01, 0x40, 0x40];
|
||||
let beep = am_fm_two_wave(0.0, 160.0, AM_FM_AMPLITUDE, 320.0);
|
||||
let amp = HdAmFmEncoding::amp7(AM_FM_AMPLITUDE);
|
||||
|
||||
let high = |f: f32| am_fm_two_wave(0.0, 160.0, AM_FM_AMPLITUDE, f);
|
||||
let low = |f: f32| am_fm_two_wave(AM_FM_AMPLITUDE, f, 0.0, 320.0);
|
||||
let two14_high = |f: f32| {
|
||||
am_fm_side(
|
||||
HdAmFmEncoding::pack_two_14bit(
|
||||
true,
|
||||
HdAmFmEncoding::freq7(true, f),
|
||||
amp,
|
||||
HOLD,
|
||||
HOLD,
|
||||
HOLD,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let two14_low = |f: f32| {
|
||||
am_fm_side(
|
||||
HdAmFmEncoding::pack_two_14bit(
|
||||
false,
|
||||
HdAmFmEncoding::freq7(false, f),
|
||||
amp,
|
||||
HOLD,
|
||||
HOLD,
|
||||
HOLD,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let three7_high = |f: f32| {
|
||||
am_fm_side(
|
||||
HdAmFmEncoding::pack_three_7bit(
|
||||
true,
|
||||
true,
|
||||
HdAmFmEncoding::freq7(true, f),
|
||||
HOLD,
|
||||
HOLD,
|
||||
HOLD,
|
||||
HOLD,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
|
||||
let mut segments = vec![
|
||||
AmFmSegment {
|
||||
name: "M marker: 3 beeps (two-wave high 320 Hz, 105 ms)".to_string(),
|
||||
ms: AM_FM_MEASURE_MARKER_MS,
|
||||
side_at_fn: Arc::new(move |s| {
|
||||
if s % 20 < 7 {
|
||||
Some(beep)
|
||||
} else if s % 20 == 7 {
|
||||
Some(neutral)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
},
|
||||
am_fm_measure_phases(
|
||||
"R1 two-wave high band 320 / 640 / 1000 Hz",
|
||||
high(320.0),
|
||||
high(640.0),
|
||||
high(1000.0),
|
||||
),
|
||||
am_fm_measure_phases(
|
||||
"R2 two-wave low band 80 / 160 / 320 Hz",
|
||||
low(80.0),
|
||||
low(160.0),
|
||||
low(320.0),
|
||||
),
|
||||
am_fm_measure_phases(
|
||||
"R3 Two14bit high band 320 / 640 / 1000 Hz (compare with R1)",
|
||||
two14_high(320.0),
|
||||
two14_high(640.0),
|
||||
two14_high(1000.0),
|
||||
),
|
||||
am_fm_measure_phases(
|
||||
"R4 Two14bit low band 80 / 160 / 320 Hz (compare with R2, works at 80 Hz)",
|
||||
two14_low(80.0),
|
||||
two14_low(160.0),
|
||||
two14_low(320.0),
|
||||
),
|
||||
am_fm_measure_phases(
|
||||
"R5 two-wave high 640 Hz, then Three7bit high band frequency 320, then 1000 Hz",
|
||||
high(640.0),
|
||||
three7_high(320.0),
|
||||
three7_high(1000.0),
|
||||
),
|
||||
am_fm_measure_phases(
|
||||
"R6 hold control: two-wave high 640 Hz, then only code 24 for 2 s",
|
||||
high(640.0),
|
||||
am_fm_measure_codes3(true, HOLD, HOLD, HOLD),
|
||||
am_fm_measure_codes3(true, HOLD, HOLD, HOLD),
|
||||
),
|
||||
];
|
||||
|
||||
for code in am_fm_measure_codes() {
|
||||
segments.push(am_fm_measure_code_segment(code, true));
|
||||
}
|
||||
|
||||
for &code in &AM_FM_MEASURE_LOW_CODES {
|
||||
segments.push(am_fm_measure_code_segment(code, false));
|
||||
}
|
||||
|
||||
segments
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::encoding::crisp_notes::HdSideSample;
|
||||
use crate::planner::amfm_planner::{HdAmFmPlanner, HdAmFmSideKind};
|
||||
|
||||
fn slots(segment: &AmFmSegment) -> i32 {
|
||||
segment.ms / 15
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_schedule_is_fixed() {
|
||||
let segments = hd_am_fm_measure_segments();
|
||||
let ids: Vec<String> = segments
|
||||
.iter()
|
||||
.map(|s| s.name.split(' ').next().unwrap().to_string())
|
||||
.collect();
|
||||
|
||||
let mut expected: Vec<String> = vec![
|
||||
"M".into(),
|
||||
"R1".into(),
|
||||
"R2".into(),
|
||||
"R3".into(),
|
||||
"R4".into(),
|
||||
"R5".into(),
|
||||
"R6".into(),
|
||||
];
|
||||
for c in (12..=31).filter(|&c| c != HdAmFmEncoding::HOLD) {
|
||||
expected.push(format!("H{}", c));
|
||||
}
|
||||
for c in 12..=16 {
|
||||
expected.push(format!("L{}", c));
|
||||
}
|
||||
|
||||
assert_eq!(ids, expected);
|
||||
assert_eq!(segments[0].ms, 900);
|
||||
for s in segments.iter().skip(1) {
|
||||
assert_eq!(s.ms, 3015);
|
||||
}
|
||||
assert_eq!(AM_FM_MEASURE_SEGMENT_MS, 3 * AM_FM_MEASURE_PHASE_SLOTS * 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_every_slot_builds() {
|
||||
for segment in hd_am_fm_measure_segments() {
|
||||
for slot in 0..slots(&segment) {
|
||||
let side = segment.side_at(slot);
|
||||
let is_valid = side.is_none() || side.as_ref().map_or(false, |s| s.len() == 4);
|
||||
assert!(is_valid, "segment {}", segment.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_code_segments_apply_the_code_ten_times() {
|
||||
for segment in hd_am_fm_measure_segments()
|
||||
.into_iter()
|
||||
.filter(|s| s.name.starts_with('H') || s.name.starts_with('L'))
|
||||
{
|
||||
let high = segment.name.starts_with('H');
|
||||
let code_str = segment.name.split(' ').next().unwrap();
|
||||
let code: i32 = code_str[1..].parse().unwrap();
|
||||
let keep = if am_fm_measure_changes_amplitude(code) {
|
||||
HdAmFmEncoding::HOLD
|
||||
} else {
|
||||
HdAmFmEncoding::code(0.45)
|
||||
};
|
||||
let mut applied = 0;
|
||||
|
||||
for slot in AM_FM_MEASURE_PHASE_SLOTS..slots(&segment) {
|
||||
let side_bytes = segment.side_at(slot).unwrap();
|
||||
let v = u32::from_le_bytes(side_bytes);
|
||||
|
||||
assert_eq!(v >> 30, 3, "segment {}", segment.name);
|
||||
|
||||
for sample in 0..3 {
|
||||
let lo = ((v >> (25 - 10 * sample)) & 31) as i32;
|
||||
let hi = ((v >> (20 - 10 * sample)) & 31) as i32;
|
||||
let measured = if high { hi } else { lo };
|
||||
let other = if high { lo } else { hi };
|
||||
|
||||
assert_eq!(other, HdAmFmEncoding::HOLD, "segment {}", segment.name);
|
||||
assert!(
|
||||
measured == code || measured == keep,
|
||||
"segment {}, slot {}, sample {}, measured {}, expected {} or {}",
|
||||
segment.name,
|
||||
slot,
|
||||
sample,
|
||||
measured,
|
||||
code,
|
||||
keep
|
||||
);
|
||||
|
||||
if measured == code {
|
||||
applied += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(applied, 10, "segment {}", segment.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_amplitude_up_codes_stay_below_full_scale() {
|
||||
assert!(AM_FM_MEASURE_WEAK * 2.0f32.powf(10.0 * 0.125) < 1.0);
|
||||
assert!(am_fm_measure_changes_amplitude(17));
|
||||
assert!(!am_fm_measure_changes_amplitude(23));
|
||||
assert!(am_fm_measure_changes_amplitude(31));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_step_buckets() {
|
||||
let steps = [1, 2, 3, 4, 7, 8, 15, 16, 40];
|
||||
let buckets = [0, 1, 1, 2, 2, 3, 3, 4, 4];
|
||||
|
||||
for (s, b) in steps.iter().zip(buckets.iter()) {
|
||||
assert_eq!(HdAmFmPlanner::step_bucket(*s), *b);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
format_steps(&[5, 4, 3, 2, 1], &[1, 1, 1, 1, 1]),
|
||||
"1:4 2-3:3 4-7:2 8-15:1 16+:0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fallback_detail_counts_band_and_steps() {
|
||||
let low160 = HdSideSample::new(0.45, 160.0, 0.0, 320.0);
|
||||
let mut p = HdAmFmPlanner::new();
|
||||
p.add(0, &low160, &low160);
|
||||
let mut packet = [0u8; 8];
|
||||
assert!(p.poll(15, &mut packet));
|
||||
|
||||
p.add(15, &HdSideSample::new(0.45, 170.0, 0.0, 320.0), &low160);
|
||||
p.add(21, &HdSideSample::new(0.45, 165.0, 0.0, 320.0), &low160);
|
||||
assert!(p.poll(30, &mut packet));
|
||||
|
||||
assert_eq!(p.last_left(), HdAmFmSideKind::Fallback);
|
||||
assert_eq!(p.fallback_band_low(), 1);
|
||||
assert_eq!(p.fallback_band_high() + p.fallback_band_both(), 0);
|
||||
assert_eq!(p.frequency_steps_low(), &[0, 2, 0, 0, 0]);
|
||||
assert_eq!(p.frequency_steps_high().iter().sum::<i64>(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fallback_bands_add_up_to_the_fallbacks() {
|
||||
let mut p = HdAmFmPlanner::new();
|
||||
let freqs = [80.0f32, 200.0, 120.0, 160.0, 300.0];
|
||||
let mut now = 0;
|
||||
let mut packet = [0u8; 8];
|
||||
|
||||
for i in 0..40 {
|
||||
p.add(
|
||||
now,
|
||||
&HdSideSample::new(
|
||||
0.45,
|
||||
freqs[i % freqs.len()],
|
||||
0.2,
|
||||
if i % 3 == 0 { 640.0 } else { 320.0 },
|
||||
),
|
||||
&HdSideSample::new(0.0, 160.0, 0.3, freqs[(i + 1) % freqs.len()] * 4.0),
|
||||
);
|
||||
p.add(
|
||||
now + 7,
|
||||
&HdSideSample::new(0.3, freqs[(i + 2) % freqs.len()], 0.2, 320.0),
|
||||
&HdSideSample::new(0.0, 160.0, 0.3, 700.0),
|
||||
);
|
||||
p.poll(now + 15, &mut packet);
|
||||
now += 15;
|
||||
}
|
||||
|
||||
assert!(p.fallback_sides() > 0);
|
||||
assert_eq!(
|
||||
p.fallback_band_low() + p.fallback_band_high() + p.fallback_band_both(),
|
||||
p.fallback_sides()
|
||||
);
|
||||
assert!(p.fallback_band_high() + p.fallback_band_both() > 0);
|
||||
assert!(
|
||||
p.frequency_steps_low().iter().sum::<i64>()
|
||||
+ p.frequency_steps_high().iter().sum::<i64>()
|
||||
> 0
|
||||
);
|
||||
}
|
||||
}
|
||||
2049
third_party/renhdrum/src/planner/amfm_planner.rs
vendored
Normal file
2049
third_party/renhdrum/src/planner/amfm_planner.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
9
third_party/renhdrum/src/planner/mod.rs
vendored
Normal file
9
third_party/renhdrum/src/planner/mod.rs
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod amfm_measure;
|
||||
pub mod amfm_planner;
|
||||
|
||||
pub use amfm_measure::{
|
||||
am_fm_measure_changes_amplitude, am_fm_measure_codes, format_steps, hd_am_fm_measure_segments,
|
||||
AmFmSegment, AM_FM_AMPLITUDE, AM_FM_MEASURE_LOW_CODES, AM_FM_MEASURE_MARKER_MS,
|
||||
AM_FM_MEASURE_PHASE_SLOTS, AM_FM_MEASURE_SEGMENT_MS, AM_FM_MEASURE_WEAK, AM_FM_PACKET_MS,
|
||||
};
|
||||
pub use amfm_planner::{HdAmFmFallbackKind, HdAmFmPlanner, HdAmFmSideKind};
|
||||
914
third_party/renhdrum/src/play_report.rs
vendored
Normal file
914
third_party/renhdrum/src/play_report.rs
vendored
Normal file
@@ -0,0 +1,914 @@
|
||||
use crate::status::RumbleTransport;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PlayEvent {
|
||||
FpsLow,
|
||||
VramHigh,
|
||||
RumbleDense,
|
||||
RumbleMerged,
|
||||
AutoSlowOn,
|
||||
AutoSlowOff,
|
||||
PadConnect,
|
||||
PadDisconnect,
|
||||
PadTransport,
|
||||
GyroLost,
|
||||
Battery,
|
||||
RumbleConfig,
|
||||
Count,
|
||||
}
|
||||
|
||||
pub struct PlayReport;
|
||||
|
||||
impl PlayReport {
|
||||
pub const OFF_FLAG_FILE: &'static str = "report_stats_off";
|
||||
pub const TICK_MS: i32 = 1000;
|
||||
pub const PERF_INTERVAL_SECONDS: i32 = 30;
|
||||
pub const RUMBLE_INTERVAL_SECONDS: i32 = 10;
|
||||
|
||||
pub const MIN_FPS_SAMPLE: f64 = 3.0;
|
||||
pub const FPS_LOW_THRESHOLD: f64 = 25.0;
|
||||
pub const VRAM_HIGH_FRACTION: f64 = 0.9;
|
||||
|
||||
pub const RUMBLE_DENSE_SAMPLES_PER_SECOND: i32 = 90;
|
||||
pub const MERGED_HIGH_PERCENT: f64 = 50.0;
|
||||
pub const MERGED_MIN_SAMPLES: i32 = 20;
|
||||
|
||||
pub const EVENT_NAMES: [&'static str; 12] = [
|
||||
"fps_low",
|
||||
"vram_high",
|
||||
"rumble_dense",
|
||||
"rumble_merged",
|
||||
"autoslow_on",
|
||||
"autoslow_off",
|
||||
"pad_connect",
|
||||
"pad_disconnect",
|
||||
"pad_transport",
|
||||
"gyro_lost",
|
||||
"battery",
|
||||
"rumble_config",
|
||||
];
|
||||
|
||||
pub fn event_name(kind: PlayEvent) -> &'static str {
|
||||
let i = kind as usize;
|
||||
if i < Self::EVENT_NAMES.len() {
|
||||
Self::EVENT_NAMES[i]
|
||||
} else {
|
||||
"unknown"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_time(ms: i64) -> String {
|
||||
let ms = ms.max(0);
|
||||
let seconds = ms / 1000;
|
||||
format!("{:02}:{:02}", seconds / 60, seconds % 60)
|
||||
}
|
||||
|
||||
pub fn transport_name(transport: RumbleTransport) -> &'static str {
|
||||
match transport {
|
||||
RumbleTransport::Usb => "USB",
|
||||
RumbleTransport::Bluetooth => "BT",
|
||||
RumbleTransport::Virtual => "Virtual",
|
||||
_ => "?",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn power_level_name(level: i32) -> &'static str {
|
||||
match level {
|
||||
0 => "empty",
|
||||
1 => "low",
|
||||
2 => "medium",
|
||||
3 => "full",
|
||||
4 => "max",
|
||||
5 => "wired",
|
||||
-1 => "n/a",
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn merged_percent(samples: i64, packets: i64) -> f64 {
|
||||
if samples <= 0 {
|
||||
0.0
|
||||
} else {
|
||||
(((samples - packets) as f64 * 100.0) / samples as f64).clamp(0.0, 100.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clean(text: &str) -> String {
|
||||
if text.is_empty() {
|
||||
return "?".to_string();
|
||||
}
|
||||
text.replace('|', "/").replace(['\n', '\r'], " ")
|
||||
}
|
||||
|
||||
pub fn format_perf(
|
||||
t_ms: i64,
|
||||
fps: &StatWindow,
|
||||
fifo: &StatWindow,
|
||||
ram_gb: f64,
|
||||
vram_used_gb: f64,
|
||||
vram_budget_gb: f64,
|
||||
cpu_process: &StatWindow,
|
||||
cpu_machine: &StatWindow,
|
||||
) -> String {
|
||||
let mut s = format!("Perf | t={} | fps ", Self::format_time(t_ms));
|
||||
|
||||
if fps.count > 0 {
|
||||
s.push_str(&format!(
|
||||
"avg={:.1} min={:.1} max={:.1}",
|
||||
fps.average(),
|
||||
fps.min,
|
||||
fps.max
|
||||
));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
|
||||
s.push_str(" | fifo=");
|
||||
Self::append_percent(&mut s, fifo);
|
||||
|
||||
s.push_str(&format!(" | ram={:.2}GB | vram=", ram_gb));
|
||||
|
||||
if vram_budget_gb > 0.0 {
|
||||
s.push_str(&format!("{:.2}/{:.2}GB", vram_used_gb, vram_budget_gb));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
|
||||
s.push_str(" | cpu=");
|
||||
Self::append_percent(&mut s, cpu_process);
|
||||
s.push('/');
|
||||
Self::append_percent(&mut s, cpu_machine);
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
fn append_percent(s: &mut String, window: &StatWindow) {
|
||||
if window.count > 0 {
|
||||
s.push_str(&format!("{:.0}%", window.average()));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_rumble(
|
||||
t_ms: i64,
|
||||
player: &str,
|
||||
controller: &str,
|
||||
transport: RumbleTransport,
|
||||
avg_samples: f64,
|
||||
max_samples: i32,
|
||||
max_window_ms: i32,
|
||||
packets_per_second: f64,
|
||||
merged_percent: f64,
|
||||
pacing: Option<&str>,
|
||||
auto_slow: Option<&str>,
|
||||
sync: Option<&str>,
|
||||
clicks: Option<i64>,
|
||||
link: Option<&str>,
|
||||
) -> String {
|
||||
let pacing_str = match pacing {
|
||||
Some(p) if !p.is_empty() => Self::clean(p),
|
||||
_ => "off".to_string(),
|
||||
};
|
||||
|
||||
let auto_slow_str = auto_slow.unwrap_or("n/a");
|
||||
|
||||
let mut s = format!(
|
||||
"Rumble | t={} | {} {} {} | samples/s avg={:.1} max={}/{}ms | packets/s={:.1} | merged={:.0}% | pacing={} | autoslow={}",
|
||||
Self::format_time(t_ms),
|
||||
player,
|
||||
Self::clean(controller),
|
||||
Self::transport_name(transport),
|
||||
avg_samples,
|
||||
max_samples,
|
||||
max_window_ms,
|
||||
packets_per_second,
|
||||
merged_percent,
|
||||
pacing_str,
|
||||
auto_slow_str
|
||||
);
|
||||
|
||||
if let Some(c) = clicks {
|
||||
s.push_str(&format!(" | click={}", c));
|
||||
}
|
||||
|
||||
if let Some(l) = link {
|
||||
if !l.is_empty() {
|
||||
s.push_str(" | link ");
|
||||
s.push_str(l);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(sy) = sync {
|
||||
if !sy.is_empty() {
|
||||
s.push_str(" | sync ");
|
||||
s.push_str(sy);
|
||||
}
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
pub fn format_link(
|
||||
writes: i64,
|
||||
write_sum_us: i64,
|
||||
write_max_us: i64,
|
||||
reports: i64,
|
||||
seconds: f64,
|
||||
report_gap_max_us: i64,
|
||||
read_skipped: i64,
|
||||
queued_max: i32,
|
||||
bt_sync: bool,
|
||||
bt_gap_us: i64,
|
||||
backoffs: i64,
|
||||
skipped_small: i64,
|
||||
long_gaps: i64,
|
||||
long_gaps_skip: i64,
|
||||
long_gaps_lock: i64,
|
||||
long_gaps_clean: i64,
|
||||
bt_after_input: bool,
|
||||
) -> String {
|
||||
let mut s = "write=".to_string();
|
||||
|
||||
if writes > 0 {
|
||||
s.push_str(&format!(
|
||||
"{:.1}/{:.1}ms",
|
||||
write_sum_us as f64 / 1000.0 / writes as f64,
|
||||
write_max_us as f64 / 1000.0
|
||||
));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
|
||||
s.push_str(&format!(
|
||||
" reports={:.0}/s gapmax={:.0}ms skipread={} queue={}",
|
||||
reports as f64 / seconds.max(1.0),
|
||||
report_gap_max_us as f64 / 1000.0,
|
||||
read_skipped,
|
||||
queued_max
|
||||
));
|
||||
|
||||
if long_gaps >= 0 {
|
||||
s.push_str(&format!(
|
||||
" g80={} g80skip={} g80lock={} g80clean={}",
|
||||
long_gaps, long_gaps_skip, long_gaps_lock, long_gaps_clean
|
||||
));
|
||||
}
|
||||
|
||||
if bt_after_input {
|
||||
s.push_str(" b1=on");
|
||||
}
|
||||
|
||||
if bt_sync {
|
||||
s.push_str(&format!(
|
||||
" btgap={:.0}ms slow={} small={}",
|
||||
bt_gap_us as f64 / 1000.0,
|
||||
backoffs,
|
||||
skipped_small
|
||||
));
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
pub fn format_sync(
|
||||
sent_report: i64,
|
||||
sent_fallback: i64,
|
||||
wait_busy: i64,
|
||||
read_skipped: i64,
|
||||
gap_count: i64,
|
||||
gap_min_us: i64,
|
||||
gap_max_us: i64,
|
||||
gap_sum_us: i64,
|
||||
pump_cpu_us: i64,
|
||||
pump_alive_us: i64,
|
||||
) -> String {
|
||||
let mut s = format!(
|
||||
"report={} fallback={} busy={} skipread={} gap=",
|
||||
sent_report, sent_fallback, wait_busy, read_skipped
|
||||
);
|
||||
|
||||
if gap_count > 0 {
|
||||
s.push_str(&format!(
|
||||
"{:.1}/{:.1}/{:.1}ms",
|
||||
gap_min_us as f64 / 1000.0,
|
||||
gap_sum_us as f64 / 1000.0 / gap_count as f64,
|
||||
gap_max_us as f64 / 1000.0
|
||||
));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
|
||||
s.push_str(" pump=");
|
||||
|
||||
if pump_alive_us > 0 && pump_cpu_us >= 0 {
|
||||
s.push_str(&format!(
|
||||
"{:.2}%",
|
||||
pump_cpu_us as f64 * 100.0 / pump_alive_us as f64
|
||||
));
|
||||
} else {
|
||||
s.push_str("n/a");
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
pub fn format_event(t_ms: i64, kind: PlayEvent, detail: &str, suppressed: i32) -> String {
|
||||
let mut s = format!(
|
||||
"Event | t={} | {}",
|
||||
Self::format_time(t_ms),
|
||||
Self::event_name(kind)
|
||||
);
|
||||
|
||||
if !detail.is_empty() {
|
||||
s.push_str(" | ");
|
||||
s.push_str(&Self::clean(detail));
|
||||
}
|
||||
|
||||
if suppressed > 0 {
|
||||
s.push_str(&format!(" | +{} suppressed", suppressed));
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
pub fn format_game_start(
|
||||
title_id: &str,
|
||||
name: &str,
|
||||
version: Option<&str>,
|
||||
mods: Option<&[&str]>,
|
||||
) -> String {
|
||||
let ver_str = match version {
|
||||
Some(v) if !v.trim().is_empty() => {
|
||||
format!("v{}", Self::clean(v).trim_start_matches('v'))
|
||||
}
|
||||
_ => "v?".to_string(),
|
||||
};
|
||||
|
||||
let mut s = format!(
|
||||
"Game | start | {} | {} | {} | mods: ",
|
||||
Self::clean(title_id),
|
||||
Self::clean(name),
|
||||
ver_str
|
||||
);
|
||||
|
||||
match mods {
|
||||
Some(m) if !m.is_empty() => {
|
||||
for (i, mod_name) in m.iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.push_str(", ");
|
||||
}
|
||||
s.push_str(&Self::clean(mod_name).replace(',', ";"));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
s.push_str("none");
|
||||
}
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
pub fn format_game_stop(
|
||||
played_ms: i64,
|
||||
events: &PlayEventLimiter,
|
||||
timer_ticks: i64,
|
||||
timer_ms: f64,
|
||||
) -> String {
|
||||
let mut s = format!(
|
||||
"Game | stop | played={} | events",
|
||||
Self::format_time(played_ms)
|
||||
);
|
||||
|
||||
let mut any = false;
|
||||
for i in 0..PlayEvent::Count as usize {
|
||||
let kind = match i {
|
||||
0 => PlayEvent::FpsLow,
|
||||
1 => PlayEvent::VramHigh,
|
||||
2 => PlayEvent::RumbleDense,
|
||||
3 => PlayEvent::RumbleMerged,
|
||||
4 => PlayEvent::AutoSlowOn,
|
||||
5 => PlayEvent::AutoSlowOff,
|
||||
6 => PlayEvent::PadConnect,
|
||||
7 => PlayEvent::PadDisconnect,
|
||||
8 => PlayEvent::PadTransport,
|
||||
9 => PlayEvent::GyroLost,
|
||||
10 => PlayEvent::Battery,
|
||||
11 => PlayEvent::RumbleConfig,
|
||||
_ => break,
|
||||
};
|
||||
let total = events.total(kind);
|
||||
if total > 0 {
|
||||
s.push_str(&format!(" {}={}", Self::event_name(kind), total));
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !any {
|
||||
s.push_str(" none");
|
||||
}
|
||||
|
||||
let avg_us = if timer_ticks > 0 {
|
||||
timer_ms * 1000.0 / timer_ticks as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let share = if played_ms > 0 {
|
||||
timer_ms * 100.0 / played_ms as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
s.push_str(&format!(
|
||||
" | stats timer cpu={:.1}ms ticks={} avg={:.1}us share={:.4}%",
|
||||
timer_ms, timer_ticks, avg_us, share
|
||||
));
|
||||
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct StatWindow {
|
||||
pub count: i32,
|
||||
pub sum: f64,
|
||||
pub min: f64,
|
||||
pub max: f64,
|
||||
}
|
||||
|
||||
impl StatWindow {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn average(&self) -> f64 {
|
||||
if self.count > 0 {
|
||||
self.sum / self.count as f64
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&mut self, value: f64) {
|
||||
if self.count == 0 {
|
||||
self.min = value;
|
||||
self.max = value;
|
||||
} else {
|
||||
self.min = self.min.min(value);
|
||||
self.max = self.max.max(value);
|
||||
}
|
||||
self.count += 1;
|
||||
self.sum += value;
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlayEventLimiter {
|
||||
last_ms: [i64; PlayEvent::Count as usize],
|
||||
logged: [bool; PlayEvent::Count as usize],
|
||||
suppressed: [i32; PlayEvent::Count as usize],
|
||||
total: [i32; PlayEvent::Count as usize],
|
||||
}
|
||||
|
||||
impl Default for PlayEventLimiter {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
last_ms: [0; PlayEvent::Count as usize],
|
||||
logged: [false; PlayEvent::Count as usize],
|
||||
suppressed: [0; PlayEvent::Count as usize],
|
||||
total: [0; PlayEvent::Count as usize],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayEventLimiter {
|
||||
pub const MIN_INTERVAL_MS: i64 = 5000;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn try_log(&mut self, kind: PlayEvent, now_ms: i64, suppressed: &mut i32) -> bool {
|
||||
let i = kind as usize;
|
||||
if i >= PlayEvent::Count as usize {
|
||||
*suppressed = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
self.total[i] += 1;
|
||||
|
||||
if self.logged[i] && now_ms - self.last_ms[i] < Self::MIN_INTERVAL_MS {
|
||||
self.suppressed[i] += 1;
|
||||
*suppressed = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
*suppressed = self.suppressed[i];
|
||||
self.suppressed[i] = 0;
|
||||
self.last_ms[i] = now_ms;
|
||||
self.logged[i] = true;
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn total(&self, kind: PlayEvent) -> i32 {
|
||||
let i = kind as usize;
|
||||
if i < PlayEvent::Count as usize {
|
||||
self.total[i]
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn window(values: &[f64]) -> StatWindow {
|
||||
let mut w = StatWindow::new();
|
||||
for &v in values {
|
||||
w.add(v);
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time_is_minutes_and_seconds() {
|
||||
assert_eq!(PlayReport::format_time(0), "00:00");
|
||||
assert_eq!(PlayReport::format_time(999), "00:00");
|
||||
assert_eq!(PlayReport::format_time(5 * 60_000 + 30_000), "05:30");
|
||||
assert_eq!(PlayReport::format_time(75 * 60_000 + 3_000), "75:03");
|
||||
assert_eq!(PlayReport::format_time(125 * 60_000 + 59_999), "125:59");
|
||||
assert_eq!(PlayReport::format_time(-5), "00:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_perf_line() {
|
||||
let line = PlayReport::format_perf(
|
||||
330_000,
|
||||
&window(&[30.0, 27.14, 30.2]),
|
||||
&window(&[10.0, 14.0]),
|
||||
5.214,
|
||||
2.1,
|
||||
7.4,
|
||||
&window(&[28.0]),
|
||||
&window(&[41.0]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line,
|
||||
"Perf | t=05:30 | fps avg=29.1 min=27.1 max=30.2 | fifo=12% | ram=5.21GB | vram=2.10/7.40GB | cpu=28%/41%"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_perf_line_without_values() {
|
||||
let line = PlayReport::format_perf(
|
||||
30_000,
|
||||
&StatWindow::default(),
|
||||
&StatWindow::default(),
|
||||
1.5,
|
||||
0.0,
|
||||
0.0,
|
||||
&window(&[3.0]),
|
||||
&StatWindow::default(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line,
|
||||
"Perf | t=00:30 | fps n/a | fifo=n/a | ram=1.50GB | vram=n/a | cpu=3%/n/a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rumble_line_usb() {
|
||||
let line = PlayReport::format_rumble(
|
||||
330_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
142.34,
|
||||
168,
|
||||
250,
|
||||
33.1,
|
||||
76.7,
|
||||
Some("30 ms (auto-slow)"),
|
||||
Some("on"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line,
|
||||
"Rumble | t=05:30 | P1 Pro Controller USB | samples/s avg=142.3 max=168/250ms | packets/s=33.1 | merged=77% | pacing=30 ms (auto-slow) | autoslow=on"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rumble_line_with_sync() {
|
||||
let sync = PlayReport::format_sync(
|
||||
210, 2, 95, 40, 212, 15_900, 24_100, 3_580_000, 1_200, 10_000_000,
|
||||
);
|
||||
let line = PlayReport::format_rumble(
|
||||
330_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
142.34,
|
||||
168,
|
||||
250,
|
||||
21.2,
|
||||
85.1,
|
||||
Some("15 ms"),
|
||||
Some("off"),
|
||||
Some(&sync),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert!(line.ends_with("| autoslow=off | sync report=210 fallback=2 busy=95 skipread=40 gap=15.9/16.9/24.1ms pump=0.01%"));
|
||||
assert!(line.starts_with("Rumble | t=05:30 | P1 Pro Controller USB | samples/s avg=142.3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rumble_line_with_click_comes_before_sync() {
|
||||
let sync = PlayReport::format_sync(
|
||||
210, 2, 95, 40, 212, 15_900, 24_100, 3_580_000, 1_200, 10_000_000,
|
||||
);
|
||||
let line = PlayReport::format_rumble(
|
||||
330_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
142.34,
|
||||
168,
|
||||
250,
|
||||
21.2,
|
||||
85.1,
|
||||
Some("15 ms"),
|
||||
Some("off"),
|
||||
Some(&sync),
|
||||
Some(37),
|
||||
None,
|
||||
);
|
||||
|
||||
assert!(line.contains("| autoslow=off | click=37 | sync report=210"));
|
||||
|
||||
let no_sync = PlayReport::format_rumble(
|
||||
330_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
142.34,
|
||||
168,
|
||||
250,
|
||||
21.2,
|
||||
85.1,
|
||||
Some("15 ms"),
|
||||
Some("on"),
|
||||
None,
|
||||
Some(0),
|
||||
None,
|
||||
);
|
||||
|
||||
assert!(no_sync.ends_with("| autoslow=on | click=0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_fields_without_data_say_not_available() {
|
||||
assert_eq!(
|
||||
PlayReport::format_sync(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
"report=0 fallback=0 busy=0 skipread=0 gap=n/a pump=n/a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rumble_line_bluetooth() {
|
||||
let line = PlayReport::format_rumble(
|
||||
60_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Bluetooth,
|
||||
12.0,
|
||||
30,
|
||||
1000,
|
||||
8.0,
|
||||
33.3,
|
||||
Some("L2"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
line,
|
||||
"Rumble | t=01:00 | P1 Pro Controller BT | samples/s avg=12.0 max=30/1000ms | packets/s=8.0 | merged=33% | pacing=L2 | autoslow=n/a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_fields_bluetooth() {
|
||||
let link = PlayReport::format_link(
|
||||
600, 3_660_000, 38_000, 660, 10.0, 52_400, 4, 1, false, 0, 0, 0, -1, 0, 0, 0, false,
|
||||
);
|
||||
assert_eq!(
|
||||
link,
|
||||
"write=6.1/38.0ms reports=66/s gapmax=52ms skipread=4 queue=1"
|
||||
);
|
||||
|
||||
let sync = PlayReport::format_link(
|
||||
150, 900_000, 21_000, 655, 10.0, 31_000, 0, 1, true, 67_500, 2, 12, -1, 0, 0, 0, false,
|
||||
);
|
||||
assert_eq!(
|
||||
sync,
|
||||
"write=6.0/21.0ms reports=66/s gapmax=31ms skipread=0 queue=1 btgap=68ms slow=2 small=12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_fields_long_gaps_and_card_b1() {
|
||||
let link = PlayReport::format_link(
|
||||
150, 900_000, 21_000, 655, 10.0, 131_000, 2, 1, false, 0, 0, 0, 4, 1, 0, 3, true,
|
||||
);
|
||||
assert_eq!(
|
||||
link,
|
||||
"write=6.0/21.0ms reports=66/s gapmax=131ms skipread=2 queue=1 g80=4 g80skip=1 g80lock=0 g80clean=3 b1=on"
|
||||
);
|
||||
|
||||
let off = PlayReport::format_link(
|
||||
150, 900_000, 21_000, 655, 10.0, 31_000, 0, 1, false, 0, 0, 0, 0, 0, 0, 0, false,
|
||||
);
|
||||
assert_eq!(
|
||||
off,
|
||||
"write=6.0/21.0ms reports=66/s gapmax=31ms skipread=0 queue=1 g80=0 g80skip=0 g80lock=0 g80clean=0"
|
||||
);
|
||||
assert_eq!(
|
||||
PlayReport::format_link(
|
||||
150, 900_000, 21_000, 655, 10.0, 31_000, 0, 1, false, 0, 0, 0, -1, 0, 0, 0, false
|
||||
),
|
||||
"write=6.0/21.0ms reports=66/s gapmax=31ms skipread=0 queue=1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_fields_without_writes() {
|
||||
assert_eq!(
|
||||
PlayReport::format_link(0, 0, 0, 0, 0.5, 0, 0, 0, false, 0, 0, 0, -1, 0, 0, 0, false),
|
||||
"write=n/a reports=0/s gapmax=0ms skipread=0 queue=0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rumble_line_with_link_comes_after_click_and_before_sync() {
|
||||
let link = PlayReport::format_link(
|
||||
150, 900_000, 21_000, 655, 10.0, 31_000, 0, 1, true, 45_000, 0, 3, -1, 0, 0, 0, false,
|
||||
);
|
||||
let sync = PlayReport::format_sync(
|
||||
150, 0, 12, 0, 149, 45_100, 60_200, 7_000_000, 900, 10_000_000,
|
||||
);
|
||||
let line = PlayReport::format_rumble(
|
||||
60_000,
|
||||
"P1",
|
||||
"Pro Controller",
|
||||
RumbleTransport::Bluetooth,
|
||||
12.0,
|
||||
30,
|
||||
1000,
|
||||
8.0,
|
||||
33.3,
|
||||
Some("balanced"),
|
||||
None,
|
||||
Some(&sync),
|
||||
Some(2),
|
||||
Some(&link),
|
||||
);
|
||||
|
||||
assert!(line.contains("| pacing=balanced | autoslow=n/a | click=2 | link write=6.0/21.0ms reports=66/s gapmax=31ms skipread=0 queue=1 btgap=45ms slow=0 small=3 | sync report=150"));
|
||||
assert!(line.ends_with("pump=0.01%"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_line() {
|
||||
assert_eq!(
|
||||
PlayReport::format_event(331_000, PlayEvent::FpsLow, "fps=22.4 (< 25)", 0),
|
||||
"Event | t=05:31 | fps_low | fps=22.4 (< 25)"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PlayReport::format_event(
|
||||
331_000,
|
||||
PlayEvent::RumbleDense,
|
||||
"P1 Pro|Controller USB\nsamples=150/s",
|
||||
3
|
||||
),
|
||||
"Event | t=05:31 | rumble_dense | P1 Pro/Controller USB samples=150/s | +3 suppressed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_every_event_has_a_name() {
|
||||
for i in 0..PlayEvent::Count as usize {
|
||||
let kind = match i {
|
||||
0 => PlayEvent::FpsLow,
|
||||
1 => PlayEvent::VramHigh,
|
||||
2 => PlayEvent::RumbleDense,
|
||||
3 => PlayEvent::RumbleMerged,
|
||||
4 => PlayEvent::AutoSlowOn,
|
||||
5 => PlayEvent::AutoSlowOff,
|
||||
6 => PlayEvent::PadConnect,
|
||||
7 => PlayEvent::PadDisconnect,
|
||||
8 => PlayEvent::PadTransport,
|
||||
9 => PlayEvent::GyroLost,
|
||||
10 => PlayEvent::Battery,
|
||||
11 => PlayEvent::RumbleConfig,
|
||||
_ => break,
|
||||
};
|
||||
let name = PlayReport::event_name(kind);
|
||||
assert!(name.chars().all(|c| c.is_ascii_lowercase() || c == '_'));
|
||||
}
|
||||
assert_eq!(PlayReport::event_name(PlayEvent::AutoSlowOn), "autoslow_on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_game_start_line() {
|
||||
assert_eq!(
|
||||
PlayReport::format_game_start(
|
||||
"0100F2C0115B6000",
|
||||
"Sample Adventure Title",
|
||||
Some("1.2.1"),
|
||||
Some(&["Sample Optimizer", "UltraCam, 1080p"])
|
||||
),
|
||||
"Game | start | 0100F2C0115B6000 | Sample Adventure Title | v1.2.1 | mods: Sample Optimizer, UltraCam; 1080p"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PlayReport::format_game_start("01006FE013472000", "Sample Platformer", None, None),
|
||||
"Game | start | 01006FE013472000 | Sample Platformer | v? | mods: none"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_game_stop_line() {
|
||||
let mut events = PlayEventLimiter::new();
|
||||
let mut suppressed = 0;
|
||||
|
||||
events.try_log(PlayEvent::FpsLow, 0, &mut suppressed);
|
||||
events.try_log(PlayEvent::FpsLow, 1000, &mut suppressed);
|
||||
events.try_log(PlayEvent::RumbleDense, 2000, &mut suppressed);
|
||||
|
||||
let line = PlayReport::format_game_stop(600_000, &events, 600, 24.6);
|
||||
assert_eq!(
|
||||
line,
|
||||
"Game | stop | played=10:00 | events fps_low=2 rumble_dense=1 | stats timer cpu=24.6ms ticks=600 avg=41.0us share=0.0041%"
|
||||
);
|
||||
|
||||
let empty = PlayReport::format_game_stop(1000, &PlayEventLimiter::new(), 0, 0.0);
|
||||
assert!(empty.contains("| events none |"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merged_percent() {
|
||||
assert_eq!(PlayReport::merged_percent(100, 30), 70.0);
|
||||
assert_eq!(PlayReport::merged_percent(10, 10), 0.0);
|
||||
assert_eq!(PlayReport::merged_percent(10, 20), 0.0);
|
||||
assert_eq!(PlayReport::merged_percent(0, 0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stat_window_keeps_min_max_average() {
|
||||
let mut w = window(&[30.0, 20.0, 40.0]);
|
||||
assert_eq!(w.count, 3);
|
||||
assert_eq!(w.min, 20.0);
|
||||
assert_eq!(w.max, 40.0);
|
||||
assert_eq!(w.average(), 30.0);
|
||||
|
||||
w.reset();
|
||||
assert_eq!(w.count, 0);
|
||||
assert_eq!(w.average(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_limiter_allows_one_line_per_kind_every_five_seconds() {
|
||||
let mut limiter = PlayEventLimiter::new();
|
||||
let mut suppressed = 0;
|
||||
|
||||
assert!(limiter.try_log(PlayEvent::FpsLow, 10_000, &mut suppressed));
|
||||
assert_eq!(suppressed, 0);
|
||||
|
||||
assert!(!limiter.try_log(PlayEvent::FpsLow, 12_000, &mut suppressed));
|
||||
assert!(!limiter.try_log(PlayEvent::FpsLow, 14_000, &mut suppressed));
|
||||
|
||||
assert!(limiter.try_log(PlayEvent::FpsLow, 15_000, &mut suppressed));
|
||||
assert_eq!(suppressed, 2);
|
||||
|
||||
assert_eq!(limiter.total(PlayEvent::FpsLow), 4);
|
||||
}
|
||||
}
|
||||
172
third_party/renhdrum/src/preset.rs
vendored
Normal file
172
third_party/renhdrum/src/preset.rs
vendored
Normal file
@@ -0,0 +1,172 @@
|
||||
use crate::settings::RumbleConfigController;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum HdRumblePresetKind {
|
||||
Standard = 0,
|
||||
Crisp = 1,
|
||||
Custom = 2,
|
||||
}
|
||||
|
||||
pub struct HdRumblePreset;
|
||||
|
||||
impl HdRumblePreset {
|
||||
/// Writes pacing fields of `kind` into `config`. Does not touch HD Rumble on/off,
|
||||
/// strength multipliers or DualSense settings. `HdRumblePresetKind::Custom` changes nothing.
|
||||
pub fn apply(kind: HdRumblePresetKind, config: &mut RumbleConfigController) {
|
||||
if kind == HdRumblePresetKind::Custom {
|
||||
return;
|
||||
}
|
||||
|
||||
config.hd_rumble_usb_interval_ms =
|
||||
RumbleConfigController::DEFAULT_HD_RUMBLE_USB_INTERVAL_MS;
|
||||
config.hd_rumble_usb_auto_slow = true;
|
||||
config.hd_rumble_bluetooth_level =
|
||||
RumbleConfigController::STANDARD_HD_RUMBLE_BLUETOOTH_LEVEL;
|
||||
config.hd_rumble_experimental_sync_to_input = false;
|
||||
config.hd_rumble_experimental_sync_bluetooth = false;
|
||||
config.hd_rumble_sync_auto_slow = false;
|
||||
config.hd_rumble_experimental_click_pulse = kind == HdRumblePresetKind::Crisp;
|
||||
}
|
||||
|
||||
pub fn detect(config: &RumbleConfigController) -> HdRumblePresetKind {
|
||||
for &kind in &[HdRumblePresetKind::Standard, HdRumblePresetKind::Crisp] {
|
||||
let mut expected = RumbleConfigController::default();
|
||||
Self::apply(kind, &mut expected);
|
||||
|
||||
if config.hd_rumble_usb_interval_ms == expected.hd_rumble_usb_interval_ms
|
||||
&& config.hd_rumble_usb_auto_slow == expected.hd_rumble_usb_auto_slow
|
||||
&& config.hd_rumble_bluetooth_level == expected.hd_rumble_bluetooth_level
|
||||
&& config.hd_rumble_experimental_sync_to_input
|
||||
== expected.hd_rumble_experimental_sync_to_input
|
||||
&& config.hd_rumble_experimental_sync_bluetooth
|
||||
== expected.hd_rumble_experimental_sync_bluetooth
|
||||
&& config.hd_rumble_sync_auto_slow == expected.hd_rumble_sync_auto_slow
|
||||
&& config.hd_rumble_experimental_click_pulse
|
||||
== expected.hd_rumble_experimental_click_pulse
|
||||
{
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
HdRumblePresetKind::Custom
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PRESETS: [HdRumblePresetKind; 2] =
|
||||
[HdRumblePresetKind::Standard, HdRumblePresetKind::Crisp];
|
||||
|
||||
#[test]
|
||||
fn default_config_is_standard() {
|
||||
assert_eq!(
|
||||
HdRumblePreset::detect(&RumbleConfigController::default()),
|
||||
HdRumblePresetKind::Standard
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_then_detect_round_trips() {
|
||||
for kind in PRESETS {
|
||||
let mut config = RumbleConfigController::default();
|
||||
config.hd_rumble_usb_interval_ms = 30;
|
||||
config.hd_rumble_bluetooth_level = 3;
|
||||
|
||||
HdRumblePreset::apply(kind, &mut config);
|
||||
assert_eq!(HdRumblePreset::detect(&config), kind);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_keeps_unrelated_settings() {
|
||||
let mut config = RumbleConfigController::default();
|
||||
config.enable_hd_rumble = false;
|
||||
config.strong_rumble = 1.5;
|
||||
config.weak_rumble = 0.5;
|
||||
config.enable_dualsense_haptics = false;
|
||||
config.dualsense_haptics_volume = 40;
|
||||
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Crisp, &mut config);
|
||||
|
||||
assert!(!config.enable_hd_rumble);
|
||||
assert_eq!(config.strong_rumble, 1.5);
|
||||
assert_eq!(config.weak_rumble, 0.5);
|
||||
assert!(!config.enable_dualsense_haptics);
|
||||
assert_eq!(config.dualsense_haptics_volume, 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_one_field_makes_it_custom() {
|
||||
let mut config = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Standard, &mut config);
|
||||
config.hd_rumble_experimental_click_pulse = true;
|
||||
assert_eq!(HdRumblePreset::detect(&config), HdRumblePresetKind::Crisp);
|
||||
|
||||
config.hd_rumble_usb_interval_ms = 10;
|
||||
assert_eq!(HdRumblePreset::detect(&config), HdRumblePresetKind::Custom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_apply_changes_nothing() {
|
||||
let mut config = RumbleConfigController::default();
|
||||
config.hd_rumble_bluetooth_level = 3;
|
||||
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Custom, &mut config);
|
||||
assert_eq!(config.hd_rumble_bluetooth_level, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_preset_is_faster_than_the_bluetooth_standard_or_usb15() {
|
||||
for kind in PRESETS {
|
||||
let mut config = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(kind, &mut config);
|
||||
|
||||
assert!(
|
||||
config.hd_rumble_bluetooth_level
|
||||
<= RumbleConfigController::STANDARD_HD_RUMBLE_BLUETOOTH_LEVEL
|
||||
);
|
||||
assert!(config.hd_rumble_usb_interval_ms >= 15);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_preset_turns_sync_on() {
|
||||
for kind in PRESETS {
|
||||
let mut config = RumbleConfigController::default();
|
||||
config.hd_rumble_experimental_sync_to_input = true;
|
||||
config.hd_rumble_experimental_sync_bluetooth = true;
|
||||
|
||||
HdRumblePreset::apply(kind, &mut config);
|
||||
|
||||
assert!(!config.hd_rumble_experimental_sync_to_input);
|
||||
assert!(!config.hd_rumble_experimental_sync_bluetooth);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_on_is_custom() {
|
||||
let mut config = RumbleConfigController::default();
|
||||
config.hd_rumble_experimental_sync_to_input = true;
|
||||
assert_eq!(HdRumblePreset::detect(&config), HdRumblePresetKind::Custom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_flags() {
|
||||
let mut standard = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Standard, &mut standard);
|
||||
assert!(!standard.hd_rumble_experimental_click_pulse);
|
||||
|
||||
let mut crisp = RumbleConfigController::default();
|
||||
HdRumblePreset::apply(HdRumblePresetKind::Crisp, &mut crisp);
|
||||
assert!(crisp.hd_rumble_experimental_click_pulse);
|
||||
|
||||
assert_eq!(
|
||||
RumbleConfigController::default().hd_rumble_bluetooth_level,
|
||||
4,
|
||||
"Standard = Bluetooth Level 4 (with B1 + B2)"
|
||||
);
|
||||
}
|
||||
}
|
||||
1243
third_party/renhdrum/src/settings.rs
vendored
Normal file
1243
third_party/renhdrum/src/settings.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
853
third_party/renhdrum/src/status.rs
vendored
Normal file
853
third_party/renhdrum/src/status.rs
vendored
Normal file
@@ -0,0 +1,853 @@
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, RwLock};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RumbleTransport {
|
||||
Unknown = 0,
|
||||
Usb = 1,
|
||||
Bluetooth = 2,
|
||||
Virtual = 3,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RumbleBackendKind {
|
||||
Standard = 0,
|
||||
NintendoHd = 1,
|
||||
DualSense = 2,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DualSenseHapticsStatus {
|
||||
None = 0,
|
||||
WaitingForGame = 1,
|
||||
Running = 2,
|
||||
Bluetooth = 3,
|
||||
DeviceNotFound = 4,
|
||||
Off = 5,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PlayerIndex {
|
||||
Player1 = 0,
|
||||
Player2 = 1,
|
||||
Player3 = 2,
|
||||
Player4 = 3,
|
||||
Player5 = 4,
|
||||
Player6 = 5,
|
||||
Player7 = 6,
|
||||
Player8 = 7,
|
||||
Handheld = 8,
|
||||
Unknown = 9,
|
||||
Auto = 10,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SyncCounters {
|
||||
pub sent_report: i64,
|
||||
pub sent_fallback: i64,
|
||||
pub wait_busy: i64,
|
||||
pub read_skipped: i64,
|
||||
pub received: i64,
|
||||
pub merged: i64,
|
||||
pub gap_count: i64,
|
||||
pub gap_min_us: i64,
|
||||
pub gap_max_us: i64,
|
||||
pub gap_sum_us: i64,
|
||||
pub pump_loops: i64,
|
||||
pub pump_cpu_us: i64,
|
||||
pub pump_alive_us: i64,
|
||||
pub pump_busy_us: i64,
|
||||
pub pump_running: bool,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LinkCounters {
|
||||
pub writes: i64,
|
||||
pub write_sum_us: i64,
|
||||
pub reports: i64,
|
||||
pub read_skipped: i64,
|
||||
pub bt_sync: bool,
|
||||
pub bt_gap_us: i64,
|
||||
pub backoffs: i64,
|
||||
pub skipped_small: i64,
|
||||
pub ema_write_us: i64,
|
||||
pub ema_report_gap_us: i64,
|
||||
pub long_gaps: i64,
|
||||
pub long_gaps_skip: i64,
|
||||
pub long_gaps_lock: i64,
|
||||
pub long_gaps_clean: i64,
|
||||
pub bt_after_input: bool,
|
||||
}
|
||||
|
||||
impl Default for LinkCounters {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
writes: 0,
|
||||
write_sum_us: 0,
|
||||
reports: 0,
|
||||
read_skipped: 0,
|
||||
bt_sync: false,
|
||||
bt_gap_us: 0,
|
||||
backoffs: 0,
|
||||
skipped_small: 0,
|
||||
ema_write_us: 0,
|
||||
ema_report_gap_us: 0,
|
||||
long_gaps: -1,
|
||||
long_gaps_skip: 0,
|
||||
long_gaps_lock: 0,
|
||||
long_gaps_clean: 0,
|
||||
bt_after_input: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GapState {
|
||||
gap_count: i64,
|
||||
gap_sum_us: i64,
|
||||
gap_min_us: i64,
|
||||
gap_max_us: i64,
|
||||
link_write_max_us: i64,
|
||||
link_gap_max_us: i64,
|
||||
link_queued_max: i32,
|
||||
}
|
||||
|
||||
impl Default for GapState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
gap_count: 0,
|
||||
gap_sum_us: 0,
|
||||
gap_min_us: i64::MAX,
|
||||
gap_max_us: 0,
|
||||
link_write_max_us: 0,
|
||||
link_gap_max_us: 0,
|
||||
link_queued_max: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Entry {
|
||||
pub controller: String,
|
||||
pub transport: RumbleTransport,
|
||||
pub backend: RumbleBackendKind,
|
||||
rumble_enabled: AtomicBool,
|
||||
detail: RwLock<Option<String>>,
|
||||
detail_reason: RwLock<Option<String>>,
|
||||
haptics: AtomicI32,
|
||||
triggers_on: AtomicBool,
|
||||
trigger_profile: RwLock<Option<String>>,
|
||||
samples: AtomicI64,
|
||||
packets: AtomicI64,
|
||||
clicks: AtomicI64,
|
||||
click_active: AtomicBool,
|
||||
window_peak_rate: AtomicI32,
|
||||
auto_slow_active: AtomicBool,
|
||||
auto_slow_changes: AtomicI32,
|
||||
motion_restarts: AtomicI32,
|
||||
settings_text: RwLock<Option<String>>,
|
||||
settings_version: AtomicI32,
|
||||
sync_active: AtomicBool,
|
||||
sync: RwLock<Option<SyncCounters>>,
|
||||
link: RwLock<Option<LinkCounters>>,
|
||||
gap_state: Mutex<GapState>,
|
||||
power_reader: Mutex<Option<Box<dyn Fn() -> i32 + Send + Sync>>>,
|
||||
slot: AtomicI32,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub const POWER_UNAVAILABLE: i32 = -2;
|
||||
|
||||
pub fn new(controller: &str, transport: RumbleTransport, backend: RumbleBackendKind) -> Self {
|
||||
Self {
|
||||
controller: controller.to_string(),
|
||||
transport,
|
||||
backend,
|
||||
rumble_enabled: AtomicBool::new(true),
|
||||
detail: RwLock::new(None),
|
||||
detail_reason: RwLock::new(None),
|
||||
haptics: AtomicI32::new(DualSenseHapticsStatus::None as i32),
|
||||
triggers_on: AtomicBool::new(false),
|
||||
trigger_profile: RwLock::new(None),
|
||||
samples: AtomicI64::new(0),
|
||||
packets: AtomicI64::new(0),
|
||||
clicks: AtomicI64::new(0),
|
||||
click_active: AtomicBool::new(false),
|
||||
window_peak_rate: AtomicI32::new(0),
|
||||
auto_slow_active: AtomicBool::new(false),
|
||||
auto_slow_changes: AtomicI32::new(0),
|
||||
motion_restarts: AtomicI32::new(0),
|
||||
settings_text: RwLock::new(None),
|
||||
settings_version: AtomicI32::new(0),
|
||||
sync_active: AtomicBool::new(false),
|
||||
sync: RwLock::new(None),
|
||||
link: RwLock::new(None),
|
||||
gap_state: Mutex::new(GapState::default()),
|
||||
power_reader: Mutex::new(None),
|
||||
slot: AtomicI32::new(-1),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rumble_enabled(&self) -> bool {
|
||||
self.rumble_enabled.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_rumble_enabled(&self, enabled: bool) {
|
||||
self.rumble_enabled.store(enabled, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn detail(&self) -> Option<String> {
|
||||
self.detail.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn detail_reason(&self) -> Option<String> {
|
||||
self.detail_reason.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn set_pacing(&self, pacing: &str) {
|
||||
*self.detail_reason.write().unwrap() = None;
|
||||
*self.detail.write().unwrap() = Some(pacing.to_string());
|
||||
}
|
||||
|
||||
pub fn set_not_sending(&self, reason: &str) {
|
||||
*self.detail_reason.write().unwrap() = Some(reason.to_string());
|
||||
*self.detail.write().unwrap() = None;
|
||||
}
|
||||
|
||||
pub fn haptics(&self) -> DualSenseHapticsStatus {
|
||||
match self.haptics.load(Ordering::Acquire) {
|
||||
1 => DualSenseHapticsStatus::WaitingForGame,
|
||||
2 => DualSenseHapticsStatus::Running,
|
||||
3 => DualSenseHapticsStatus::Bluetooth,
|
||||
4 => DualSenseHapticsStatus::DeviceNotFound,
|
||||
5 => DualSenseHapticsStatus::Off,
|
||||
_ => DualSenseHapticsStatus::None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_haptics(&self, status: DualSenseHapticsStatus) {
|
||||
self.haptics.store(status as i32, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn triggers_on(&self) -> bool {
|
||||
self.triggers_on.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_triggers_on(&self, on: bool) {
|
||||
self.triggers_on.store(on, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn trigger_profile(&self) -> Option<String> {
|
||||
self.trigger_profile.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn set_trigger_profile(&self, profile: Option<String>) {
|
||||
*self.trigger_profile.write().unwrap() = profile;
|
||||
}
|
||||
|
||||
pub fn samples(&self) -> i64 {
|
||||
self.samples.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn packets(&self) -> i64 {
|
||||
self.packets.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn clicks(&self) -> i64 {
|
||||
self.clicks.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn add_sample(&self) {
|
||||
self.samples.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn add_packet(&self) {
|
||||
self.packets.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn add_click(&self) {
|
||||
self.clicks.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn click_active(&self) -> bool {
|
||||
self.click_active.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_click_active(&self, active: bool) {
|
||||
self.click_active.store(active, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn report_window_rate(&self, rate: i32) {
|
||||
let mut cur = self.window_peak_rate.load(Ordering::Relaxed);
|
||||
while rate > cur {
|
||||
match self.window_peak_rate.compare_exchange_weak(
|
||||
cur,
|
||||
rate,
|
||||
Ordering::Relaxed,
|
||||
Ordering::Relaxed,
|
||||
) {
|
||||
Ok(_) => break,
|
||||
Err(actual) => cur = actual,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_window_peak(&self) -> i32 {
|
||||
self.window_peak_rate.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn auto_slow_active(&self) -> bool {
|
||||
self.auto_slow_active.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn auto_slow_changes(&self) -> i32 {
|
||||
self.auto_slow_changes.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_auto_slow(&self, active: bool) {
|
||||
self.auto_slow_active.store(active, Ordering::Release);
|
||||
self.auto_slow_changes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn sync_active(&self) -> bool {
|
||||
self.sync_active.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn sync(&self) -> Option<SyncCounters> {
|
||||
self.sync.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn set_sync_active(&self, active: bool) {
|
||||
self.sync_active.store(active, Ordering::Release);
|
||||
if !active {
|
||||
*self.sync.write().unwrap() = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn report_sync(&self, counters: SyncCounters) {
|
||||
{
|
||||
let mut state = self.gap_state.lock().unwrap();
|
||||
state.gap_count += counters.gap_count;
|
||||
state.gap_sum_us += counters.gap_sum_us;
|
||||
if counters.gap_count > 0 {
|
||||
state.gap_min_us = state.gap_min_us.min(counters.gap_min_us);
|
||||
state.gap_max_us = state.gap_max_us.max(counters.gap_max_us);
|
||||
}
|
||||
}
|
||||
*self.sync.write().unwrap() = Some(counters);
|
||||
}
|
||||
|
||||
pub fn link(&self) -> Option<LinkCounters> {
|
||||
self.link.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn report_link(
|
||||
&self,
|
||||
counters: LinkCounters,
|
||||
write_max_us: i64,
|
||||
report_gap_max_us: i64,
|
||||
queued_max: i32,
|
||||
) {
|
||||
{
|
||||
let mut state = self.gap_state.lock().unwrap();
|
||||
state.link_write_max_us = state.link_write_max_us.max(write_max_us);
|
||||
state.link_gap_max_us = state.link_gap_max_us.max(report_gap_max_us);
|
||||
state.link_queued_max = state.link_queued_max.max(queued_max);
|
||||
}
|
||||
*self.link.write().unwrap() = Some(counters);
|
||||
}
|
||||
|
||||
pub fn take_link_max_window(&self) -> (i64, i64, i32) {
|
||||
let mut state = self.gap_state.lock().unwrap();
|
||||
let res = (
|
||||
state.link_write_max_us,
|
||||
state.link_gap_max_us,
|
||||
state.link_queued_max,
|
||||
);
|
||||
state.link_write_max_us = 0;
|
||||
state.link_gap_max_us = 0;
|
||||
state.link_queued_max = 0;
|
||||
res
|
||||
}
|
||||
|
||||
pub fn take_sync_gap_window(&self) -> (i64, i64, i64, i64) {
|
||||
let mut state = self.gap_state.lock().unwrap();
|
||||
let count = state.gap_count;
|
||||
let min_us = if count > 0 { state.gap_min_us } else { 0 };
|
||||
let max_us = state.gap_max_us;
|
||||
let sum_us = state.gap_sum_us;
|
||||
|
||||
state.gap_count = 0;
|
||||
state.gap_sum_us = 0;
|
||||
state.gap_min_us = i64::MAX;
|
||||
state.gap_max_us = 0;
|
||||
|
||||
(count, min_us, max_us, sum_us)
|
||||
}
|
||||
|
||||
pub fn motion_restarts(&self) -> i32 {
|
||||
self.motion_restarts.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn add_motion_restart(&self) {
|
||||
self.motion_restarts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn settings_text(&self) -> Option<String> {
|
||||
self.settings_text.read().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn settings_version(&self) -> i32 {
|
||||
self.settings_version.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_settings(&self, text: &str) {
|
||||
*self.settings_text.write().unwrap() = Some(text.to_string());
|
||||
self.settings_version.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn read_power_level(&self) -> i32 {
|
||||
if let Ok(guard) = self.power_reader.lock() {
|
||||
if let Some(ref reader) = *guard {
|
||||
return reader();
|
||||
}
|
||||
}
|
||||
Self::POWER_UNAVAILABLE
|
||||
}
|
||||
|
||||
pub fn set_power_reader<F: Fn() -> i32 + Send + Sync + 'static>(&self, reader: Option<F>) {
|
||||
if let Ok(mut guard) = self.power_reader.lock() {
|
||||
*guard = reader.map(|r| Box::new(r) as Box<dyn Fn() -> i32 + Send + Sync>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RumbleStatus;
|
||||
|
||||
impl RumbleStatus {
|
||||
pub const SLOT_COUNT: usize = 9;
|
||||
|
||||
fn slots() -> &'static RwLock<[Option<Arc<Entry>>; Self::SLOT_COUNT]> {
|
||||
static SLOTS: OnceLock<RwLock<[Option<Arc<Entry>>; RumbleStatus::SLOT_COUNT]>> =
|
||||
OnceLock::new();
|
||||
SLOTS.get_or_init(|| RwLock::new([None, None, None, None, None, None, None, None, None]))
|
||||
}
|
||||
|
||||
pub fn register(entry: Arc<Entry>, player: PlayerIndex) {
|
||||
let slot = player as usize;
|
||||
if slot >= Self::SLOT_COUNT {
|
||||
Self::unregister(&entry);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut slots = Self::slots().write().unwrap();
|
||||
if entry.slot.load(Ordering::Acquire) == slot as i32 {
|
||||
if let Some(ref current) = slots[slot] {
|
||||
if Arc::ptr_eq(current, &entry) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self::unregister_locked(&mut slots, &entry);
|
||||
|
||||
entry.slot.store(slot as i32, Ordering::Release);
|
||||
slots[slot] = Some(entry);
|
||||
}
|
||||
|
||||
pub fn unregister(entry: &Arc<Entry>) {
|
||||
let mut slots = Self::slots().write().unwrap();
|
||||
Self::unregister_locked(&mut slots, entry);
|
||||
}
|
||||
|
||||
fn unregister_locked(slots: &mut [Option<Arc<Entry>>; Self::SLOT_COUNT], entry: &Arc<Entry>) {
|
||||
let slot = entry.slot.load(Ordering::Acquire);
|
||||
if slot < 0 || slot as usize >= Self::SLOT_COUNT {
|
||||
return;
|
||||
}
|
||||
let slot = slot as usize;
|
||||
if let Some(ref current) = slots[slot] {
|
||||
if Arc::ptr_eq(current, entry) {
|
||||
slots[slot] = None;
|
||||
}
|
||||
}
|
||||
entry.slot.store(-1, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn get(slot: usize) -> Option<Arc<Entry>> {
|
||||
if slot < Self::SLOT_COUNT {
|
||||
Self::slots().read().unwrap()[slot].clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn player_label(slot: usize) -> String {
|
||||
if slot == PlayerIndex::Handheld as usize {
|
||||
"HH".to_string()
|
||||
} else {
|
||||
format!("P{}", slot + 1)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn transport_label(transport: RumbleTransport) -> Option<&'static str> {
|
||||
match transport {
|
||||
RumbleTransport::Usb => Some("Dây"),
|
||||
RumbleTransport::Bluetooth => Some("Bluetooth"),
|
||||
RumbleTransport::Virtual => Some("Ảo"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pacing_label(pacing: &str) -> String {
|
||||
if pacing.len() > 1
|
||||
&& pacing.starts_with('L')
|
||||
&& pacing.chars().nth(1).is_some_and(|c| c.is_ascii_digit())
|
||||
{
|
||||
format!("mức {}", &pacing[1..])
|
||||
} else {
|
||||
pacing.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format(slot: usize, entry: &Entry) -> String {
|
||||
let mut line = String::new();
|
||||
line.push_str(&Self::player_label(slot));
|
||||
line.push(' ');
|
||||
line.push_str(&entry.controller);
|
||||
|
||||
if let Some(t) = Self::transport_label(entry.transport) {
|
||||
line.push_str(" · ");
|
||||
line.push_str(t);
|
||||
}
|
||||
|
||||
line.push_str(" · ");
|
||||
|
||||
if !entry.rumble_enabled() {
|
||||
if entry.backend == RumbleBackendKind::NintendoHd {
|
||||
line.push_str("HD Rumble tắt");
|
||||
} else {
|
||||
line.push_str("Rung tắt");
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
match entry.backend {
|
||||
RumbleBackendKind::NintendoHd => {
|
||||
let detail = entry.detail();
|
||||
if let Some(ref d) = detail {
|
||||
line.push_str("HD Rumble bật · ");
|
||||
line.push_str(&Self::pacing_label(d));
|
||||
if entry.sync_active() {
|
||||
line.push_str(" · sync");
|
||||
}
|
||||
if entry.click_active() {
|
||||
line.push_str(" · click");
|
||||
}
|
||||
} else {
|
||||
line.push_str("HD Rumble tắt");
|
||||
}
|
||||
}
|
||||
RumbleBackendKind::DualSense => {
|
||||
if entry.haptics() == DualSenseHapticsStatus::Running {
|
||||
line.push_str("Haptic bật");
|
||||
} else {
|
||||
line.push_str("Haptic tắt");
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
line.push_str("Rung thường");
|
||||
}
|
||||
}
|
||||
|
||||
line
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nintendo_bluetooth_hd_rumble_on() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Bluetooth,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("L2");
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Bluetooth · HD Rumble bật · mức 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nintendo_usb_hd_rumble_on() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("15 ms");
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms"
|
||||
);
|
||||
|
||||
entry.set_pacing("30 ms (tự giãn)");
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 30 ms (tự giãn)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nintendo_click_is_shown_after_the_sync() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("15 ms");
|
||||
entry.set_click_active(true);
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms · click"
|
||||
);
|
||||
|
||||
entry.set_sync_active(true);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms · sync · click"
|
||||
);
|
||||
|
||||
entry.set_click_active(false);
|
||||
entry.set_sync_active(false);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nintendo_usb_sync_is_shown_after_the_pacing() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("15 ms");
|
||||
entry.set_sync_active(true);
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms · sync"
|
||||
);
|
||||
|
||||
entry.set_sync_active(false);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Dây · HD Rumble bật · 15 ms"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nintendo_bluetooth_sync_shows_the_balanced_profile() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Bluetooth,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("L2");
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Bluetooth · HD Rumble bật · mức 2"
|
||||
);
|
||||
|
||||
entry.set_pacing("cân bằng");
|
||||
entry.set_sync_active(true);
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Pro Controller · Bluetooth · HD Rumble bật · cân bằng · sync"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_max_window_keeps_the_largest_and_resets() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Bluetooth,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
let counters = LinkCounters {
|
||||
writes: 10,
|
||||
write_sum_us: 60_000,
|
||||
reports: 66,
|
||||
read_skipped: 0,
|
||||
bt_sync: false,
|
||||
bt_gap_us: 0,
|
||||
backoffs: 0,
|
||||
skipped_small: 0,
|
||||
ema_write_us: 6_000,
|
||||
ema_report_gap_us: 15_000,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(entry.link().is_none());
|
||||
|
||||
entry.report_link(counters.clone(), 38_000, 20_000, 1);
|
||||
let mut counters2 = counters;
|
||||
counters2.writes = 20;
|
||||
entry.report_link(counters2, 12_000, 52_000, 3);
|
||||
|
||||
assert_eq!(entry.link().unwrap().writes, 20);
|
||||
assert_eq!(entry.take_link_max_window(), (38_000, 52_000, 3));
|
||||
assert_eq!(entry.take_link_max_window(), (0, 0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_gap_window_accumulates_and_resets() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
|
||||
let make_counters = |count, min, max, sum| SyncCounters {
|
||||
sent_report: 0,
|
||||
sent_fallback: 0,
|
||||
wait_busy: 0,
|
||||
read_skipped: 0,
|
||||
received: 0,
|
||||
merged: 0,
|
||||
gap_count: count,
|
||||
gap_min_us: min,
|
||||
gap_max_us: max,
|
||||
gap_sum_us: sum,
|
||||
pump_loops: 0,
|
||||
pump_cpu_us: 0,
|
||||
pump_alive_us: 0,
|
||||
pump_busy_us: 0,
|
||||
pump_running: true,
|
||||
};
|
||||
|
||||
entry.report_sync(make_counters(60, 15_000, 32_000, 1_000_000));
|
||||
entry.report_sync(make_counters(0, 0, 0, 0));
|
||||
entry.report_sync(make_counters(40, 8_000, 24_000, 700_000));
|
||||
|
||||
assert_eq!(
|
||||
entry.take_sync_gap_window(),
|
||||
(100, 8_000, 32_000, 1_700_000)
|
||||
);
|
||||
assert_eq!(entry.take_sync_gap_window(), (0, 0, 0, 0));
|
||||
assert_eq!(entry.sync().unwrap().gap_count, 40);
|
||||
|
||||
entry.set_sync_active(false);
|
||||
assert!(entry.sync().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nintendo_not_sending_is_off() {
|
||||
let entry = Entry::new(
|
||||
"Joy-Con L",
|
||||
RumbleTransport::Bluetooth,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_pacing("L2");
|
||||
entry.set_not_sending("HD tắt");
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(1, &entry),
|
||||
"P2 Joy-Con L · Bluetooth · HD Rumble tắt"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rumble_off_in_config() {
|
||||
let entry = Entry::new(
|
||||
"Pro Controller",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
);
|
||||
entry.set_rumble_enabled(false);
|
||||
entry.set_pacing("15 ms");
|
||||
|
||||
assert_eq!(
|
||||
RumbleStatus::format(8, &entry),
|
||||
"HH Pro Controller · Dây · HD Rumble tắt"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dualsense_haptics() {
|
||||
let entry = Entry::new(
|
||||
"DualSense",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::DualSense,
|
||||
);
|
||||
entry.set_haptics(DualSenseHapticsStatus::Running);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 DualSense · Dây · Haptic bật"
|
||||
);
|
||||
|
||||
entry.set_haptics(DualSenseHapticsStatus::Bluetooth);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 DualSense · Dây · Haptic tắt"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_controller_standard_rumble() {
|
||||
let entry = Entry::new(
|
||||
"Xbox Controller",
|
||||
RumbleTransport::Unknown,
|
||||
RumbleBackendKind::Standard,
|
||||
);
|
||||
assert_eq!(
|
||||
RumbleStatus::format(0, &entry),
|
||||
"P1 Xbox Controller · Rung thường"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_moves_and_unregister_keeps_newer_entry() {
|
||||
let first = Arc::new(Entry::new(
|
||||
"Pro",
|
||||
RumbleTransport::Usb,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
));
|
||||
let second = Arc::new(Entry::new(
|
||||
"Pro",
|
||||
RumbleTransport::Bluetooth,
|
||||
RumbleBackendKind::NintendoHd,
|
||||
));
|
||||
|
||||
RumbleStatus::register(first.clone(), PlayerIndex::Player1);
|
||||
assert!(Arc::ptr_eq(&RumbleStatus::get(0).unwrap(), &first));
|
||||
|
||||
RumbleStatus::register(first.clone(), PlayerIndex::Player2);
|
||||
assert!(RumbleStatus::get(0).is_none());
|
||||
assert!(Arc::ptr_eq(&RumbleStatus::get(1).unwrap(), &first));
|
||||
|
||||
// Reconnect: newer pad is registered before old one is closed
|
||||
RumbleStatus::register(second.clone(), PlayerIndex::Player2);
|
||||
RumbleStatus::unregister(&first);
|
||||
assert!(Arc::ptr_eq(&RumbleStatus::get(1).unwrap(), &second));
|
||||
|
||||
RumbleStatus::unregister(&second);
|
||||
assert!(RumbleStatus::get(1).is_none());
|
||||
}
|
||||
}
|
||||
27
third_party/renhdrum/src/test_pattern.rs
vendored
Normal file
27
third_party/renhdrum/src/test_pattern.rs
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
/// Experimental test patterns of the Rumble dialog (Nintendo HD Rumble pads only): the 0.2.4.5 click patterns
|
||||
/// (hidden since 0.2.5, see docs/hdrumble-click-pulse.md) and the AM/FM hearing tests (0.2.5.2, 0.2.5.5).
|
||||
/// Each segment runs 2 s with a 1 s pause; the log names the segment that is running.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RumbleTestPattern {
|
||||
/// (a) 10 ms pulses the usual way, (b) the same pulses as controller MCU click packets.
|
||||
PulseCompare,
|
||||
|
||||
/// (c) every click packet shape on its own.
|
||||
ClickShapes,
|
||||
|
||||
/// (a), (b) and (c) one after another.
|
||||
All,
|
||||
|
||||
/// AM/FM hearing test (0.2.5.2, USB only): the controller MCU's three 5-bit samples per packet
|
||||
/// compared with regular two-wave packets, 10 segments.
|
||||
AmFm,
|
||||
|
||||
/// Hearing test of the forms that set one band's frequency inside the packet (0.2.5.5, USB only): switchbrew
|
||||
/// FormatThree7bit and FormatTwo14bit next to two-wave references, 10 segments.
|
||||
AmFmFrequency,
|
||||
|
||||
/// Pitch measurement (0.2.5.7, USB only): marker beeps, two-wave / Two14bit / Three7bit frequency ladders and every
|
||||
/// unknown 5-bit code (12..23, 25..31) applied 1x then 10x, 31 segments of ~3 s, recorded with a phone and analysed by FFT.
|
||||
AmFmMeasure,
|
||||
}
|
||||
148
third_party/renhdrum/src/trace.rs
vendored
Normal file
148
third_party/renhdrum/src/trace.rs
vendored
Normal file
@@ -0,0 +1,148 @@
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::settings::HdRumbleSettings;
|
||||
|
||||
pub const TRACE_FLAG_FILE: &str = "hdrumble_trace.txt";
|
||||
/// Old flag name from the Xbox-only trace, still honoured.
|
||||
pub const TRACE_FLAG_FILE_LEGACY: &str = "hdrumble_xbox_trace.txt";
|
||||
pub const TRACE_CSV_PREFIX: &str = "hdrumble_trace-";
|
||||
static TRACE_SEQ: AtomicU32 = AtomicU32::new(0);
|
||||
/// Brontide can exit without running cleanup, so unflushed lines must stay few.
|
||||
const FLUSH_EVERY_LINES: u32 = 64;
|
||||
|
||||
fn pct(motor: u16) -> u32 {
|
||||
(f32::from(motor) / 65535.0 * 100.0).round() as u32
|
||||
}
|
||||
|
||||
pub struct RumbleTrace {
|
||||
kind: &'static str,
|
||||
start: Instant,
|
||||
path: PathBuf,
|
||||
writer: Option<BufWriter<File>>,
|
||||
unflushed: u32,
|
||||
}
|
||||
|
||||
impl RumbleTrace {
|
||||
/// kind is pro, joycon, dualsense or xbox; it goes in the file name and the K line.
|
||||
pub fn open_in(kind: &'static str, base_dir: Option<&Path>) -> Option<Self> {
|
||||
let flag = HdRumbleSettings::try_read_flag_int_in(TRACE_FLAG_FILE, base_dir)
|
||||
.or_else(|| HdRumbleSettings::try_read_flag_int_in(TRACE_FLAG_FILE_LEGACY, base_dir))?;
|
||||
if flag == 0 {
|
||||
return None;
|
||||
}
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let seq = TRACE_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
// One file per run: a reopened emulator must never erase the last session
|
||||
let name = format!(
|
||||
"{TRACE_CSV_PREFIX}{kind}-{secs}-{}-{seq}.csv",
|
||||
std::process::id()
|
||||
);
|
||||
Some(Self {
|
||||
kind,
|
||||
start: Instant::now(),
|
||||
path: HdRumbleSettings::flag_path(&name, base_dir),
|
||||
writer: None,
|
||||
unflushed: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Created on the first line, so opening the emulator without rumble leaves no empty file.
|
||||
fn line(&mut self, text: std::fmt::Arguments) {
|
||||
if self.writer.is_none() {
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.path);
|
||||
self.writer = file.ok().map(BufWriter::new);
|
||||
if let Some(writer) = &mut self.writer {
|
||||
let _ = writeln!(writer, "K,{}", self.kind);
|
||||
}
|
||||
}
|
||||
let Some(writer) = &mut self.writer else {
|
||||
return;
|
||||
};
|
||||
let _ = writer.write_fmt(text);
|
||||
self.unflushed += 1;
|
||||
if self.unflushed >= FLUSH_EVERY_LINES {
|
||||
let _ = writer.flush();
|
||||
self.unflushed = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Microseconds since the trace was opened, for doors that get no timestamp from the caller.
|
||||
pub fn elapsed_us(&self) -> i64 {
|
||||
i64::try_from(self.start.elapsed().as_micros()).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
pub fn log_sample(
|
||||
&mut self,
|
||||
t_us: i64,
|
||||
is_right: bool,
|
||||
low_amp: f32,
|
||||
low_freq: f32,
|
||||
high_amp: f32,
|
||||
high_freq: f32,
|
||||
) {
|
||||
let side = if is_right { 'R' } else { 'L' };
|
||||
self.line(format_args!(
|
||||
"G,{t_us},{side},{low_amp},{low_freq},{high_amp},{high_freq}\n"
|
||||
));
|
||||
}
|
||||
|
||||
/// Like log_sample, plus the amplitudes the game sent before the Switch 2 curve (extra columns at the end).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn log_sample_raw(
|
||||
&mut self,
|
||||
t_us: i64,
|
||||
is_right: bool,
|
||||
low_amp: f32,
|
||||
low_freq: f32,
|
||||
high_amp: f32,
|
||||
high_freq: f32,
|
||||
raw_low: f32,
|
||||
raw_high: f32,
|
||||
) {
|
||||
let side = if is_right { 'R' } else { 'L' };
|
||||
self.line(format_args!(
|
||||
"G,{t_us},{side},{low_amp},{low_freq},{high_amp},{high_freq},{raw_low},{raw_high}
|
||||
"
|
||||
));
|
||||
}
|
||||
|
||||
/// A packet the engine really handed out: the 8 rumble bytes after header and counter.
|
||||
pub fn log_packet(&mut self, t_us: i64, packet: &[u8; 10]) {
|
||||
let b = &packet[2..];
|
||||
self.line(format_args!(
|
||||
"P,{t_us},{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}
|
||||
",
|
||||
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]
|
||||
));
|
||||
}
|
||||
|
||||
pub fn log_output(&mut self, t_us: i64, motors: [u16; 4], kind_low: &str, kind_high: &str) {
|
||||
let [lg, rg, lt, rt] = motors.map(pct);
|
||||
self.line(format_args!(
|
||||
"O,{t_us},{lg},{rg},{lt},{rt},{kind_low},{kind_high}\n"
|
||||
));
|
||||
}
|
||||
|
||||
/// SDL refused the last send. Shows a stop command that never reached the pad.
|
||||
pub fn log_refused(&mut self, motors: Option<[u16; 4]>) {
|
||||
let [lg, rg, lt, rt] = motors.unwrap_or_default().map(pct);
|
||||
self.line(format_args!("R,{lg},{rg},{lt},{rt}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RumbleTrace {
|
||||
fn drop(&mut self) {
|
||||
if let Some(writer) = &mut self.writer {
|
||||
let _ = writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
630
third_party/renhdrum/src/valve/grip.rs
vendored
Normal file
630
third_party/renhdrum/src/valve/grip.rs
vendored
Normal file
@@ -0,0 +1,630 @@
|
||||
//! Steam Controller (2026) grip haptics: HID report 0x88, mu-law PCM, 31 samples per grip.
|
||||
//! Experimental: layout and gain table come from iafx's measurements (RenHDrum#5);
|
||||
//! the mu-law encoder is written from ITU-T G.711, no third-party code is copied.
|
||||
|
||||
use crate::dualsense::haptics::{
|
||||
DualSenseHapticsDsp, DUALSENSE_CHANNELS, DUALSENSE_LEFT_CHANNEL, DUALSENSE_RIGHT_CHANNEL,
|
||||
};
|
||||
|
||||
pub const VALVE_GRIP_REPORT_SIZE: usize = 64;
|
||||
pub const VALVE_GRIP_REPORT_ID: u8 = 0x88;
|
||||
/// Samples per grip in one report.
|
||||
pub const VALVE_GRIP_SAMPLES: usize = 31;
|
||||
pub const VALVE_GRIP_FORMAT_MULAW_8K: u8 = 8;
|
||||
pub const VALVE_GRIP_FORMAT_MULAW_4K: u8 = 9;
|
||||
/// 31 samples at 8 kHz / 4 kHz.
|
||||
pub const VALVE_GRIP_PERIOD_NS_8K: u64 = 3_875_000;
|
||||
pub const VALVE_GRIP_PERIOD_NS_4K: u64 = 7_750_000;
|
||||
|
||||
pub const VALVE_GRIP_MODE_REPORT_ID: u8 = 0x86;
|
||||
pub const VALVE_GRIP_MODE_REPORT_SIZE: usize = 4;
|
||||
pub const VALVE_GRIP_MODE_REPORT_COUNT: usize = 2;
|
||||
pub const VALVE_GRIP_MODE_OP_OFF: u8 = 1;
|
||||
pub const VALVE_GRIP_MODE_OP_ON: u8 = 2;
|
||||
pub const VALVE_GRIP_CHANNEL_LEFT: u8 = 2;
|
||||
pub const VALVE_GRIP_CHANNEL_RIGHT: u8 = 5;
|
||||
pub const VALVE_GRIP_MODE_REFRESH_NS: u64 = 3_000_000_000;
|
||||
pub const VALVE_GRIP_IDLE_OFF_NS: u64 = 100_000_000;
|
||||
/// 40 ppm clock drift compensation: skip 1 report every 25,000 continuous packets.
|
||||
pub const VALVE_GRIP_DRIFT_SKIP_INTERVAL: u32 = 25_000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(i32)]
|
||||
pub enum ValveGripBuildOutcome {
|
||||
Silent = 0,
|
||||
Active = 1,
|
||||
DriftSkip = 2,
|
||||
}
|
||||
|
||||
const LEFT_OFFSET: usize = 2;
|
||||
const RIGHT_OFFSET: usize = 33;
|
||||
/// 48 kHz frames per sample at the slowest format (4 kHz).
|
||||
const MAX_DECIMATION: usize = 12;
|
||||
/// mu-law codes of a zero sample (positive and negative zero).
|
||||
const MULAW_SILENCE: [u8; 2] = [0xFF, 0x7F];
|
||||
|
||||
/// G.711 mu-law encoder. `sample` is -1..1 (clamped).
|
||||
pub fn mulaw_encode(sample: f32) -> u8 {
|
||||
const BIAS: i32 = 33; // 0x84 >> 2
|
||||
const CLIP: i32 = 8159;
|
||||
// ends of the 8 segments, 14-bit magnitude domain
|
||||
const SEG_END: [i32; 8] = [0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF];
|
||||
|
||||
let pcm = (sample.clamp(-1.0, 1.0) * 32767.0).round() as i32;
|
||||
let (mag, mask) = if pcm < 0 {
|
||||
((-pcm) >> 2, 0x7Fu8)
|
||||
} else {
|
||||
(pcm >> 2, 0xFFu8)
|
||||
};
|
||||
let mag = mag.min(CLIP) + BIAS;
|
||||
let Some(seg) = SEG_END.iter().position(|&end| mag <= end) else {
|
||||
return 0x7F ^ mask;
|
||||
};
|
||||
(((seg as u8) << 4) | ((mag >> (seg + 1)) & 0xF) as u8) ^ mask
|
||||
}
|
||||
|
||||
/// Gain of a grip against a DualSense, linear. Straight line in dB over log frequency through
|
||||
/// (40 Hz, -5 dB), (500 Hz, -5 dB), (800 Hz, -20 dB); flat beyond the ends.
|
||||
// ponytail: 1 person, 1 controller (iafx, RenHDrum#5); at amplitude 0.8-1.0 they measured -7/-8 dB, not modelled. Edit the table when a second measurement exists.
|
||||
pub fn grip_gain(hz: f32) -> f32 {
|
||||
const TABLE: [(f32, f32); 3] = [(40.0, -5.0), (500.0, -5.0), (800.0, -20.0)];
|
||||
let hz = hz.clamp(TABLE[0].0, TABLE[2].0);
|
||||
let db = TABLE
|
||||
.windows(2)
|
||||
.find(|w| hz <= w[1].0)
|
||||
.map(|w| {
|
||||
let t = (hz / w[0].0).ln() / (w[1].0 / w[0].0).ln();
|
||||
w[0].1 + (w[1].1 - w[0].1) * t
|
||||
})
|
||||
.unwrap_or(TABLE[2].1);
|
||||
10f32.powf(db / 20.0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn fill_silent_report(out: &mut [u8; VALVE_GRIP_REPORT_SIZE]) {
|
||||
*out = [MULAW_SILENCE[0]; VALVE_GRIP_REPORT_SIZE];
|
||||
out[0] = VALVE_GRIP_REPORT_ID;
|
||||
out[1] = VALVE_GRIP_SAMPLES as u8;
|
||||
}
|
||||
|
||||
/// Returns the HID report period in nanoseconds for a Steam grip format (`8` or `9`).
|
||||
#[inline]
|
||||
pub const fn valve_grip_period_ns(format: u8) -> Option<u64> {
|
||||
match format {
|
||||
VALVE_GRIP_FORMAT_MULAW_8K => Some(VALVE_GRIP_PERIOD_NS_8K),
|
||||
VALVE_GRIP_FORMAT_MULAW_4K => Some(VALVE_GRIP_PERIOD_NS_4K),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the two 4-byte HID `0x86` mode reports (channels 2 and 5) into `out`.
|
||||
#[inline]
|
||||
pub fn valve_grip_mode_reports(
|
||||
op: u8,
|
||||
format: u8,
|
||||
out: &mut [[u8; VALVE_GRIP_MODE_REPORT_SIZE]; VALVE_GRIP_MODE_REPORT_COUNT],
|
||||
) {
|
||||
out[0] = [
|
||||
VALVE_GRIP_MODE_REPORT_ID,
|
||||
op,
|
||||
VALVE_GRIP_CHANNEL_LEFT,
|
||||
format,
|
||||
];
|
||||
out[1] = [
|
||||
VALVE_GRIP_MODE_REPORT_ID,
|
||||
op,
|
||||
VALVE_GRIP_CHANNEL_RIGHT,
|
||||
format,
|
||||
];
|
||||
}
|
||||
|
||||
/// Builds the two 4-byte `0x86` "off" reports for channels 2 and 5 (for detach / exit paths).
|
||||
/// Accepts format `0`, `8`, or `9`; returns `false` on unknown format.
|
||||
pub fn build_valve_grip_mode_off(
|
||||
format: u8,
|
||||
out: &mut [[u8; VALVE_GRIP_MODE_REPORT_SIZE]; VALVE_GRIP_MODE_REPORT_COUNT],
|
||||
) -> bool {
|
||||
if format != 0 && valve_grip_period_ns(format).is_none() {
|
||||
return false;
|
||||
}
|
||||
valve_grip_mode_reports(VALVE_GRIP_MODE_OP_OFF, format, out);
|
||||
true
|
||||
}
|
||||
|
||||
/// Pulls 31 samples per grip from the DSP at 8 kHz (format 8) or 4 kHz (format 9).
|
||||
pub struct ValveGripPacker {
|
||||
pcm: [f32; VALVE_GRIP_SAMPLES * MAX_DECIMATION * DUALSENSE_CHANNELS],
|
||||
}
|
||||
|
||||
impl Default for ValveGripPacker {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pcm: [0.0; VALVE_GRIP_SAMPLES * MAX_DECIMATION * DUALSENSE_CHANNELS],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ValveGripPacker {
|
||||
/// Writes one report 0x88 into `out`. Returns true when any sample is not silent.
|
||||
/// Unknown `format`: the report is left silent and the DSP is not advanced.
|
||||
pub fn build(
|
||||
&mut self,
|
||||
dsp: &mut DualSenseHapticsDsp,
|
||||
format: u8,
|
||||
out: &mut [u8; VALVE_GRIP_REPORT_SIZE],
|
||||
) -> bool {
|
||||
fill_silent_report(out);
|
||||
let decimation = match format {
|
||||
VALVE_GRIP_FORMAT_MULAW_8K => 6,
|
||||
VALVE_GRIP_FORMAT_MULAW_4K => 12,
|
||||
_ => return false,
|
||||
};
|
||||
let stride = decimation * DUALSENSE_CHANNELS;
|
||||
let pcm = &mut self.pcm[..VALVE_GRIP_SAMPLES * stride];
|
||||
dsp.fill_interleaved_f32(pcm);
|
||||
|
||||
let mut signal = false;
|
||||
for (i, block) in pcm.chunks_exact(stride).enumerate() {
|
||||
for (offset, channel) in [
|
||||
(LEFT_OFFSET, DUALSENSE_LEFT_CHANNEL),
|
||||
(RIGHT_OFFSET, DUALSENSE_RIGHT_CHANNEL),
|
||||
] {
|
||||
let mean = block
|
||||
.as_chunks::<DUALSENSE_CHANNELS>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|f| f[channel])
|
||||
.sum::<f32>()
|
||||
/ decimation as f32;
|
||||
let code = mulaw_encode(mean);
|
||||
out[offset + i] = code;
|
||||
signal |= !MULAW_SILENCE.contains(&code);
|
||||
}
|
||||
}
|
||||
signal
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-allocation Steam Controller (2026) grip session manager:
|
||||
/// - packs `0x88` PCM reports with optional 40 ppm clock-drift packet skipping;
|
||||
/// - tracks `0x86` PCM mode keep-alive (on at first vibration, refresh every 3 s or on write stall,
|
||||
/// off after 100 ms of silence).
|
||||
pub struct ValveGripState {
|
||||
packer: ValveGripPacker,
|
||||
drift_comp: bool,
|
||||
active_stream: bool,
|
||||
active_packets: u32,
|
||||
silent_ns: u64,
|
||||
mode_on: bool,
|
||||
last_on_ns: u64,
|
||||
last_active_ns: u64,
|
||||
pending_active: bool,
|
||||
built_since_tick: bool,
|
||||
}
|
||||
|
||||
impl Default for ValveGripState {
|
||||
fn default() -> Self {
|
||||
Self::new(false)
|
||||
}
|
||||
}
|
||||
|
||||
impl ValveGripState {
|
||||
pub fn new(drift_comp: bool) -> Self {
|
||||
Self {
|
||||
packer: ValveGripPacker::default(),
|
||||
drift_comp,
|
||||
active_stream: false,
|
||||
active_packets: 0,
|
||||
silent_ns: 0,
|
||||
mode_on: false,
|
||||
last_on_ns: 0,
|
||||
last_active_ns: 0,
|
||||
pending_active: false,
|
||||
built_since_tick: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn reset_stream(&mut self) {
|
||||
self.active_stream = false;
|
||||
self.active_packets = 0;
|
||||
self.silent_ns = 0;
|
||||
}
|
||||
|
||||
/// Builds one `0x88` report (or returns `DriftSkip` once per 25,000 continuous packets when
|
||||
/// `drift_comp` is enabled, leaving DSP phase untouched). Returns `None` on unknown `format`.
|
||||
pub fn build_report(
|
||||
&mut self,
|
||||
dsp: &mut DualSenseHapticsDsp,
|
||||
format: u8,
|
||||
out: &mut [u8; VALVE_GRIP_REPORT_SIZE],
|
||||
) -> Option<ValveGripBuildOutcome> {
|
||||
let period_ns = valve_grip_period_ns(format)?;
|
||||
if self.drift_comp
|
||||
&& self.active_stream
|
||||
&& self.active_packets + 1 >= VALVE_GRIP_DRIFT_SKIP_INTERVAL
|
||||
{
|
||||
fill_silent_report(out);
|
||||
self.active_packets = 0;
|
||||
self.built_since_tick = true;
|
||||
if self.silent_ns == 0 {
|
||||
self.pending_active = true;
|
||||
}
|
||||
return Some(ValveGripBuildOutcome::DriftSkip);
|
||||
}
|
||||
|
||||
let signal = self.packer.build(dsp, format, out);
|
||||
self.built_since_tick = true;
|
||||
if signal {
|
||||
self.active_stream = true;
|
||||
self.silent_ns = 0;
|
||||
self.active_packets += 1;
|
||||
self.pending_active = true;
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
} else {
|
||||
if self.active_stream {
|
||||
self.silent_ns = self.silent_ns.saturating_add(period_ns);
|
||||
if self.silent_ns >= VALVE_GRIP_IDLE_OFF_NS {
|
||||
self.reset_stream();
|
||||
} else {
|
||||
self.active_packets += 1;
|
||||
}
|
||||
}
|
||||
Some(ValveGripBuildOutcome::Silent)
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates the `0x86` mode state machine at `now_ns`. Returns `None` on unknown `format`,
|
||||
/// `Some(0)` when nothing needs sending, or `Some(2)` with two 4-byte `0x86` reports in `out`.
|
||||
pub fn mode_tick(
|
||||
&mut self,
|
||||
dsp: &DualSenseHapticsDsp,
|
||||
format: u8,
|
||||
now_ns: u64,
|
||||
stalled: bool,
|
||||
out: &mut [[u8; VALVE_GRIP_MODE_REPORT_SIZE]; VALVE_GRIP_MODE_REPORT_COUNT],
|
||||
) -> Option<usize> {
|
||||
valve_grip_period_ns(format)?;
|
||||
let is_active = if self.built_since_tick {
|
||||
self.pending_active
|
||||
} else {
|
||||
dsp.has_active_target()
|
||||
};
|
||||
self.pending_active = false;
|
||||
self.built_since_tick = false;
|
||||
|
||||
if !self.mode_on {
|
||||
if is_active {
|
||||
self.mode_on = true;
|
||||
self.last_on_ns = now_ns;
|
||||
self.last_active_ns = now_ns;
|
||||
valve_grip_mode_reports(VALVE_GRIP_MODE_OP_ON, format, out);
|
||||
return Some(VALVE_GRIP_MODE_REPORT_COUNT);
|
||||
}
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
if is_active {
|
||||
self.last_active_ns = now_ns;
|
||||
if stalled || now_ns.saturating_sub(self.last_on_ns) >= VALVE_GRIP_MODE_REFRESH_NS {
|
||||
self.last_on_ns = now_ns;
|
||||
valve_grip_mode_reports(VALVE_GRIP_MODE_OP_ON, format, out);
|
||||
return Some(VALVE_GRIP_MODE_REPORT_COUNT);
|
||||
}
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
if now_ns.saturating_sub(self.last_active_ns) >= VALVE_GRIP_IDLE_OFF_NS {
|
||||
self.mode_on = false;
|
||||
self.reset_stream();
|
||||
valve_grip_mode_reports(VALVE_GRIP_MODE_OP_OFF, format, out);
|
||||
return Some(VALVE_GRIP_MODE_REPORT_COUNT);
|
||||
}
|
||||
|
||||
if stalled || now_ns.saturating_sub(self.last_on_ns) >= VALVE_GRIP_MODE_REFRESH_NS {
|
||||
self.last_on_ns = now_ns;
|
||||
valve_grip_mode_reports(VALVE_GRIP_MODE_OP_ON, format, out);
|
||||
return Some(VALVE_GRIP_MODE_REPORT_COUNT);
|
||||
}
|
||||
|
||||
Some(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn db(g: f32) -> f32 {
|
||||
20.0 * g.log10()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mulaw_matches_g711_reference_values() {
|
||||
assert_eq!(mulaw_encode(0.0), 0xFF);
|
||||
assert_eq!(mulaw_encode(1.0), 0x80);
|
||||
assert_eq!(mulaw_encode(-1.0), 0x00);
|
||||
// 1000/32767 -> 0xCE (decodes to 988), mirrored -> 0x4E
|
||||
assert_eq!(mulaw_encode(1000.0 / 32767.0), 0xCE);
|
||||
assert_eq!(mulaw_encode(-1000.0 / 32767.0), 0x4E);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_grip_gain_table() {
|
||||
assert!((db(grip_gain(40.0)) + 5.0).abs() < 0.01);
|
||||
assert!((db(grip_gain(500.0)) + 5.0).abs() < 0.01);
|
||||
assert!((db(grip_gain(800.0)) + 20.0).abs() < 0.01);
|
||||
assert!((db(grip_gain(632.0)) + 12.5).abs() < 0.1);
|
||||
assert!((db(grip_gain(10.0)) + 5.0).abs() < 0.01);
|
||||
assert!((db(grip_gain(1000.0)) + 20.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_silent_dsp_gives_silent_report() {
|
||||
for format in [8, 9] {
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
let mut out = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
assert!(!ValveGripPacker::default().build(&mut dsp, format, &mut out));
|
||||
assert_eq!((out[0], out[1]), (0x88, 31));
|
||||
assert!(out[2..].iter().all(|&b| b == 0xFF));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_format_is_silent_and_false() {
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
let mut out = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
assert!(!ValveGripPacker::default().build(&mut dsp, 7, &mut out));
|
||||
assert!(out[2..].iter().all(|&b| b == 0xFF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_left_target_fills_only_left_bytes() {
|
||||
for format in [8, 9] {
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
dsp.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
let mut packer = ValveGripPacker::default();
|
||||
let mut out = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
let mut left = false;
|
||||
// the DSP takes its target at the next slot, so look at several reports
|
||||
for _ in 0..8 {
|
||||
packer.build(&mut dsp, format, &mut out);
|
||||
left |= out[2..33].iter().any(|b| !MULAW_SILENCE.contains(b));
|
||||
assert!(out[33..64].iter().all(|b| MULAW_SILENCE.contains(b)));
|
||||
}
|
||||
assert!(left);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mode2_law_differs_from_mode0() {
|
||||
let _g = crate::nx2::NX2_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let report = |mode| {
|
||||
crate::nx2::set_nx2_mode(mode);
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
dsp.set_half_target(false, 0.01, 160.0, 0.0, 320.0);
|
||||
let mut packer = ValveGripPacker::default();
|
||||
let mut out = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
for _ in 0..8 {
|
||||
packer.build(&mut dsp, 8, &mut out);
|
||||
}
|
||||
crate::nx2::set_nx2_mode(0);
|
||||
out
|
||||
};
|
||||
assert_ne!(report(2), report(0), "L1 law must change the level");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mode_tick_timeline_on_refresh_stall_and_off() {
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
let mut state = ValveGripState::new(true);
|
||||
let mut reports = [[0u8; 4]; 2];
|
||||
let mut out64 = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
|
||||
// Idle at start: stays off, even if stalled.
|
||||
assert_eq!(state.mode_tick(&dsp, 8, 0, false, &mut reports), Some(0));
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 1_000_000, true, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
|
||||
// First vibration at t = 0: emits 0x86 "on" for channels 2 and 5.
|
||||
dsp.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
assert_eq!(
|
||||
state.build_report(&mut dsp, 8, &mut out64),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
assert_eq!(state.mode_tick(&dsp, 8, 0, false, &mut reports), Some(2));
|
||||
assert_eq!(reports, [[0x86, 2, 2, 8], [0x86, 2, 5, 8]]);
|
||||
|
||||
// Active before 3 s: nothing to emit.
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 2_999_999_999, false, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
|
||||
// At 3 s and 6 s while active: refreshes "on".
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 3_000_000_000, false, &mut reports),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(reports, [[0x86, 2, 2, 8], [0x86, 2, 5, 8]]);
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 5_999_999_999, false, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_000_000_000, false, &mut reports),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(reports, [[0x86, 2, 2, 8], [0x86, 2, 5, 8]]);
|
||||
|
||||
// Write stall at 6.5 s: emits "on" immediately.
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_500_000_000, true, &mut reports),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(reports, [[0x86, 2, 2, 8], [0x86, 2, 5, 8]]);
|
||||
|
||||
// Stop vibrating and drain smoothing until silent.
|
||||
dsp.set_half_target(false, 0.0, 160.0, 0.0, 320.0);
|
||||
for _ in 0..16 {
|
||||
let _ = state.build_report(&mut dsp, 8, &mut out64);
|
||||
}
|
||||
assert_eq!(
|
||||
state.build_report(&mut dsp, 8, &mut out64),
|
||||
Some(ValveGripBuildOutcome::Silent)
|
||||
);
|
||||
|
||||
// 99 ms after last active: still on; at 100 ms: emits "off", then stays quiet.
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_500_000_000, false, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_599_000_000, false, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_600_000_000, false, &mut reports),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(reports, [[0x86, 1, 2, 8], [0x86, 1, 5, 8]]);
|
||||
assert_eq!(
|
||||
state.mode_tick(&dsp, 8, 6_700_000_000, false, &mut reports),
|
||||
Some(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mode_off_helper() {
|
||||
let mut reports = [[0u8; 4]; 2];
|
||||
assert!(build_valve_grip_mode_off(8, &mut reports));
|
||||
assert_eq!(reports, [[0x86, 1, 2, 8], [0x86, 1, 5, 8]]);
|
||||
assert!(build_valve_grip_mode_off(9, &mut reports));
|
||||
assert_eq!(reports, [[0x86, 1, 2, 9], [0x86, 1, 5, 9]]);
|
||||
assert!(build_valve_grip_mode_off(0, &mut reports));
|
||||
assert_eq!(reports, [[0x86, 1, 2, 0], [0x86, 1, 5, 0]]);
|
||||
assert!(!build_valve_grip_mode_off(7, &mut reports));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_drift_compensation_skips_once_per_25000_without_advancing_phase() {
|
||||
let mut dsp_drift = DualSenseHapticsDsp::new_grip(100, false);
|
||||
let mut dsp_plain = DualSenseHapticsDsp::new_grip(100, false);
|
||||
dsp_drift.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
dsp_plain.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
|
||||
let mut drift = ValveGripState::new(true);
|
||||
let mut plain = ValveGripState::new(false);
|
||||
let mut out_drift = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
let mut out_plain = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
|
||||
let mut skips = 0;
|
||||
let mut plain_skips = 0;
|
||||
for i in 0..25_000 {
|
||||
let res_d = drift.build_report(&mut dsp_drift, 8, &mut out_drift);
|
||||
if res_d == Some(ValveGripBuildOutcome::DriftSkip) {
|
||||
assert_eq!(i, 24_999);
|
||||
skips += 1;
|
||||
} else {
|
||||
assert_eq!(res_d, Some(ValveGripBuildOutcome::Active));
|
||||
assert_eq!(
|
||||
plain.build_report(&mut dsp_plain, 8, &mut out_plain),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
assert_eq!(out_drift, out_plain);
|
||||
}
|
||||
if i == 24_999 {
|
||||
// On the skipped packet, dsp_drift did not advance: verify dsp_plain has 0 skips.
|
||||
assert_ne!(
|
||||
plain.build_report(&mut dsp_plain, 8, &mut out_plain),
|
||||
Some(ValveGripBuildOutcome::DriftSkip)
|
||||
);
|
||||
plain_skips += 0;
|
||||
}
|
||||
}
|
||||
assert_eq!(skips, 1);
|
||||
assert_eq!(plain_skips, 0);
|
||||
|
||||
// Next packet after the skip matches plain's 25,000th built packet (already consumed above),
|
||||
// so compare one more step cleanly on fresh DSPs or advance drift once now:
|
||||
assert_eq!(
|
||||
drift.build_report(&mut dsp_drift, 8, &mut out_drift),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
assert_eq!(out_drift, out_plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_drift_counter_resets_after_100ms_pause() {
|
||||
// (1) Reset via >= 100 ms of silent reports
|
||||
let mut dsp = DualSenseHapticsDsp::new_grip(100, false);
|
||||
dsp.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
let mut state = ValveGripState::new(true);
|
||||
let mut out = [0u8; VALVE_GRIP_REPORT_SIZE];
|
||||
|
||||
for _ in 0..24_000 {
|
||||
assert_eq!(
|
||||
state.build_report(&mut dsp, 8, &mut out),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
}
|
||||
dsp.set_half_target(false, 0.0, 160.0, 0.0, 320.0);
|
||||
let mut silent_seen = 0;
|
||||
for _ in 0..64 {
|
||||
if state.build_report(&mut dsp, 8, &mut out) == Some(ValveGripBuildOutcome::Silent) {
|
||||
silent_seen += 1;
|
||||
}
|
||||
}
|
||||
assert!(silent_seen >= 26); // >= 100 ms at 8 kHz (26 * 3.875 ms = 100.75 ms)
|
||||
|
||||
dsp.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
for _ in 0..24_000 {
|
||||
assert_eq!(
|
||||
state.build_report(&mut dsp, 8, &mut out),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
}
|
||||
|
||||
// (2) Reset via mode_tick detecting 100 ms silence without calling build_report for 100 ms
|
||||
let mut dsp2 = DualSenseHapticsDsp::new_grip(100, false);
|
||||
let mut state2 = ValveGripState::new(true);
|
||||
let mut mode_reports = [[0u8; 4]; 2];
|
||||
dsp2.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
assert_eq!(
|
||||
state2.mode_tick(&dsp2, 9, 0, false, &mut mode_reports),
|
||||
Some(2)
|
||||
);
|
||||
for _ in 0..24_000 {
|
||||
assert_eq!(
|
||||
state2.build_report(&mut dsp2, 9, &mut out),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
state2.mode_tick(&dsp2, 9, 50_000_000, false, &mut mode_reports),
|
||||
Some(0)
|
||||
);
|
||||
dsp2.set_half_target(false, 0.0, 160.0, 0.0, 320.0);
|
||||
assert_eq!(
|
||||
state2.mode_tick(&dsp2, 9, 150_000_000, false, &mut mode_reports),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(mode_reports, [[0x86, 1, 2, 9], [0x86, 1, 5, 9]]);
|
||||
|
||||
dsp2.set_half_target(false, 0.5, 160.0, 0.0, 320.0);
|
||||
assert_eq!(
|
||||
state2.mode_tick(&dsp2, 9, 200_000_000, false, &mut mode_reports),
|
||||
Some(2)
|
||||
);
|
||||
for _ in 0..24_000 {
|
||||
assert_eq!(
|
||||
state2.build_report(&mut dsp2, 9, &mut out),
|
||||
Some(ValveGripBuildOutcome::Active)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
8
third_party/renhdrum/src/valve/mod.rs
vendored
Normal file
8
third_party/renhdrum/src/valve/mod.rs
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
pub mod grip;
|
||||
|
||||
pub use grip::{
|
||||
build_valve_grip_mode_off, grip_gain, mulaw_encode, ValveGripBuildOutcome, ValveGripPacker,
|
||||
ValveGripState, VALVE_GRIP_FORMAT_MULAW_4K, VALVE_GRIP_FORMAT_MULAW_8K,
|
||||
VALVE_GRIP_MODE_REPORT_COUNT, VALVE_GRIP_MODE_REPORT_SIZE, VALVE_GRIP_PERIOD_NS_4K,
|
||||
VALVE_GRIP_PERIOD_NS_8K, VALVE_GRIP_REPORT_SIZE,
|
||||
};
|
||||
633
third_party/renhdrum/src/xbox/classify.rs
vendored
Normal file
633
third_party/renhdrum/src/xbox/classify.rs
vendored
Normal file
@@ -0,0 +1,633 @@
|
||||
//! Feature extraction and causal archetype classification for a single Switch rumble band.
|
||||
|
||||
/// Below this level the band is completely silent.
|
||||
pub const FAINT: f32 = 0.002;
|
||||
/// Quiet threshold separating silence/wind from active rumble.
|
||||
pub const SILENCE: f32 = 0.01;
|
||||
/// Minimum level to start a hit from silence (above ambient wind `0.003..0.011`).
|
||||
pub const KICK_MIN: f32 = 0.013;
|
||||
/// `Ambient` needs its smoothed level at or above this. Certain 3D titles idle on dither at 1/255
|
||||
/// (`~0.004`) for many seconds; 2D platformer wind sits at 2-3/255 (`~0.009`).
|
||||
pub const AMBIENT_MIN: f32 = 0.005;
|
||||
/// Time constant of the `Ambient` smoothing (`150 ms`).
|
||||
const AMBIENT_TAU_S: f32 = 0.15;
|
||||
/// Level jump within `RISE_WINDOW_US` that starts a new hit even without returning to silence.
|
||||
pub const ONSET_RISE: f32 = 0.15;
|
||||
/// Window for measuring rapid level rises (`35 ms`).
|
||||
pub const RISE_WINDOW_US: i64 = 35_000;
|
||||
/// Maximum gap between repeated hits in a `Rhythm` or `Pulse` run (`400 ms`).
|
||||
pub const RUN_GAP_US: i64 = 400_000;
|
||||
/// Minimum level for a single first hit to be classified as `Impact`.
|
||||
pub const IMPACT_MIN: f32 = 0.60;
|
||||
/// Minimum level for an upward jump inside a hit to trigger `Impact` (Metroid blasts >= 0.60).
|
||||
pub const IMPACT_JUMP_MIN: f32 = 0.60;
|
||||
/// Minimum rise within `20 ms` for a single first hit to be classified as `Impact`.
|
||||
pub const IMPACT_RISE: f32 = 0.35;
|
||||
const TRIG_REST_US_FOR_IMPACT: i64 = 50_000;
|
||||
/// Maximum brief silence gap bridged inside a continuous rumble (`100 ms`), so game-side periodic
|
||||
/// engine/hoverbike envelopes stay `Sustained` across 80-90 ms dips while still resetting on real pauses.
|
||||
const BRIEF_DIP_MAX_US: i64 = 100_000;
|
||||
/// `a_ref` floor so quiet passages never inflate weak pulses into `Rhythm`.
|
||||
pub const A_REF_FLOOR: f32 = 0.18;
|
||||
/// Decay time constant of `a_ref` in seconds (`10 s`).
|
||||
pub const A_REF_TAU_S: f32 = 10.0;
|
||||
/// Ratio of `a_ref` required for a repeating run to count as `Rhythm` (`0.625 * 0.48 = 0.30`).
|
||||
pub const RHYTHM_REF_RATIO: f32 = 0.625;
|
||||
/// Ratio of `run_peak` below which a hit in a `Rhythm` run is classified as `Echo`.
|
||||
pub const ECHO_PEAK_RATIO: f32 = 0.4;
|
||||
/// Minimum continuous non-silent duration for `Sustained` (`300 ms`).
|
||||
pub const SUSTAINED_MIN_US: i64 = 300_000;
|
||||
/// Minimum ratio of `hit_peak` for a held rumble to remain `Sustained`.
|
||||
pub const SUSTAINED_HOLD_RATIO: f32 = 0.6;
|
||||
/// Minimum continuous non-silent duration for `Texture` (`150 ms`).
|
||||
pub const TEXTURE_MIN_US: i64 = 150_000;
|
||||
/// Sliding window for counting direction reversals in `Texture` (`200 ms`).
|
||||
pub const TEXTURE_WINDOW_US: i64 = 200_000;
|
||||
/// Minimum number of clear direction reversals in `200 ms` for `Texture`.
|
||||
pub const TEXTURE_MIN_REVERSALS: usize = 3;
|
||||
/// Minimum amplitude swing to count as a clear reversal in `Texture`.
|
||||
/// Tuned from step 1b traces (Morph Ball roll / surface rumble).
|
||||
pub const TEXTURE_REV_DELTA: f32 = 0.015;
|
||||
|
||||
/// Longest held note inside a strong run; held past this it is `Sustained` (Wonder notes reach 500 ms).
|
||||
const STRONG_NOTE_MAX_US: i64 = 600_000;
|
||||
|
||||
const HISTORY_CAP: usize = 64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RumbleKind {
|
||||
Ambient,
|
||||
Tap,
|
||||
Impact,
|
||||
Rhythm,
|
||||
Pulse,
|
||||
Echo,
|
||||
Sustained,
|
||||
Texture,
|
||||
}
|
||||
|
||||
impl RumbleKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ambient => "Ambient",
|
||||
Self::Tap => "Tap",
|
||||
Self::Impact => "Impact",
|
||||
Self::Rhythm => "Rhythm",
|
||||
Self::Pulse => "Pulse",
|
||||
Self::Echo => "Echo",
|
||||
Self::Sustained => "Sustained",
|
||||
Self::Texture => "Texture",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct HistoryPoint {
|
||||
t_us: i64,
|
||||
level: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BandClassifier {
|
||||
base_freq: f32,
|
||||
pub level: f32,
|
||||
pub freq: f32,
|
||||
pub freq_delta: f32,
|
||||
pub level_delta: f32,
|
||||
pub pitch: f32,
|
||||
pub pan: f32,
|
||||
/// Reference amplitude `max(0.18, A(t), a_ref * exp(-dt / 10 s))`.
|
||||
/// Used ONLY as a classification threshold, never multiplied into motor force.
|
||||
pub a_ref: f32,
|
||||
/// Smoothed level used only to gate `Ambient`.
|
||||
pub ambient_env: f32,
|
||||
last_sample_us: Option<i64>,
|
||||
pub hit_start_us: Option<i64>,
|
||||
pub hit_peak: f32,
|
||||
pub hit_onset_freq: f32,
|
||||
pub hit_onset_level: f32,
|
||||
pub freq_step_hz: f32,
|
||||
pub prev_gap_us: Option<i64>,
|
||||
pub run_hits: u32,
|
||||
pub run_peak: f32,
|
||||
pub run_until_us: i64,
|
||||
pub strong_run: bool,
|
||||
pub hit_is_impact: bool,
|
||||
last_silence_us: i64,
|
||||
continuous_start_us: Option<i64>,
|
||||
history: [HistoryPoint; HISTORY_CAP],
|
||||
history_len: usize,
|
||||
}
|
||||
|
||||
impl BandClassifier {
|
||||
pub fn new(base_freq: f32) -> Self {
|
||||
Self {
|
||||
base_freq,
|
||||
level: 0.0,
|
||||
freq: base_freq,
|
||||
freq_delta: 0.0,
|
||||
level_delta: 0.0,
|
||||
pitch: 0.0,
|
||||
pan: 0.0,
|
||||
a_ref: A_REF_FLOOR,
|
||||
ambient_env: 0.0,
|
||||
last_sample_us: None,
|
||||
hit_start_us: None,
|
||||
hit_peak: 0.0,
|
||||
hit_onset_freq: base_freq,
|
||||
hit_onset_level: 0.0,
|
||||
freq_step_hz: 0.0,
|
||||
prev_gap_us: None,
|
||||
run_hits: 0,
|
||||
run_peak: 0.0,
|
||||
run_until_us: 0,
|
||||
strong_run: false,
|
||||
hit_is_impact: false,
|
||||
last_silence_us: 0,
|
||||
continuous_start_us: None,
|
||||
history: [HistoryPoint::default(); HISTORY_CAP],
|
||||
history_len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_sample(
|
||||
&mut self,
|
||||
now_us: i64,
|
||||
left_amp: f32,
|
||||
left_freq: f32,
|
||||
right_amp: f32,
|
||||
right_freq: f32,
|
||||
) -> bool {
|
||||
self.push_sample_ext(now_us, left_amp, left_freq, right_amp, right_freq, false)
|
||||
}
|
||||
|
||||
pub fn merge_partner_sample(
|
||||
&mut self,
|
||||
now_us: i64,
|
||||
left_amp: f32,
|
||||
left_freq: f32,
|
||||
right_amp: f32,
|
||||
right_freq: f32,
|
||||
) -> bool {
|
||||
self.push_sample_ext(now_us, left_amp, left_freq, right_amp, right_freq, true)
|
||||
}
|
||||
|
||||
fn push_sample_ext(
|
||||
&mut self,
|
||||
now_us: i64,
|
||||
left_amp: f32,
|
||||
left_freq: f32,
|
||||
right_amp: f32,
|
||||
right_freq: f32,
|
||||
same_frame: bool,
|
||||
) -> bool {
|
||||
let prev_sample_us = self.last_sample_us;
|
||||
if !same_frame {
|
||||
if let Some(prev_us) = self.last_sample_us {
|
||||
if now_us > prev_us {
|
||||
let dt_s = (now_us - prev_us) as f32 / 1_000_000.0;
|
||||
self.a_ref = (self.a_ref * (-dt_s / A_REF_TAU_S).exp()).max(A_REF_FLOOR);
|
||||
}
|
||||
} else {
|
||||
self.last_silence_us = now_us;
|
||||
}
|
||||
}
|
||||
self.last_sample_us = Some(now_us);
|
||||
|
||||
let prev_level = self.level;
|
||||
let prev_freq = self.freq;
|
||||
self.level = left_amp.max(right_amp);
|
||||
if !same_frame {
|
||||
self.ambient_env = match prev_sample_us {
|
||||
Some(prev_us) if now_us > prev_us => {
|
||||
let dt_s = (now_us - prev_us) as f32 / 1_000_000.0;
|
||||
let alpha = 1.0 - (-dt_s / AMBIENT_TAU_S).exp();
|
||||
self.ambient_env + alpha * (self.level - self.ambient_env)
|
||||
}
|
||||
Some(_) => self.ambient_env,
|
||||
None => self.level,
|
||||
};
|
||||
}
|
||||
let stereo_diff = if left_amp > FAINT && right_amp > FAINT {
|
||||
(left_freq - right_freq).abs()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let new_freq = if left_amp >= right_amp {
|
||||
left_freq
|
||||
} else {
|
||||
right_freq
|
||||
};
|
||||
let step_hz = (new_freq - prev_freq).abs();
|
||||
if !same_frame {
|
||||
self.level_delta = (self.level - prev_level).abs();
|
||||
self.freq_delta = stereo_diff + (new_freq - prev_freq).abs();
|
||||
self.freq_step_hz = step_hz;
|
||||
} else {
|
||||
self.level_delta = self.level_delta.max((self.level - prev_level).abs());
|
||||
self.freq_delta = self
|
||||
.freq_delta
|
||||
.max(stereo_diff + (new_freq - prev_freq).abs());
|
||||
self.freq_step_hz = self.freq_step_hz.max(step_hz);
|
||||
}
|
||||
let sum = left_amp + right_amp;
|
||||
self.pan = if sum > 0.0 {
|
||||
(right_amp - left_amp) / sum
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
self.freq = new_freq;
|
||||
self.pitch = Self::relative_pitch(self.freq, self.base_freq);
|
||||
self.a_ref = self.a_ref.max(self.level).max(A_REF_FLOOR);
|
||||
|
||||
let prev_silence_us = self.last_silence_us;
|
||||
if self.level <= SILENCE {
|
||||
if prev_level > SILENCE || self.hit_start_us.is_none() {
|
||||
self.last_silence_us = now_us;
|
||||
}
|
||||
if now_us - self.last_silence_us > BRIEF_DIP_MAX_US {
|
||||
self.continuous_start_us = None;
|
||||
}
|
||||
} else if prev_level <= SILENCE {
|
||||
if now_us - prev_silence_us > BRIEF_DIP_MAX_US
|
||||
|| self.continuous_start_us.is_none()
|
||||
|| self
|
||||
.hit_start_us
|
||||
.is_some_and(|start| prev_silence_us - start < 160_000)
|
||||
{
|
||||
self.continuous_start_us = Some(now_us);
|
||||
}
|
||||
} else if self.continuous_start_us.is_none() {
|
||||
self.continuous_start_us = Some(now_us);
|
||||
}
|
||||
|
||||
let rise_20ms = self.level - self.min_level_since(now_us - RISE_WINDOW_US, prev_level);
|
||||
self.record_history(now_us, self.level);
|
||||
|
||||
let non_silent_us = if self.level <= SILENCE || prev_level <= SILENCE {
|
||||
0
|
||||
} else {
|
||||
now_us - self.last_silence_us
|
||||
};
|
||||
|
||||
let recent_onset = self
|
||||
.hit_start_us
|
||||
.is_some_and(|start| now_us - start <= RISE_WINDOW_US);
|
||||
let from_silence = prev_level <= SILENCE && self.level >= KICK_MIN;
|
||||
let impact_jump = !from_silence
|
||||
&& !recent_onset
|
||||
&& self.level > prev_level
|
||||
&& self.level >= IMPACT_JUMP_MIN
|
||||
&& rise_20ms >= IMPACT_RISE;
|
||||
let sharp_jump = impact_jump
|
||||
|| (!recent_onset
|
||||
&& (self.level - prev_level) >= 0.05
|
||||
&& rise_20ms >= ONSET_RISE
|
||||
&& non_silent_us < TEXTURE_MIN_US);
|
||||
|
||||
let started_this_frame = self
|
||||
.hit_start_us
|
||||
.is_some_and(|start| (now_us - start).abs() <= 500);
|
||||
|
||||
if same_frame && started_this_frame {
|
||||
self.hit_peak = self.hit_peak.max(self.level);
|
||||
self.hit_onset_level = self.hit_onset_level.max(self.level);
|
||||
self.run_peak = self.run_peak.max(self.level);
|
||||
if self.level >= RHYTHM_REF_RATIO * self.a_ref {
|
||||
self.strong_run = true;
|
||||
}
|
||||
if (self.level >= IMPACT_JUMP_MIN || self.level >= IMPACT_MIN)
|
||||
&& rise_20ms >= IMPACT_RISE
|
||||
{
|
||||
self.hit_is_impact = true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let silence_gap_us = if from_silence {
|
||||
now_us - prev_silence_us
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let repeated = self
|
||||
.hit_start_us
|
||||
.is_some_and(|_| now_us < self.run_until_us)
|
||||
&& silence_gap_us < RUN_GAP_US
|
||||
&& !impact_jump;
|
||||
let strong_thresh = RHYTHM_REF_RATIO * self.a_ref;
|
||||
let is_strong = self.level >= strong_thresh;
|
||||
|
||||
let mut new_hit = false;
|
||||
if from_silence || sharp_jump {
|
||||
new_hit = true;
|
||||
if from_silence {
|
||||
self.last_silence_us = now_us;
|
||||
}
|
||||
let gap = self.hit_start_us.map(|prev| now_us - prev);
|
||||
self.prev_gap_us = gap;
|
||||
|
||||
if repeated {
|
||||
// Faint pulses (like 0.038 propeller blades) right after a strong note run start
|
||||
// a fresh Pulse run instead of becoming Echo if they are below 15% of the strong run peak.
|
||||
if self.strong_run && self.level < 0.15 * self.run_peak {
|
||||
self.run_hits = 2;
|
||||
self.run_peak = self.level;
|
||||
self.strong_run = false;
|
||||
} else if self.run_peak < 0.05
|
||||
&& self.level >= 0.12
|
||||
&& self.level >= self.run_peak * 3.0
|
||||
{
|
||||
self.run_hits = 1;
|
||||
self.run_peak = self.level;
|
||||
self.strong_run = is_strong;
|
||||
} else {
|
||||
self.run_hits += 1;
|
||||
self.run_peak = self.run_peak.max(self.level);
|
||||
self.strong_run = self.strong_run || is_strong;
|
||||
}
|
||||
} else {
|
||||
self.run_hits = 1;
|
||||
self.run_peak = self.level;
|
||||
self.strong_run = is_strong;
|
||||
}
|
||||
let quiet_gap_ok = from_silence;
|
||||
let strong_impact = self.level >= 0.75
|
||||
&& gap.is_none_or(|g| g >= TRIG_REST_US_FOR_IMPACT)
|
||||
&& quiet_gap_ok;
|
||||
self.hit_is_impact =
|
||||
((self.run_hits == 1 && self.level >= IMPACT_MIN) || strong_impact || impact_jump)
|
||||
&& rise_20ms >= IMPACT_RISE;
|
||||
self.hit_start_us = Some(now_us);
|
||||
self.hit_onset_level = self.level;
|
||||
self.hit_peak = self.level;
|
||||
self.hit_onset_freq = self.freq;
|
||||
self.run_until_us = now_us + RUN_GAP_US;
|
||||
} else if let Some(start_us) = self.hit_start_us {
|
||||
if self.level > self.hit_peak {
|
||||
self.hit_peak = self.level;
|
||||
self.run_peak = self.run_peak.max(self.level);
|
||||
if self.level >= RHYTHM_REF_RATIO * self.a_ref {
|
||||
self.strong_run = true;
|
||||
}
|
||||
if self.run_hits == 1
|
||||
&& (now_us - start_us) <= RISE_WINDOW_US
|
||||
&& (self.level >= IMPACT_JUMP_MIN || self.level >= IMPACT_MIN || impact_jump)
|
||||
&& rise_20ms >= IMPACT_RISE
|
||||
{
|
||||
self.hit_is_impact = true;
|
||||
}
|
||||
}
|
||||
if self.run_hits >= 2
|
||||
&& self.strong_run
|
||||
&& self.level >= KICK_MIN
|
||||
&& now_us < self.run_until_us
|
||||
{
|
||||
self.run_until_us = now_us + RUN_GAP_US;
|
||||
}
|
||||
if self.level <= SILENCE && silence_gap_us >= RUN_GAP_US {
|
||||
self.run_until_us = 0;
|
||||
}
|
||||
}
|
||||
|
||||
new_hit
|
||||
}
|
||||
|
||||
/// True once the band has rumbled on without a real pause for `SUSTAINED_MIN_US`.
|
||||
pub fn settled(&self, now_us: i64) -> bool {
|
||||
self.continuous_start_us
|
||||
.is_some_and(|start| now_us - start >= SUSTAINED_MIN_US)
|
||||
}
|
||||
|
||||
pub fn classify(&self, now_us: i64) -> Option<RumbleKind> {
|
||||
if self.level <= FAINT {
|
||||
return None;
|
||||
}
|
||||
let in_run_window = self
|
||||
.hit_start_us
|
||||
.is_some_and(|_| now_us < self.run_until_us);
|
||||
if self.level < KICK_MIN {
|
||||
let quiet_after_single_tap = self
|
||||
.hit_start_us
|
||||
.is_some_and(|start| self.run_hits <= 1 && now_us - start >= 250_000);
|
||||
if (!in_run_window || quiet_after_single_tap) && self.ambient_env >= AMBIENT_MIN {
|
||||
return Some(RumbleKind::Ambient);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let non_silent_us = now_us - self.last_silence_us;
|
||||
let since_hit_us = self
|
||||
.hit_start_us
|
||||
.map_or(non_silent_us, |start| now_us - start);
|
||||
let bridged_us = self
|
||||
.continuous_start_us
|
||||
.map_or(non_silent_us, |start| now_us - start);
|
||||
let textured = self.reversals_since(now_us - TEXTURE_WINDOW_US) >= TEXTURE_MIN_REVERSALS;
|
||||
// Bumps inside a rolling texture are part of the surface, not separate blasts
|
||||
let rolling = textured && bridged_us >= TEXTURE_MIN_US;
|
||||
if self.hit_is_impact && since_hit_us < 250_000 && !rolling {
|
||||
return Some(RumbleKind::Impact);
|
||||
}
|
||||
// Melody notes last up to 500 ms, so a strong run keeps its notes whole: leaving Rhythm
|
||||
// here would add a second blip on the light motor late in every note.
|
||||
// Slow regular beats stay Pulse for their whole beat instead of flipping to Texture
|
||||
let note_limit_us = if self.strong_run && !textured {
|
||||
STRONG_NOTE_MAX_US
|
||||
} else if self.strong_run {
|
||||
TEXTURE_MIN_US
|
||||
} else {
|
||||
self.prev_gap_us
|
||||
.map_or(TEXTURE_MIN_US, |gap| gap.max(TEXTURE_MIN_US))
|
||||
};
|
||||
let in_repeating_run = self.run_hits >= 2 && in_run_window && non_silent_us < note_limit_us;
|
||||
|
||||
if !in_repeating_run {
|
||||
if non_silent_us >= TEXTURE_MIN_US
|
||||
&& self.reversals_since(now_us - TEXTURE_WINDOW_US) >= TEXTURE_MIN_REVERSALS
|
||||
{
|
||||
return Some(RumbleKind::Texture);
|
||||
}
|
||||
if non_silent_us >= SUSTAINED_MIN_US
|
||||
&& self.level >= SUSTAINED_HOLD_RATIO * self.hit_peak
|
||||
{
|
||||
return Some(RumbleKind::Sustained);
|
||||
}
|
||||
if self.hit_is_impact {
|
||||
return Some(RumbleKind::Impact);
|
||||
}
|
||||
return Some(RumbleKind::Tap);
|
||||
}
|
||||
|
||||
if self.strong_run {
|
||||
if self.hit_peak < ECHO_PEAK_RATIO * self.run_peak {
|
||||
Some(RumbleKind::Echo)
|
||||
} else {
|
||||
Some(RumbleKind::Rhythm)
|
||||
}
|
||||
} else if bridged_us >= SUSTAINED_MIN_US
|
||||
&& self.level >= SUSTAINED_HOLD_RATIO * self.hit_peak
|
||||
&& self.level >= 0.06
|
||||
{
|
||||
Some(RumbleKind::Sustained)
|
||||
} else {
|
||||
Some(RumbleKind::Pulse)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn relative_pitch(freq: f32, base_freq: f32) -> f32 {
|
||||
if freq <= 0.0 || base_freq <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
(freq / base_freq).log2().clamp(-1.0, 1.0)
|
||||
}
|
||||
|
||||
fn min_level_since(&self, since_us: i64, fallback: f32) -> f32 {
|
||||
let mut min_val = fallback;
|
||||
for pt in &self.history[..self.history_len] {
|
||||
if pt.t_us >= since_us && pt.level < min_val {
|
||||
min_val = pt.level;
|
||||
}
|
||||
}
|
||||
min_val
|
||||
}
|
||||
|
||||
fn record_history(&mut self, now_us: i64, level: f32) {
|
||||
let cutoff = now_us - TEXTURE_WINDOW_US;
|
||||
let mut keep = 0;
|
||||
for i in 0..self.history_len {
|
||||
if self.history[i].t_us >= cutoff {
|
||||
self.history[keep] = self.history[i];
|
||||
keep += 1;
|
||||
}
|
||||
}
|
||||
self.history_len = keep;
|
||||
if self.history_len > 0 {
|
||||
let last = &mut self.history[self.history_len - 1];
|
||||
if now_us - last.t_us < 1_000 {
|
||||
last.t_us = now_us;
|
||||
last.level = level;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.history_len == HISTORY_CAP {
|
||||
self.history.copy_within(1..HISTORY_CAP, 0);
|
||||
self.history_len -= 1;
|
||||
}
|
||||
self.history[self.history_len] = HistoryPoint {
|
||||
t_us: now_us,
|
||||
level,
|
||||
};
|
||||
self.history_len += 1;
|
||||
}
|
||||
|
||||
fn reversals_since(&self, since_us: i64) -> usize {
|
||||
let mut revs = 0;
|
||||
let mut dir: i8 = 0;
|
||||
let mut anchor: Option<f32> = None;
|
||||
for pt in &self.history[..self.history_len] {
|
||||
if pt.t_us < since_us {
|
||||
continue;
|
||||
}
|
||||
let Some(a) = anchor else {
|
||||
anchor = Some(pt.level);
|
||||
continue;
|
||||
};
|
||||
let diff = pt.level - a;
|
||||
if diff.abs() >= TEXTURE_REV_DELTA {
|
||||
let d = if diff > 0.0 { 1 } else { -1 };
|
||||
if dir != 0 && d != dir {
|
||||
revs += 1;
|
||||
}
|
||||
dir = d;
|
||||
anchor = Some(pt.level);
|
||||
} else if (dir > 0 && pt.level > a) || (dir < 0 && pt.level < a) {
|
||||
anchor = Some(pt.level);
|
||||
}
|
||||
}
|
||||
revs
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn first_048_note_is_tap_and_second_is_rhythm() {
|
||||
let mut c = BandClassifier::new(320.0);
|
||||
c.push_sample(0, 0.48, 320.0, 0.0, 320.0);
|
||||
assert_eq!(c.classify(0), Some(RumbleKind::Tap));
|
||||
|
||||
c.push_sample(160_000, 0.0, 320.0, 0.0, 320.0);
|
||||
c.push_sample(170_000, 0.48, 320.0, 0.0, 320.0);
|
||||
assert_eq!(c.classify(170_000), Some(RumbleKind::Rhythm));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharp_081_after_silence_is_impact() {
|
||||
let mut c = BandClassifier::new(160.0);
|
||||
c.push_sample(0, 0.81, 160.0, 0.0, 160.0);
|
||||
assert_eq!(c.classify(0), Some(RumbleKind::Impact));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faint_0038_every_120ms_right_after_048_notes_is_pulse_not_ambient() {
|
||||
let mut c = BandClassifier::new(160.0);
|
||||
c.push_sample(0, 0.48, 160.0, 0.0, 160.0);
|
||||
c.push_sample(160_000, 0.0, 160.0, 0.0, 160.0);
|
||||
c.push_sample(170_000, 0.48, 160.0, 0.0, 160.0);
|
||||
c.push_sample(330_000, 0.0, 160.0, 0.0, 160.0);
|
||||
|
||||
for k in 0..3 {
|
||||
let at = 350_000 + k * 120_000;
|
||||
c.push_sample(at, 0.038, 160.0, 0.0, 160.0);
|
||||
assert_eq!(c.classify(at), Some(RumbleKind::Pulse));
|
||||
c.push_sample(at + 30_000, 0.0, 160.0, 0.0, 160.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fading_010_after_note_run_is_echo() {
|
||||
let mut c = BandClassifier::new(320.0);
|
||||
c.push_sample(0, 0.48, 320.0, 0.0, 320.0);
|
||||
c.push_sample(160_000, 0.0, 320.0, 0.0, 320.0);
|
||||
c.push_sample(170_000, 0.48, 320.0, 0.0, 320.0);
|
||||
c.push_sample(330_000, 0.0, 320.0, 0.0, 320.0);
|
||||
|
||||
c.push_sample(340_000, 0.10, 320.0, 0.0, 320.0);
|
||||
assert_eq!(c.classify(340_000), Some(RumbleKind::Echo));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steady_030_for_400ms_is_sustained_and_170ms_note_is_never_sustained() {
|
||||
let mut c = BandClassifier::new(160.0);
|
||||
for step in 0..=40 {
|
||||
let t = step * 10_000;
|
||||
c.push_sample(t, 0.30, 160.0, 0.0, 160.0);
|
||||
if t < 300_000 {
|
||||
assert_ne!(c.classify(t), Some(RumbleKind::Sustained));
|
||||
}
|
||||
}
|
||||
assert_eq!(c.classify(400_000), Some(RumbleKind::Sustained));
|
||||
|
||||
// 170 ms note never reaches Sustained
|
||||
let mut note = BandClassifier::new(320.0);
|
||||
for step in 0..17 {
|
||||
let t = step * 10_000;
|
||||
note.push_sample(t, 0.48, 320.0, 0.0, 320.0);
|
||||
assert_ne!(note.classify(t), Some(RumbleKind::Sustained));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rapid_oscillation_around_020_for_400ms_is_texture_not_tap_run() {
|
||||
let mut c = BandClassifier::new(160.0);
|
||||
for step in 0..=40 {
|
||||
let t = step * 10_000;
|
||||
let amp = if step % 2 == 0 { 0.24 } else { 0.16 };
|
||||
c.push_sample(t, amp, 160.0, 0.0, 160.0);
|
||||
}
|
||||
assert_eq!(c.classify(400_000), Some(RumbleKind::Texture));
|
||||
assert_eq!(c.run_hits, 1);
|
||||
}
|
||||
}
|
||||
249
third_party/renhdrum/src/xbox/direct.rs
vendored
Normal file
249
third_party/renhdrum/src/xbox/direct.rs
vendored
Normal file
@@ -0,0 +1,249 @@
|
||||
//! Xbox "Direct" mode (plan 120): the two bands of each Switch side drive the grip motors and
|
||||
//! the triggers straight, without the rotor model. Moved from lichii `renhdrum_pad.cpp`
|
||||
//! (same arithmetic). The host calls `push` per half sample and `tick` on its timer, and sends
|
||||
//! what they return. Settings come from the store: `gain`, `low_boost`, `xbox_strength`,
|
||||
//! `xbox_detail`, `xbox_accents`, `xbox_trigger_mix`.
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
use crate::ffi::RENHDRUM_ERR_NULL_PTR;
|
||||
use crate::options::{renhdrum_store_shape_amplitude, RenHdcStore};
|
||||
|
||||
/// A sudden rise of this much (15 % of the range) gets a short burst so the motor spins up.
|
||||
const KICK_RISE: i32 = 65535 * 15 / 100;
|
||||
const KICK_US: i64 = 25_000;
|
||||
|
||||
/// Return mask of `push` / `tick`: grip motors changed (`out[0..2]`), triggers changed (`out[2..4]`).
|
||||
pub const XBOX_DIRECT_SEND_GRIPS: i32 = 1;
|
||||
pub const XBOX_DIRECT_SEND_TRIGGERS: i32 = 2;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RenHdcXboxDirect {
|
||||
low: [f32; 2],
|
||||
high: [f32; 2],
|
||||
sent: [u16; 2],
|
||||
target: [u16; 2],
|
||||
trigger_sent: [u16; 2],
|
||||
trigger_target: [u16; 2],
|
||||
kick_until_us: i64,
|
||||
}
|
||||
|
||||
impl RenHdcXboxDirect {
|
||||
fn push(
|
||||
&mut self,
|
||||
s: &RenHdcStore,
|
||||
now_us: i64,
|
||||
is_right: bool,
|
||||
low_amp: f32,
|
||||
high_amp: f32,
|
||||
triggers: bool,
|
||||
) -> ([u16; 4], i32) {
|
||||
let shape = |a: f32| unsafe { renhdrum_store_shape_amplitude(s, a) };
|
||||
let side = is_right as usize;
|
||||
self.low[side] = shape(low_amp);
|
||||
self.high[side] = shape(high_amp);
|
||||
let scale = s.value("xbox_strength") as f32 / 100.0;
|
||||
let mix = s.value("xbox_detail") as f32 / 100.0;
|
||||
let to_motor = |v: f32| ((v * scale).min(1.0) * 65535.0) as u16;
|
||||
let low = self.low[0].max(self.low[1]);
|
||||
let high = self.high[0].max(self.high[1]);
|
||||
// The big motor also carries part of the fine vibration, where it is felt
|
||||
let target = [to_motor(low.max(high * mix)), to_motor(high)];
|
||||
let accent = s.value("xbox_accents") as f32 / 100.0;
|
||||
let kicked = |t: u16| (t as f32 + (65535.0 - t as f32) * accent) as u16;
|
||||
let trigger_mix = s.value("xbox_trigger_mix") as f32 / 100.0;
|
||||
let on_trigger = |v: u16| (v as f32 * trigger_mix) as u16;
|
||||
let trigger_full = [to_motor(self.high[0]), to_motor(self.high[1])];
|
||||
let trigger_target = [on_trigger(trigger_full[0]), on_trigger(trigger_full[1])];
|
||||
|
||||
let mut direct = [0u16; 2];
|
||||
let mut trigger = [0u16; 2];
|
||||
let (mut send_direct, mut send_trigger) = (false, false);
|
||||
let rise = |i: usize| target[i] as i32 - self.target[i] as i32 >= KICK_RISE;
|
||||
let kicking = self.kick_until_us != 0 && now_us < self.kick_until_us;
|
||||
if !kicking && accent > 0.0 && (rise(0) || rise(1)) {
|
||||
self.kick_until_us = now_us + KICK_US;
|
||||
trigger = [
|
||||
on_trigger(kicked(trigger_full[0])),
|
||||
on_trigger(kicked(trigger_full[1])),
|
||||
];
|
||||
send_trigger = true;
|
||||
direct = [
|
||||
if rise(0) {
|
||||
kicked(target[0])
|
||||
} else {
|
||||
target[0]
|
||||
},
|
||||
if rise(1) {
|
||||
kicked(target[1])
|
||||
} else {
|
||||
target[1]
|
||||
},
|
||||
];
|
||||
send_direct = true;
|
||||
} else if kicking {
|
||||
// Settle on the latest target when the kick ends (tick); a stop ends it now
|
||||
if target == [0, 0] {
|
||||
self.kick_until_us = 0;
|
||||
direct = target;
|
||||
send_direct = true;
|
||||
trigger = trigger_target;
|
||||
send_trigger = true;
|
||||
}
|
||||
} else {
|
||||
self.kick_until_us = 0;
|
||||
direct = target;
|
||||
send_direct = direct != self.sent;
|
||||
trigger = trigger_target;
|
||||
send_trigger = trigger != self.trigger_sent;
|
||||
}
|
||||
self.target = target;
|
||||
self.trigger_target = trigger_target;
|
||||
if send_direct {
|
||||
self.sent = direct;
|
||||
}
|
||||
send_trigger = send_trigger && triggers;
|
||||
if send_trigger {
|
||||
self.trigger_sent = trigger;
|
||||
}
|
||||
pack(direct, trigger, send_direct, send_trigger)
|
||||
}
|
||||
|
||||
fn tick(&mut self, now_us: i64, triggers: bool) -> ([u16; 4], i32) {
|
||||
if self.kick_until_us == 0 || now_us < self.kick_until_us {
|
||||
return ([0; 4], 0);
|
||||
}
|
||||
self.kick_until_us = 0;
|
||||
let settle = self.target;
|
||||
let send_settle = settle != self.sent;
|
||||
self.sent = settle;
|
||||
let settle_trigger = self.trigger_target;
|
||||
let send_trigger = triggers && settle_trigger != self.trigger_sent;
|
||||
if send_trigger {
|
||||
self.trigger_sent = settle_trigger;
|
||||
}
|
||||
pack(settle, settle_trigger, send_settle, send_trigger)
|
||||
}
|
||||
}
|
||||
|
||||
fn pack(g: [u16; 2], t: [u16; 2], send_g: bool, send_t: bool) -> ([u16; 4], i32) {
|
||||
let mut mask = 0;
|
||||
if send_g {
|
||||
mask |= XBOX_DIRECT_SEND_GRIPS;
|
||||
}
|
||||
if send_t {
|
||||
mask |= XBOX_DIRECT_SEND_TRIGGERS;
|
||||
}
|
||||
([g[0], g[1], t[0], t[1]], mask)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn renhdrum_xbox_direct_create() -> *mut RenHdcXboxDirect {
|
||||
Box::into_raw(Box::default())
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_xbox_direct_destroy(d: *mut RenHdcXboxDirect) {
|
||||
if !d.is_null() {
|
||||
drop(Box::from_raw(d));
|
||||
}
|
||||
}
|
||||
|
||||
/// One half sample (raw game amplitudes; `gain` / `low_boost` of the store are applied inside).
|
||||
/// Returns a mask: bit 0 = send grips `out_motors4[0..2]` (SDL_RumbleJoystick, 2000 ms),
|
||||
/// bit 1 = send triggers `out_motors4[2..4]` (SDL_RumbleJoystickTriggers, 2000 ms); 0 = nothing
|
||||
/// to send; <0 = error. `triggers`: the pad has trigger motors the host will drive.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_xbox_direct_push(
|
||||
d: *mut RenHdcXboxDirect,
|
||||
s: *const RenHdcStore,
|
||||
now_us: i64,
|
||||
is_right: bool,
|
||||
low_amp: f32,
|
||||
high_amp: f32,
|
||||
triggers: bool,
|
||||
out_motors4: *mut u16,
|
||||
) -> i32 {
|
||||
if d.is_null() || s.is_null() || out_motors4.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
let (m, mask) = (*d).push(&*s, now_us, is_right, low_amp, high_amp, triggers);
|
||||
std::ptr::copy_nonoverlapping(m.as_ptr(), out_motors4, 4);
|
||||
mask
|
||||
}
|
||||
|
||||
/// Call on the host timer: when a burst ends, returns the settled motor values (same mask as push).
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn renhdrum_xbox_direct_tick(
|
||||
d: *mut RenHdcXboxDirect,
|
||||
now_us: i64,
|
||||
triggers: bool,
|
||||
out_motors4: *mut u16,
|
||||
) -> i32 {
|
||||
if d.is_null() || out_motors4.is_null() {
|
||||
return RENHDRUM_ERR_NULL_PTR;
|
||||
}
|
||||
let (m, mask) = (*d).tick(now_us, triggers);
|
||||
std::ptr::copy_nonoverlapping(m.as_ptr(), out_motors4, 4);
|
||||
mask
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::{renhdrum_store_create, renhdrum_store_destroy, renhdrum_store_set};
|
||||
use std::ffi::CString;
|
||||
|
||||
fn set(s: *mut RenHdcStore, k: &str, v: i32) {
|
||||
let k = CString::new(k).unwrap();
|
||||
unsafe { renhdrum_store_set(s, k.as_ptr(), v) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steady_level_with_defaults_and_stop() {
|
||||
let s = renhdrum_store_create();
|
||||
let st = unsafe { &*s };
|
||||
let mut d = RenHdcXboxDirect::default();
|
||||
// 0.1 never rises 15 % of the range: no kick, plain target (strength 100 %, detail 50 %)
|
||||
let (m, mask) = d.push(st, 0, false, 0.1, 0.05, true);
|
||||
assert_eq!(mask, 3);
|
||||
assert_eq!(m[0], (0.1f32 * 65535.0) as u16); // max(low 0.1, high * 0.5)
|
||||
assert_eq!(m[1], (0.05f32 * 65535.0) as u16);
|
||||
assert_eq!(m[2], (((0.05f32 * 65535.0) as u16) as f32 * 0.2) as u16);
|
||||
// same again: nothing to send
|
||||
assert_eq!(d.push(st, 1_000, false, 0.1, 0.05, true).1, 0);
|
||||
// stop
|
||||
let (m, mask) = d.push(st, 2_000, false, 0.0, 0.0, true);
|
||||
assert_eq!((m, mask), ([0; 4], 3));
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kick_on_rise_then_tick_settles() {
|
||||
let s = renhdrum_store_create();
|
||||
let st = unsafe { &*s };
|
||||
let mut d = RenHdcXboxDirect::default();
|
||||
let (m, mask) = d.push(st, 0, false, 0.5, 0.0, false);
|
||||
let target = (0.5f32 * 65535.0) as u16;
|
||||
assert_eq!(mask, 1); // triggers off: not sent
|
||||
assert_eq!(
|
||||
m[0],
|
||||
(target as f32 + (65535.0 - target as f32) * 0.5) as u16
|
||||
);
|
||||
assert_eq!(d.tick(10_000, false).1, 0); // burst still running
|
||||
let (m, mask) = d.tick(25_000, false);
|
||||
assert_eq!((m[0], m[1], mask), (target, 0, 1));
|
||||
assert_eq!(d.tick(30_000, false).1, 0);
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accents_zero_means_no_kick_and_strength_scales() {
|
||||
let s = renhdrum_store_create();
|
||||
set(s, "xbox_accents", 0);
|
||||
set(s, "xbox_strength", 50);
|
||||
let mut d = RenHdcXboxDirect::default();
|
||||
let (m, mask) = d.push(unsafe { &*s }, 0, true, 0.6, 0.0, false);
|
||||
assert_eq!((m[0], mask), ((0.3f32 * 65535.0) as u16, 1));
|
||||
unsafe { renhdrum_store_destroy(s) };
|
||||
}
|
||||
}
|
||||
2302
third_party/renhdrum/src/xbox/mod.rs
vendored
Normal file
2302
third_party/renhdrum/src/xbox/mod.rs
vendored
Normal file
File diff suppressed because it is too large
Load Diff
89
third_party/renhdrum/src/xbox/rotor.rs
vendored
Normal file
89
third_party/renhdrum/src/xbox/rotor.rs
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
//! First-order lag model of the four ERM rotors on an Xbox One S controller (model 1708).
|
||||
//! Time constants are estimated from general ERM motors and have not yet been measured on a real
|
||||
//! 1708 pad; keep them as top-level constants so they can be tuned after accelerometer measurement.
|
||||
|
||||
/// Left grip (heavy rotor) spin-up time constant in microseconds (85 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const LG_TAU_UP_US: f32 = 85_000.0;
|
||||
/// Left grip (heavy rotor) spin-down time constant in microseconds (150 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const LG_TAU_DOWN_US: f32 = 150_000.0;
|
||||
|
||||
/// Right grip (light rotor) spin-up time constant in microseconds (50 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const RG_TAU_UP_US: f32 = 50_000.0;
|
||||
/// Right grip (light rotor) spin-down time constant in microseconds (80 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const RG_TAU_DOWN_US: f32 = 80_000.0;
|
||||
|
||||
/// Trigger rotor spin-up time constant in microseconds (20 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const TRIG_TAU_UP_US: f32 = 20_000.0;
|
||||
/// Trigger rotor spin-down time constant in microseconds (30 ms).
|
||||
/// Estimated from general ERM, not yet measured on model 1708.
|
||||
pub const TRIG_TAU_DOWN_US: f32 = 30_000.0;
|
||||
|
||||
const TAU_UP_US: [f32; 4] = [LG_TAU_UP_US, RG_TAU_UP_US, TRIG_TAU_UP_US, TRIG_TAU_UP_US];
|
||||
const TAU_DOWN_US: [f32; 4] = [
|
||||
LG_TAU_DOWN_US,
|
||||
RG_TAU_DOWN_US,
|
||||
TRIG_TAU_DOWN_US,
|
||||
TRIG_TAU_DOWN_US,
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct RotorModel {
|
||||
pub omega: [f32; 4],
|
||||
}
|
||||
|
||||
impl RotorModel {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Advance the four rotor speed estimates `[LG, RG, LT, RT]` by `dt_us` under drive `u` (`0.0..=1.0`).
|
||||
pub fn step(&mut self, dt_us: i64, u: [f32; 4]) {
|
||||
if dt_us <= 0 {
|
||||
return;
|
||||
}
|
||||
let dt = dt_us as f32;
|
||||
for i in 0..4 {
|
||||
let target = u[i].clamp(0.0, 1.0);
|
||||
let tau = if target >= self.omega[i] {
|
||||
TAU_UP_US[i]
|
||||
} else {
|
||||
TAU_DOWN_US[i]
|
||||
};
|
||||
// Sub-step if dt exceeds tau/4 so large jumps between samples decay accurately
|
||||
let steps = ((dt / (tau * 0.25)).ceil() as usize).clamp(1, 256);
|
||||
let sub_dt = dt / steps as f32;
|
||||
let alpha = (sub_dt / tau).clamp(0.0, 1.0);
|
||||
for _ in 0..steps {
|
||||
self.omega[i] = (self.omega[i] + alpha * (target - self.omega[i])).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rotor_decays_near_zero_after_500ms_and_lg_spins_up_slower_than_trigger() {
|
||||
let mut r = RotorModel::new();
|
||||
for _ in 0..5 {
|
||||
r.step(10_000, [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
// LG (tau_up = 85 ms) spins up slower than RG (50 ms) and trigger (20 ms)
|
||||
assert!(r.omega[0] < r.omega[1]);
|
||||
assert!(r.omega[1] < r.omega[2]);
|
||||
|
||||
for _ in 0..50 {
|
||||
r.step(10_000, [0.0; 4]);
|
||||
}
|
||||
for w in r.omega {
|
||||
assert!(w < 0.05, "expected rotor near zero after 500 ms, got {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
9
third_party/reshade_fx/LICENSE.md
vendored
Normal file
9
third_party/reshade_fx/LICENSE.md
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
Copyright 2014 Patrick Mours. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
10
third_party/reshade_fx/PROVENANCE.md
vendored
Normal file
10
third_party/reshade_fx/PROVENANCE.md
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
# ReShade FX
|
||||
|
||||
The standalone ReShade FX parser, preprocessor and SPIR-V generator from
|
||||
<https://github.com/crosire/reshade/tree/7bf9de8b33bcc76c3177007e65d73c72dd0f34c0/source>.
|
||||
The selected files are unmodified copies of ReShade's own under BSD-3-Clause. See `LICENSE.md`.
|
||||
|
||||
Triforce supplies its restricted include resolver outside this directory (gpu/vk/reshade/fx_files.cpp, nx2/reshade_fx.py). The ReShade runtime,
|
||||
injector, overlay and other shader backends are outside this source subset.
|
||||
|
||||
tree-sha256: 2fa06c201e7c58eeb0c1bf792e88cbf50faf6c395e5477c2c7bdf1a079651e78
|
||||
422
third_party/reshade_fx/source/effect_codegen.hpp
vendored
Normal file
422
third_party/reshade_fx/source/effect_codegen.hpp
vendored
Normal file
@@ -0,0 +1,422 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_module.hpp"
|
||||
#include <memory> // std::unique_ptr
|
||||
#include <algorithm> // std::find_if
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// A SSA code generation back-end interface for the parser to call into.
|
||||
/// </summary>
|
||||
class codegen
|
||||
{
|
||||
friend class parser;
|
||||
|
||||
public:
|
||||
/// <summary>
|
||||
/// Virtual destructor to guarantee that memory of the implementations deriving from this interface is properly destroyed.
|
||||
/// </summary>
|
||||
virtual ~codegen() {}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the module describing the generated code.
|
||||
/// </summary>
|
||||
effect_module &module() { return _module; }
|
||||
|
||||
/// <summary>
|
||||
/// Finalizes and returns the generated code for the entire module (all entry points).
|
||||
/// </summary>
|
||||
virtual std::string finalize_code() const = 0;
|
||||
/// <summary>
|
||||
/// Finalizes and assembles the generated code for the specified entry point (and no other entry points).
|
||||
/// </summary>
|
||||
/// <param name="entry_point_name">Name of the entry point function to generate code for.</param>
|
||||
/// <param name="binary">Output binary code.</param>
|
||||
/// <param name="assembly">Output assembly code.</param>
|
||||
/// <param name="errors">Output list of error messages.</param>
|
||||
virtual bool assemble_code_for_entry_point(const std::string &entry_point_name, std::string &binary, std::string &assembly, std::string &errors) const = 0;
|
||||
|
||||
protected:
|
||||
/// <summary>
|
||||
/// An opaque ID referring to a SSA value or basic block.
|
||||
/// </summary>
|
||||
using id = uint32_t;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a new struct type.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="info">Description of the type.</param>
|
||||
/// <returns>New SSA ID of the type.</returns>
|
||||
virtual id define_struct(const location &loc, struct_type &info) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new texture binding.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="info">Description of the texture object.</param>
|
||||
/// <returns>New SSA ID of the binding.</returns>
|
||||
virtual id define_texture(const location &loc, texture &info) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new sampler binding.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="tex_info">Description of the texture this sampler object references.</param>
|
||||
/// <param name="info">Description of the sampler object.</param>
|
||||
/// <returns>New SSA ID of the binding.</returns>
|
||||
virtual id define_sampler(const location &loc, const texture &tex_info, sampler &info) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new storage binding.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="tex_info">Description of the texture this storage object references.</param>
|
||||
/// <param name="info">Description of the storage object.</param>
|
||||
/// <returns>New SSA ID of the binding.</returns>
|
||||
virtual id define_storage(const location &loc, const texture &tex_info, storage &info) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new uniform variable.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="info">Description of the uniform variable.</param>
|
||||
/// <returns>New SSA ID of the variable.</returns>
|
||||
virtual id define_uniform(const location &loc, uniform &info) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new variable.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="type">Data type of the variable.</param>
|
||||
/// <param name="name">Name of the variable.</param>
|
||||
/// <param name="global"><c>true</c> if this variable is in global scope, <c>false</c> otherwise.</param>
|
||||
/// <param name="initializer_value">SSA ID of an optional initializer value.</param>
|
||||
/// <returns>New SSA ID of the variable.</returns>
|
||||
virtual id define_variable(const location &loc, const type &type, std::string name = std::string(), bool global = false, id initializer_value = 0) = 0;
|
||||
/// <summary>
|
||||
/// Defines a new function and its function parameters and make it current.
|
||||
/// Any code added after this call is added to this function.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="info">Description of the function.</param>
|
||||
/// <returns>New SSA ID of the function.</returns>
|
||||
virtual id define_function(const location &loc, function &info) = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a new effect technique.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this definition (for debugging).</param>
|
||||
/// <param name="info">Description of the technique.</param>
|
||||
void define_technique(technique &&info) { _module.techniques.push_back(std::move(info)); }
|
||||
/// <summary>
|
||||
/// Makes a function a shader entry point.
|
||||
/// </summary>
|
||||
/// <param name="function">Function to use as entry point. May be overwritten to point to a new uniquely generated function.</param>
|
||||
virtual void define_entry_point(function &function) = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the access chain and add a load operation to the output.
|
||||
/// </summary>
|
||||
/// <param name="chain">Access chain pointing to the variable to load from.</param>
|
||||
/// <param name="force_new_id">Set to <see langword="true"/> to force this to return a new SSA ID for l-value loads.</param>
|
||||
/// <returns>New SSA ID with the loaded value.</returns>
|
||||
virtual id emit_load(const expression &chain, bool force_new_id = false) = 0;
|
||||
/// <summary>
|
||||
/// Resolves the access chain and add a store operation to the output.
|
||||
/// </summary>
|
||||
/// <param name="chain">Access chain pointing to the variable to store to.</param>
|
||||
/// <param name="value">SSA ID of the value to store.</param>
|
||||
virtual void emit_store(const expression &chain, id value) = 0;
|
||||
/// <summary>
|
||||
/// Resolves the access chain, but do not add a load operation. This returns a pointer instead.
|
||||
/// </summary>
|
||||
/// <param name="chain">Access chain pointing to the variable to resolve.</param>
|
||||
/// <param name="chain_index">Output value which is set to the index in the access chain up to which the access chain went.</param>
|
||||
/// <returns>New SSA ID with a pointer to the value.</returns>
|
||||
virtual id emit_access_chain(const expression &chain, size_t &chain_index) { chain_index = chain.chain.size(); return emit_load(chain); }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a SSA constant value.
|
||||
/// </summary>
|
||||
/// <param name="type">Data type of the constant.</param>
|
||||
/// <param name="data">Actual constant data to convert into a SSA ID.</param>
|
||||
/// <returns>New SSA ID with the constant value.</returns>
|
||||
virtual id emit_constant(const type &type, const constant &data) = 0;
|
||||
id emit_constant(const type &data_type, uint32_t value)
|
||||
{
|
||||
// Create a constant value of the specified type
|
||||
constant data = {}; // Initialize to zero, so that components not set below still have a defined value for lookup via std::memcmp
|
||||
for (unsigned int i = 0; i < data_type.components(); ++i)
|
||||
{
|
||||
if (data_type.is_integral())
|
||||
data.as_uint[i] = value;
|
||||
else
|
||||
data.as_float[i] = static_cast<float>(value);
|
||||
}
|
||||
return emit_constant(data_type, data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds an unary operation to the output (built-in operation with one argument).
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this operation (for debugging).</param>
|
||||
/// <param name="op">Unary operator to use.</param>
|
||||
/// <param name="type">Data type of the input value.</param>
|
||||
/// <param name="val">SSA ID of value to perform the operation on.</param>
|
||||
/// <returns>New SSA ID with the result of the operation.</returns>
|
||||
virtual id emit_unary_op(const location &loc, tokenid op, const type &type, id val) = 0;
|
||||
/// <summary>
|
||||
/// Adds a binary operation to the output (built-in operation with two arguments).
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this operation (for debugging).</param>
|
||||
/// <param name="op">Binary operator to use.</param>
|
||||
/// <param name="res_type">Data type of the result.</param>
|
||||
/// <param name="type">Data type of the input values.</param>
|
||||
/// <param name="lhs">SSA ID of the value on the left-hand side of the binary operation.</param>
|
||||
/// <param name="rhs">SSA ID of the value on the right-hand side of the binary operation.</param>
|
||||
/// <returns>New SSA ID with the result of the operation.</returns>
|
||||
virtual id emit_binary_op(const location &loc, tokenid op, const type &res_type, const type &type, id lhs, id rhs) = 0;
|
||||
id emit_binary_op(const location &loc, tokenid op, const type &type, id lhs, id rhs) { return emit_binary_op(loc, op, type, type, lhs, rhs); }
|
||||
/// <summary>
|
||||
/// Adds a ternary operation to the output (built-in operation with three arguments).
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this operation (for debugging).</param>
|
||||
/// <param name="op">Ternary operator to use.</param>
|
||||
/// <param name="type">Data type of the input values.</param>
|
||||
/// <param name="condition">SSA ID of the condition value of the ternary operation.</param>
|
||||
/// <param name="true_value">SSA ID of the first value of the ternary operation.</param>
|
||||
/// <param name="false_value">SSA ID of the second value of the ternary operation.</param>
|
||||
/// <returns>New SSA ID with the result of the operation.</returns>
|
||||
virtual id emit_ternary_op(const location &loc, tokenid op, const type &type, id condition, id true_value, id false_value) = 0;
|
||||
/// <summary>
|
||||
/// Adds a function call to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this operation (for debugging).</param>
|
||||
/// <param name="function">SSA ID of the function to call.</param>
|
||||
/// <param name="res_type">Data type of the call result.</param>
|
||||
/// <param name="args">List of SSA IDs representing the call arguments.</param>
|
||||
/// <returns>New SSA ID with the result of the function call.</returns>
|
||||
virtual id emit_call(const location &loc, id function, const type &res_type, const std::vector<expression> &args) = 0;
|
||||
/// <summary>
|
||||
/// Adds an intrinsic function call to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this operation (for debugging).</param>
|
||||
/// <param name="function">Intrinsic to call.</param>
|
||||
/// <param name="res_type">Data type of the call result.</param>
|
||||
/// <param name="args">List of SSA IDs representing the call arguments.</param>
|
||||
/// <returns>New SSA ID with the result of the function call.</returns>
|
||||
virtual id emit_call_intrinsic(const location &loc, id function, const type &res_type, const std::vector<expression> &args) = 0;
|
||||
/// <summary>
|
||||
/// Adds a type constructor call to the output.
|
||||
/// </summary>
|
||||
/// <param name="type">Data type to construct.</param>
|
||||
/// <param name="args">List of SSA IDs representing the scalar constructor arguments.</param>
|
||||
/// <returns>New SSA ID with the constructed value.</returns>
|
||||
virtual id emit_construct(const location &loc, const type &type, const std::vector<expression> &args) = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Adds a structured branch control flow to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this branch (for debugging).</param>
|
||||
/// <param name="flags">0 - default, 1 - flatten, 2 - do not flatten</param>
|
||||
virtual void emit_if(const location &loc, id condition_value, id condition_block, id true_statement_block, id false_statement_block, unsigned int flags) = 0;
|
||||
/// <summary>
|
||||
/// Adds a branch control flow with a SSA phi operation to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this branch (for debugging).</param>
|
||||
/// <returns>New SSA ID with the result of the phi operation.</returns>
|
||||
virtual id emit_phi(const location &loc, id condition_value, id condition_block, id true_value, id true_statement_block, id false_value, id false_statement_block, const type &type) = 0;
|
||||
/// <summary>
|
||||
/// Adds a structured loop control flow to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this loop (for debugging).</param>
|
||||
/// <param name="flags">0 - default, 1 - unroll, 2 - do not unroll</param>
|
||||
virtual void emit_loop(const location &loc, id condition_value, id prev_block, id header_block, id condition_block, id loop_block, id continue_block, unsigned int flags) = 0;
|
||||
/// <summary>
|
||||
/// Adds a structured switch control flow to the output.
|
||||
/// </summary>
|
||||
/// <param name="loc">Source location matching this switch (for debugging).</param>
|
||||
/// <param name="flags">0 - default, 1 - flatten, 2 - do not flatten</param>
|
||||
virtual void emit_switch(const location &loc, id selector_value, id selector_block, id default_label, id default_block, const std::vector<id> &case_literal_and_labels, const std::vector<id> &case_blocks, unsigned int flags) = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Adds a pragma operator to the output.
|
||||
/// </summary>
|
||||
/// <param name="pragma">Argument of the pragma operator.</param>
|
||||
virtual void emit_pragma(const std::string &pragma) = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see langword="true"/> if code is currently added to a basic block.
|
||||
/// </summary>
|
||||
bool is_in_block() const { return _current_block != 0; }
|
||||
/// <summary>
|
||||
/// Returns <see langword="true"/> if code is currently added to a function.
|
||||
/// </summary>
|
||||
bool is_in_function() const { return _current_function != nullptr; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new basic block.
|
||||
/// </summary>
|
||||
/// <returns>New ID of the basic block.</returns>
|
||||
virtual id create_block() { return make_id(); }
|
||||
/// <summary>
|
||||
/// Overwrites the current block ID.
|
||||
/// </summary>
|
||||
/// <param name="id">ID of the block to make current.</param>
|
||||
/// <returns>ID of the previous basic block.</returns>
|
||||
virtual id set_block(id id) = 0;
|
||||
/// <summary>
|
||||
/// Creates a new basic block and makes it current.
|
||||
/// </summary>
|
||||
/// <param name="id">ID of the basic block to create and make current.</param>
|
||||
virtual void enter_block(id id) = 0;
|
||||
/// <summary>
|
||||
/// Returns from the current basic block and kills the shader invocation.
|
||||
/// </summary>
|
||||
/// <returns>ID of the current basic block.</returns>
|
||||
virtual id leave_block_and_kill() = 0;
|
||||
/// <summary>
|
||||
/// Returns from the current basic block and hands control flow over to the function call side.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional SSA ID of a return value.</param>
|
||||
/// <returns>ID of the current basic block.</returns>
|
||||
virtual id leave_block_and_return(id value = 0) = 0;
|
||||
/// <summary>
|
||||
/// Diverges the current control flow and enters a switch.
|
||||
/// </summary>
|
||||
/// <param name="value">SSA ID of the selector value to decide the switch path.</param>
|
||||
/// <returns>ID of the current basic block.</returns>
|
||||
virtual id leave_block_and_switch(id value, id default_target) = 0;
|
||||
/// <summary>
|
||||
/// Diverges the current control flow and jumps to the specified target block.
|
||||
/// </summary>
|
||||
/// <param name="target">ID of the basic block to jump to.</param>
|
||||
/// <param name="is_continue">Set to <see langword="true"/> if this corresponds to a loop continue statement.</param>
|
||||
/// <returns>ID of the current basic block.</returns>
|
||||
virtual id leave_block_and_branch(id target, unsigned int loop_flow = 0) = 0;
|
||||
/// <summary>
|
||||
/// Diverges the current control flow and jumps to one of the specified target blocks, depending on the condition.
|
||||
/// </summary>
|
||||
/// <param name="condition">SSA ID of a value used to choose which path to take.</param>
|
||||
/// <param name="true_target">ID of the basic block to jump to when the condition is true.</param>
|
||||
/// <param name="false_target">ID of the basic block to jump to when the condition is false.</param>
|
||||
/// <returns>ID of the current basic block.</returns>
|
||||
virtual id leave_block_and_branch_conditional(id condition, id true_target, id false_target) = 0;
|
||||
/// <summary>
|
||||
/// Leaves the current function. Any code added after this call is added in the global scope.
|
||||
/// </summary>
|
||||
virtual void leave_function() = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Calculates sampler and storage bindings to take as little binding space as possible for each entry point.
|
||||
/// </summary>
|
||||
virtual void optimize_bindings();
|
||||
|
||||
/// <summary>
|
||||
/// Looks up an existing struct type.
|
||||
/// </summary>
|
||||
/// <param name="id">SSA ID of the type to find.</param>
|
||||
/// <returns>Reference to the struct description.</returns>
|
||||
const struct_type &get_struct(id id) const
|
||||
{
|
||||
const auto it = std::find_if(_structs.begin(), _structs.end(),
|
||||
[id](const struct_type &info) { return info.id == id; });
|
||||
return *it;
|
||||
}
|
||||
/// <summary>
|
||||
/// Looks up an existing texture object.
|
||||
/// </summary>
|
||||
/// <param name="id">SSA ID of the texture object to find.</param>
|
||||
/// <returns>Reference to the texture description.</returns>
|
||||
texture &get_texture(id id)
|
||||
{
|
||||
const auto it = std::find_if(_module.textures.begin(), _module.textures.end(),
|
||||
[id](const texture &info) { return info.id == id; });
|
||||
return *it;
|
||||
}
|
||||
/// <summary>
|
||||
/// Looks up an existing sampler object.
|
||||
/// </summary>
|
||||
/// <param name="id">SSA ID of the sampler object to find.</param>
|
||||
/// <returns>Reference to the sampler description.</returns>
|
||||
sampler &get_sampler(id id)
|
||||
{
|
||||
const auto it = std::find_if(_module.samplers.begin(), _module.samplers.end(),
|
||||
[id](const sampler &info) { return info.id == id; });
|
||||
return *it;
|
||||
}
|
||||
/// <summary>
|
||||
/// Looks up an existing storage object.
|
||||
/// </summary>
|
||||
/// <param name="id">SSA ID of the storage object to find.</param>
|
||||
/// <returns>Reference to the storage description.</returns>
|
||||
storage &get_storage(id id)
|
||||
{
|
||||
const auto it = std::find_if(_module.storages.begin(), _module.storages.end(),
|
||||
[id](const storage &info) { return info.id == id; });
|
||||
return *it;
|
||||
}
|
||||
/// <summary>
|
||||
/// Looks up an existing function definition.
|
||||
/// </summary>
|
||||
/// <param name="id">SSA ID of the function variable to find.</param>
|
||||
/// <returns>Reference to the function description.</returns>
|
||||
function &get_function(id id)
|
||||
{
|
||||
const auto it = std::find_if(_functions.begin(), _functions.end(),
|
||||
[id](const std::unique_ptr<function> &info) { return info->id == id; });
|
||||
return *it->get();
|
||||
}
|
||||
function *find_function(const std::string &unique_name)
|
||||
{
|
||||
const auto it = std::find_if(_functions.begin(), _functions.end(),
|
||||
[&unique_name](const std::unique_ptr<function> &info) { return info->unique_name == unique_name; });
|
||||
return it != _functions.end() ? it->get() : nullptr;
|
||||
}
|
||||
const function *find_function(const std::string &unique_name) const
|
||||
{
|
||||
return const_cast<codegen *>(this)->find_function(unique_name);
|
||||
}
|
||||
|
||||
id make_id() { return _next_id++; }
|
||||
|
||||
effect_module _module;
|
||||
std::vector<struct_type> _structs;
|
||||
std::vector<std::unique_ptr<function>> _functions;
|
||||
|
||||
id _next_id = 1;
|
||||
id _last_block = 0;
|
||||
id _current_block = 0;
|
||||
function *_current_function = nullptr;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Creates a back-end implementation for GLSL code generation.
|
||||
/// </summary>
|
||||
/// <param name="vulkan_semantics">Generate GLSL for OpenGL or for Vulkan.</param>
|
||||
/// <param name="debug_info">Whether to append debug information like line directives to the generated code.</param>
|
||||
/// <param name="uniforms_to_spec_constants">Whether to convert uniform variables to specialization constants.</param>
|
||||
/// <param name="enable_16bit_types">Use real 16-bit types for the minimum precision types "min16int", "min16uint" and "min16float".</param>
|
||||
/// <param name="flip_vert_y">Insert code to flip the Y component of the output position in vertex shaders.</param>
|
||||
codegen *create_codegen_glsl(bool vulkan_semantics, bool debug_info, bool uniforms_to_spec_constants, bool enable_16bit_types = false, bool flip_vert_y = false);
|
||||
/// <summary>
|
||||
/// Creates a back-end implementation for HLSL code generation.
|
||||
/// </summary>
|
||||
/// <param name="shader_model">The HLSL shader model version (e.g. 30, 41, 50, 60, ...)</param>
|
||||
/// <param name="debug_info">Whether to append debug information like line directives to the generated code.</param>
|
||||
/// <param name="uniforms_to_spec_constants">Whether to convert uniform variables to specialization constants.</param>
|
||||
codegen *create_codegen_hlsl(unsigned int shader_model, bool debug_info, bool uniforms_to_spec_constants);
|
||||
codegen *create_codegen_dxbc(unsigned int shader_model, bool debug_info, bool uniforms_to_spec_constants, int optimization_level);
|
||||
codegen *create_codegen_dxil(unsigned int shader_model, bool debug_info, bool uniforms_to_spec_constants, int optimization_level);
|
||||
/// <summary>
|
||||
/// Creates a back-end implementation for SPIR-V code generation.
|
||||
/// </summary>
|
||||
/// <param name="vulkan_semantics">Generate SPIR-V for OpenGL or for Vulkan.</param>
|
||||
/// <param name="debug_info">Whether to append debug information like line directives to the generated code.</param>
|
||||
/// <param name="uniforms_to_spec_constants">Whether to convert uniform variables to specialization constants.</param>
|
||||
/// <param name="enable_16bit_types">Use real 16-bit types for the minimum precision types "min16int", "min16uint" and "min16float".</param>
|
||||
/// <param name="flip_vert_y">Insert code to flip the Y component of the output position in vertex shaders.</param>
|
||||
codegen *create_codegen_spirv(bool vulkan_semantics, bool debug_info, bool uniforms_to_spec_constants, bool enable_16bit_types = false, bool flip_vert_y = false);
|
||||
}
|
||||
2594
third_party/reshade_fx/source/effect_codegen_spirv.cpp
vendored
Normal file
2594
third_party/reshade_fx/source/effect_codegen_spirv.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
637
third_party/reshade_fx/source/effect_expression.cpp
vendored
Normal file
637
third_party/reshade_fx/source/effect_expression.cpp
vendored
Normal file
@@ -0,0 +1,637 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#include "effect_expression.hpp"
|
||||
#include <cmath> // std::fmod
|
||||
#include <cassert>
|
||||
#include <cstring> // std::memcpy, std::memset
|
||||
#include <algorithm> // std::max, std::min
|
||||
|
||||
reshadefx::type reshadefx::type::merge(const type &lhs, const type &rhs)
|
||||
{
|
||||
type result;
|
||||
result.base = std::max(lhs.base, rhs.base);
|
||||
|
||||
// Non-numeric types cannot be vectors or matrices
|
||||
if (!result.is_numeric())
|
||||
{
|
||||
result.rows = 0;
|
||||
result.cols = 0;
|
||||
}
|
||||
// If one side of the expression is scalar, it needs to be promoted to the same dimension as the other side
|
||||
else if ((lhs.rows == 1 && lhs.cols == 1) || (rhs.rows == 1 && rhs.cols == 1))
|
||||
{
|
||||
result.rows = std::max(lhs.rows, rhs.rows);
|
||||
result.cols = std::max(lhs.cols, rhs.cols);
|
||||
}
|
||||
else // Otherwise dimensions match or one side is truncated to match the other one
|
||||
{
|
||||
result.rows = std::min(lhs.rows, rhs.rows);
|
||||
result.cols = std::min(lhs.cols, rhs.cols);
|
||||
}
|
||||
|
||||
// Some qualifiers propagate to the result
|
||||
result.qualifiers = (lhs.qualifiers & type::q_precise) | (rhs.qualifiers & type::q_precise);
|
||||
|
||||
// Cannot merge array types, assume no arrays
|
||||
result.array_length = 0;
|
||||
assert(lhs.array_length == 0 && rhs.array_length == 0);
|
||||
|
||||
// In case this is a structure, assume they are the same
|
||||
result.struct_definition = rhs.struct_definition;
|
||||
assert(lhs.struct_definition == rhs.struct_definition || lhs.struct_definition == 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string reshadefx::type::description() const
|
||||
{
|
||||
std::string result;
|
||||
switch (base)
|
||||
{
|
||||
case t_void:
|
||||
result = "void";
|
||||
break;
|
||||
case t_bool:
|
||||
result = "bool";
|
||||
break;
|
||||
case t_min16int:
|
||||
result = "min16int";
|
||||
break;
|
||||
case t_int:
|
||||
result = "int";
|
||||
break;
|
||||
case t_min16uint:
|
||||
result = "min16uint";
|
||||
break;
|
||||
case t_uint:
|
||||
result = "uint";
|
||||
break;
|
||||
case t_min16float:
|
||||
result = "min16float";
|
||||
break;
|
||||
case t_float:
|
||||
result = "float";
|
||||
break;
|
||||
case t_string:
|
||||
result = "string";
|
||||
break;
|
||||
case t_struct:
|
||||
result = "struct";
|
||||
break;
|
||||
case t_texture1d:
|
||||
result = "texture1D";
|
||||
break;
|
||||
case t_texture2d:
|
||||
result = "texture2D";
|
||||
break;
|
||||
case t_texture3d:
|
||||
result = "texture3D";
|
||||
break;
|
||||
case t_sampler1d_int:
|
||||
result = "sampler1D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler2d_int:
|
||||
result = "sampler2D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler3d_int:
|
||||
result = "sampler3D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler1d_uint:
|
||||
result = "sampler1D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler2d_uint:
|
||||
result = "sampler2D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler3d_uint:
|
||||
result = "sampler3D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler1d_float:
|
||||
result = "sampler1D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler2d_float:
|
||||
result = "sampler2D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_sampler3d_float:
|
||||
result = "sampler3D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage1d_int:
|
||||
result = "storage1D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage2d_int:
|
||||
result = "storage2D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage3d_int:
|
||||
result = "storage3D<int" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage1d_uint:
|
||||
result = "storage1D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage2d_uint:
|
||||
result = "storage2D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage3d_uint:
|
||||
result = "storage3D<uint" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage1d_float:
|
||||
result = "storage1D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage2d_float:
|
||||
result = "storage2D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_storage3d_float:
|
||||
result = "storage3D<float" + std::to_string(rows) + '>';
|
||||
break;
|
||||
case t_function:
|
||||
assert(false);
|
||||
break;
|
||||
}
|
||||
|
||||
if (is_numeric())
|
||||
{
|
||||
if (rows > 1 || cols > 1)
|
||||
result += std::to_string(rows);
|
||||
if (cols > 1)
|
||||
result += 'x' + std::to_string(cols);
|
||||
}
|
||||
|
||||
if (is_array())
|
||||
{
|
||||
result += '[';
|
||||
if (is_bounded_array())
|
||||
result += std::to_string(array_length);
|
||||
result += ']';
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void reshadefx::expression::reset_to_lvalue(const reshadefx::location &loc, uint32_t in_base, const reshadefx::type &in_type)
|
||||
{
|
||||
type = in_type;
|
||||
base = in_base;
|
||||
location = loc;
|
||||
is_lvalue = true;
|
||||
is_constant = false;
|
||||
chain.clear();
|
||||
|
||||
// Make sure uniform l-values cannot be assigned to by making them constant
|
||||
if (in_type.has(type::q_uniform))
|
||||
type.qualifiers |= type::q_const;
|
||||
|
||||
// Strip away global variable qualifiers
|
||||
type.qualifiers &= ~(type::q_extern | type::q_static | type::q_uniform | type::q_groupshared);
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue(const reshadefx::location &loc, uint32_t in_base, const reshadefx::type &in_type)
|
||||
{
|
||||
type = in_type;
|
||||
type.qualifiers |= type::q_const;
|
||||
base = in_base;
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = false;
|
||||
chain.clear();
|
||||
|
||||
// Strip away global variable qualifiers
|
||||
type.qualifiers &= ~(type::q_extern | type::q_static | type::q_uniform | type::q_groupshared);
|
||||
}
|
||||
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, bool data)
|
||||
{
|
||||
type = { type::t_bool, 1, 1, type::q_const };
|
||||
base = 0; constant = {}; constant.as_uint[0] = data;
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, float data)
|
||||
{
|
||||
type = { type::t_float, 1, 1, type::q_const };
|
||||
base = 0; constant = {}; constant.as_float[0] = data;
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, int32_t data)
|
||||
{
|
||||
type = { type::t_int, 1, 1, type::q_const };
|
||||
base = 0; constant = {}; constant.as_int[0] = data;
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, uint32_t data)
|
||||
{
|
||||
type = { type::t_uint, 1, 1, type::q_const };
|
||||
base = 0; constant = {}; constant.as_uint[0] = data;
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, std::string data)
|
||||
{
|
||||
type = { type::t_string, 0, 0, type::q_const };
|
||||
base = 0; constant = {}; constant.string_data = std::move(data);
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
void reshadefx::expression::reset_to_rvalue_constant(const reshadefx::location &loc, reshadefx::constant data, const reshadefx::type &in_type)
|
||||
{
|
||||
type = in_type;
|
||||
type.qualifiers |= type::q_const;
|
||||
base = 0; constant = std::move(data);
|
||||
location = loc;
|
||||
is_lvalue = false;
|
||||
is_constant = true;
|
||||
chain.clear();
|
||||
}
|
||||
|
||||
void reshadefx::expression::add_cast_operation(const reshadefx::type &cast_type)
|
||||
{
|
||||
// First try to simplify the cast with a swizzle operation (only works with scalars and vectors)
|
||||
if (type.cols == 1 && cast_type.cols == 1 && type.rows != cast_type.rows)
|
||||
{
|
||||
signed char swizzle[] = { 0, 1, 2, 3 };
|
||||
// Ignore components in a demotion cast
|
||||
for (unsigned int i = cast_type.rows; i < 4; ++i)
|
||||
swizzle[i] = -1;
|
||||
// Use the last component to fill in a promotion cast
|
||||
for (unsigned int i = type.rows; i < cast_type.rows; ++i)
|
||||
swizzle[i] = swizzle[type.rows - 1];
|
||||
|
||||
add_swizzle_access(swizzle, cast_type.rows);
|
||||
}
|
||||
|
||||
if (type == cast_type)
|
||||
return; // There is nothing more to do if the expression is already of the target type at this point
|
||||
|
||||
if (is_constant)
|
||||
{
|
||||
const auto cast_constant = [](reshadefx::constant &constant, const reshadefx::type &from, const reshadefx::type &to) {
|
||||
// Handle scalar to vector promotion first
|
||||
if (from.is_scalar() && !to.is_scalar())
|
||||
for (unsigned int i = 1; i < to.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[0];
|
||||
|
||||
// Next check whether the type needs casting as well (and don't convert between signed/unsigned, since that is handled by the union)
|
||||
if (from.base == to.base || from.is_floating_point() == to.is_floating_point())
|
||||
return;
|
||||
|
||||
if (!to.is_floating_point())
|
||||
for (unsigned int i = 0; i < to.components(); ++i)
|
||||
constant.as_uint[i] = static_cast<int>(constant.as_float[i]);
|
||||
else
|
||||
for (unsigned int i = 0; i < to.components(); ++i)
|
||||
constant.as_float[i] = static_cast<float>(constant.as_int[i]);
|
||||
};
|
||||
|
||||
for (struct constant &element : constant.array_data)
|
||||
cast_constant(element, type, cast_type);
|
||||
|
||||
cast_constant(constant, type, cast_type);
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(!type.is_array() && !cast_type.is_array());
|
||||
|
||||
chain.push_back({ operation::op_cast, type, cast_type });
|
||||
}
|
||||
|
||||
type = cast_type;
|
||||
type.qualifiers |= type::q_const; // Casting always makes expression not modifiable
|
||||
}
|
||||
void reshadefx::expression::add_member_access(unsigned int index, const reshadefx::type &in_type)
|
||||
{
|
||||
assert(type.is_struct());
|
||||
|
||||
chain.push_back({ operation::op_member, type, in_type, index });
|
||||
|
||||
// The type is now the type of the member that was accessed
|
||||
type = in_type;
|
||||
is_constant = false;
|
||||
}
|
||||
void reshadefx::expression::add_dynamic_index_access(uint32_t index_expression)
|
||||
{
|
||||
assert(!is_constant); // Cannot have dynamic indexing into constant in SPIR-V
|
||||
assert(type.is_array() || (type.is_numeric() && !type.is_scalar()));
|
||||
|
||||
struct type prev_type = type;
|
||||
|
||||
if (type.is_array())
|
||||
{
|
||||
type.array_length = 0;
|
||||
}
|
||||
else if (type.is_matrix())
|
||||
{
|
||||
type.rows = type.cols;
|
||||
type.cols = 1;
|
||||
}
|
||||
else if (type.is_vector())
|
||||
{
|
||||
type.rows = 1;
|
||||
}
|
||||
|
||||
chain.push_back({ operation::op_dynamic_index, prev_type, type, index_expression });
|
||||
}
|
||||
void reshadefx::expression::add_constant_index_access(unsigned int index)
|
||||
{
|
||||
assert(type.is_array() || (type.is_numeric() && !type.is_scalar()));
|
||||
|
||||
struct type prev_type = type;
|
||||
|
||||
if (type.is_array())
|
||||
{
|
||||
assert(index < type.array_length);
|
||||
|
||||
type.array_length = 0;
|
||||
}
|
||||
else if (type.is_matrix())
|
||||
{
|
||||
assert(index < type.components());
|
||||
|
||||
type.rows = type.cols;
|
||||
type.cols = 1;
|
||||
}
|
||||
else if (type.is_vector())
|
||||
{
|
||||
assert(index < type.components());
|
||||
|
||||
type.rows = 1;
|
||||
}
|
||||
|
||||
if (is_constant)
|
||||
{
|
||||
if (prev_type.is_array())
|
||||
{
|
||||
constant = constant.array_data[index];
|
||||
}
|
||||
else if (prev_type.is_matrix()) // Indexing into a matrix returns a row of it as a vector
|
||||
{
|
||||
for (unsigned int i = 0; i < prev_type.cols; ++i)
|
||||
constant.as_uint[i] = constant.as_uint[index * prev_type.cols + i];
|
||||
}
|
||||
else // Indexing into a vector returns the element as a scalar
|
||||
{
|
||||
constant.as_uint[0] = constant.as_uint[index];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
chain.push_back({ operation::op_constant_index, prev_type, type, index });
|
||||
}
|
||||
}
|
||||
void reshadefx::expression::add_swizzle_access(const signed char swizzle[4], unsigned int length)
|
||||
{
|
||||
assert(type.is_numeric() && !type.is_array());
|
||||
assert(length <= 4);
|
||||
|
||||
const struct type prev_type = type;
|
||||
|
||||
type.rows = length;
|
||||
type.cols = 1;
|
||||
|
||||
// To form a l-value, swizzling must contain no duplicate components
|
||||
for (unsigned int i = 0; i < length; ++i)
|
||||
for (unsigned int k = i + 1; k < length; ++k)
|
||||
if (swizzle[k] == swizzle[i])
|
||||
type.qualifiers |= type::q_const;
|
||||
|
||||
if (is_constant)
|
||||
{
|
||||
assert(constant.array_data.empty());
|
||||
|
||||
uint32_t data[16];
|
||||
std::memcpy(data, &constant.as_uint[0], sizeof(data));
|
||||
for (unsigned int i = 0; i < length; ++i)
|
||||
constant.as_uint[i] = data[swizzle[i]];
|
||||
std::memset(&constant.as_uint[length], 0, sizeof(uint32_t) * (16 - length)); // Clear the rest of the constant
|
||||
}
|
||||
else if (length == 1 && prev_type.is_vector()) // Use indexing when possible since the code generation logic is simpler in SPIR-V
|
||||
{
|
||||
chain.push_back({ operation::op_constant_index, prev_type, type, static_cast<uint32_t>(swizzle[0]) });
|
||||
}
|
||||
else if (prev_type.is_matrix())
|
||||
{
|
||||
chain.push_back({ operation::op_matrix_swizzle, prev_type, type, 0, { swizzle[0], swizzle[1], swizzle[2], swizzle[3] } });
|
||||
}
|
||||
else
|
||||
{
|
||||
chain.push_back({ operation::op_swizzle, prev_type, type, 0, { swizzle[0], swizzle[1], swizzle[2], swizzle[3] } });
|
||||
}
|
||||
}
|
||||
|
||||
bool reshadefx::expression::evaluate_constant_expression(reshadefx::tokenid op)
|
||||
{
|
||||
if (!is_constant)
|
||||
return false;
|
||||
|
||||
switch (op)
|
||||
{
|
||||
case tokenid::exclaim:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = !constant.as_uint[i];
|
||||
break;
|
||||
case tokenid::minus:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_float[i] = -constant.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_int[i] = -constant.as_int[i];
|
||||
break;
|
||||
case tokenid::tilde:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = ~constant.as_uint[i];
|
||||
break;
|
||||
default:
|
||||
// Unknown operator token, so nothing to do
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
bool reshadefx::expression::evaluate_constant_expression(reshadefx::tokenid op, const reshadefx::constant &rhs)
|
||||
{
|
||||
if (!is_constant)
|
||||
return false;
|
||||
|
||||
switch (op)
|
||||
{
|
||||
case tokenid::percent:
|
||||
if (type.is_floating_point()) {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
// Floating point modulo with zero is defined and results in NaN
|
||||
if (rhs.as_float[i] == 0)
|
||||
constant.as_float[i] = std::numeric_limits<float>::quiet_NaN();
|
||||
else
|
||||
constant.as_float[i] = std::fmod(constant.as_float[i], rhs.as_float[i]);
|
||||
}
|
||||
else if (type.is_signed()) {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
// Integer modulo with zero on the other hand is not defined, so do not fold this expression in that case
|
||||
if (rhs.as_int[i] == 0)
|
||||
return false;
|
||||
else
|
||||
constant.as_int[i] %= rhs.as_int[i];
|
||||
}
|
||||
else {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
if (rhs.as_uint[i] == 0)
|
||||
return false;
|
||||
else
|
||||
constant.as_uint[i] %= rhs.as_uint[i];
|
||||
}
|
||||
break;
|
||||
case tokenid::star:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_float[i] *= rhs.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] *= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::plus:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_float[i] += rhs.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] += rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::minus:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_float[i] -= rhs.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] -= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::slash:
|
||||
if (type.is_floating_point()) {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
// Floating point division by zero is well defined and results in infinity or NaN
|
||||
constant.as_float[i] /= rhs.as_float[i];
|
||||
}
|
||||
else if (type.is_signed()) {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
// Integer division by zero on the other hand is not defined, so do not fold this expression in that case
|
||||
if (rhs.as_int[i] == 0)
|
||||
return false;
|
||||
else
|
||||
constant.as_int[i] /= rhs.as_int[i];
|
||||
}
|
||||
else {
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
if (rhs.as_uint[i] == 0)
|
||||
return false;
|
||||
else
|
||||
constant.as_uint[i] /= rhs.as_uint[i];
|
||||
}
|
||||
break;
|
||||
case tokenid::ampersand:
|
||||
case tokenid::ampersand_ampersand:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] &= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::pipe:
|
||||
case tokenid::pipe_pipe:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] |= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::caret:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] ^= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::less:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] < rhs.as_float[i];
|
||||
else if (type.is_signed())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_int[i] < rhs.as_int[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] < rhs.as_uint[i];
|
||||
type.base = type::t_bool; // Logic operations change the type to boolean
|
||||
break;
|
||||
case tokenid::less_equal:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] <= rhs.as_float[i];
|
||||
else if (type.is_signed())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_int[i] <= rhs.as_int[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] <= rhs.as_uint[i];
|
||||
type.base = type::t_bool;
|
||||
break;
|
||||
case tokenid::greater:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] > rhs.as_float[i];
|
||||
else if (type.is_signed())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_int[i] > rhs.as_int[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] > rhs.as_uint[i];
|
||||
type.base = type::t_bool;
|
||||
break;
|
||||
case tokenid::greater_equal:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] >= rhs.as_float[i];
|
||||
else if (type.is_signed())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_int[i] >= rhs.as_int[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] >= rhs.as_uint[i];
|
||||
type.base = type::t_bool;
|
||||
break;
|
||||
case tokenid::equal_equal:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] == rhs.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] == rhs.as_uint[i];
|
||||
type.base = type::t_bool;
|
||||
break;
|
||||
case tokenid::exclaim_equal:
|
||||
if (type.is_floating_point())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_float[i] != rhs.as_float[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] = constant.as_uint[i] != rhs.as_uint[i];
|
||||
type.base = type::t_bool;
|
||||
break;
|
||||
case tokenid::less_less:
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] <<= rhs.as_uint[i];
|
||||
break;
|
||||
case tokenid::greater_greater:
|
||||
if (type.is_signed())
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_int[i] >>= rhs.as_int[i];
|
||||
else
|
||||
for (unsigned int i = 0; i < type.components(); ++i)
|
||||
constant.as_uint[i] >>= rhs.as_uint[i];
|
||||
break;
|
||||
default:
|
||||
// Unknown operator token, so nothing to do
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
252
third_party/reshade_fx/source/effect_expression.hpp
vendored
Normal file
252
third_party/reshade_fx/source/effect_expression.hpp
vendored
Normal file
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_token.hpp"
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// Structure which encapsulates a parsed value type
|
||||
/// </summary>
|
||||
struct type
|
||||
{
|
||||
enum datatype : uint32_t
|
||||
{
|
||||
t_void,
|
||||
t_bool,
|
||||
t_min16int,
|
||||
t_int,
|
||||
t_min16uint,
|
||||
t_uint,
|
||||
t_min16float,
|
||||
t_float,
|
||||
t_string,
|
||||
t_struct,
|
||||
t_texture1d,
|
||||
t_texture2d,
|
||||
t_texture3d,
|
||||
t_sampler1d_int,
|
||||
t_sampler2d_int,
|
||||
t_sampler3d_int,
|
||||
t_sampler1d_uint,
|
||||
t_sampler2d_uint,
|
||||
t_sampler3d_uint,
|
||||
t_sampler1d_float,
|
||||
t_sampler2d_float,
|
||||
t_sampler3d_float,
|
||||
t_storage1d_int,
|
||||
t_storage2d_int,
|
||||
t_storage3d_int,
|
||||
t_storage1d_uint,
|
||||
t_storage2d_uint,
|
||||
t_storage3d_uint,
|
||||
t_storage1d_float,
|
||||
t_storage2d_float,
|
||||
t_storage3d_float,
|
||||
t_function,
|
||||
};
|
||||
enum qualifier : uint32_t
|
||||
{
|
||||
q_extern = 1 << 0,
|
||||
q_static = 1 << 1,
|
||||
q_uniform = 1 << 2,
|
||||
q_volatile = 1 << 3,
|
||||
q_precise = 1 << 4,
|
||||
q_groupshared = 1 << 14,
|
||||
q_in = 1 << 5,
|
||||
q_out = 1 << 6,
|
||||
q_inout = q_in | q_out,
|
||||
q_const = 1 << 8,
|
||||
q_linear = 1 << 10,
|
||||
q_noperspective = 1 << 11,
|
||||
q_centroid = 1 << 12,
|
||||
q_nointerpolation = 1 << 13,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets the result type of an operation involving the two input types.
|
||||
/// </summary>
|
||||
static type merge(const type &lhs, const type &rhs);
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the ranking between two types which can be used to select the best matching function overload. The higher the rank, the better the match. A value of zero indicates that the types are not compatible.
|
||||
/// </summary>
|
||||
static unsigned int rank(const type &src, const type &dst);
|
||||
|
||||
/// <summary>
|
||||
/// Returns a human-readable description of this type definition.
|
||||
/// </summary>
|
||||
std::string description() const;
|
||||
|
||||
bool has(qualifier x) const { return (qualifiers & x) == x; }
|
||||
|
||||
bool is_void() const { return base == t_void; }
|
||||
bool is_boolean() const { return base == t_bool; }
|
||||
bool is_numeric() const { return base >= t_bool && base <= t_float; }
|
||||
bool is_integral() const { return (base >= t_bool && base <= t_uint) || (base >= t_sampler1d_int && base <= t_sampler3d_uint) || (base >= t_storage1d_int && base <= t_storage3d_uint); }
|
||||
bool is_floating_point() const { return base == t_min16float || base == t_float || (base >= t_sampler1d_float && base <= t_sampler3d_float) || (base >= t_storage1d_float && base <= t_storage3d_float); }
|
||||
bool is_signed() const { return base == t_min16int || base == t_int || (base >= t_sampler1d_int && base <= t_sampler3d_int) || (base >= t_storage1d_int && base <= t_storage3d_int) || is_floating_point(); }
|
||||
bool is_unsigned() const { return base == t_min16uint || base == t_uint || (base >= t_sampler1d_uint && base <= t_sampler3d_uint) || (base >= t_storage1d_uint && base <= t_storage3d_uint); }
|
||||
|
||||
bool is_struct() const { return base == t_struct; }
|
||||
bool is_object() const { return is_texture() || is_sampler() || is_storage(); }
|
||||
bool is_texture() const { return base >= t_texture1d && base <= t_texture3d; }
|
||||
bool is_sampler() const { return base >= t_sampler1d_int && base <= t_sampler3d_float; }
|
||||
bool is_storage() const { return base >= t_storage1d_int && base <= t_storage3d_float; }
|
||||
bool is_function() const { return base == t_function; }
|
||||
|
||||
bool is_array() const { return array_length != 0; }
|
||||
bool is_bounded_array() const { return is_array() && array_length != 0xFFFFFFFF; }
|
||||
bool is_unbounded_array() const { return array_length == 0xFFFFFFFF; }
|
||||
bool is_scalar() const { return is_numeric() && !is_matrix() && !is_vector() && !is_array(); }
|
||||
bool is_vector() const { return is_numeric() && rows > 1 && cols == 1; }
|
||||
bool is_matrix() const { return is_numeric() && rows >= 1 && cols > 1; }
|
||||
|
||||
unsigned int precision() const { return base == t_min16int || base == t_min16uint || base == t_min16float ? 16 : 32; }
|
||||
unsigned int components() const { return rows * cols; }
|
||||
unsigned int texture_dimension() const { return base >= t_texture1d && base <= t_storage3d_float ? ((base - t_texture1d) % 3) + 1 : 0; }
|
||||
|
||||
friend bool operator==(const type &lhs, const type &rhs)
|
||||
{
|
||||
return lhs.base == rhs.base && lhs.rows == rhs.rows && lhs.cols == rhs.cols && lhs.array_length == rhs.array_length && lhs.struct_definition == rhs.struct_definition;
|
||||
}
|
||||
friend bool operator!=(const type &lhs, const type &rhs)
|
||||
{
|
||||
return !operator==(lhs, rhs);
|
||||
}
|
||||
|
||||
// Underlying base type ('int', 'float', ...)
|
||||
datatype base : 8;
|
||||
// Number of rows if this is a vector type
|
||||
uint32_t rows : 4;
|
||||
// Number of columns if this is a matrix type
|
||||
uint32_t cols : 4;
|
||||
// Bit mask of all the qualifiers decorating the type
|
||||
uint32_t qualifiers : 16;
|
||||
// Number of elements if this is an array type, 0xFFFFFFFF if it is an unsized array
|
||||
uint32_t array_length;
|
||||
// ID of the matching struct if this is a struct type
|
||||
uint32_t struct_definition;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Structure which encapsulates a parsed constant value
|
||||
/// </summary>
|
||||
struct constant
|
||||
{
|
||||
union
|
||||
{
|
||||
float as_float[16];
|
||||
int32_t as_int[16];
|
||||
uint32_t as_uint[16];
|
||||
};
|
||||
|
||||
// Optional string associated with this constant
|
||||
std::string string_data;
|
||||
// Optional additional elements if this is an array constant
|
||||
std::vector<constant> array_data;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Structures which keeps track of the access chain of an expression
|
||||
/// </summary>
|
||||
struct expression
|
||||
{
|
||||
struct operation
|
||||
{
|
||||
enum op_type
|
||||
{
|
||||
op_cast,
|
||||
op_member,
|
||||
op_dynamic_index,
|
||||
op_constant_index,
|
||||
op_swizzle,
|
||||
op_matrix_swizzle,
|
||||
};
|
||||
|
||||
op_type op;
|
||||
reshadefx::type from, to;
|
||||
uint32_t index;
|
||||
signed char swizzle[4];
|
||||
};
|
||||
|
||||
uint32_t base = 0;
|
||||
reshadefx::type type = {};
|
||||
reshadefx::constant constant = {};
|
||||
bool is_lvalue = false;
|
||||
bool is_constant = false;
|
||||
reshadefx::location location;
|
||||
std::vector<operation> chain;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the expression to a l-value.
|
||||
/// </summary>
|
||||
/// <param name="loc">Code location of the expression.</param>
|
||||
/// <param name="base">SSA ID of the l-value.</param>
|
||||
/// <param name="type">Value type of the expression result.</param>
|
||||
void reset_to_lvalue(const reshadefx::location &loc, uint32_t base, const reshadefx::type &type);
|
||||
/// <summary>
|
||||
/// Initializes the expression to a r-value.
|
||||
/// </summary>
|
||||
/// <param name="loc">Code location of the expression.</param>
|
||||
/// <param name="base">SSA ID of the r-value.</param>
|
||||
/// <param name="type">Value type of the expression result.</param>
|
||||
void reset_to_rvalue(const reshadefx::location &loc, uint32_t base, const reshadefx::type &type);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the expression to a constant value.
|
||||
/// </summary>
|
||||
/// <param name="loc">Code location of the constant expression.</param>
|
||||
/// <param name="data">Constant value to initialize to.</param>
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, bool data);
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, float data);
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, int32_t data);
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, uint32_t data);
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, std::string data);
|
||||
void reset_to_rvalue_constant(const reshadefx::location &loc, reshadefx::constant data, const reshadefx::type &type);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a cast operation to the current access chain.
|
||||
/// </summary>
|
||||
/// <param name="type">Type to cast the expression to.</param>
|
||||
void add_cast_operation(const reshadefx::type &type);
|
||||
/// <summary>
|
||||
/// Adds a structure member lookup to the current access chain.
|
||||
/// </summary>
|
||||
/// <param name="index">Index of the member to dereference.</param>
|
||||
/// <param name="type">Value type of the member.</param>
|
||||
void add_member_access(unsigned int index, const reshadefx::type &type);
|
||||
/// <summary>
|
||||
/// Adds an index operation to the current access chain.
|
||||
/// </summary>
|
||||
/// <param name="index_expression">SSA ID of the indexing value.</param>
|
||||
void add_dynamic_index_access(uint32_t index_expression);
|
||||
/// <summary>
|
||||
/// Adds an constant index operation to the current access chain.
|
||||
/// </summary>
|
||||
/// <param name="index">Constant indexing value.</param>
|
||||
void add_constant_index_access(unsigned int index);
|
||||
/// <summary>
|
||||
/// Adds a swizzle operation to the current access chain.
|
||||
/// </summary>
|
||||
/// <param name="swizzle">Swizzle for each component. -1 = unused, 0 = x, 1 = y, 2 = z, 3 = w.</param>
|
||||
/// <param name="length">Number of components in the swizzle. The maximum is 4.</param>
|
||||
void add_swizzle_access(const signed char swizzle[4], unsigned int length);
|
||||
|
||||
/// <summary>
|
||||
/// Applies an unary operation to this constant expression.
|
||||
/// </summary>
|
||||
/// <param name="op">Unary operator to apply.</param>
|
||||
bool evaluate_constant_expression(reshadefx::tokenid op);
|
||||
/// <summary>
|
||||
/// Applies a binary operation to this constant expression.
|
||||
/// </summary>
|
||||
/// <param name="op">Binary operator to apply.</param>
|
||||
/// <param name="rhs">Constant value to use as right-hand side of the binary operation.</param>
|
||||
bool evaluate_constant_expression(reshadefx::tokenid op, const reshadefx::constant &rhs);
|
||||
};
|
||||
}
|
||||
1220
third_party/reshade_fx/source/effect_lexer.cpp
vendored
Normal file
1220
third_party/reshade_fx/source/effect_lexer.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
112
third_party/reshade_fx/source/effect_lexer.hpp
vendored
Normal file
112
third_party/reshade_fx/source/effect_lexer.hpp
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_token.hpp"
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// A lexical analyzer for C-like languages.
|
||||
/// </summary>
|
||||
class lexer
|
||||
{
|
||||
public:
|
||||
explicit lexer(
|
||||
std::string input,
|
||||
bool ignore_comments = true,
|
||||
bool ignore_whitespace = true,
|
||||
bool ignore_pp_directives = true,
|
||||
bool ignore_line_directives = false,
|
||||
bool ignore_keywords = false,
|
||||
bool escape_string_literals = true,
|
||||
const location &start_location = location()) :
|
||||
_input(std::move(input)),
|
||||
_cur_location(start_location),
|
||||
_ignore_comments(ignore_comments),
|
||||
_ignore_whitespace(ignore_whitespace),
|
||||
_ignore_pp_directives(ignore_pp_directives),
|
||||
_ignore_line_directives(ignore_line_directives),
|
||||
_ignore_keywords(ignore_keywords),
|
||||
_escape_string_literals(escape_string_literals)
|
||||
{
|
||||
_cur = _input.data();
|
||||
_end = _cur + _input.size();
|
||||
}
|
||||
|
||||
lexer(const lexer &lexer) { operator=(lexer); }
|
||||
lexer &operator=(const lexer &lexer)
|
||||
{
|
||||
_input = lexer._input;
|
||||
_cur_location = lexer._cur_location;
|
||||
reset_to_offset(lexer._cur - lexer._input.data());
|
||||
_end = _input.data() + _input.size();
|
||||
_ignore_comments = lexer._ignore_comments;
|
||||
_ignore_whitespace = lexer._ignore_whitespace;
|
||||
_ignore_pp_directives = lexer._ignore_pp_directives;
|
||||
_ignore_keywords = lexer._ignore_keywords;
|
||||
_escape_string_literals = lexer._escape_string_literals;
|
||||
_ignore_line_directives = lexer._ignore_line_directives;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current position in the input string.
|
||||
/// </summary>
|
||||
size_t input_offset() const { return _cur - _input.data(); }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the input string this lexical analyzer works on.
|
||||
/// </summary>
|
||||
/// <returns>Constant reference to the input string.</returns>
|
||||
const std::string &input_string() const { return _input; }
|
||||
|
||||
/// <summary>
|
||||
/// Performs lexical analysis on the input string and return the next token in sequence.
|
||||
/// </summary>
|
||||
/// <returns>Next token from the input string.</returns>
|
||||
token lex();
|
||||
|
||||
/// <summary>
|
||||
/// Advances to the next token that is not whitespace.
|
||||
/// </summary>
|
||||
void skip_space();
|
||||
/// <summary>
|
||||
/// Advances to the next new line, ignoring all tokens.
|
||||
/// </summary>
|
||||
void skip_to_next_line();
|
||||
|
||||
/// <summary>
|
||||
/// Resets position to the specified <paramref name="offset"/>.
|
||||
/// </summary>
|
||||
/// <param name="offset">Offset in characters from the start of the input string.</param>
|
||||
void reset_to_offset(size_t offset);
|
||||
|
||||
private:
|
||||
/// <summary>
|
||||
/// Skips an arbitrary amount of characters in the input string.
|
||||
/// </summary>
|
||||
/// <param name="length">Number of input characters to skip.</param>
|
||||
void skip(size_t length);
|
||||
|
||||
void parse_identifier(token &tok) const;
|
||||
bool parse_pp_directive(token &tok);
|
||||
void parse_string_literal(token &tok, bool escape);
|
||||
void parse_numeric_literal(token &tok) const;
|
||||
|
||||
std::string _input;
|
||||
location _cur_location;
|
||||
const std::string::value_type *_cur, *_end;
|
||||
|
||||
bool _ignore_comments;
|
||||
bool _ignore_whitespace;
|
||||
bool _ignore_pp_directives;
|
||||
bool _ignore_line_directives;
|
||||
bool _ignore_keywords;
|
||||
bool _escape_string_literals;
|
||||
};
|
||||
}
|
||||
421
third_party/reshade_fx/source/effect_module.hpp
vendored
Normal file
421
third_party/reshade_fx/source/effect_module.hpp
vendored
Normal file
@@ -0,0 +1,421 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_expression.hpp"
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// Describes an annotation attached to a variable.
|
||||
/// </summary>
|
||||
struct annotation
|
||||
{
|
||||
reshadefx::type type = {};
|
||||
std::string name;
|
||||
reshadefx::constant value = {};
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a struct member or parameter.
|
||||
/// </summary>
|
||||
struct member_type
|
||||
{
|
||||
reshadefx::type type = {};
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string semantic;
|
||||
reshadefx::location location;
|
||||
bool has_default_value = false;
|
||||
reshadefx::constant default_value = {};
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a struct type defined in effect code.
|
||||
/// </summary>
|
||||
struct struct_type
|
||||
{
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
std::vector<member_type> member_list;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Available texture types.
|
||||
/// </summary>
|
||||
enum class texture_type : uint8_t
|
||||
{
|
||||
texture_1d = 1,
|
||||
texture_2d = 2,
|
||||
texture_3d = 3
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Available texture formats.
|
||||
/// </summary>
|
||||
enum class texture_format : uint8_t
|
||||
{
|
||||
unknown = 0,
|
||||
|
||||
r8 = 61,
|
||||
r16f = 54,
|
||||
r16 = 56,
|
||||
r32f = 41,
|
||||
r32u = 42,
|
||||
r32i = 43,
|
||||
|
||||
rg8 = 49,
|
||||
rg16f = 34,
|
||||
rg16 = 35,
|
||||
rg32f = 16,
|
||||
|
||||
rgba8 = 28,
|
||||
rgba16f = 10,
|
||||
rgba16 = 11,
|
||||
rgba32f = 2,
|
||||
rgba32u = 3,
|
||||
rgba32i = 4,
|
||||
|
||||
rgb10a2 = 24,
|
||||
rg11b10f = 26
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the properties of a <see cref="texture"/> object.
|
||||
/// </summary>
|
||||
struct texture_desc
|
||||
{
|
||||
uint32_t width = 1;
|
||||
uint32_t height = 1;
|
||||
uint16_t depth = 1;
|
||||
uint16_t levels = 1;
|
||||
texture_type type = texture_type::texture_2d;
|
||||
texture_format format = texture_format::unknown;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a texture object defined in effect code.
|
||||
/// </summary>
|
||||
struct texture : texture_desc
|
||||
{
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
std::string semantic;
|
||||
std::vector<annotation> annotations;
|
||||
bool render_target = false;
|
||||
bool storage_access = false;
|
||||
uint32_t semantic_binding = 0xFFFFFFFF;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the binding of the texture view portion of a <see cref="sampler"/> object.
|
||||
/// </summary>
|
||||
struct texture_binding
|
||||
{
|
||||
/// <summary>
|
||||
/// Index of the corresponding sampler object in <see cref="effect_module::samplers"/>.
|
||||
/// </summary>
|
||||
size_t index = 0;
|
||||
/// <summary>
|
||||
/// HLSL tX register index or GLSL/SPIR-V binding index.
|
||||
/// This is only relevant when using the generated code specialized for each entry point, otherwise binding is the same as the <see cref="index"/>.
|
||||
/// </summary>
|
||||
uint32_t entry_point_binding = 0;
|
||||
bool srgb = false;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Texture filtering modes available for texture sampling operations.
|
||||
/// </summary>
|
||||
enum class filter_mode : uint8_t
|
||||
{
|
||||
min_mag_mip_point = 0,
|
||||
min_mag_point_mip_linear = 0x1,
|
||||
min_point_mag_linear_mip_point = 0x4,
|
||||
min_point_mag_mip_linear = 0x5,
|
||||
min_linear_mag_mip_point = 0x10,
|
||||
min_linear_mag_point_mip_linear = 0x11,
|
||||
min_mag_linear_mip_point = 0x14,
|
||||
min_mag_mip_linear = 0x15,
|
||||
anisotropic = 0x55
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Sampling behavior at texture coordinates outside the bounds of a texture resource.
|
||||
/// </summary>
|
||||
enum class texture_address_mode : uint8_t
|
||||
{
|
||||
wrap = 1,
|
||||
mirror = 2,
|
||||
clamp = 3,
|
||||
border = 4
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the properties of a <see cref="sampler"/> object.
|
||||
/// </summary>
|
||||
struct sampler_desc
|
||||
{
|
||||
filter_mode filter = filter_mode::min_mag_mip_linear;
|
||||
texture_address_mode address_u = texture_address_mode::clamp;
|
||||
texture_address_mode address_v = texture_address_mode::clamp;
|
||||
texture_address_mode address_w = texture_address_mode::clamp;
|
||||
float min_lod = -3.402823466e+38f;
|
||||
float max_lod = +3.402823466e+38f; // FLT_MAX
|
||||
float lod_bias = 0.0f;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a texture sampler object defined in effect code.
|
||||
/// </summary>
|
||||
struct sampler : sampler_desc
|
||||
{
|
||||
reshadefx::type type = {};
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
std::string texture_name;
|
||||
std::vector<annotation> annotations;
|
||||
bool srgb = false;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the binding of the sampler state portion of a <see cref="sampler"/> object.
|
||||
/// </summary>
|
||||
struct sampler_binding
|
||||
{
|
||||
/// <summary>
|
||||
/// Index of the corresponding sampler object in <see cref="effect_module::samplers"/>.
|
||||
/// </summary>
|
||||
size_t index = 0;
|
||||
/// <summary>
|
||||
/// HLSL sX register index or GLSL/SPIR-V binding.
|
||||
/// This is only relevant when using the generated code specialized for each entry point, otherwise binding is the same as the <see cref="index"/>.
|
||||
/// </summary>
|
||||
uint32_t entry_point_binding = 0;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the properties of a <see cref="storage"/> object.
|
||||
/// </summary>
|
||||
struct storage_desc
|
||||
{
|
||||
uint16_t level = 0;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a texture storage object defined in effect code.
|
||||
/// </summary>
|
||||
struct storage : storage_desc
|
||||
{
|
||||
reshadefx::type type = {};
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
std::string texture_name;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the binding of a <see cref="storage"/> object.
|
||||
/// </summary>
|
||||
struct storage_binding
|
||||
{
|
||||
/// <summary>
|
||||
/// Index of the corresponding storage object in <see cref="effect_module::storages"/>.
|
||||
/// </summary>
|
||||
size_t index = 0;
|
||||
/// <summary>
|
||||
/// HLSL uX register index or GLSL/SPIR-V binding.
|
||||
/// This is only relevant when using the generated code specialized for each entry point, otherwise binding is the same as the <see cref="index"/>.
|
||||
/// </summary>
|
||||
uint32_t entry_point_binding = 0;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a uniform variable defined in effect code.
|
||||
/// </summary>
|
||||
struct uniform
|
||||
{
|
||||
reshadefx::type type = {};
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
uint32_t size = 0;
|
||||
uint32_t offset = 0;
|
||||
std::vector<annotation> annotations;
|
||||
bool has_initializer_value = false;
|
||||
reshadefx::constant initializer_value = {};
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Type of a shader entry point.
|
||||
/// </summary>
|
||||
enum class shader_type
|
||||
{
|
||||
unknown,
|
||||
vertex,
|
||||
pixel,
|
||||
compute
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a function defined in effect code.
|
||||
/// </summary>
|
||||
struct function
|
||||
{
|
||||
reshadefx::type return_type = {};
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::string unique_name;
|
||||
std::string return_semantic;
|
||||
std::vector<member_type> parameter_list;
|
||||
shader_type type = shader_type::unknown;
|
||||
int num_threads[3] = {};
|
||||
std::vector<uint32_t> referenced_samplers;
|
||||
std::vector<uint32_t> referenced_storages;
|
||||
std::vector<uint32_t> referenced_functions;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Color or alpha blending operations.
|
||||
/// </summary>
|
||||
enum class blend_op : uint8_t
|
||||
{
|
||||
add = 1,
|
||||
subtract,
|
||||
reverse_subtract,
|
||||
min,
|
||||
max
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Blend factors in color or alpha blending operations, which modulate values between the pixel shader output and render target.
|
||||
/// </summary>
|
||||
enum class blend_factor : uint8_t
|
||||
{
|
||||
zero = 0,
|
||||
one = 1,
|
||||
source_color,
|
||||
one_minus_source_color,
|
||||
dest_color,
|
||||
one_minus_dest_color,
|
||||
source_alpha,
|
||||
one_minus_source_alpha,
|
||||
dest_alpha,
|
||||
one_minus_dest_alpha
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Stencil operations that can be performed during depth-stencil testing.
|
||||
/// </summary>
|
||||
enum class stencil_op : uint8_t
|
||||
{
|
||||
zero = 0,
|
||||
keep,
|
||||
replace,
|
||||
increment_saturate,
|
||||
decrement_saturate,
|
||||
invert,
|
||||
increment,
|
||||
decrement
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Comparison operations for depth-stencil testing.
|
||||
/// </summary>
|
||||
enum class stencil_func : uint8_t
|
||||
{
|
||||
never,
|
||||
less,
|
||||
equal,
|
||||
less_equal,
|
||||
greater,
|
||||
not_equal,
|
||||
greater_equal,
|
||||
always
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the possible primitives.
|
||||
/// </summary>
|
||||
enum class primitive_topology : uint8_t
|
||||
{
|
||||
point_list = 1,
|
||||
line_list,
|
||||
line_strip,
|
||||
triangle_list,
|
||||
triangle_strip
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes a render pass with all its state info.
|
||||
/// </summary>
|
||||
struct pass
|
||||
{
|
||||
std::string name;
|
||||
std::string render_target_names[8] = {};
|
||||
std::string vs_entry_point;
|
||||
std::string ps_entry_point;
|
||||
std::string cs_entry_point;
|
||||
bool generate_mipmaps = true;
|
||||
bool clear_render_targets = false;
|
||||
bool blend_enable[8] = { false, false, false, false, false, false, false, false };
|
||||
blend_factor source_color_blend_factor[8] = { blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one };
|
||||
blend_factor dest_color_blend_factor[8] = { blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero };
|
||||
blend_op color_blend_op[8] = { blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add };
|
||||
blend_factor source_alpha_blend_factor[8] = { blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one };
|
||||
blend_factor dest_alpha_blend_factor[8] = { blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero };
|
||||
blend_op alpha_blend_op[8] = { blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add };
|
||||
bool srgb_write_enable = false;
|
||||
uint8_t render_target_write_mask[8] = { 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF };
|
||||
bool stencil_enable = false;
|
||||
uint8_t stencil_read_mask = 0xFF;
|
||||
uint8_t stencil_write_mask = 0xFF;
|
||||
uint8_t stencil_reference_value = 0;
|
||||
stencil_func stencil_comparison_func = stencil_func::always;
|
||||
stencil_op stencil_pass_op = stencil_op::keep;
|
||||
stencil_op stencil_fail_op = stencil_op::keep;
|
||||
stencil_op stencil_depth_fail_op = stencil_op::keep;
|
||||
primitive_topology topology = primitive_topology::triangle_list;
|
||||
uint32_t num_vertices = 3;
|
||||
uint32_t viewport_width = 0;
|
||||
uint32_t viewport_height = 0;
|
||||
uint32_t viewport_dispatch_z = 1;
|
||||
|
||||
// Bindings specific for the code generation target (in case of combined texture and sampler, 'texture_bindings' and 'sampler_bindings' will be the same size and point to the same bindings, otherwise they are independent)
|
||||
std::vector<texture_binding> texture_bindings;
|
||||
std::vector<sampler_binding> sampler_bindings;
|
||||
std::vector<storage_binding> storage_bindings;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A collection of passes that make up an effect.
|
||||
/// </summary>
|
||||
struct technique
|
||||
{
|
||||
std::string name;
|
||||
std::vector<pass> passes;
|
||||
std::vector<annotation> annotations;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// In-memory representation of an effect file.
|
||||
/// </summary>
|
||||
struct effect_module
|
||||
{
|
||||
std::vector<texture> textures;
|
||||
std::vector<sampler> samplers;
|
||||
std::vector<storage> storages;
|
||||
|
||||
std::vector<uniform> uniforms;
|
||||
std::vector<uniform> spec_constants;
|
||||
uint32_t total_uniform_size = 0;
|
||||
|
||||
std::vector<technique> techniques;
|
||||
std::vector<std::pair<std::string, shader_type>> entry_points;
|
||||
};
|
||||
}
|
||||
88
third_party/reshade_fx/source/effect_parser.hpp
vendored
Normal file
88
third_party/reshade_fx/source/effect_parser.hpp
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_symbol_table.hpp"
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// A parser for the ReShade FX shader language.
|
||||
/// </summary>
|
||||
class parser : symbol_table
|
||||
{
|
||||
public:
|
||||
// Define constructor explicitly because lexer class is not included here
|
||||
parser();
|
||||
~parser();
|
||||
|
||||
/// <summary>
|
||||
/// Parses the provided source code and generate code for it.
|
||||
/// </summary>
|
||||
/// <param name="source">Source code string to parse.</param>
|
||||
/// <param name="backend">Code generation implementation to use.</param>
|
||||
/// <returns><see langword="true"/> if parsing was successfull, <see langword="false"/> otherwise.</returns>
|
||||
bool parse(std::string source, class codegen *backend);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of error messages.
|
||||
/// </summary>
|
||||
const std::string &errors() const { return _errors; }
|
||||
|
||||
private:
|
||||
void error(const location &location, unsigned int code, const std::string &message);
|
||||
void warning(const location &location, unsigned int code, const std::string &message);
|
||||
|
||||
void backup();
|
||||
void restore();
|
||||
|
||||
bool peek(char tok) const { return _token_next.id == static_cast<tokenid>(tok); }
|
||||
bool peek(tokenid tokid) const { return _token_next.id == tokid; }
|
||||
void consume();
|
||||
void consume_until(char tok) { return consume_until(static_cast<tokenid>(tok)); }
|
||||
void consume_until(tokenid tokid);
|
||||
bool accept(char tok) { return accept(static_cast<tokenid>(tok)); }
|
||||
bool accept(tokenid tokid);
|
||||
bool expect(char tok) { return expect(static_cast<tokenid>(tok)); }
|
||||
bool expect(tokenid tokid);
|
||||
|
||||
bool accept_symbol(std::string &identifier, scoped_symbol &symbol);
|
||||
bool accept_type_class(type &type);
|
||||
bool accept_type_qualifiers(type &type);
|
||||
bool accept_unary_op();
|
||||
bool accept_postfix_op();
|
||||
bool peek_multary_op(unsigned int &precedence) const;
|
||||
bool accept_assignment_op();
|
||||
|
||||
bool parse_top(bool &parse_success);
|
||||
bool parse_struct();
|
||||
bool parse_function(type type, std::string name, shader_type stype, int num_threads[3]);
|
||||
bool parse_variable(type type, std::string name, bool global = false);
|
||||
bool parse_technique();
|
||||
bool parse_technique_pass(pass &info);
|
||||
bool parse_type(type &type);
|
||||
bool parse_array_length(type &type);
|
||||
bool parse_expression(expression &expression);
|
||||
bool parse_expression_unary(expression &expression);
|
||||
bool parse_expression_multary(expression &expression, unsigned int precedence = 0);
|
||||
bool parse_expression_assignment(expression &expression);
|
||||
bool parse_annotations(std::vector<annotation> &annotations);
|
||||
bool parse_statement(bool scoped);
|
||||
bool parse_statement_block(bool scoped);
|
||||
|
||||
std::string _errors;
|
||||
|
||||
class lexer *_lexer = nullptr;
|
||||
class codegen *_codegen = nullptr;
|
||||
|
||||
token _token;
|
||||
token _token_next;
|
||||
token _token_backup;
|
||||
|
||||
std::vector<uint32_t> _loop_break_target_stack;
|
||||
std::vector<uint32_t> _loop_continue_target_stack;
|
||||
};
|
||||
}
|
||||
1819
third_party/reshade_fx/source/effect_parser_exp.cpp
vendored
Normal file
1819
third_party/reshade_fx/source/effect_parser_exp.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2766
third_party/reshade_fx/source/effect_parser_stmt.cpp
vendored
Normal file
2766
third_party/reshade_fx/source/effect_parser_stmt.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1389
third_party/reshade_fx/source/effect_preprocessor.cpp
vendored
Normal file
1389
third_party/reshade_fx/source/effect_preprocessor.cpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
158
third_party/reshade_fx/source/effect_preprocessor.hpp
vendored
Normal file
158
third_party/reshade_fx/source/effect_preprocessor.hpp
vendored
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_token.hpp"
|
||||
#include <memory> // std::unique_ptr
|
||||
#include <filesystem>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// A C-style preprocessor implementation.
|
||||
/// </summary>
|
||||
class preprocessor
|
||||
{
|
||||
public:
|
||||
struct macro
|
||||
{
|
||||
std::string replacement_list;
|
||||
std::vector<std::string> parameters;
|
||||
bool is_predefined = false;
|
||||
bool is_variadic = false;
|
||||
bool is_function_like = false;
|
||||
};
|
||||
|
||||
// Define constructor explicitly because lexer class is not included here
|
||||
preprocessor();
|
||||
~preprocessor();
|
||||
|
||||
/// <summary>
|
||||
/// Adds an include directory to the list of search paths used when resolving #include directives.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the directory to add.</param>
|
||||
void add_include_path(const std::filesystem::path &path);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new macro definition. This is equal to appending '#define name definition' to this preprocessor instance.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of the macro to define.</param>
|
||||
/// <param name="definition">Definition of the macro function or value.</param>
|
||||
/// <returns><see langword="true"/> if the macro did not exist, <see langword="false"/> otherwise.</returns>
|
||||
bool add_macro_definition(const std::string &name, const macro &definition);
|
||||
/// <summary>
|
||||
/// Adds a new macro value definition. This is equal to appending '#define name value' to this preprocessor instance.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of the macro to define.</param>
|
||||
/// <param name="value">Value to define that macro to.</param>
|
||||
/// <returns><see langword="true"/> if the macro did not exist, <see langword="false"/> otherwise.</returns>
|
||||
bool add_macro_definition(const std::string &name, std::string value = "1")
|
||||
{
|
||||
return add_macro_definition(name, macro { std::move(value), {}, true });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the specified file, parses its contents and appends them to the output.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the file to parse.</param>
|
||||
/// <returns><see langword="true"/> if parsing was successful, <see langword="false"/> otherwise.</returns>
|
||||
bool append_file(const std::filesystem::path &path);
|
||||
/// <summary>
|
||||
/// Parses the specified string and appends it to the output.
|
||||
/// </summary>
|
||||
/// <param name="source_code">String to parse.</param>
|
||||
/// <param name="path">Optional file path to identify this string with.</param>
|
||||
/// <returns><see langword="true"/> if parsing was successful, <see langword="false"/> otherwise.</returns>
|
||||
bool append_string(std::string source_code, const std::filesystem::path &path = std::filesystem::path());
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of error messages.
|
||||
/// </summary>
|
||||
const std::string &errors() const { return _errors; }
|
||||
/// <summary>
|
||||
/// Gets the current pre-processed output string.
|
||||
/// </summary>
|
||||
const std::string &output() const { return _output; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of paths to all the included files.
|
||||
/// </summary>
|
||||
std::vector<std::filesystem::path> included_files() const;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of all defines that were used in #ifdef and #ifndef lines.
|
||||
/// </summary>
|
||||
std::vector<std::pair<std::string, std::string>> used_macro_definitions() const;
|
||||
|
||||
private:
|
||||
struct if_level
|
||||
{
|
||||
bool value;
|
||||
bool skipping;
|
||||
token pp_token;
|
||||
size_t input_index;
|
||||
};
|
||||
struct input_level
|
||||
{
|
||||
std::string name;
|
||||
std::unique_ptr<class lexer> lexer;
|
||||
token next_token;
|
||||
std::unordered_set<std::string> hidden_macros;
|
||||
};
|
||||
|
||||
void error(const location &location, const std::string &message);
|
||||
void warning(const location &location, const std::string &message);
|
||||
|
||||
void push(std::string input, const std::string &name = std::string());
|
||||
|
||||
bool peek(tokenid tokid) const;
|
||||
void consume();
|
||||
void consume_until(tokenid tokid);
|
||||
bool accept(tokenid tokid, bool ignore_whitespace = true);
|
||||
bool expect(tokenid tokid);
|
||||
|
||||
void parse();
|
||||
void parse_def();
|
||||
void parse_undef();
|
||||
void parse_if();
|
||||
void parse_ifdef();
|
||||
void parse_ifndef();
|
||||
void parse_elif();
|
||||
void parse_else();
|
||||
void parse_endif();
|
||||
void parse_error();
|
||||
void parse_warning();
|
||||
void parse_pragma();
|
||||
void parse_include();
|
||||
|
||||
bool evaluate_expression();
|
||||
bool evaluate_identifier_as_macro();
|
||||
|
||||
bool is_defined(const std::string &name) const;
|
||||
void expand_macro(const std::string &name, const macro &definition, const std::vector<std::string> &arguments);
|
||||
void create_macro_replacement_list(macro &definition);
|
||||
|
||||
std::string _output, _errors;
|
||||
|
||||
std::vector<input_level> _input_stack;
|
||||
size_t _next_input_index = 0;
|
||||
size_t _current_input_index = 0;
|
||||
reshadefx::token _token;
|
||||
std::string _current_token_raw_data;
|
||||
reshadefx::location _output_location;
|
||||
|
||||
unsigned short _recursion_count = 0;
|
||||
std::unordered_set<std::string> _used_macros;
|
||||
std::unordered_map<std::string, macro> _macros;
|
||||
|
||||
std::vector<if_level> _if_stack;
|
||||
|
||||
std::vector<std::filesystem::path> _include_paths;
|
||||
std::unordered_map<std::string, std::string> _file_cache;
|
||||
};
|
||||
}
|
||||
456
third_party/reshade_fx/source/effect_symbol_table.cpp
vendored
Normal file
456
third_party/reshade_fx/source/effect_symbol_table.cpp
vendored
Normal file
@@ -0,0 +1,456 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#include "effect_symbol_table.hpp"
|
||||
#include <cassert>
|
||||
#include <malloc.h> // alloca
|
||||
#include <algorithm> // std::upper_bound, std::sort
|
||||
#include <functional> // std::greater
|
||||
|
||||
enum class intrinsic_id
|
||||
{
|
||||
#define IMPLEMENT_INTRINSIC_SPIRV(name, i, code) name##i,
|
||||
#include "effect_symbol_table_intrinsics.inl"
|
||||
};
|
||||
|
||||
struct intrinsic : reshadefx::function
|
||||
{
|
||||
intrinsic(const char *name, intrinsic_id id, const reshadefx::type &ret_type, std::initializer_list<reshadefx::type> arg_types)
|
||||
{
|
||||
function::return_type = ret_type;
|
||||
function::id = static_cast<uint32_t>(id);
|
||||
function::name = name;
|
||||
function::parameter_list.reserve(arg_types.size());
|
||||
for (const reshadefx::type &arg_type : arg_types)
|
||||
function::parameter_list.push_back({ arg_type });
|
||||
}
|
||||
};
|
||||
|
||||
#define void { reshadefx::type::t_void }
|
||||
#define bool { reshadefx::type::t_bool, 1, 1 }
|
||||
#define bool2 { reshadefx::type::t_bool, 2, 1 }
|
||||
#define bool3 { reshadefx::type::t_bool, 3, 1 }
|
||||
#define bool4 { reshadefx::type::t_bool, 4, 1 }
|
||||
#define int { reshadefx::type::t_int, 1, 1 }
|
||||
#define int2 { reshadefx::type::t_int, 2, 1 }
|
||||
#define int3 { reshadefx::type::t_int, 3, 1 }
|
||||
#define int4 { reshadefx::type::t_int, 4, 1 }
|
||||
#define int2x3 { reshadefx::type::t_int, 2, 3 }
|
||||
#define int2x2 { reshadefx::type::t_int, 2, 2 }
|
||||
#define int2x4 { reshadefx::type::t_int, 2, 4 }
|
||||
#define int3x2 { reshadefx::type::t_int, 3, 2 }
|
||||
#define int3x3 { reshadefx::type::t_int, 3, 3 }
|
||||
#define int3x4 { reshadefx::type::t_int, 3, 4 }
|
||||
#define int4x2 { reshadefx::type::t_int, 4, 2 }
|
||||
#define int4x3 { reshadefx::type::t_int, 4, 3 }
|
||||
#define int4x4 { reshadefx::type::t_int, 4, 4 }
|
||||
#define out_int { reshadefx::type::t_int, 1, 1, reshadefx::type::q_out }
|
||||
#define out_int2 { reshadefx::type::t_int, 2, 1, reshadefx::type::q_out }
|
||||
#define out_int3 { reshadefx::type::t_int, 3, 1, reshadefx::type::q_out }
|
||||
#define out_int4 { reshadefx::type::t_int, 4, 1, reshadefx::type::q_out }
|
||||
#define inout_int { reshadefx::type::t_int, 1, 1, reshadefx::type::q_inout | reshadefx::type::q_groupshared }
|
||||
#define uint { reshadefx::type::t_uint, 1, 1 }
|
||||
#define uint2 { reshadefx::type::t_uint, 2, 1 }
|
||||
#define uint3 { reshadefx::type::t_uint, 3, 1 }
|
||||
#define uint4 { reshadefx::type::t_uint, 4, 1 }
|
||||
#define inout_uint { reshadefx::type::t_uint, 1, 1, reshadefx::type::q_inout | reshadefx::type::q_groupshared }
|
||||
#define float { reshadefx::type::t_float, 1, 1 }
|
||||
#define float2 { reshadefx::type::t_float, 2, 1 }
|
||||
#define float3 { reshadefx::type::t_float, 3, 1 }
|
||||
#define float4 { reshadefx::type::t_float, 4, 1 }
|
||||
#define float2x3 { reshadefx::type::t_float, 2, 3 }
|
||||
#define float2x2 { reshadefx::type::t_float, 2, 2 }
|
||||
#define float2x4 { reshadefx::type::t_float, 2, 4 }
|
||||
#define float3x2 { reshadefx::type::t_float, 3, 2 }
|
||||
#define float3x3 { reshadefx::type::t_float, 3, 3 }
|
||||
#define float3x4 { reshadefx::type::t_float, 3, 4 }
|
||||
#define float4x2 { reshadefx::type::t_float, 4, 2 }
|
||||
#define float4x3 { reshadefx::type::t_float, 4, 3 }
|
||||
#define float4x4 { reshadefx::type::t_float, 4, 4 }
|
||||
#define out_float { reshadefx::type::t_float, 1, 1, reshadefx::type::q_out }
|
||||
#define out_float2 { reshadefx::type::t_float, 2, 1, reshadefx::type::q_out }
|
||||
#define out_float3 { reshadefx::type::t_float, 3, 1, reshadefx::type::q_out }
|
||||
#define out_float4 { reshadefx::type::t_float, 4, 1, reshadefx::type::q_out }
|
||||
#define sampler1d_int { reshadefx::type::t_sampler1d_int, 1, 1 }
|
||||
#define sampler2d_int { reshadefx::type::t_sampler2d_int, 1, 1 }
|
||||
#define sampler3d_int { reshadefx::type::t_sampler3d_int, 1, 1 }
|
||||
#define sampler1d_int4 { reshadefx::type::t_sampler1d_int, 4, 1 }
|
||||
#define sampler2d_int4 { reshadefx::type::t_sampler2d_int, 4, 1 }
|
||||
#define sampler3d_int4 { reshadefx::type::t_sampler3d_int, 4, 1 }
|
||||
#define sampler1d_uint { reshadefx::type::t_sampler1d_uint, 1, 1 }
|
||||
#define sampler2d_uint { reshadefx::type::t_sampler2d_uint, 1, 1 }
|
||||
#define sampler3d_uint { reshadefx::type::t_sampler3d_uint, 1, 1 }
|
||||
#define sampler1d_uint4 { reshadefx::type::t_sampler1d_uint, 4, 1 }
|
||||
#define sampler2d_uint4 { reshadefx::type::t_sampler2d_uint, 4, 1 }
|
||||
#define sampler3d_uint4 { reshadefx::type::t_sampler3d_uint, 4, 1 }
|
||||
#define sampler1d_float { reshadefx::type::t_sampler1d_float, 1, 1 }
|
||||
#define sampler2d_float { reshadefx::type::t_sampler2d_float, 1, 1 }
|
||||
#define sampler3d_float { reshadefx::type::t_sampler3d_float, 1, 1 }
|
||||
#define sampler1d_float4 { reshadefx::type::t_sampler1d_float, 4, 1 }
|
||||
#define sampler2d_float4 { reshadefx::type::t_sampler2d_float, 4, 1 }
|
||||
#define sampler3d_float4 { reshadefx::type::t_sampler3d_float, 4, 1 }
|
||||
#define storage1d_int { reshadefx::type::t_storage1d_int, 1, 1 }
|
||||
#define storage2d_int { reshadefx::type::t_storage2d_int, 1, 1 }
|
||||
#define storage3d_int { reshadefx::type::t_storage3d_int, 1, 1 }
|
||||
#define storage1d_int4 { reshadefx::type::t_storage1d_int, 4, 1 }
|
||||
#define storage2d_int4 { reshadefx::type::t_storage2d_int, 4, 1 }
|
||||
#define storage3d_int4 { reshadefx::type::t_storage3d_int, 4, 1 }
|
||||
#define storage1d_uint { reshadefx::type::t_storage1d_uint, 1, 1 }
|
||||
#define storage2d_uint { reshadefx::type::t_storage2d_uint, 1, 1 }
|
||||
#define storage3d_uint { reshadefx::type::t_storage3d_uint, 1, 1 }
|
||||
#define storage1d_uint4 { reshadefx::type::t_storage1d_uint, 4, 1 }
|
||||
#define storage2d_uint4 { reshadefx::type::t_storage2d_uint, 4, 1 }
|
||||
#define storage3d_uint4 { reshadefx::type::t_storage3d_uint, 4, 1 }
|
||||
#define storage1d_float { reshadefx::type::t_storage1d_float, 1, 1 }
|
||||
#define storage2d_float { reshadefx::type::t_storage2d_float, 1, 1 }
|
||||
#define storage3d_float { reshadefx::type::t_storage3d_float, 1, 1 }
|
||||
#define storage1d_float4 { reshadefx::type::t_storage1d_float, 4, 1 }
|
||||
#define storage2d_float4 { reshadefx::type::t_storage2d_float, 4, 1 }
|
||||
#define storage3d_float4 { reshadefx::type::t_storage3d_float, 4, 1 }
|
||||
#define inout_storage1d_int { reshadefx::type::t_storage1d_int, 1, 1, reshadefx::type::q_inout }
|
||||
#define inout_storage2d_int { reshadefx::type::t_storage2d_int, 1, 1, reshadefx::type::q_inout }
|
||||
#define inout_storage3d_int { reshadefx::type::t_storage3d_int, 1, 1, reshadefx::type::q_inout }
|
||||
#define inout_storage1d_uint { reshadefx::type::t_storage1d_uint, 1, 1, reshadefx::type::q_inout }
|
||||
#define inout_storage2d_uint { reshadefx::type::t_storage2d_uint, 1, 1, reshadefx::type::q_inout }
|
||||
#define inout_storage3d_uint { reshadefx::type::t_storage3d_uint, 1, 1, reshadefx::type::q_inout }
|
||||
|
||||
// Import intrinsic function definitions
|
||||
static const intrinsic s_intrinsics[] =
|
||||
{
|
||||
#define DEFINE_INTRINSIC(name, i, ret_type, ...) intrinsic(#name, intrinsic_id::name##i, ret_type, { __VA_ARGS__ }),
|
||||
#include "effect_symbol_table_intrinsics.inl"
|
||||
};
|
||||
|
||||
#undef void
|
||||
#undef bool
|
||||
#undef bool2
|
||||
#undef bool3
|
||||
#undef bool4
|
||||
#undef int
|
||||
#undef int2
|
||||
#undef int3
|
||||
#undef int4
|
||||
#undef uint
|
||||
#undef uint2
|
||||
#undef uint3
|
||||
#undef uint4
|
||||
#undef float
|
||||
#undef float2
|
||||
#undef float3
|
||||
#undef float4
|
||||
|
||||
unsigned int reshadefx::type::rank(const type &src, const type &dst)
|
||||
{
|
||||
if (src.is_array() != dst.is_array() || (src.array_length != dst.array_length && src.is_bounded_array() && dst.is_bounded_array()))
|
||||
return 0; // Arrays of different sizes are not compatible
|
||||
if (src.is_struct() || dst.is_struct())
|
||||
return src.struct_definition == dst.struct_definition ? 32 : 0; // Structs are only compatible if they are the same type
|
||||
if (!src.is_numeric() || !dst.is_numeric())
|
||||
return src.base == dst.base && src.rows == dst.rows && src.cols == dst.cols ? 32 : 0; // Numeric values are not compatible with other types
|
||||
if (src.is_matrix() && (!dst.is_matrix() || src.rows != dst.rows || src.cols != dst.cols))
|
||||
return 0; // Matrix truncation or dimensions do not match
|
||||
|
||||
// This table is based on the following rules:
|
||||
// - Floating point has a higher rank than integer types
|
||||
// - Integer to floating point promotion has a higher rank than floating point to integer conversion
|
||||
// - Signed to unsigned integer conversion has a higher rank than unsigned to signed integer conversion
|
||||
static const unsigned int ranks[7][7] = {
|
||||
{ 5, 4, 4, 4, 4, 4, 4 }, // bool
|
||||
{ 3, 5, 5, 2, 2, 4, 4 }, // min16int
|
||||
{ 3, 5, 5, 2, 2, 4, 4 }, // int
|
||||
{ 3, 1, 1, 5, 5, 4, 4 }, // min16uint
|
||||
{ 3, 1, 1, 5, 5, 4, 4 }, // uint
|
||||
{ 3, 3, 3, 3, 3, 6, 6 }, // min16float
|
||||
{ 3, 3, 3, 3, 3, 6, 6 } // float
|
||||
};
|
||||
|
||||
assert(src.base > 0 && src.base <= 7); // bool - float
|
||||
assert(dst.base > 0 && dst.base <= 7);
|
||||
|
||||
const unsigned int rank = ranks[src.base - 1][dst.base - 1] << 2;
|
||||
|
||||
if ((src.is_scalar() && dst.is_vector()))
|
||||
return rank >> 1; // Scalar to vector promotion has a lower rank
|
||||
if ((src.is_vector() && dst.is_scalar()) || (src.is_vector() == dst.is_vector() && src.rows > dst.rows && src.cols >= dst.cols))
|
||||
return rank >> 2; // Vector to scalar conversion has an even lower rank
|
||||
if ((src.is_vector() != dst.is_vector()) || src.is_matrix() != dst.is_matrix() || src.components() != dst.components())
|
||||
return 0; // If components weren't converted at this point, the types are not compatible
|
||||
|
||||
return rank * src.components(); // More components causes a higher rank
|
||||
}
|
||||
|
||||
reshadefx::symbol_table::symbol_table()
|
||||
{
|
||||
_current_scope.name = "::";
|
||||
_current_scope.level = 0;
|
||||
_current_scope.namespace_level = 0;
|
||||
}
|
||||
|
||||
void reshadefx::symbol_table::enter_scope()
|
||||
{
|
||||
_current_scope.level++;
|
||||
}
|
||||
void reshadefx::symbol_table::enter_namespace(const std::string &name)
|
||||
{
|
||||
_current_scope.name += name + "::";
|
||||
_current_scope.level++;
|
||||
_current_scope.namespace_level++;
|
||||
}
|
||||
void reshadefx::symbol_table::leave_scope()
|
||||
{
|
||||
assert(_current_scope.level > 0);
|
||||
|
||||
for (auto &symbol : _symbol_stack)
|
||||
{
|
||||
std::vector<scoped_symbol> &scope_list = symbol.second;
|
||||
|
||||
for (auto scope_it = scope_list.begin(); scope_it != scope_list.end();)
|
||||
{
|
||||
if (scope_it->scope.level > scope_it->scope.namespace_level &&
|
||||
scope_it->scope.level >= _current_scope.level)
|
||||
{
|
||||
scope_it = scope_list.erase(scope_it);
|
||||
}
|
||||
else
|
||||
{
|
||||
++scope_it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_current_scope.level--;
|
||||
}
|
||||
void reshadefx::symbol_table::leave_namespace()
|
||||
{
|
||||
assert(_current_scope.level > 0);
|
||||
assert(_current_scope.namespace_level > 0);
|
||||
|
||||
_current_scope.name.erase(_current_scope.name.substr(0, _current_scope.name.size() - 2).rfind("::") + 2);
|
||||
_current_scope.level--;
|
||||
_current_scope.namespace_level--;
|
||||
}
|
||||
|
||||
bool reshadefx::symbol_table::insert_symbol(const std::string &name, const symbol &symbol, bool global)
|
||||
{
|
||||
assert(symbol.id != 0 || symbol.op == symbol_type::constant);
|
||||
|
||||
// Make sure the symbol does not exist yet
|
||||
if (symbol.op != symbol_type::function && find_symbol(name, _current_scope, true).id != 0)
|
||||
return false;
|
||||
|
||||
// Insertion routine which keeps the symbol stack sorted by namespace level
|
||||
const auto insert_sorted = [](auto &vec, const auto &item) {
|
||||
return vec.insert(
|
||||
std::upper_bound(vec.begin(), vec.end(), item,
|
||||
[](auto lhs, auto rhs) {
|
||||
return lhs.scope.namespace_level < rhs.scope.namespace_level;
|
||||
}), item);
|
||||
};
|
||||
|
||||
// Global symbols are accessible from every scope
|
||||
if (global)
|
||||
{
|
||||
scope scope = { "", 0, 0 };
|
||||
|
||||
// Walk scope chain from global scope back to current one
|
||||
for (size_t pos = 0; pos != std::string::npos; pos = _current_scope.name.find("::", pos))
|
||||
{
|
||||
// Extract scope name
|
||||
scope.name = _current_scope.name.substr(0, pos += 2);
|
||||
const std::string previous_scope_name = _current_scope.name.substr(pos);
|
||||
|
||||
// Insert symbol into this scope
|
||||
insert_sorted(_symbol_stack[previous_scope_name + name], scoped_symbol { symbol, scope });
|
||||
|
||||
// Continue walking up the scope chain
|
||||
scope.level = ++scope.namespace_level;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// This is a local symbol so it's sufficient to update the symbol stack with just the current scope
|
||||
insert_sorted(_symbol_stack[name], scoped_symbol { symbol, _current_scope });
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
reshadefx::scoped_symbol reshadefx::symbol_table::find_symbol(const std::string &name) const
|
||||
{
|
||||
// Default to start search with current scope and walk back the scope chain
|
||||
return find_symbol(name, _current_scope, false);
|
||||
}
|
||||
reshadefx::scoped_symbol reshadefx::symbol_table::find_symbol(const std::string &name, const scope &scope, bool exclusive) const
|
||||
{
|
||||
const auto stack_it = _symbol_stack.find(name);
|
||||
|
||||
// Check if symbol does exist
|
||||
if (stack_it == _symbol_stack.end() || stack_it->second.empty())
|
||||
return {};
|
||||
|
||||
// Walk up the scope chain starting at the requested scope level and find a matching symbol
|
||||
scoped_symbol result = {};
|
||||
|
||||
for (auto it = stack_it->second.rbegin(), end = stack_it->second.rend(); it != end; ++it)
|
||||
{
|
||||
if (it->scope.level > scope.level ||
|
||||
it->scope.namespace_level > scope.namespace_level || (it->scope.namespace_level == scope.namespace_level && it->scope.name != scope.name))
|
||||
continue;
|
||||
if (exclusive && it->scope.level < scope.level)
|
||||
continue;
|
||||
|
||||
if (it->op == symbol_type::constant || it->op == symbol_type::variable || it->op == symbol_type::structure)
|
||||
return *it; // Variables and structures have the highest priority and are always picked immediately
|
||||
else if (result.id == 0)
|
||||
result = *it; // Function names have a lower priority, so continue searching in case a variable with the same name exists
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static int compare_functions(const std::vector<reshadefx::expression> &arguments, const reshadefx::function *function1, const reshadefx::function *function2)
|
||||
{
|
||||
const size_t num_arguments = arguments.size();
|
||||
|
||||
// Check if the first function matches the argument types
|
||||
bool function1_viable = true;
|
||||
const auto function1_ranks = static_cast<unsigned int *>(alloca(num_arguments * sizeof(unsigned int)));
|
||||
for (size_t i = 0; i < num_arguments; ++i)
|
||||
{
|
||||
if ((function1_ranks[i] = reshadefx::type::rank(arguments[i].type, function1->parameter_list[i].type)) == 0)
|
||||
{
|
||||
function1_viable = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Catch case where the second function does not exist
|
||||
if (function2 == nullptr)
|
||||
return function1_viable ? -1 : 1; // If the first function is not viable, this compare fails
|
||||
|
||||
// Check if the second function matches the argument types
|
||||
bool function2_viable = true;
|
||||
const auto function2_ranks = static_cast<unsigned int *>(alloca(num_arguments * sizeof(unsigned int)));
|
||||
for (size_t i = 0; i < num_arguments; ++i)
|
||||
{
|
||||
if ((function2_ranks[i] = reshadefx::type::rank(arguments[i].type, function2->parameter_list[i].type)) == 0)
|
||||
{
|
||||
function2_viable = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If one of the functions is not viable, then the other one automatically wins
|
||||
if (!function1_viable || !function2_viable)
|
||||
return function2_viable - function1_viable;
|
||||
|
||||
// Both functions are possible, so find the one with the higher ranking
|
||||
std::sort(function1_ranks, function1_ranks + num_arguments, std::greater<unsigned int>());
|
||||
std::sort(function2_ranks, function2_ranks + num_arguments, std::greater<unsigned int>());
|
||||
|
||||
for (size_t i = 0; i < num_arguments; ++i)
|
||||
if (function1_ranks[i] > function2_ranks[i])
|
||||
return -1; // Left function wins
|
||||
else if (function2_ranks[i] > function1_ranks[i])
|
||||
return +1; // Right function wins
|
||||
|
||||
return 0; // Both functions are equally viable
|
||||
}
|
||||
|
||||
bool reshadefx::symbol_table::resolve_function_call(const std::string &name, const std::vector<expression> &arguments, const scope &scope, symbol &out_data, bool &is_ambiguous) const
|
||||
{
|
||||
out_data.op = symbol_type::function;
|
||||
|
||||
const function *result = nullptr;
|
||||
unsigned int num_overloads = 0;
|
||||
unsigned int overload_namespace = scope.namespace_level;
|
||||
|
||||
// Look up function name in the symbol stack and loop through the associated symbols
|
||||
const auto stack_it = _symbol_stack.find(name);
|
||||
|
||||
if (stack_it != _symbol_stack.end() && !stack_it->second.empty())
|
||||
{
|
||||
for (auto it = stack_it->second.rbegin(), end = stack_it->second.rend(); it != end; ++it)
|
||||
{
|
||||
if (it->op != symbol_type::function)
|
||||
continue;
|
||||
if (it->scope.level > scope.level ||
|
||||
it->scope.namespace_level > scope.namespace_level || (it->scope.namespace_level == scope.namespace_level && it->scope.name != scope.name))
|
||||
continue;
|
||||
|
||||
const function *const function = it->function;
|
||||
|
||||
if (function == nullptr)
|
||||
continue;
|
||||
|
||||
if (function->parameter_list.empty())
|
||||
{
|
||||
if (arguments.empty())
|
||||
{
|
||||
out_data.id = it->id;
|
||||
out_data.type = function->return_type;
|
||||
out_data.function = result = function;
|
||||
num_overloads = 1;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (arguments.size() > function->parameter_list.size() || (arguments.size() < function->parameter_list.size() && !function->parameter_list[arguments.size()].has_default_value))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// A new possibly-matching function was found, compare it against the current result
|
||||
const int comparison = compare_functions(arguments, function, result);
|
||||
|
||||
if (comparison < 0) // The new function is a better match
|
||||
{
|
||||
out_data.id = it->id;
|
||||
out_data.type = function->return_type;
|
||||
out_data.function = result = function;
|
||||
num_overloads = 1;
|
||||
overload_namespace = it->scope.namespace_level;
|
||||
}
|
||||
else if (comparison == 0 && overload_namespace == it->scope.namespace_level) // Both functions are equally viable, so the call is ambiguous
|
||||
{
|
||||
++num_overloads;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try matching against intrinsic functions if no matching user-defined function was found up to this point
|
||||
if (num_overloads == 0)
|
||||
{
|
||||
for (const intrinsic &intrinsic : s_intrinsics)
|
||||
{
|
||||
if (intrinsic.name != name || intrinsic.parameter_list.size() != arguments.size())
|
||||
continue;
|
||||
|
||||
// A new possibly-matching intrinsic function was found, compare it against the current result
|
||||
const int comparison = compare_functions(arguments, &intrinsic, result);
|
||||
|
||||
if (comparison < 0) // The new function is a better match
|
||||
{
|
||||
out_data.op = symbol_type::intrinsic;
|
||||
out_data.id = intrinsic.id;
|
||||
out_data.type = intrinsic.return_type;
|
||||
out_data.function = &intrinsic;
|
||||
result = out_data.function;
|
||||
num_overloads = 1;
|
||||
}
|
||||
else if (comparison == 0 && overload_namespace == 0) // Both functions are equally viable, so the call is ambiguous (intrinsics are always in the global namespace)
|
||||
{
|
||||
++num_overloads;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is_ambiguous = num_overloads > 1;
|
||||
|
||||
return num_overloads == 1;
|
||||
}
|
||||
103
third_party/reshade_fx/source/effect_symbol_table.hpp
vendored
Normal file
103
third_party/reshade_fx/source/effect_symbol_table.hpp
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "effect_module.hpp"
|
||||
#include <unordered_map> // Used for symbol lookup table
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// A scope encapsulating symbols.
|
||||
/// </summary>
|
||||
struct scope
|
||||
{
|
||||
std::string name;
|
||||
uint32_t level, namespace_level;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration of all possible symbol types.
|
||||
/// </summary>
|
||||
enum class symbol_type
|
||||
{
|
||||
invalid,
|
||||
variable,
|
||||
constant,
|
||||
function,
|
||||
intrinsic,
|
||||
structure,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A single symbol in the symbol table.
|
||||
/// </summary>
|
||||
struct symbol
|
||||
{
|
||||
symbol_type op = symbol_type::invalid;
|
||||
uint32_t id = 0;
|
||||
reshadefx::type type = {};
|
||||
reshadefx::constant constant = {};
|
||||
const reshadefx::function *function = nullptr;
|
||||
};
|
||||
struct scoped_symbol : symbol
|
||||
{
|
||||
struct scope scope; // Store scope together with symbol data
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A symbol table managing a list of scopes and symbols.
|
||||
/// </summary>
|
||||
class symbol_table
|
||||
{
|
||||
public:
|
||||
symbol_table();
|
||||
|
||||
/// <summary>
|
||||
/// Enters a new scope as child of the current one.
|
||||
/// </summary>
|
||||
void enter_scope();
|
||||
/// <summary>
|
||||
/// Enters a new namespace as child of the current one.
|
||||
/// </summary>
|
||||
void enter_namespace(const std::string &name);
|
||||
/// <summary>
|
||||
/// Leaves the current scope and enter the parent one.
|
||||
/// </summary>
|
||||
void leave_scope();
|
||||
/// <summary>
|
||||
/// Leaves the current namespace and enter the parent one.
|
||||
/// </summary>
|
||||
void leave_namespace();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current scope the symbol table operates in.
|
||||
/// </summary>
|
||||
const scope ¤t_scope() const { return _current_scope; }
|
||||
|
||||
/// <summary>
|
||||
/// Inserts an new symbol in the symbol table.
|
||||
/// Returns <see langword="false"/> if a symbol by that name and type already exists.
|
||||
/// </summary>
|
||||
bool insert_symbol(const std::string &name, const symbol &symbol, bool global = false);
|
||||
|
||||
/// <summary>
|
||||
/// Looks for an existing symbol with the specified <paramref name="name"/>.
|
||||
/// </summary>
|
||||
scoped_symbol find_symbol(const std::string &name) const;
|
||||
scoped_symbol find_symbol(const std::string &name, const scope &scope, bool exclusive) const;
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the best function or intrinsic overload matching the argument list.
|
||||
/// </summary>
|
||||
bool resolve_function_call(const std::string &name, const std::vector<expression> &args, const scope &scope, symbol &data, bool &ambiguous) const;
|
||||
|
||||
private:
|
||||
scope _current_scope;
|
||||
// Lookup table from name to matching symbols
|
||||
std::unordered_map<std::string, std::vector<scoped_symbol>> _symbol_stack;
|
||||
};
|
||||
}
|
||||
4587
third_party/reshade_fx/source/effect_symbol_table_intrinsics.inl
vendored
Normal file
4587
third_party/reshade_fx/source/effect_symbol_table_intrinsics.inl
vendored
Normal file
File diff suppressed because it is too large
Load Diff
279
third_party/reshade_fx/source/effect_token.hpp
vendored
Normal file
279
third_party/reshade_fx/source/effect_token.hpp
vendored
Normal file
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Patrick Mours
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace reshadefx
|
||||
{
|
||||
/// <summary>
|
||||
/// Structure which keeps track of a code location.
|
||||
/// </summary>
|
||||
struct location
|
||||
{
|
||||
location() : line(1), column(1) {}
|
||||
explicit location(uint32_t line, uint32_t column = 1) : line(line), column(column) {}
|
||||
explicit location(std::string source, uint32_t line, uint32_t column = 1) : source(std::move(source)), line(line), column(column) {}
|
||||
|
||||
std::string source;
|
||||
uint32_t line, column;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A collection of identifiers for various possible tokens.
|
||||
/// </summary>
|
||||
enum class tokenid
|
||||
{
|
||||
unknown = -1,
|
||||
end_of_file = 0,
|
||||
end_of_line = '\n',
|
||||
|
||||
// operators
|
||||
space = ' ',
|
||||
exclaim = '!',
|
||||
hash = '#',
|
||||
dollar = '$',
|
||||
percent = '%',
|
||||
ampersand = '&',
|
||||
parenthesis_open = '(',
|
||||
parenthesis_close = ')',
|
||||
star = '*',
|
||||
plus = '+',
|
||||
comma = ',',
|
||||
minus = '-',
|
||||
dot = '.',
|
||||
slash = '/',
|
||||
colon = ':',
|
||||
semicolon = ';',
|
||||
less = '<',
|
||||
equal = '=',
|
||||
greater = '>',
|
||||
question = '?',
|
||||
at = '@',
|
||||
bracket_open = '[',
|
||||
backslash = '\\',
|
||||
bracket_close = ']',
|
||||
caret = '^',
|
||||
brace_open = '{',
|
||||
pipe = '|',
|
||||
brace_close = '}',
|
||||
tilde = '~',
|
||||
exclaim_equal = 256 /* != */,
|
||||
percent_equal /* %= */,
|
||||
ampersand_ampersand /* && */,
|
||||
ampersand_equal /* &= */,
|
||||
star_equal /* *= */,
|
||||
plus_plus /* ++*/,
|
||||
plus_equal /* += */,
|
||||
minus_minus /* -- */,
|
||||
minus_equal /* -= */,
|
||||
arrow /* -> */,
|
||||
ellipsis /* ... */,
|
||||
slash_equal /* /= */,
|
||||
colon_colon /* :: */,
|
||||
less_less_equal /* <<= */,
|
||||
less_less /* << */,
|
||||
less_equal /* <= */,
|
||||
equal_equal /* == */,
|
||||
greater_greater_equal /* >>= */,
|
||||
greater_greater /* >> */,
|
||||
greater_equal /* >= */,
|
||||
caret_equal /* ^= */,
|
||||
pipe_equal /* |= */,
|
||||
pipe_pipe /* || */,
|
||||
|
||||
// identifiers
|
||||
reserved,
|
||||
identifier,
|
||||
|
||||
// literals
|
||||
true_literal,
|
||||
false_literal,
|
||||
int_literal,
|
||||
uint_literal,
|
||||
float_literal,
|
||||
string_literal,
|
||||
|
||||
// keywords
|
||||
pragma,
|
||||
namespace_,
|
||||
struct_,
|
||||
technique,
|
||||
pass,
|
||||
for_,
|
||||
while_,
|
||||
do_,
|
||||
if_,
|
||||
else_,
|
||||
switch_,
|
||||
case_,
|
||||
default_,
|
||||
break_,
|
||||
continue_,
|
||||
return_,
|
||||
discard_,
|
||||
extern_,
|
||||
static_,
|
||||
uniform_,
|
||||
volatile_,
|
||||
precise,
|
||||
groupshared,
|
||||
in,
|
||||
out,
|
||||
inout,
|
||||
const_,
|
||||
linear,
|
||||
noperspective,
|
||||
centroid,
|
||||
nointerpolation,
|
||||
|
||||
void_,
|
||||
bool_,
|
||||
bool2,
|
||||
bool3,
|
||||
bool4,
|
||||
bool2x2,
|
||||
bool2x3,
|
||||
bool2x4,
|
||||
bool3x2,
|
||||
bool3x3,
|
||||
bool3x4,
|
||||
bool4x2,
|
||||
bool4x3,
|
||||
bool4x4,
|
||||
int_,
|
||||
int2,
|
||||
int3,
|
||||
int4,
|
||||
int2x2,
|
||||
int2x3,
|
||||
int2x4,
|
||||
int3x2,
|
||||
int3x3,
|
||||
int3x4,
|
||||
int4x2,
|
||||
int4x3,
|
||||
int4x4,
|
||||
min16int,
|
||||
min16int2,
|
||||
min16int3,
|
||||
min16int4,
|
||||
min16int2x2,
|
||||
min16int2x3,
|
||||
min16int2x4,
|
||||
min16int3x2,
|
||||
min16int3x3,
|
||||
min16int3x4,
|
||||
min16int4x2,
|
||||
min16int4x3,
|
||||
min16int4x4,
|
||||
uint_,
|
||||
uint2,
|
||||
uint3,
|
||||
uint4,
|
||||
uint2x2,
|
||||
uint2x3,
|
||||
uint2x4,
|
||||
uint3x2,
|
||||
uint3x3,
|
||||
uint3x4,
|
||||
uint4x2,
|
||||
uint4x3,
|
||||
uint4x4,
|
||||
min16uint,
|
||||
min16uint2,
|
||||
min16uint3,
|
||||
min16uint4,
|
||||
min16uint2x2,
|
||||
min16uint2x3,
|
||||
min16uint2x4,
|
||||
min16uint3x2,
|
||||
min16uint3x3,
|
||||
min16uint3x4,
|
||||
min16uint4x2,
|
||||
min16uint4x3,
|
||||
min16uint4x4,
|
||||
float_,
|
||||
float2,
|
||||
float3,
|
||||
float4,
|
||||
float2x2,
|
||||
float2x3,
|
||||
float2x4,
|
||||
float3x2,
|
||||
float3x3,
|
||||
float3x4,
|
||||
float4x2,
|
||||
float4x3,
|
||||
float4x4,
|
||||
min16float,
|
||||
min16float2,
|
||||
min16float3,
|
||||
min16float4,
|
||||
min16float2x2,
|
||||
min16float2x3,
|
||||
min16float2x4,
|
||||
min16float3x2,
|
||||
min16float3x3,
|
||||
min16float3x4,
|
||||
min16float4x2,
|
||||
min16float4x3,
|
||||
min16float4x4,
|
||||
vector,
|
||||
matrix,
|
||||
string_,
|
||||
texture1d,
|
||||
texture2d,
|
||||
texture3d,
|
||||
sampler1d,
|
||||
sampler2d,
|
||||
sampler3d,
|
||||
storage1d,
|
||||
storage2d,
|
||||
storage3d,
|
||||
|
||||
// preprocessor directives
|
||||
hash_def,
|
||||
hash_undef,
|
||||
hash_if,
|
||||
hash_ifdef,
|
||||
hash_ifndef,
|
||||
hash_else,
|
||||
hash_elif,
|
||||
hash_endif,
|
||||
hash_error,
|
||||
hash_warning,
|
||||
hash_pragma,
|
||||
hash_include,
|
||||
hash_unknown,
|
||||
|
||||
single_line_comment,
|
||||
multi_line_comment,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A structure describing a single token in the input string.
|
||||
/// </summary>
|
||||
struct token
|
||||
{
|
||||
tokenid id;
|
||||
reshadefx::location location;
|
||||
size_t offset, length;
|
||||
union
|
||||
{
|
||||
int literal_as_int;
|
||||
unsigned int literal_as_uint;
|
||||
float literal_as_float;
|
||||
};
|
||||
std::string literal_as_string;
|
||||
|
||||
operator tokenid() const { return id; }
|
||||
|
||||
static std::string id_to_name(tokenid id);
|
||||
};
|
||||
}
|
||||
38
third_party/stb_image/LICENSE
vendored
Normal file
38
third_party/stb_image/LICENSE
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
The software libraries in this repository are in the public domain. Most
|
||||
of them are also available under the MIT license -- choose whichever you prefer.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE A - MIT License
|
||||
Copyright (c) 2017 Sean Barrett
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
This is free and unencumbered software released into the public domain.
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
7
third_party/stb_image/PROVENANCE.md
vendored
Normal file
7
third_party/stb_image/PROVENANCE.md
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
# stb_image
|
||||
|
||||
`stb_image.h` and `LICENSE` are unmodified copies from
|
||||
<https://github.com/nothings/stb/tree/6b5799bae8a1fe3792691ef4b72ae26434c3e799>.
|
||||
Triforce uses the MIT option for its PNG decoder for ReShade FX textures.
|
||||
|
||||
tree-sha256: 786b25c5966cff4dd9119a39af43ed727eec8aa57ff34a07f41f6d2b422a58e1
|
||||
7812
third_party/stb_image/stb_image.h
vendored
Normal file
7812
third_party/stb_image/stb_image.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
21
third_party/xess/PROVENANCE.md
vendored
Normal file
21
third_party/xess/PROVENANCE.md
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# Intel XeSS Super Resolution API headers
|
||||
|
||||
Intel's MIT-licensed XeSS-SR API headers, the Vulkan path only: `inc/xess/xess.h`, `inc/xess/xess_vk.h` and their licence
|
||||
`inc/MIT.txt`, at the same paths as in <https://github.com/intel/xess>, commit `de0fb9c1c510661c571164e1418ceca8101dab69`
|
||||
(main, after the 3.0.2 release). Licence: MIT (`inc/MIT.txt`, Copyright (c) 2026 Intel Corporation; each header says
|
||||
`SPDX-License-Identifier: MIT`).
|
||||
|
||||
Not the `v3.0.2` tag: its headers carry Intel's proprietary notice, not the MIT one; the commit above is the first whose
|
||||
`inc/` is MIT. Only these headers are taken. Nothing else of the SDK is here: not the D3D12 or D3D11 headers, not XeSS Frame
|
||||
Generation or XeLL (D3D12 only), not the import library, and never `libxess.dll`, which is Intel's under the Intel Simplified
|
||||
Software License: the player puts it beside the game (readme, Intel XeSS); nothing downloads it. `gpu/vk/vk_xess.cpp` compiles
|
||||
against these headers for their types and loads the player's `libxess.dll` at run time through `GetProcAddress`.
|
||||
|
||||
The files are Intel's, unmodified but for their line endings: Intel's repository stores them with CRLF, and this repository keeps
|
||||
text files with LF (`.gitattributes`). With CRLF put back they are Intel's blobs byte for byte (git blob ids:
|
||||
`inc/xess/xess.h` 5d16b101994190f22cdf43e695ca1fccc9a79a1d, `inc/xess/xess_vk.h` 1349d81d4474975e8dccd5783ceae5d8dc2d9de8,
|
||||
`inc/MIT.txt` 478eb06298afb556e6248b434b7aec2c93ea4bdb).
|
||||
|
||||
Nothing in this folder is edited. A change belongs in a new folder with its own note.
|
||||
|
||||
tree-sha256: 2ad625a8596454f22f0474f3af8d3b121b0ed746428f2bac0cadd4bfd580a91d
|
||||
17
third_party/xess/inc/MIT.txt
vendored
Normal file
17
third_party/xess/inc/MIT.txt
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
Copyright (c) 2026 Intel Corporation
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
||||
software and associated documentation files (the "Software"), to deal in the Software
|
||||
without restriction, including without limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
|
||||
to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies
|
||||
or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
||||
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
426
third_party/xess/inc/xess/xess.h
vendored
Normal file
426
third_party/xess/inc/xess/xess.h
vendored
Normal file
@@ -0,0 +1,426 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2026 Intel Corporation
|
||||
*
|
||||
* SPDX-License-Identifier: MIT
|
||||
******************************************************************************/
|
||||
|
||||
#ifndef XESS_H
|
||||
#define XESS_H
|
||||
|
||||
#ifdef XESS_SHARED_LIB
|
||||
#ifdef _WIN32
|
||||
#ifdef XESS_EXPORT_API
|
||||
#define XESS_API __declspec(dllexport)
|
||||
#else
|
||||
#define XESS_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define XESS_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define XESS_API
|
||||
#endif
|
||||
|
||||
#if !defined _MSC_VER || (_MSC_VER >= 1929)
|
||||
#define XESS_PRAGMA(x) _Pragma(#x)
|
||||
#else
|
||||
#define XESS_PRAGMA(x) __pragma(x)
|
||||
#endif
|
||||
#define XESS_PACK_B_X(x) XESS_PRAGMA(pack(push, x))
|
||||
#define XESS_PACK_E() XESS_PRAGMA(pack(pop))
|
||||
#define XESS_PACK_B() XESS_PACK_B_X(8)
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct _xess_context_handle_t* xess_context_handle_t;
|
||||
|
||||
XESS_PACK_B()
|
||||
/**
|
||||
* @brief XeSS version.
|
||||
*
|
||||
* XeSS uses major.minor.patch version format and Numeric 90+ scheme for development stage builds.
|
||||
*/
|
||||
typedef struct _xess_version_t
|
||||
{
|
||||
/** A major version increment indicates a new API and potentially a
|
||||
* break in functionality. */
|
||||
uint16_t major;
|
||||
/** A minor version increment indicates incremental changes such as
|
||||
* optional inputs or flags. This does not break existing functionality. */
|
||||
uint16_t minor;
|
||||
/** A patch version increment may include performance or quality tweaks or fixes for known issues.
|
||||
* There's no change in the interfaces.
|
||||
* Versions beyond 90 used for development builds to change the interface for the next release.
|
||||
*/
|
||||
uint16_t patch;
|
||||
/** Reserved for future use. */
|
||||
uint16_t reserved;
|
||||
} xess_version_t;
|
||||
XESS_PACK_E()
|
||||
|
||||
XESS_PACK_B()
|
||||
/**
|
||||
* @brief 2D variable.
|
||||
*/
|
||||
typedef struct _xess_2d_t
|
||||
{
|
||||
uint32_t x;
|
||||
uint32_t y;
|
||||
} xess_2d_t;
|
||||
XESS_PACK_E()
|
||||
|
||||
/**
|
||||
* @brief 2D coordinates.
|
||||
*/
|
||||
typedef xess_2d_t xess_coord_t;
|
||||
|
||||
/**
|
||||
* @brief XeSS quality settings.
|
||||
*/
|
||||
typedef enum _xess_quality_settings_t
|
||||
{
|
||||
XESS_QUALITY_SETTING_ULTRA_PERFORMANCE = 100,
|
||||
XESS_QUALITY_SETTING_PERFORMANCE = 101,
|
||||
XESS_QUALITY_SETTING_BALANCED = 102,
|
||||
XESS_QUALITY_SETTING_QUALITY = 103,
|
||||
XESS_QUALITY_SETTING_ULTRA_QUALITY = 104,
|
||||
XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS = 105,
|
||||
XESS_QUALITY_SETTING_AA = 106,
|
||||
} xess_quality_settings_t;
|
||||
|
||||
/**
|
||||
* @brief XeSS initialization flags.
|
||||
*/
|
||||
typedef enum _xess_init_flags_t
|
||||
{
|
||||
XESS_INIT_FLAG_NONE = 0,
|
||||
/** Use motion vectors at target resolution. */
|
||||
XESS_INIT_FLAG_HIGH_RES_MV = 1 << 0,
|
||||
/** Use inverted (increased precision) depth encoding */
|
||||
XESS_INIT_FLAG_INVERTED_DEPTH = 1 << 1,
|
||||
/** Use exposure texture to scale input color. */
|
||||
XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE = 1 << 2,
|
||||
/** Use responsive pixel mask texture. */
|
||||
XESS_INIT_FLAG_RESPONSIVE_PIXEL_MASK = 1 << 3,
|
||||
/** Use velocity in NDC */
|
||||
XESS_INIT_FLAG_USE_NDC_VELOCITY = 1 << 4,
|
||||
/** Use external descriptor heap */
|
||||
XESS_INIT_FLAG_EXTERNAL_DESCRIPTOR_HEAP = 1 << 5,
|
||||
/** Disable tonemapping for input and output */
|
||||
XESS_INIT_FLAG_LDR_INPUT_COLOR = 1 << 6,
|
||||
/** Remove jitter from input velocity*/
|
||||
XESS_INIT_FLAG_JITTERED_MV = 1 << 7,
|
||||
/** Enable automatic exposure calculation. */
|
||||
XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE = 1 << 8
|
||||
} xess_init_flags_t;
|
||||
|
||||
XESS_PACK_B()
|
||||
/**
|
||||
* @brief Properties for internal XeSS resources.
|
||||
*/
|
||||
typedef struct _xess_properties_t
|
||||
{
|
||||
/** Required amount of descriptors for XeSS */
|
||||
uint32_t requiredDescriptorCount;
|
||||
/** The heap size required by XeSS for temporary buffer storage. */
|
||||
uint64_t tempBufferHeapSize;
|
||||
/** The heap size required by XeSS for temporary texture storage. */
|
||||
uint64_t tempTextureHeapSize;
|
||||
} xess_properties_t;
|
||||
XESS_PACK_E()
|
||||
|
||||
/**
|
||||
* @brief XeSS return codes.
|
||||
*/
|
||||
typedef enum _xess_result_t
|
||||
{
|
||||
/** Warning. Folder to store dump data doesn't exist. Write operation skipped.*/
|
||||
XESS_RESULT_WARNING_NONEXISTING_FOLDER = 1,
|
||||
/** An old or outdated driver. */
|
||||
XESS_RESULT_WARNING_OLD_DRIVER = 2,
|
||||
/** XeSS operation was successful. */
|
||||
XESS_RESULT_SUCCESS = 0,
|
||||
/** XeSS not supported on the GPU. An SM 6.4 capable GPU is required. */
|
||||
XESS_RESULT_ERROR_UNSUPPORTED_DEVICE = -1,
|
||||
/** An unsupported driver. */
|
||||
XESS_RESULT_ERROR_UNSUPPORTED_DRIVER = -2,
|
||||
/** Execute called without initialization. */
|
||||
XESS_RESULT_ERROR_UNINITIALIZED = -3,
|
||||
/** Invalid argument such as descriptor handles. */
|
||||
XESS_RESULT_ERROR_INVALID_ARGUMENT = -4,
|
||||
/** Not enough available GPU memory. */
|
||||
XESS_RESULT_ERROR_DEVICE_OUT_OF_MEMORY = -5,
|
||||
/** Device function failed, such as resource or descriptor creation. */
|
||||
XESS_RESULT_ERROR_DEVICE = -6,
|
||||
/** The function is not implemented */
|
||||
XESS_RESULT_ERROR_NOT_IMPLEMENTED = -7,
|
||||
/** Invalid context. */
|
||||
XESS_RESULT_ERROR_INVALID_CONTEXT = -8,
|
||||
/** Operation not finished yet. */
|
||||
XESS_RESULT_ERROR_OPERATION_IN_PROGRESS = -9,
|
||||
/** Operation not supported in current configuration. */
|
||||
XESS_RESULT_ERROR_UNSUPPORTED = -10,
|
||||
/** The library cannot be loaded. */
|
||||
XESS_RESULT_ERROR_CANT_LOAD_LIBRARY = -11,
|
||||
/** Call to function done in invalid order. */
|
||||
XESS_RESULT_ERROR_WRONG_CALL_ORDER = -12,
|
||||
|
||||
/** Unknown internal failure */
|
||||
XESS_RESULT_ERROR_UNKNOWN = -1000,
|
||||
} xess_result_t;
|
||||
|
||||
/**
|
||||
* @brief XeSS logging level
|
||||
*/
|
||||
typedef enum _xess_logging_level_t
|
||||
{
|
||||
XESS_LOGGING_LEVEL_DEBUG = 0,
|
||||
XESS_LOGGING_LEVEL_INFO = 1,
|
||||
XESS_LOGGING_LEVEL_WARNING = 2,
|
||||
XESS_LOGGING_LEVEL_ERROR = 3
|
||||
} xess_logging_level_t;
|
||||
|
||||
/**
|
||||
* A logging callback provided by the application. This callback can be called from other threads.
|
||||
* Message pointer is only valid inside function and may be invalid right after return call.
|
||||
* Message is a null-terminated utf-8 string
|
||||
*/
|
||||
typedef void (*xess_app_log_callback_t)(const char *message, xess_logging_level_t loggingLevel);
|
||||
|
||||
#ifndef XESS_TYPES_ONLY
|
||||
|
||||
/** @addtogroup xess XeSS API exports
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Gets the XeSS version. This is baked into the XeSS SDK release.
|
||||
* @param[out] pVersion Returned XeSS version.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetVersion(xess_version_t* pVersion);
|
||||
|
||||
/**
|
||||
* @brief Gets the version of the loaded Intel XeFX library. When running on Intel platforms
|
||||
* this function will return the version of the loaded Intel XeFX library, for other
|
||||
* platforms 0.0.0 will be returned.
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param[out] pVersion Returned Intel XeFX library version.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetIntelXeFXVersion(xess_context_handle_t hContext,
|
||||
xess_version_t* pVersion);
|
||||
|
||||
/**
|
||||
* @brief Gets XeSS internal resources properties.
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param pOutputResolution Output resolution to calculate properties for.
|
||||
* @param[out] pBindingProperties Returned properties.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetProperties(xess_context_handle_t hContext,
|
||||
const xess_2d_t* pOutputResolution, xess_properties_t* pBindingProperties);
|
||||
|
||||
/**
|
||||
* @brief Get the input resolution for a specified output resolution for a given quality setting.
|
||||
* XeSS expects all the input buffers except motion vectors to be in the returned resolution.
|
||||
* Motion vectors can be either in output resolution (XESS_INIT_FLAG_HIGH_RES_MV) or
|
||||
* returned resolution (default).
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param pOutputResolution Output resolution to calculate input resolution for.
|
||||
* @param qualitySettings Desired quality setting.
|
||||
* @param[out] pInputResolution Required input resolution.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetInputResolution(xess_context_handle_t hContext,
|
||||
const xess_2d_t* pOutputResolution, xess_quality_settings_t qualitySettings,
|
||||
xess_2d_t* pInputResolution);
|
||||
|
||||
/**
|
||||
* @brief Get the optimal input resolution and possible range for a specified output resolution for a given quality setting.
|
||||
* XeSS expects all the input buffers except motion vectors to be in the returned resolution range
|
||||
* and all input buffers to be in the same resolution.
|
||||
* Motion vectors can be either in output resolution (XESS_INIT_FLAG_HIGH_RES_MV) or
|
||||
* in the same resolution as other input buffers (by default).
|
||||
*
|
||||
* @note Aspect ratio of the input resolution must be the same as for the output resolution.
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param pOutputResolution Output resolution to calculate input resolution for.
|
||||
* @param qualitySettings Desired quality setting.
|
||||
* @param[out] pInputResolutionOptimal Optimal input resolution.
|
||||
* @param[out] pInputResolutionMin Required minimal input resolution.
|
||||
* @param[out] pInputResolutionMax Required maximal input resolution.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetOptimalInputResolution(xess_context_handle_t hContext,
|
||||
const xess_2d_t* pOutputResolution, xess_quality_settings_t qualitySettings,
|
||||
xess_2d_t* pInputResolutionOptimal, xess_2d_t* pInputResolutionMin, xess_2d_t* pInputResolutionMax);
|
||||
|
||||
/**
|
||||
* @brief Gets jitter scale value.
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param[out] pX Jitter scale pointer for the X axis.
|
||||
* @param[out] pY Jitter scale pointer for the Y axis.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetJitterScale(xess_context_handle_t hContext, float* pX, float* pY);
|
||||
|
||||
/**
|
||||
* @brief Gets velocity scale value.
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param[out] pX Velocity scale pointer for the X axis.
|
||||
* @param[out] pY Velocity scale pointer for the Y axis.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetVelocityScale(xess_context_handle_t hContext, float* pX, float* pY);
|
||||
|
||||
/**
|
||||
* @brief Destroys the XeSS context.
|
||||
* The user must ensure that any pending command lists are completed before destroying the context.
|
||||
* @param hContext: The XeSS context handle.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessDestroyContext(xess_context_handle_t hContext);
|
||||
|
||||
/**
|
||||
* @brief Sets jitter scale value
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param x scale for the X axis
|
||||
* @param y scale for the Y axis
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessSetJitterScale(xess_context_handle_t hContext, float x, float y);
|
||||
|
||||
/**
|
||||
* @brief Sets velocity scale value
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param x scale for the X axis
|
||||
* @param y scale for the Y axis
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessSetVelocityScale(xess_context_handle_t hContext, float x, float y);
|
||||
|
||||
/**
|
||||
* @brief Sets exposure scale value
|
||||
*
|
||||
* This value will be applied on top of any passed exposure value or automatically calculated exposure.
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param scale scale value.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessSetExposureMultiplier(xess_context_handle_t hContext, float scale);
|
||||
|
||||
/**
|
||||
* @brief Gets exposure scale value
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param[out] pScale Exposure scale pointer.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetExposureMultiplier(xess_context_handle_t hContext, float *pScale);
|
||||
|
||||
/**
|
||||
* @brief Sets maximum value for responsive mask
|
||||
*
|
||||
* This value used to clip responsive mask values. Final responsive mask value calculated as
|
||||
* clip(responsive_mask, 0.0, max_value). Value must be within range [0.0; 1.0]
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param value maximum clip value.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessSetMaxResponsiveMaskValue(xess_context_handle_t hContext, float value);
|
||||
|
||||
/**
|
||||
* @brief Gets maximum value for responsive mask
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param[out] pValue maximum clip value pointer.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetMaxResponsiveMaskValue(xess_context_handle_t hContext, float *pValue);
|
||||
|
||||
/**
|
||||
* @brief Sets logging callback
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param loggingLevel Minimum logging level for logging callback.
|
||||
* @param loggingCallback Logging callback
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessSetLoggingCallback(xess_context_handle_t hContext,
|
||||
xess_logging_level_t loggingLevel, xess_app_log_callback_t loggingCallback);
|
||||
|
||||
/**
|
||||
* @brief Indicates if the installed driver supports best XeSS experience.
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @return xessIsOptimalDriver returns XESS_RESULT_SUCCESS, or XESS_RESULT_WARNING_OLD_DRIVER
|
||||
* if installed driver may result in degraded performance or visual quality.
|
||||
* xessD3D12CreateContext(..) will return XESS_RESULT_ERROR_UNSUPPORTED_DRIVER if driver does
|
||||
* not support XeSS at all.
|
||||
*/
|
||||
XESS_API xess_result_t xessIsOptimalDriver(xess_context_handle_t hContext);
|
||||
|
||||
/**
|
||||
* @brief Forces usage of legacy (pre 1.3.0) scale factors
|
||||
*
|
||||
* Following scale factors will be applied:
|
||||
* @li XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: 3.0
|
||||
* @li XESS_QUALITY_SETTING_PERFORMANCE: 2.0
|
||||
* @li XESS_QUALITY_SETTING_BALANCED: 1.7
|
||||
* @li XESS_QUALITY_SETTING_QUALITY: 1.5
|
||||
* @li XESS_QUALITY_SETTING_ULTRA_QUALITY: 1.3
|
||||
* @li XESS_QUALITY_SETTING_AA: 1.0
|
||||
* In order to apply new scale factors application should call xessGetOptimalInputResolution and
|
||||
* initialization function (xess*Init)
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param force if set to true legacy scale factors will be forced, if set to false - scale factors
|
||||
* will be selected by XeSS
|
||||
*
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessForceLegacyScaleFactors(xess_context_handle_t hContext, bool force);
|
||||
|
||||
/**
|
||||
* @brief Returns current state of pipeline build
|
||||
* This function can only be called after xess*BuildPipelines and
|
||||
* before corresponding xess*Init.
|
||||
* This call returns XESS_RESULT_SUCCESS if pipelines already built, and
|
||||
* XESS_RESULT_ERROR_OPERATION_IN_PROGRESS if pipeline build is in progress.
|
||||
* If function called before @ref xess*BuildPipelines or after @ref xess*Init -
|
||||
* XESS_RESULT_ERROR_WRONG_CALL_ORDER will be returned.
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @return XESS_RESULT_SUCCESS if pipelines already built.
|
||||
* XESS_RESULT_ERROR_OPERATION_IN_PROGRESS if pipeline build is in progress.
|
||||
* XESS_RESULT_ERROR_WRONG_CALL_ORDER if the function is called out of order.
|
||||
*/
|
||||
XESS_API xess_result_t xessGetPipelineBuildStatus(xess_context_handle_t hContext);
|
||||
|
||||
/** @}*/
|
||||
|
||||
#endif
|
||||
|
||||
// Enum size checks. All enums must be 4 bytes
|
||||
typedef char sizecheck__LINE__[ (sizeof(xess_quality_settings_t) == 4) ? 1 : -1];
|
||||
typedef char sizecheck__LINE__[ (sizeof(xess_init_flags_t) == 4) ? 1 : -1];
|
||||
typedef char sizecheck__LINE__[ (sizeof(xess_result_t) == 4) ? 1 : -1];
|
||||
typedef char sizecheck__LINE__[ (sizeof(xess_logging_level_t) == 4) ? 1 : -1];
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
253
third_party/xess/inc/xess/xess_vk.h
vendored
Normal file
253
third_party/xess/inc/xess/xess_vk.h
vendored
Normal file
@@ -0,0 +1,253 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2026 Intel Corporation
|
||||
*
|
||||
* SPDX-License-Identifier: MIT
|
||||
******************************************************************************/
|
||||
|
||||
#ifndef XESS_VK_H
|
||||
#define XESS_VK_H
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include "xess.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
XESS_PACK_B()
|
||||
|
||||
typedef struct _xess_vk_image_view_info
|
||||
{
|
||||
VkImageView imageView;
|
||||
VkImage image;
|
||||
VkImageSubresourceRange subresourceRange;
|
||||
VkFormat format;
|
||||
unsigned int width;
|
||||
unsigned int height;
|
||||
} xess_vk_image_view_info;
|
||||
|
||||
XESS_PACK_E()
|
||||
|
||||
XESS_PACK_B()
|
||||
/**
|
||||
* @brief Execution parameters for XeSS Vulkan.
|
||||
*/
|
||||
typedef struct _xess_vk_execute_params_t
|
||||
{
|
||||
/** Input color texture. Must be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state.*/
|
||||
xess_vk_image_view_info colorTexture;
|
||||
/** Input motion vector texture. Must be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state.*/
|
||||
xess_vk_image_view_info velocityTexture;
|
||||
/** Optional depth texture. Required if XESS_INIT_FLAG_HIGH_RES_MV has not been specified.
|
||||
* Must be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state.*/
|
||||
xess_vk_image_view_info depthTexture;
|
||||
/** Optional 1x1 exposure scale texture. Required if XESS_INIT_FLAG_EXPOSURE_TEXTURE has been
|
||||
* specified. Must be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state */
|
||||
xess_vk_image_view_info exposureScaleTexture;
|
||||
/** Optional responsive pixel mask texture. Required if XESS_INIT_FLAG_RESPONSIVE_PIXEL_MASK
|
||||
* has been specified. Must be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state */
|
||||
xess_vk_image_view_info responsivePixelMaskTexture;
|
||||
/** Output texture in target resolution. Must be in VK_IMAGE_LAYOUT_GENERAL state.*/
|
||||
xess_vk_image_view_info outputTexture;
|
||||
|
||||
/** Jitter X coordinate in the range [-0.5, 0.5]. */
|
||||
float jitterOffsetX;
|
||||
/** Jitter Y coordinate in the range [-0.5, 0.5]. */
|
||||
float jitterOffsetY;
|
||||
/** Optional input color scaling. Default is 1. */
|
||||
float exposureScale;
|
||||
/** Resets the history accumulation in this frame. */
|
||||
uint32_t resetHistory;
|
||||
/** Input color width. */
|
||||
uint32_t inputWidth;
|
||||
/** Input color height. */
|
||||
uint32_t inputHeight;
|
||||
/** Base coordinate for the input color in the texture. Default is (0,0). */
|
||||
xess_coord_t inputColorBase;
|
||||
/** Base coordinate for the input motion vector in the texture. Default is (0,0). */
|
||||
xess_coord_t inputMotionVectorBase;
|
||||
/** Base coordinate for the input depth in the texture. Default is (0,0). */
|
||||
xess_coord_t inputDepthBase;
|
||||
/** Base coordinate for the input responsive pixel mask in the texture. Default is (0,0). */
|
||||
xess_coord_t inputResponsiveMaskBase;
|
||||
/** Reserved parameter. */
|
||||
xess_coord_t reserved0;
|
||||
/** Base coordinate for the output color. Default is (0,0). */
|
||||
xess_coord_t outputColorBase;
|
||||
} xess_vk_execute_params_t;
|
||||
XESS_PACK_E()
|
||||
|
||||
XESS_PACK_B()
|
||||
/**
|
||||
* @brief Initialization parameters for XeSS VK.
|
||||
*/
|
||||
typedef struct _xess_vk_init_params_t
|
||||
{
|
||||
/** Output width and height. */
|
||||
xess_2d_t outputResolution;
|
||||
/** Quality setting */
|
||||
xess_quality_settings_t qualitySetting;
|
||||
/** Initialization flags. */
|
||||
uint32_t initFlags;
|
||||
/** Specifies the node mask for internally created resources on
|
||||
* multi-adapter systems. */
|
||||
uint32_t creationNodeMask;
|
||||
/** Specifies the node visibility mask for internally created resources
|
||||
* on multi-adapter systems. */
|
||||
uint32_t visibleNodeMask;
|
||||
/** Optional externally allocated buffer memory for XeSS. If VK_NULL_HANDLE the
|
||||
* memory is allocated internally. If provided, the memory must be allocated from
|
||||
* memory type that supports allocating buffers. The memory type should be DEVICE_LOCAL.
|
||||
* This memory is not accessed by the CPU. */
|
||||
VkDeviceMemory tempBufferHeap;
|
||||
/** Offset in the externally allocated memory for temporary buffer storage. */
|
||||
uint64_t bufferHeapOffset;
|
||||
/** Optional externally allocated texture memory for XeSS. If VK_NULL_HANDLE the
|
||||
* memory is allocated internally. If provided, the memory must be allocated from
|
||||
* memory type that supports allocating textures. The memory type should be DEVICE_LOCAL.
|
||||
* This memory is not accessed by the CPU. */
|
||||
VkDeviceMemory tempTextureHeap;
|
||||
/** Offset in the externally allocated memory for temporary texture storage. */
|
||||
uint64_t textureHeapOffset;
|
||||
/** Optional pipeline cache. If not VK_NULL_HANDLE will be used for pipeline creation. */
|
||||
VkPipelineCache pipelineCache;
|
||||
} xess_vk_init_params_t;
|
||||
XESS_PACK_E()
|
||||
|
||||
/** @addtogroup xess-vulkan XeSS VK API exports
|
||||
* @{
|
||||
*/
|
||||
/**
|
||||
* @brief Get required extensions for Vulkan instance that would run XeSS.
|
||||
* This function must be called to get instance extensions need by XeSS. These
|
||||
* extensions must be enabled in subsequent vkCreateInstance call, that would create a VkInstance
|
||||
* object to be passed to @ref xessVKCreateContext
|
||||
* @param[out] instanceExtensionsCount returns a count of instance extensions to be enabled in Vulkan instance
|
||||
* @param[out] instanceExtensions returns a pointer to an array of \p instanceExtensionsCount required extension names.
|
||||
* The memory used by the array is owned by the XeSS library and should not be freed by the application.
|
||||
* @param[out] minVkApiVersion The Vulkan API version that XeSS would use. When calling vkCreateInstance, the application
|
||||
* should set VkApplicationInfo.apiVersion to value greater or equal to \p minVkApiVersion
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKGetRequiredInstanceExtensions(uint32_t* instanceExtensionsCount, const char* const** instanceExtensions, uint32_t* minVkApiVersion);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get required extensions for Vulkan device that would run XeSS.
|
||||
* This function must be called to get device extensions need by XeSS. These
|
||||
* extensions must be enabled in subsequent vkCreateDevice call, that would create a VkDevice
|
||||
* object to be passed to @ref xessVKCreateContext
|
||||
* @param instance A VkInstance object created by the user
|
||||
* @param physicalDevice A VkPhysicalDevice selected by the user from instance
|
||||
* @param[out] deviceExtensionsCount returns a count of device extensions to be enabled in Vulkan device
|
||||
* @param[out] deviceExtensions returns a pointer to an array of \p deviceExtensionsCount required extension names
|
||||
* The memory used by the array is owned by the XeSS library and should not be freed by the application.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKGetRequiredDeviceExtensions(VkInstance instance, VkPhysicalDevice physicalDevice,
|
||||
uint32_t* deviceExtensionsCount, const char* const** deviceExtensions);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get required features for Vulkan device that would run XeSS.
|
||||
* This function must be called to get device features need by XeSS. These
|
||||
* features must be enabled in subsequent vkCreateDevice call, that would create a VkDevice
|
||||
* object to be passed to @ref xessVKCreateContext.
|
||||
* @param instance A VkInstance object created by the user
|
||||
* @param physicalDevice A VkPhysicalDevice selected by the user from instance
|
||||
* @param[out] features a pointer to writable chain of feature structures, that this function would patch
|
||||
* with required features, by filling required fields and attaching new structures to the chain if needed.
|
||||
* The returned pointer should be passed to vkCreateDevice as pNext chain of VkDeviceCreateInfo structure.
|
||||
* If null is passed, than the function constructs a new structure chain that should be merged
|
||||
* into the chain that application would use with VkDeviceCreateInfo, with application responsibility to
|
||||
* avoid any duplicates with its own structures.
|
||||
*
|
||||
* It is an error to chain VkDeviceCreateInfo structure with not null pEnabledFeatures field, as this field is const
|
||||
* and cannot be patched by this function. VkPhysicalDeviceFeatures2 structure should be used instead.
|
||||
*
|
||||
* The memory used by the structures added by this funtion to the chain is owned by the XeSS library and
|
||||
* should not be freed by the application.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKGetRequiredDeviceFeatures(VkInstance instance, VkPhysicalDevice physicalDevice, void** features);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Create an XeSS VK context.
|
||||
* @param instance A VkInstance object created by the user
|
||||
* @param physicalDevice A VkPhysicalDevice selected by the user from instance
|
||||
* @param device A VK device created by the user from physicalDevice
|
||||
* @param[out] phContext Returned xess context handle.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKCreateContext(VkInstance instance, VkPhysicalDevice physicalDevice, VkDevice device,
|
||||
xess_context_handle_t* phContext);
|
||||
|
||||
/**
|
||||
* @brief Initiates pipeline build process
|
||||
* This function can only be called between @ref xessVKCreateContext and
|
||||
* @ref xessVKInit
|
||||
* This call initiates build of Vulkan pipelines and kernel compilation
|
||||
* This call can be blocking (if @p blocking set to true) or non-blocking.
|
||||
* In case of non-blocking call library will wait for pipeline build on call to
|
||||
* @ref xessVKInit
|
||||
* If @p pipelineCache passed to this call - same pipeline library must be passed
|
||||
* to @ref xessVKInit
|
||||
*
|
||||
* @param hContext The XeSS context handle.
|
||||
* @param pipelineCache Optional pointer to pipeline library for pipeline caching.
|
||||
* @param blocking Wait for kernel compilation and pipeline creation to finish or not
|
||||
* @param initFlags Initialization flags. *Must* be identical to flags passed to @ref xessVKInit
|
||||
*/
|
||||
XESS_API xess_result_t xessVKBuildPipelines(xess_context_handle_t hContext,
|
||||
VkPipelineCache pipelineCache, bool blocking, uint32_t initFlags);
|
||||
|
||||
/**
|
||||
* @brief Initialize XeSS VK.
|
||||
* This is a blocking call that initializes XeSS and triggers internal
|
||||
* resources allocation and JIT for the XeSS kernels. The user must ensure that
|
||||
* any pending command lists are completed before re-initialization. When
|
||||
* During initialization, XeSS can create staging buffers and copy queues to
|
||||
* upload internal data. These will be destroyed at the end of initialization.
|
||||
*
|
||||
* @note XeSS supports devices starting from VK_RESOURCE_HEAP_TIER_1, which means
|
||||
* that buffers and textures can not live in the same resource heap.
|
||||
*
|
||||
* @param hContext: The XeSS context handle.
|
||||
* @param pInitParams: Initialization parameters.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKInit(
|
||||
xess_context_handle_t hContext, const xess_vk_init_params_t* pInitParams);
|
||||
|
||||
/**
|
||||
* @brief Get XeSS VK initialization parameters.
|
||||
*
|
||||
* @note This function will return @ref XESS_RESULT_ERROR_UNINITIALIZED if @ref xessVKInit has not been called.
|
||||
*
|
||||
* @param hContext: The XeSS context handle.
|
||||
* @param[out] pInitParams: Returned initialization parameters.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
XESS_API xess_result_t xessVKGetInitParams(
|
||||
xess_context_handle_t hContext, xess_vk_init_params_t* pInitParams);
|
||||
|
||||
/**
|
||||
* @brief Record XeSS upscaling commands into the command list.
|
||||
* @param hContext: The XeSS context handle.
|
||||
* @param commandBuffer: The command buffer for XeSS commands.
|
||||
* @param pExecParams: Execution parameters.
|
||||
* @return XeSS return status code.
|
||||
*/
|
||||
|
||||
XESS_API xess_result_t xessVKExecute(xess_context_handle_t hContext,
|
||||
VkCommandBuffer commandBuffer, const xess_vk_execute_params_t* pExecParams);
|
||||
/** @}*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#endif // XESS_VK_H
|
||||
Reference in New Issue
Block a user