Compare commits

...

30 Commits

Author SHA1 Message Date
bicarus ebda16beae rb: update reflec beat to use new timer (#692)
## Link to GitHub Issue or related Pull Request, if one exists
Continuation of #682

## Description of change
RB uses SleepEx, so it was missed during the search while working on
#682.

## Testing
Plays about the same on a 200Hz touch monitor.
2026-05-10 19:47:33 -07:00
bicarus c29a26f183 graphics: hide subscreen window from task bar and alt+tab list when in full screen (#690)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
When booting in fullscreen, hide the subscreen from the alt+tab list and
from the task bar. Alt-tabbing to it does nothing, so this is just to
avoid confusion.

No change to windowed mode.

## Testing
Tested TDJ/SDVX/Popn. Didn't test Gitadora but it's probably fine..
2026-05-10 05:33:18 -07:00
bicarus 2014e9cf75 graphics: option to change monitor resolution (#689)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Add a new option under `Monitor` group to change the monitor resolution
before booting the game, very similar to how orientation / refresh rate
options work.

This would be useful for games like Polaris Chord that boots at current
resolution but manages to have graphical issues when not in 1080p.

## Testing
2026-05-09 21:32:43 -07:00
bicarus 33f2e1d4b7 rawinput, touch: attempt to remove touchscreens injecting mouse events (#687)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #562

## Description of change

### rawinput touch fixes
In rawinput touch handler, if the mouse events (`WM_LBUTTONDOWN`,
`WM_MOUSEMOVE`, `WM_LBUTTONUP`) originated from a touch screen, drop
them on the floor instead of treating them as touch events.

This is an attempt to fix phantom touch issues we see with some screens.

Fix another issue where, if mouse is clicked inside the window, and then
dragged outside the window and button is released, touch point (id 0)
continues to be held.

### wintouchemu fixes
If we detected a touch input recently (500ms), ignore new mouse clicks.
This isn't perfect, but hopefully it helps with filtering out mouse
clicks originating from touch screens.

Also, switch over to detecting the primary mouse button correctly, not
just the left mouse button.

### notes

Future investigation: are there really touchscreens that report a mouse
HID capability & insert mouse events? We could have a way to filter them
at rawinput level but it'll be ugly.

## Testing
Tried jubeat, beatstream..
2026-05-09 17:52:43 -07:00
bicarus eb037542b4 jubeat: introduce new algorithm for touch (#686)
## Description of change
There was enough feedback that the current algorithm is not ideal for
most touch screens because most touch screens are not 24". In the
current algorithm touching the gap is no-op, so people think the game is
dropping touches.

This PR introduces a new algorithm that inspect touches on the gap and
triggers the nearest square.

## Testing
Tested landscape and portrait jubeat.
2026-05-09 04:22:29 -07:00
bicarus 039b42ad53 fix build (#684) 2026-05-08 22:46:29 -07:00
bicarus 33b4718744 overlay: fix mouse events queued up while overlay is hidden (#683)
## Link to GitHub Issue or related Pull Request, if one exists
continuation of #677

## Description of change
When overlay was hidden, when mouse buttons were clicked, they were
queued up and replayed when overlay became visible again.

This is due to improper usage of `GetAsyncKeyState`, per documentation.

## Testing
2026-05-08 03:37:46 -07:00
bicarus 71ba9b6b47 os: implement win10 high-resolution timer as replacement for Sleep() / sleep_for() (#682)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #681 

## Description of change
`Sleep` and `sleep_for()` can be very inaccurate and varies depending on
what the OS gives us...

### `timeBeginPeriod(1)`
On boot, we are now calling `timeBeginPeriod(1)`, which affects the
whole process but makes `Sleep` more accurate. There is some risk here
if any game was relying on doing things like `Sleep(1)` and expecting it
to run for 15.6ms. Most games already call `timeBeginPeriod(1)` in the
game engine, though not the whole time, so I'm hoping that this is not
too impactful.

### Opt out of Win11 power throttling
Ensure that timer resolution change above is respected even when the
window is occluded / minimized by opting out of throttling via
`PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION`.

### Use Win10 high resolution timer instead of Sleep

On Win10 1803 and above, there is a new OS-level API for high resolution
timers; if this is available, use it
(`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`). Worth noting that WINE
doesn't support this currently.

If not, fall back to `Sleep`, which is significantly better than
`sleep_for()` in my experiments.

Callers of Sleep / sleep_for were replaced with this new timer. Most of
them anyway; calls to Sleep() with more than 100ms+ was left alone.

### Add an option as a chicken bit

To opt out I'm adding a new option called `Use Legacy Timers` which will
revert to behavior before this PR. The code paths that switched from
`sleep_for` to `Sleep` will remain in place though, not affected by the
option.

## Expected changes
In some I/O emulation modules, poll threads may run more frequently,
resulting in lower latency.

It also means that spice overall may use more CPU resources and power.
If you don't like this, you can always enable the option to opt out;
e.g., if you're on old arcade cab PC.

## Testing

DDR p4io - ok
drs touch hook - ok
IIDX camera hook - ok
CCJ trackball - ok
2026-05-08 02:25:20 -07:00
bicarus 1957917270 sdk: update cpp sample for DDR, fix DDR MDXF polling when api/sdk is providing input (#679)
## Link to GitHub Issue or related Pull Request, if one exists
#676 
#452 

## Description of change

When spice SDK or API sets or clears button and analog override, we
don't tell MDXF about it, so it may fall behind. This is a special case
for DDR MDXF I/O emulation. For Naive/Xinput I think we are getting
lucky because they usually also generate WM_INPUT events.

Update the C++ SDK sample to provide more interesting example of
emulating DDR arrows with the keyboard.

## Testing
2026-05-07 18:10:14 -07:00
bicarus b9ccddf47d launcher: prevent early hook from launching in standalone configurator (#678)
## Description of change
Seems to be an oversight when it was initially implemented; hooks should
not load when launching `spicecfg` (or `spice -cfg` or `spice64 -cfg`).
2026-05-07 00:26:18 -07:00
bicarus cd0ba51b5a sdk: introduce Spice SDK (#676)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Adds a flat-C, headers-only library for writing DLL plugins with spice.

This is meant to be an alternative to writing applications over spice
API which doesn't suit some scenarios like writing custom
high-performance I/O modules.

All you have to do is:

1. Create a 32-bit or 64-bit DLL with `spice_sdk_entry_point` as a
DLLExport
1. Include `spicesdk.h`, and optionally `spicesdk_io.h` (see
`extras\sdk\include`)
1. `spice_sdk_entry_point` will be called when hooks get initialized.
Call `init` with valid parameters.
1. When `init` returns, `SPICE_SDK_V0` will be filled out with a series
of function pointers; your DLL can now start calling into it.
1. Compile your DLL and add it as a DLL hook (`-k`) in spice when
launching the game.

See `v0_cpp.cpp` for an example.

V0 implements the following functions:

```
    log;

    get_game_info;
    get_avs_info;

    get_button;
    set_button;

    get_analog;
    set_analog;

    get_light;
    set_light;

    set_touch;
    clear_touch;

    insert_card;
    set_keypad;
```

V0 is focused on providing common utility functions needed in a lot of
DLL hooks (get AVS info, log messages to file), and implementing I/O.

In the future, we could have more interesting things like:

* scanning and modifying memory 
* installing DLL hooks
* having direct hooks into I/O emulation modules
* getting full tape LEDs
* having a callback into DX9 `Present` call
* drawing an ImGui window

More detailed documentation is coming soon in form of a wiki page.

## Testing
See included sample DLL.
2026-05-06 23:29:52 -07:00
bicarus 1f23d88c7a overlay: prevent overlay from queueing up keyboard input while overlay is not visible (#677)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #675

Yet another regression from #604 

## Description of change
When overlay was hidden (not visible) it was still accepting keyboard
input, so when it became visible again the queued up keystrokes got
processed all at once.

Also, fix a bug with monitor settings update kicking in when in windowed
mode - this really should have been only for full screen.

## Testing
Tested DDR windowed / full screen, TDJ with subscreen overlay windowed /
fullscreen.
2026-05-06 01:00:52 -07:00
bicarus-dev 46e43ab09c fix typo 2026-05-04 23:57:35 -07:00
bicarus 96950b6b4e rawinput: reimplement analog relative mode and delay (#674)
## Link to GitHub Issue or related Pull Request, if one exists
#181 

## Description of change
Implement analog relative mode and delay option using a new
millisecond-based algorithm.

## Testing
WIP
2026-05-04 22:50:11 -07:00
bicarus 5f94ef4478 overlay: fix scroll bar jumping around when regaining focus (#673)
## Link to GitHub Issue or related Pull Request, if one exists
Regression caused by #604, probably

## Description of change
When spicecfg or the game loses focus and regains it, scroll bar jumps
around. This was because we weren't keeping proper track of mouse wheel
position while not in focus, so when we gain it back, it's as if the
scroll bar was moved a huge distance.

## Testing
Tested spicecfg and in overlay.
2026-05-03 03:49:52 -07:00
bicarus c4193eddc5 iidx: millisecond-based delay option (#672)
## Link to GitHub Issue or related Pull Request, if one exists
#181 

## Description of change
Use millisecond-based calculation to add artificial delay to the TT
input.

## Testing
Tested 64 bit TDJ and LDJ.
2026-05-03 01:23:45 -07:00
bicarus c8962a0e77 overlay: setting button as always-on (#671)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change

Add a checkbox to the buttons edit dialog that lets you set a device as
"always on", accomplished by setting the device to `Naive`, vkey to
`0xff` (invalid), and `Invert`.

No backend rawinput changes.

## Testing
2026-05-02 22:42:36 -07:00
din b6a749e5db add snek to lights match map (#670)
## Description of change
add snek board to lights mapping

## Testing
with a snek board


<img width="490" height="477"
alt="DeepinScreenshot_select-area_20260502164249"
src="https://github.com/user-attachments/assets/a86affff-74c6-4d5d-b657-fab12c40aaa4"
/>
2026-05-02 15:49:19 -07:00
bicarus-dev 7dbbe9809e update iidx tt delay option text 2026-05-02 02:50:29 -07:00
bicarus 79a3e32d5d iidx: delay logic for iidx tt (#669)
## Link to GitHub Issue or related Pull Request, if one exists
Re-implements fix for #181 as it was removed by #668

## Description of change
Add two options to add artificial delay to turntable input. These
operate directly on the input logic (`get_tt`) which is called by I/O
emulation code.

Functionally, it's **identical** to the `Delay (experimental)` option we
had in the analog tab, just moved to Options tab.

## Testing
64 bit tdj: ok
64 bit ldj bi2a: ok
32 bit ldj ezusb: ok

Worth noting that TDJ bi2x_hook polls at 120Hz, bi2a at ~500Hz, and
ezusb at ~170Hz
2026-05-02 02:17:51 -07:00
bicarus c5a4e954f9 rawinput: remove experimental analog features (delay and relative axis mode) (#668)
## Link to GitHub Issue or related Pull Request, if one exists
Related to #181 

## Description of change
This PR removes two features marked as "experimental" for analog axis -
`Delay` and `Relative Axis`.

They have been in spice as experimental option for almost 2 years.. but
they have a fundamental problem of being tied to how often the analog is
polled. Not just how often the game's I/O emulation code polls it, but
literally any source (spice API, overlay, etc).

For `Delay`, the only real usage I'm aware of is for #181 which is
delaying IIDX turntable input. For this, I will follow up with a
separate PR that adds back the delay option specifically for IIDX.

For `Relative Axis` - I'm not quite sure if any one actually uses this.
This could be implemented per-game if some game demands it. Polaris
Chord already has one, for example.

## Testing
2026-05-02 00:51:21 -07:00
bicarus 7b862768b0 overlay: show name of analog control in popup title (#667) 2026-05-02 00:01:33 -07:00
bicarus af8d8dae9f rawinput: distinguish between circular and linear analog input (#665)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Currently, all analogs are treated as circular values that wrap around.
This works for knobs and turntables, but can get weird for linear values
(like tilt sensors and sliders) especially once analog options are
enabled, such as sensitivity.

This PR groups analogs into 3 buckets: circular, linear (centered), and
linear (positive). Linear types get different algorithms applied to it
when options are set (e.g., sensitivity caps out at 0, 1 instead of
wrapping around).

In linear mode:
* Sensitivity value applies an exponential response curve (power curve)
to the original value.
* Multiplier/divisor serves as a linear cut-off.
* Relative mode works as you expect, but of course, values don't wrap
around.
* Invert and deadzone work as you expect (since they applied to the
controller input anyway)
* Smoothing is removed from the UI and has no effect.
* Delay is unaffected.

Also, fix a small bug with -/+ button not working for analog `Delay`
option.

## Testing
WIP
2026-05-01 19:02:32 -07:00
llm96 d9d5823fdb rawinput: add missing nullptr check (#666)
## Link to GitHub Issue or related Pull Request, if one exists
N/A

## Description of change

Fixes a crash when opening the properties modal on a Naive button bind.


https://github.com/spice2x/spice2x.github.io/blob/82dda3380039bbaa995ee99e2d3effebbcb58082/src/spice2x/overlay/windows/config.cpp#L2081

Binds:
<img width="800" height="600" alt="image"
src="https://github.com/user-attachments/assets/18d1fcfb-085f-4a2b-8fce-36809a4bbb5a"
/>

Stack trace from Debug build:
```
overlay::windows::Config::edit_button_popup(const std::string &, const std::string &, Button *, float, int) config.cpp:2081
overlay::windows::Config::build_button(const std::string &, Button &, Button *, int, int, int) config.cpp:1050
overlay::windows::Config::build_buttons(const std::string &, std::vector<…> *, int, int) config.cpp:718
overlay::windows::Config::build_content() config.cpp:283
overlay::Window::build() window.cpp:96
overlay::SpiceOverlay::new_frame() overlay.cpp:486
graphics_d3d9_on_present(HWND__ *, IDirect3DDevice9 *, IDirect3DDevice9 *) d3d9_backend.cpp:1447
__ZN23WrappedIDirect3DDevice97PresentEPK7tagRECTS2_P6HWND__PK8_RGNDATA@20 d3d9_device.cpp:396
main_implementation(int, char **) launcher.cpp:2453
main launcher.cpp:2671
```

Relevant snippet from error log:
```
[2026/05/01 18:50:17] M:config: tab selection changed from 0 to 1
[2026/05/01 18:50:48] W:signal: exception raised: EXCEPTION_ACCESS_VIOLATION
[2026/05/01 18:50:48] W:troubleshooter: 

/-------------------------- spice2x auto-troubleshooter -----------------------\

  spice2x version: 2026-04-23
  game version: LDJ:J:A:A:2013090900

  the game has crashed
    * share this entire log file with someone for troubleshooting (log.txt)
    * spice will also attempt to create a minidump (minidump.dmp)
        minidump should only be shared with people you trust as it may contain
        sensitive data (PCBID, card ID, etc)

  log level is set to `disable` (either in avs-config.xml or using -loglevel)
      this log file may have omitted important error messages from the game
      if you are troubleshooting crashes or failures, it is recommended that you
      set AVS Log Level (-loglevel) option to `all`

  unsure what to do next?
    * update to the latest version:
        https://github.com/spice2x/spice2x.github.io/releases
    * check the FAQ:
        https://github.com/spice2x/spice2x.github.io/wiki/Known-issues

\------------------------- spice2x auto-troubleshooter ------------------------/

[2026/05/01 18:50:48] I:signal: printing callstack
[2026/05/01 18:50:48] I:stackwalker: 006A7001 (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 0068DF8C (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 0069A7C1 (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 0069B857 (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 0066461F (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 00663B7A (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 0045B548 (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 004FE1CE (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 1008AD13 (bm2dx): (unknown): dll_entry_main
[2026/05/01 18:50:48] I:stackwalker: 100934A7 (bm2dx): (unknown): dll_entry_main
[2026/05/01 18:50:48] I:stackwalker: 10088D24 (bm2dx): (unknown): dll_entry_main
[2026/05/01 18:50:48] I:stackwalker: 0044B8A6 (spice): (unknown): (unknown)
[2026/05/01 18:50:48] I:stackwalker: 77290CB7 (ntdll): (unknown): RtlGetSystemTimeAndBias
[2026/05/01 18:50:53] F:signal: end
[2026/05/01 18:50:53] I:launcher: stopping subsystems
[2026/05/01 18:50:53] I:logger: stop
[2026/05/01 18:50:53] I:audio: stopping
[2026/05/01 18:50:54] I:rawinput: disposing devices
[2026/05/01 18:50:54] I:xinput: destroyed
```

## Testing
Replicated on upstream build from `spice2x-26-04-23-full.zip`
2026-05-01 14:42:45 -07:00
bicarus 82dda33800 graphics: restore monitor settings when fullscreen is lost then restored (#664)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #663 

## Description of change
Apply monitor rotation and refresh rate again when fullscreen focus is
regained.

## Testing
Tested with sdvx7
2026-04-28 16:04:52 -07:00
bicarus 3876e38636 xinput: small fixes (#661)
## Link to GitHub Issue or related Pull Request, if one exists
#616 

## Description of change
Fix UI labels being wrong for analog stick up/down (they were reversed).

Adjust deadzone so that when sticks are bound as digital buttons, they
are not as sensitive.

Small refactoring of code.

## Testing
Tested via spicecfg using my xbox one controller.
2026-04-27 22:19:23 -07:00
bicarus 6bc1357d6a ddr: add support for analog axis-only pads and handle left+right / up+down input (#659)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Some crappy DDR soft mats (either USB-based or console pads with crappy
adapters that lack a dedicated "DDR pad mode") use X and Y analog axis
for arrows, which means they cannot cleanly report Up+Down or Left+Right
input.

According to some ancient Stepmania code, a lot of these report a middle
value (value between center and right, for example, for left+right).
Borrow this hack from Stepmania and implement it in spice as analog
input for DDR.

Also, for rawinput/xinput automatic bind scenario, update the logic so
that face buttons are always detected before analog axis / dpads for
consistency. This would help with binding any DDR pads that
simultaneously input face buttons / dpad / analog axis, so that we can
prefer face buttons when detected.

## Testing
I don't have any soft mats that have this, but it was tested with an
xbox controller.
2026-04-27 20:17:54 -07:00
Will 37218e7fe0 Try and preserve the wideness of std::filesystem::path more (#660)
As noted in #567, a filesystem path that contains non-ascii will break a
lot if using a clang toolchain.

Luckily, fmtlib has a lossy utf8 convert when you use it to print a path
(after including `fmt/std.h`). The vast majority of this diff is just
removing `.string()` from paths inside loggings calls.

There are some callsites I _didn't_ touch, mainly the options, because
it would be an ABI break to change those to be wide strings and I cbf
looking into settings upgrades. There are also some spots (avs mountpath
remapping, for example) where the path is guaranteed to be ascii, so I
didn't modify them.

ImGui doesn't appear to easily support wide strings (I mean, surely it
does, but I'm not gonna look too far into it) so I mostly just left
those alone too, with a few spots modified to re-use fmtlib's lossy
utf8.

Some of the changes are basically never gonna be hit IRL, like who would
put a file with a non-ascii _extension_ along with their modules? But
the diff is (I hope) pretty easy to validate as OK.

Testing has been somewhat minimal, I fired up the GCC build of spice2x
in a dodgy folder name, got mojibake (running via wine in linux so take
that as you will), ran the unmodified clang spice and crashed the same
way the reporter did. After modification, I get the exact same mojibake
so I assume if the terminal enjoys utf8 it'll display OK.

Claude (only used for review) thinks the commit is fine but is annoyed
that I use `fmt::detail` in the appdata censoring, which is part of the
private API; personally I don't care because it's pretty stable.
2026-04-27 20:07:15 -07:00
bicarus 678e11eade rawinput: fix up devices that report invalid max values (#658)
## Link to GitHub Issue or related Pull Request, if one exists
regression caused by #653

## Description of change
Some controllers - like the Xbox One controller I have - reports
0xffffffff as the max range value for analog, despite reporting 16-bit
width. This causes us to consider 0xffffffff as -1 so the range became
[0, -1] which is invalid.

Our automatic calibration does eventually fix this (-1 will fix itself
to become the highest actual value reported, which would be 0xffff).

This seems to be a common issue with XInput-based controllers in
general: see `Correct_Axis_Max` in
https://github.com/argonlefou/DemulShooter/blob/master/DsCore/RawInput/RawInputController.cs

#653 removed the fix that was masking this issue. Put in a new fix that
fixes these up.

## Testing
Tested with Xbox One controller.
2026-04-27 01:41:44 -07:00
bicarus f72313fe45 sdvx: work around bad logger configuration (#657)
## Link to GitHub Issue or related Pull Request, if one exists
#345 

## Description of change
SDVX4 data from certain private forum has bad logger configuration and
crashes on boot. Add an explicit workaround to fix up that broken
`avs-config.xml` file, scoped to `soundvoltex.dll` + 32-bit.

## Testing
Tested HH.
2026-04-23 01:33:49 -07:00
97 changed files with 5166 additions and 827 deletions
+36 -2
View File
@@ -607,6 +607,9 @@ set(SOURCE_FILES ${SOURCE_FILES}
reader/structuredmessage.cpp
reader/crypt.cpp
# sdk
sdk/sdk.cpp
# stubs
stubs/stubs.cpp
@@ -633,6 +636,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
util/time.cpp
util/cpuutils.cpp
util/netutils.cpp
util/precise_timer.cpp
util/sysutils.cpp
util/lz77.cpp
util/tapeled.cpp
@@ -860,6 +864,36 @@ if(NOT MSVC)
set_target_properties(spicetools_stubs_cpusbxpkm PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
endif()
# sdk_sample_v0_flat_c.dll (32 bit)
set(SOURCE_FILES sdk/sample/v0/flat_c/v0_flat_c.c)
add_library(spicetools_sdk_sample_v0_flat_c_32 SHARED ${SOURCE_FILES} ${RESOURCE_FILES} sdk/sample/v0/flat_c/v0_flat_c.def)
set_target_properties(spicetools_sdk_sample_v0_flat_c_32 PROPERTIES PREFIX "")
set_target_properties(spicetools_sdk_sample_v0_flat_c_32 PROPERTIES OUTPUT_NAME "sdk_sample_v0_flat_c")
if(NOT MSVC)
set_target_properties(spicetools_sdk_sample_v0_flat_c_32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
endif()
# sdk_sample_v0_flat_c.dll (64 bit)
set(SOURCE_FILES sdk/sample/v0/flat_c/v0_flat_c.c)
add_library(spicetools_sdk_sample_v0_flat_c_64 SHARED ${SOURCE_FILES} ${RESOURCE_FILES} sdk/sample/v0/flat_c/v0_flat_c.def)
set_target_properties(spicetools_sdk_sample_v0_flat_c_64 PROPERTIES PREFIX "")
set_target_properties(spicetools_sdk_sample_v0_flat_c_64 PROPERTIES OUTPUT_NAME "sdk_sample_v0_flat_c")
if(NOT MSVC)
set_target_properties(spicetools_sdk_sample_v0_flat_c_64 PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-m64")
endif()
# sdk_sample_v0_cpp.dll (64 bit)
set(SOURCE_FILES sdk/sample/v0/cpp/v0_cpp.cpp)
add_library(spicetools_sdk_sample_v0_cpp_64 SHARED ${SOURCE_FILES} ${RESOURCE_FILES} sdk/sample/v0/cpp/v0_cpp.def)
set_target_properties(spicetools_sdk_sample_v0_cpp_64 PROPERTIES PREFIX "")
set_target_properties(spicetools_sdk_sample_v0_cpp_64 PROPERTIES OUTPUT_NAME "sdk_sample_v0_cpp")
if(NOT MSVC)
set_target_properties(spicetools_sdk_sample_v0_cpp_64 PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-m64")
endif()
# output directories
####################
@@ -869,14 +903,14 @@ set_target_properties(spicetools_cfg spicetools_cfg_linux
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/spicetools")
# output 32bit
set_target_properties(spicetools_spice spicetools_spice_laa spicetools_spice_linux spicetools_stubs_kbt spicetools_stubs_kld spicetools_stubs_cpusbxpkm
set_target_properties(spicetools_spice spicetools_spice_laa spicetools_spice_linux spicetools_stubs_kbt spicetools_stubs_kld spicetools_stubs_cpusbxpkm spicetools_sdk_sample_v0_flat_c_32
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/archive32"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/spicetools/32"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/spicetools/32")
# output 64bit
set_target_properties(spicetools_spice64 spicetools_spice64_linux spicetools_stubs_kbt64 spicetools_stubs_kld64 spicetools_stubs_nvcuda spicetools_stubs_nvcuvid spicetools_stubs_nvEncodeAPI64
set_target_properties(spicetools_spice64 spicetools_spice64_linux spicetools_stubs_kbt64 spicetools_stubs_kld64 spicetools_stubs_nvcuda spicetools_stubs_nvcuvid spicetools_stubs_nvEncodeAPI64 spicetools_sdk_sample_v0_flat_c_64 spicetools_sdk_sample_v0_cpp_64
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/archive64"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/spicetools/64"
+10
View File
@@ -283,6 +283,16 @@ Python is the only one that is fully spec compliant.
Other libraries may be missing features and contain bugs; please feel free to
contribute code to fill the gaps if you work on a project using these libraries.
## Spice SDK (for DLL hooks / plugins)
As an alternative to Spice API, Spice SDK is available.
This is a flat C, header-only library that can be included in your DLL. Once
initialized, you can call directly into helper routines provided by Spicetools
executable, making low-latency and high-throughput interactions possible.
Check the documentation on the wiki for more details.
## License
Unless otherwise noted, all files are licensed under the GPLv3.
See the LICENSE file for the full license text.
+23 -8
View File
@@ -1,13 +1,16 @@
#include "mdxf.h"
#include "mdxf_poll.h"
#include <mutex>
#include "avs/game.h"
#include "games/ddr/ddr.h"
#include "games/ddr/io.h"
#include "launcher/launcher.h"
#include "rawinput/rawinput.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include <mutex>
#define MDFX_DEBUG_VERBOSE 0
@@ -108,9 +111,10 @@ static void mdxf_thread_start() {
MDXF_THREAD = std::thread([] {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
timeutils::PreciseSleepTimer timer;
while (MDXF_THREAD_RUNNING.load(std::memory_order_acquire)) {
mdxf_poll(false);
std::this_thread::sleep_for(THREAD_PERIOD);
timer.sleep(THREAD_PERIOD);
}
});
}
@@ -357,14 +361,17 @@ static bool __cdecl ac_io_mdxf_update_control_status_buffer_impl(int node, MDXFP
// decide on button map
const size_t *button_map = nullptr;
int player = 0;
switch (node) {
case 17:
case 25:
button_map = &buttons_p1[0];
player = 1;
break;
case 18:
case 26:
button_map = &buttons_p2[0];
player = 2;
break;
}
@@ -374,19 +381,27 @@ static bool __cdecl ac_io_mdxf_update_control_status_buffer_impl(int node, MDXFP
if (source == EXTERNAL_POLL) {
// get buttons
auto &buttons = games::ddr::get_buttons();
// get analogs
bool analog_left = false;
bool analog_right = false;
games::ddr::get_analog_x_axis(player, analog_left, analog_right);
bool analog_up = false;
bool analog_down = false;
games::ddr::get_analog_y_axis(player, analog_up, analog_down);
uint8_t up_down = 0;
uint8_t left_right = 0;
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[0]))) {
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[0])) || analog_up) {
up_down |= 0xF0;
}
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[1]))) {
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[1])) || analog_down) {
up_down |= 0x0F;
}
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[2]))) {
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[2])) || analog_left) {
left_right |= 0xF0;
}
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[3]))) {
if (GameAPI::Buttons::getState(RI_MGR, buttons.at(button_map[3])) || analog_right) {
left_right |= 0x0F;
}
current_state = (uint16_t(up_down) << 8) | left_right;
@@ -500,4 +515,4 @@ acio::MDXFModule::~MDXFModule() {
if (IS_THREAD_NEEDED) {
mdxf_thread_stop();
}
}
}
+1
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint>
#include <string>
#include "util/circular_buffer.h"
+3 -1
View File
@@ -5,6 +5,7 @@
#include "games/sdvx/sdvx.h"
#include "misc/eamuse.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
using namespace acioemu;
@@ -46,11 +47,12 @@ ICCADevice::ICCADevice(bool flip_order, bool keypad_thread, uint8_t node_count)
// keypad thread for faster polling
if (keypad_thread) {
this->keypad_thread = new std::thread([this]() {
timeutils::PreciseSleepTimer timer;
while (this->cards) {
for (int unit = 0; unit < this->node_count; unit++) {
this->update_keypad(unit, false);
}
Sleep(7);
timer.sleep(7);
}
});
}
+4
View File
@@ -6,6 +6,7 @@
#include "launcher/launcher.h"
#include "games/io.h"
#include "util/utils.h"
#include "acio/mdxf/mdxf_poll.h"
using namespace std::placeholders;
using namespace rapidjson;
@@ -104,6 +105,7 @@ namespace api::modules {
for (auto &analog : *this->analogs) {
analog.override_enabled = false;
}
mdxf_poll(true);
}
return;
}
@@ -148,6 +150,7 @@ namespace api::modules {
if (analog.getName() == name) {
analog.override_state = CLAMP(state, 0.f, 1.f);
analog.override_enabled = true;
mdxf_poll(true);
return true;
}
}
@@ -167,6 +170,7 @@ namespace api::modules {
for (auto &analog : *this->analogs) {
if (analog.getName() == name) {
analog.override_enabled = false;
mdxf_poll(true);
return true;
}
}
+4
View File
@@ -6,6 +6,7 @@
#include "launcher/launcher.h"
#include "games/io.h"
#include "util/utils.h"
#include "acio/mdxf/mdxf_poll.h"
using namespace std::placeholders;
using namespace rapidjson;
@@ -107,6 +108,7 @@ namespace api::modules {
for (auto &button : *this->buttons) {
button.override_enabled = false;
}
mdxf_poll(true);
}
return;
}
@@ -153,6 +155,7 @@ namespace api::modules {
GameAPI::Buttons::BUTTON_PRESSED : GameAPI::Buttons::BUTTON_NOT_PRESSED;
button.override_velocity = CLAMP(state, 0.f, 1.f);
button.override_enabled = true;
mdxf_poll(true);
return true;
}
}
@@ -172,6 +175,7 @@ namespace api::modules {
for (auto &button : *this->buttons) {
if (button.getName() == name) {
button.override_enabled = false;
mdxf_poll(true);
return true;
}
}
+4 -2
View File
@@ -7,6 +7,7 @@
#include "avs/game.h"
#include "external/rapidjson/document.h"
#include "misc/eamuse.h"
#include "util/precise_timer.h"
using namespace std::placeholders;
using namespace rapidjson;
@@ -58,6 +59,7 @@ namespace api::modules {
// get params
auto keypad = req.params[0].GetUint();
auto input = std::string(req.params[1].GetString());
timeutils::PreciseSleepTimer timer;
// process all chars
for (auto c : input) {
@@ -91,11 +93,11 @@ namespace api::modules {
// set
eamuse_set_keypad_overrides(keypad, state);
Sleep(sleep_time);
timer.sleep(sleep_time);
// unset
eamuse_set_keypad_overrides(keypad, 0);
Sleep(sleep_time);
timer.sleep(sleep_time);
}
}
+3 -3
View File
@@ -58,7 +58,7 @@ namespace api::modules {
// check if file exists in modules
if (!fileutils::file_exists(dll_path)) {
return error(res, "Couldn't find " + dll_path.string());
return error(res, fmt::format("Couldn't find {}", dll_path));
}
// get module
@@ -118,7 +118,7 @@ namespace api::modules {
// check if file exists in modules
if (!fileutils::file_exists(dll_path)) {
return error(res, "Couldn't find " + dll_path.string());
return error(res, fmt::format("Couldn't find {}", dll_path));
}
// get module
@@ -196,7 +196,7 @@ namespace api::modules {
// check if file exists in modules
if (!fileutils::file_exists(dll_path)) {
return error(res, "Couldn't find " + dll_path.string());
return error(res, fmt::format("Couldn't find {}", dll_path));
}
// get module
+3 -1
View File
@@ -5,6 +5,7 @@
#include <utility>
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
@@ -16,6 +17,7 @@ namespace api {
controller->init_state(this->state);
this->thread = new std::thread([this] () {
log_warning("api::serial", "listening on {} (baud: {})", this->port, this->baud);
timeutils::PreciseSleepTimer timer;
// read buffer
uint8_t read_buffer[16*1024];
@@ -160,7 +162,7 @@ namespace api {
// slow down on reconnect
if (this->running) {
Sleep(retry_time);
timer.sleep(retry_time);
}
}
});
+16 -7
View File
@@ -1168,7 +1168,7 @@ namespace avs {
// Ongaku Paradise
{"arkjc9.dll", 0xA00000},
// KAMUNITY
// KAMUNITY
{"kamunity.dll", 33554432},
};
@@ -1516,7 +1516,7 @@ namespace avs {
" * It's also possible that you have incomplete game data\n"
" * Do NOT copy over random DLLs from another game installation; DLL must match game version\n"
"\n"
, DLL_NAME, MODULE_PATH.string()) };
, DLL_NAME, MODULE_PATH) };
log_warning("avs-ea3", "{}", info_str);
log_fatal("avs-ea3", "Failed to find critical avs DLL on disk (avs2-core.dll OR {})", DLL_NAME);
}
@@ -1757,9 +1757,9 @@ namespace avs {
{
deferredlogs::defer_error_messages({
"AVS filesystem initialization failure was previously detected during boot!",
fmt::format(" ERROR: directory could not be created: {}", src_path.string().c_str()),
fmt::format(" if you see a crash, it may have been caused by bad <mounttable> contents in {}", avs::core::CFG_PATH.c_str()),
" fix the XML file and try again"
fmt::format(" ERROR: directory could not be created: {}", src_path),
fmt::format(" if you see a crash, it may have been caused by bad <mounttable> contents in {}", avs::core::CFG_PATH),
" fix the XML file and try again"
});
}
@@ -1780,14 +1780,14 @@ namespace avs {
auto created = std::filesystem::create_directories(real_path, err);
if (created) {
log_info("avs-core", "created '{}' at '{}'", avs_path, real_path.string());
log_info("avs-core", "created '{}' at '{}'", avs_path, real_path);
}
if (err) {
avs_dir_err(real_path);
log_warning("avs-core", "failed to create '{}' folder at '{}': {}",
avs_path,
real_path.string(),
real_path,
err.message());
}
}
@@ -1921,6 +1921,15 @@ namespace avs {
// create nvram and raw directories if possible for mounttable configurations
create_avs_config_fs_table(config, config_node);
#if !SPICE64
// sdvx4 bad log config fix
if (avs::game::DLL_NAME == "soundvoltex.dll" && // it's too early for avs::game::is_model
property_search_safe(config, config_node, "/log/enable_console")) {
log_info("avs-core", "applying SDVX4 avs-config.xml fix for <log><enable_console>");
property_search_remove_safe(config, config_node, "/log/enable_console");
}
#endif
// set log level
if (!LOG_LEVEL_CUSTOM.empty()) {
property_search_remove_safe(config, config_node, "/log/level");
+2 -2
View File
@@ -151,8 +151,8 @@ namespace avs {
" * It's also possible that you have incomplete game data\n"
" * Do NOT copy over random DLLs from another game installation; DLL must match game version\n"
"\n"
, DLL_NAME, MODULE_PATH.string()) };
, DLL_NAME, MODULE_PATH) };
log_warning("avs-ea3", "{}", info_str);
log_fatal("avs-ea3", "Failed to find critical ea3 DLL on disk (avs2-ea3.dll OR {})", DLL_NAME);
}
+4 -5
View File
@@ -73,11 +73,10 @@ namespace avs {
// load game instance
const auto dll_path = MODULE_PATH / DLL_NAME;
const auto dll_path_s = dll_path.string();
log_info("avs-game", "DLL path: {}", dll_path_s.c_str());
log_info("avs-game", "DLL path: {}", dll_path);
// MAX_PATH is 260
if (130 <= dll_path_s.length()) {
if (const auto dll_path_len = dll_path.wstring().length(); 130 <= dll_path_len) {
log_warning(
"avs-game",
"PATH TOO LONG WARNING\n\n"
@@ -93,7 +92,7 @@ namespace avs {
"long, often resulting in random crashes. Move the game contents to\n"
"a directory with shorter path.\n"
"-------------------------------------------------------------------\n\n",
dll_path_s, dll_path_s.length());
dll_path, dll_path_len);
}
// ddr gamemdx.dll user error
@@ -112,7 +111,7 @@ namespace avs {
// file not found on disk
if (!fileutils::file_exists(dll_path)) {
log_warning("avs-game", "game DLL could not be found on disk: {}", dll_path.string().c_str());
log_warning("avs-game", "game DLL could not be found on disk: {}", dll_path);
log_warning("avs-game", "double check -exec and -modules parameters; unless you know what you're doing, leave them blank");
}
+37 -37
View File
@@ -39,8 +39,8 @@
<button name="VEFX" vkey="10" analogtype="0" devid="Player 1" invert="false" debounce_up="0" debounce_down="0" velocity_threshold="0"/>
</buttons>
<analogs>
<analog name="Turntable P1" devid="Player 1" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Turntable P2" devid="Player 2" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Turntable P1" devid="Player 1" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Turntable P2" devid="Player 2" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
</analogs>
<lights>
<light name="P1 1" devid="Player 1" index="0"/>
@@ -117,8 +117,8 @@
<keypad_buttons/>
<!-- Assumes analog mode. Need to invert direction since this FW is designed for INF. -->
<analogs>
<analog name="Turntable P1" devid="arcin (1p)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="true" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Turntable P2" devid="arcin (2p)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="true" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Turntable P1" devid="arcin (1p)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="true" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Turntable P2" devid="arcin (2p)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="true" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
</analogs>
<lights>
<light name="P1 1" devid="arcin (1p)" index="0"/>
@@ -144,34 +144,34 @@
<buttons/>
<keypad_buttons/>
<analogs>
<analog name="Key 1" devid="Analogs key 01-28" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 2" devid="Analogs key 01-28" index="5" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 3" devid="Analogs key 01-28" index="6" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 4" devid="Analogs key 01-28" index="7" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 5" devid="Analogs key 01-28" index="8" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 6" devid="Analogs key 01-28" index="9" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 7" devid="Analogs key 01-28" index="10" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 8" devid="Analogs key 01-28" index="11" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 9" devid="Analogs key 01-28" index="12" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 10" devid="Analogs key 01-28" index="13" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 11" devid="Analogs key 01-28" index="14" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 12" devid="Analogs key 01-28" index="15" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 13" devid="Analogs key 01-28" index="16" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 14" devid="Analogs key 01-28" index="17" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 15" devid="Analogs key 01-28" index="18" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 16" devid="Analogs key 01-28" index="19" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 17" devid="Analogs key 01-28" index="20" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 18" devid="Analogs key 01-28" index="21" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 19" devid="Analogs key 01-28" index="22" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 20" devid="Analogs key 01-28" index="23" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 21" devid="Analogs key 01-28" index="24" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 22" devid="Analogs key 01-28" index="25" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 23" devid="Analogs key 01-28" index="26" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 24" devid="Analogs key 01-28" index="27" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 25" devid="Analogs key 01-28" index="28" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 26" devid="Analogs key 01-28" index="29" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 27" devid="Analogs key 01-28" index="30" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 28" devid="Analogs key 01-28" index="31" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Key 1" devid="Analogs key 01-28" index="4" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 2" devid="Analogs key 01-28" index="5" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 3" devid="Analogs key 01-28" index="6" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 4" devid="Analogs key 01-28" index="7" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 5" devid="Analogs key 01-28" index="8" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 6" devid="Analogs key 01-28" index="9" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 7" devid="Analogs key 01-28" index="10" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 8" devid="Analogs key 01-28" index="11" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 9" devid="Analogs key 01-28" index="12" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 10" devid="Analogs key 01-28" index="13" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 11" devid="Analogs key 01-28" index="14" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 12" devid="Analogs key 01-28" index="15" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 13" devid="Analogs key 01-28" index="16" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 14" devid="Analogs key 01-28" index="17" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 15" devid="Analogs key 01-28" index="18" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 16" devid="Analogs key 01-28" index="19" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 17" devid="Analogs key 01-28" index="20" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 18" devid="Analogs key 01-28" index="21" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 19" devid="Analogs key 01-28" index="22" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 20" devid="Analogs key 01-28" index="23" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 21" devid="Analogs key 01-28" index="24" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 22" devid="Analogs key 01-28" index="25" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 23" devid="Analogs key 01-28" index="26" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 24" devid="Analogs key 01-28" index="27" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 25" devid="Analogs key 01-28" index="28" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 26" devid="Analogs key 01-28" index="29" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 27" devid="Analogs key 01-28" index="30" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Key 28" devid="Analogs key 01-28" index="31" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
</analogs>
<lights>
<light name="Key 1 R" devid="Lights 01-14" index="0"/>
@@ -277,9 +277,9 @@
</buttons>
<keypad_buttons/>
<analogs>
<analog name="Guitar P1 Wail X" devid="Gitaller P1" index="1" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Guitar P1 Wail Y" devid="Gitaller P1" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Guitar P1 Wail Z" devid="Gitaller P1" index="5" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="Guitar P1 Wail X" devid="Gitaller P1" index="1" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Guitar P1 Wail Y" devid="Gitaller P1" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="Guitar P1 Wail Z" devid="Gitaller P1" index="5" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
</analogs>
<lights/>
<!-- Gen 1 FAUCETWO in HID mode; should also work for later gens -->
@@ -296,8 +296,8 @@
</buttons>
<keypad_buttons/>
<analogs>
<analog name="VOL-L" devid="Buttons (MI_01)" index="1" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="VOL-R" devid="Buttons (MI_01)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay="0"/>
<analog name="VOL-L" devid="Buttons (MI_01)" index="1" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
<analog name="VOL-R" devid="Buttons (MI_01)" index="0" sensivity="1" deadzone="0" deadzone_mirror="false" invert="false" smoothing="false" multiplier="1" relative="false" delay_ms="0"/>
</analogs>
<lights>
<light name="BT-A" devid="Lights (MI_02)" index="24"/>
+10 -14
View File
@@ -68,8 +68,8 @@ DIST_FOLDER="./dist"
DIST_NAME="spice2x-$(date +%y)-$(date +%m)-$(date +%d).zip"
DIST_NAME_EXTRAS="spice2x-$(date +%y)-$(date +%m)-$(date +%d)-full.zip"
DIST_COMMENT=${DIST_NAME}$'\n'"$GIT_BRANCH - $GIT_HEAD"$'\nThank you for playing.'
TARGETS_32="spicetools_stubs_kbt spicetools_stubs_kld spicetools_cfg spicetools_cfg_linux spicetools_spice spicetools_spice_laa spicetools_spice_linux spicetools_stubs_cpusbxpkm"
TARGETS_64="spicetools_stubs_kbt64 spicetools_stubs_kld64 spicetools_stubs_nvEncodeAPI64 spicetools_stubs_nvcuvid spicetools_stubs_nvcuda spicetools_spice64 spicetools_spice64_linux"
TARGETS_32="spicetools_stubs_kbt spicetools_stubs_kld spicetools_cfg spicetools_cfg_linux spicetools_spice spicetools_spice_laa spicetools_spice_linux spicetools_stubs_cpusbxpkm spicetools_sdk_sample_v0_flat_c_32"
TARGETS_64="spicetools_stubs_kbt64 spicetools_stubs_kld64 spicetools_stubs_nvEncodeAPI64 spicetools_stubs_nvcuvid spicetools_stubs_nvcuda spicetools_spice64 spicetools_spice64_linux spicetools_sdk_sample_v0_flat_c_64 spicetools_sdk_sample_v0_cpp_64"
TARGETS_XP32="spicetools_cfg spicetools_spice"
TARGETS_XP64="spicetools_spice64"
@@ -269,6 +269,8 @@ rm -rf ${OUTDIR_EXTRAS}
mkdir -p ${OUTDIR_EXTRAS}
mkdir -p ${OUTDIR_EXTRAS}/largeaddressaware
mkdir -p ${OUTDIR_EXTRAS}/linux
mkdir -p ${OUTDIR_EXTRAS}/sdk/samples/32
mkdir -p ${OUTDIR_EXTRAS}/sdk/samples/64
if ((BUILD_XP > 0))
then
mkdir -p ${OUTDIR_EXTRAS}/winxp
@@ -281,16 +283,8 @@ then
cp ${BUILDDIR_32}/spicetools/spicecfg-pdb.pdb ${OUTDIR} 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/spice-pdb.exe ${OUTDIR} 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/spice-pdb.pdb ${OUTDIR} 2>/dev/null
#cp ${BUILDDIR_32}/spicetools/32/kbt.dll ${OUTDIR}/stubs/32 2>/dev/null
#cp ${BUILDDIR_32}/spicetools/32/kld.dll ${OUTDIR}/stubs/32 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/spice64-pdb.exe ${OUTDIR} 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/spice64-pdb.pdb ${OUTDIR} 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/kbt.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/kld.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/nvEncodeAPI64.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/nvcuda.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/nvcuvid.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_32}/spicetools/32/cpusbxpkm.dll ${OUTDIR}/stubs/32 2>/dev/null
else
# release files
cp ${BUILDDIR_32}/spicetools/spicecfg.exe ${OUTDIR} 2>/dev/null
@@ -298,16 +292,15 @@ else
cp ${BUILDDIR_32}/spicetools/32/spice.exe ${OUTDIR} 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/spice_laa.exe ${OUTDIR_EXTRAS}/largeaddressaware/spice.exe 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/spice_linux.exe ${OUTDIR_EXTRAS}/linux/spice.exe 2>/dev/null
#cp ${BUILDDIR_32}/spicetools/32/kbt.dll ${OUTDIR}/stubs/32 2>/dev/null
#cp ${BUILDDIR_32}/spicetools/32/kld.dll ${OUTDIR}/stubs/32 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/spice64.exe ${OUTDIR} 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/spice64_linux.exe ${OUTDIR_EXTRAS}/linux/spice64.exe 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/kbt.dll ${OUTDIR}/stubs/64 2>/dev/null
#cp ${BUILDDIR_64}/spicetools/64/kld.dll ${OUTDIR}/stubs/64 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/nvEncodeAPI64.dll ${OUTDIR}/stubs/64 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/nvcuda.dll ${OUTDIR}/stubs/64 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/nvcuvid.dll ${OUTDIR}/stubs/64 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/cpusbxpkm.dll ${OUTDIR}/stubs/32 2>/dev/null
cp ${BUILDDIR_32}/spicetools/32/sdk_sample_v0_flat_c.dll ${OUTDIR_EXTRAS}/sdk/samples/32/v0_flat_c.dll 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/sdk_sample_v0_flat_c.dll ${OUTDIR_EXTRAS}/sdk/samples/64/v0_flat_c.dll 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/sdk_sample_v0_cpp.dll ${OUTDIR_EXTRAS}/sdk/samples/64/v0_cpp.dll 2>/dev/null
if ((BUILD_XP > 0))
then
cp ${BUILDDIR_WINXP_32}/spicetools/spicecfg.exe ${OUTDIR_EXTRAS}/winxp 2>/dev/null
@@ -326,6 +319,9 @@ then
echo "WARNING: Couldn't get git to create the archive. Is this a git repository?"
fi
# sdk headers
cp -r ./sdk/include ${OUTDIR_EXTRAS}/sdk
# copy resources
rm -rf ${OUTDIR_EXTRAS}/api
mkdir ${OUTDIR_EXTRAS}/api
+2 -2
View File
@@ -1,7 +1,7 @@
docker build --pull external/docker -t spicetools/deps
docker build --build-context gitroot=%cd%/../../.git . -t spicetools/spice
docker run --rm -it -v %cd%/dist:/src/src/spice2x/dist -v %cd%/bin:/src/src/spice2x/bin -v %cd%/.ccache:/src/src/spice2x/.ccache spicetools/spice %*
docker run --rm -i -v %cd%/dist:/src/src/spice2x/dist -v %cd%/bin:/src/src/spice2x/bin -v %cd%/.ccache:/src/src/spice2x/.ccache spicetools/spice %*
@REM to generate PDBs, set DEBUG to 1 in build_all.sh, place cv2pdb in external\cv2pdb, and run below
@REM external\cv2pdb\cv2pdb.exe bin\spice2x\spicecfg.exe bin\spice2x\spicecfg-pdb.exe bin\spice2x\spicecfg-pdb.pdb
@REM external\cv2pdb\cv2pdb.exe bin\spice2x\spice.exe bin\spice2x\spice-pdb.exe bin\spice2x\spice-pdb.pdb
@REM external\cv2pdb\cv2pdb.exe bin\spice2x\spice64.exe bin\spice2x\spice64-pdb.exe bin\spice2x\spice64-pdb.pdb
@REM external\cv2pdb\cv2pdb.exe bin\spice2x\spice64.exe bin\spice2x\spice64-pdb.exe bin\spice2x\spice64-pdb.pdb
+102 -15
View File
@@ -207,22 +207,38 @@ float Analog::applyMultiplier(float value) {
}
float Analog::normalizeAnalogValue(float value) {
// effectively the same as fmodf(value, 1.f)
// for small values, this is MUCH faster than fmodf.
float new_value = value;
while (new_value > 1.f) {
new_value -= 1.f;
if (getType() == GameAPI::Analogs::AnalogType::Circular) {
// effectively the same as fmodf(value, 1.f)
// for small values, this is MUCH faster than fmodf.
float new_value = value;
while (new_value > 1.f) {
new_value -= 1.f;
}
while (new_value < 0.f) {
new_value += 1.f;
}
return new_value;
} else {
// clamp to [0, 1] range
return std::clamp(value, 0.f, 1.f);
}
while (new_value < 0.f) {
new_value += 1.f;
}
return new_value;
}
float Analog::applyDeadzone(float raw_value) {
float value = raw_value;
const auto deadzone = this->getDeadzone();
if (deadzone > 0) {
auto deadzone = this->getDeadzone();
// in the past, positive deadzone applied in the center, negative deadzone applied to 0
// after each analog value received a type (circular/linear) this has been simpliifed to
// positive values only since we can figure out where the rest value is
// for back compat, treat negative value as positive
if (deadzone < 0.f) {
deadzone = -deadzone;
}
// relative mode assumes that user is using a stick, so center is neutral regardless of analog type
if (getType() != GameAPI::Analogs::AnalogType::LinearPositive || isRelativeMode()) {
// calculate values
const auto delta = value - 0.5f;
@@ -255,7 +271,7 @@ float Analog::applyDeadzone(float raw_value) {
}
}
} else if (deadzone < 0) {
} else {
// invert for mirror
if (this->getDeadzoneMirror()) {
@@ -263,8 +279,8 @@ float Analog::applyDeadzone(float raw_value) {
}
// deadzone from minimum value
if (deadzone > -1 && value > -deadzone) {
value = std::min(1.f, (value + deadzone) / (1.f + deadzone));
if (deadzone < 1.f && deadzone < value) {
value = std::max(0.f, (value - deadzone) / (1.f - deadzone));
} else {
value = 0.f;
}
@@ -275,4 +291,75 @@ float Analog::applyDeadzone(float raw_value) {
}
}
return value;
}
}
float Analog::getRelativeModeValue(float raw_value) {
const auto now = get_performance_seconds();
auto delta_time = now - this->rel_mode_last_read_time_s;
if (this->rel_mode_last_read_time_s != 0.f) {
// some heuristics to prevent huge jumps:
// * if we went for more than 250ms without polls, discard it (e.g., during loading screens)
// * cap the delta at 100ms to prevent huge jumps in case of very infrequent polling
if (delta_time < 0.f || 0.25f < delta_time) {
delta_time = 0.f;
} else if (delta_time > 0.1f) {
delta_time = 0.1f;
}
// scale [0, 1] to [-1, 1] to simplify calculations
const auto delta_raw_value = (raw_value - 0.5f) * 2.f;
// target is one revolution per second at max speed at 1.0 sensitivity
auto adjusted_delta_value = delta_raw_value * delta_time;
// multiplier / divisor
if (this->getMultiplier() > 1) {
adjusted_delta_value *= this->getMultiplier();
} else if (this->getMultiplier() < -1) {
adjusted_delta_value /= -this->getMultiplier();
}
// sensitivity
if (this->isSensitivitySet()) {
adjusted_delta_value *= this->getSensitivity();
}
// calculate the new absolute value
this->rel_mode_absolute_value += adjusted_delta_value;
}
// update for next poll
this->rel_mode_last_read_time_s = now;
this->rel_mode_absolute_value = normalizeAnalogValue(this->rel_mode_absolute_value);
return this->rel_mode_absolute_value;
}
float Analog::getDelayedValue(float raw_value) {
const double delay_ms = static_cast<double>(this->getDelayMs());
if (delay_ms == 0.0) {
return raw_value;
}
// always push a new value
const auto now = get_performance_milliseconds();
this->delayed_inputs.emplace(now, raw_value);
// drain the queue down to reasonable length to prevent unconstrained growth
// this would accommodate 1 second at ~1000Hz which is overkill
// (UI only allows for 250ms of delay)
while (this->delayed_inputs.size() > 1024) {
this->delayed_inputs.pop();
}
// pop until we find the oldest value still inside the delay window
while (this->delayed_inputs.size() > 1) {
const auto delta_t = now - this->delayed_inputs.front().time_in_ms;
if (delta_t <= delay_ms) {
break;
}
this->delayed_inputs.pop();
}
return this->delayed_inputs.front().value;
}
+46 -18
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint>
#include <array>
#include <string>
#include <cmath>
@@ -13,12 +14,32 @@ namespace rawinput {
class RawInputManager;
}
namespace GameAPI::Analogs {
enum class AnalogType {
// default; values wrap around (below 0 turns into 1, over 1 is 0)
// knobs, turntables
Circular = 0,
// typical joystick that rests at the center and caps at [0, 1]
LinearCentered = 1,
// one-directional value (sliders and instruments like piano/drum velocity)
// starts at 0 and goes up to 1
LinearPositive = 2,
};
}
struct AnalogMovingAverage {
double time_in_ms;
float sine;
float cosine;
};
struct AnalogDelayEntry {
double time_in_ms;
float value;
};
class Analog {
private:
std::string name;
@@ -31,10 +52,11 @@ private:
float last_state = 0.5f;
bool sensitivity_set = false;
bool deadzone_set = false;
GameAPI::Analogs::AnalogType type = GameAPI::Analogs::AnalogType::Circular;
// smoothing function
bool smoothing = false;
std::array<AnalogMovingAverage, ANALOG_HISTORY_CNT> vector_history;
std::array<AnalogMovingAverage, ANALOG_HISTORY_CNT> vector_history = {};
int vector_history_index = 0;
float smoothed_last_state = 0.f;
@@ -48,12 +70,13 @@ private:
unsigned short divisor_region = 0;
// relative input mode
float absolute_value_for_rel_mode = 0.5f;
float rel_mode_absolute_value = 0.5f;
float rel_mode_last_read_time_s = 0.f;
bool relative_mode = false;
// circular buffer (delayed input)
int delay_buffer_depth = 0;
std::queue<float> delay_buffer;
// delay
uint32_t delay_ms = 0;
std::queue<AnalogDelayEntry> delayed_inputs;
float calculateAngularDifference(float old_rads, float new_rads);
float normalizeAngle(float rads);
@@ -66,7 +89,8 @@ public:
float override_state = 0.5f;
explicit Analog(std::string name) : name(std::move(name)) {
vector_history.fill({0.0, 0.f, 0.f});
};
explicit Analog(std::string name, GameAPI::Analogs::AnalogType type) : name(std::move(name)), type(type) {
};
std::string getDisplayString(rawinput::RawInputManager* manager);
@@ -74,6 +98,8 @@ public:
float applyAngularSensitivity(float raw_rads);
float applyMultiplier(float raw_value);
float applyDeadzone(float raw_value);
float getRelativeModeValue(float raw_value);
float getDelayedValue(float raw_value);
inline bool isSet() {
if (this->override_enabled) {
@@ -90,8 +116,8 @@ public:
deadzone_mirror = false;
setMultiplier(1);
setRelativeMode(false);
setDelayBufferDepth(0);
setLastState(0.5f);
setDelayMs(0);
}
inline void clearBindings() {
@@ -193,25 +219,27 @@ public:
}
inline void setRelativeMode(bool relative_mode) {
if (relative_mode) {
this->smoothing = false;
}
this->relative_mode = relative_mode;
this->absolute_value_for_rel_mode = 0.5f;
this->rel_mode_absolute_value = 0.5f;
this->rel_mode_last_read_time_s = 0.f;
}
inline float getAbsoluteValue(float relative_delta) {
this->absolute_value_for_rel_mode =
normalizeAnalogValue(this->absolute_value_for_rel_mode + relative_delta);
return this->absolute_value_for_rel_mode;
inline GameAPI::Analogs::AnalogType getType() const {
return this->type;
}
inline int getDelayBufferDepth() const {
return this->delay_buffer_depth;
inline void setType(GameAPI::Analogs::AnalogType type) {
this->type = type;
}
inline void setDelayBufferDepth(int depth) {
this->delay_buffer_depth = depth;
inline uint32_t getDelayMs() const {
return this->delay_ms;
}
inline std::queue<float> &getDelayBuffer() {
return this->delay_buffer;
inline void setDelayMs(uint32_t delay_ms) {
this->delay_ms = delay_ms;
}
};
+109 -56
View File
@@ -679,81 +679,98 @@ float GameAPI::Analogs::getState(rawinput::RawInputManager *manager, rawinput::D
}
// deadzone
if (analog.isDeadzoneSet()) {
// do not apply deadzone to circular analogs since it doesn't make sense (except in relative mode)
if (analog.isDeadzoneSet() &&
(analog.getType() != AnalogType::Circular || analog.isRelativeMode())) {
value = analog.applyDeadzone(value);
}
if (analog.isRelativeMode()) {
float relative_delta = value - 0.5f;
// built-in scaling to make values reasonable
relative_delta /= 80.f;
if (analog.getType() == AnalogType::Circular) {
// integer multiplier/divisor
const auto mult = analog.getMultiplier();
if (mult < -1) {
relative_delta /= -mult;
} else if (1 < mult) {
relative_delta *= mult;
}
if (analog.isRelativeMode()) {
value = analog.getRelativeModeValue(value);
// sensitivity (ranges from 0.0 to 4.0)
if (analog.isSensitivitySet()) {
relative_delta *= analog.getSensitivity();
}
} else {
// integer multiplier
value = analog.applyMultiplier(value);
// translate relative movement to absolute value
value = analog.getAbsoluteValue(relative_delta);
// smoothing/sensitivity
if (analog.getSmoothing() || analog.isSensitivitySet()) {
float rads = value * (float) M_TAU;
} else {
// integer multiplier
value = analog.applyMultiplier(value);
// smoothing
if (analog.getSmoothing()) {
// smoothing/sensitivity
if (analog.getSmoothing() || analog.isSensitivitySet()) {
float rads = value * (float) M_TAU;
// preserve direction
if (rads >= M_TAU) {
rads -= 0.0001f;
}
// smoothing
if (analog.getSmoothing()) {
// preserve direction
if (rads >= M_TAU) {
rads -= 0.0001f;
// calculate angle
rads = analog.getSmoothedValue(rads);
}
// calculate angle
rads = analog.getSmoothedValue(rads);
// sensitivity
if (analog.isSensitivitySet()) {
rads = analog.applyAngularSensitivity(rads);
}
// apply to value
value = rads * (float) M_1_TAU;
}
}
} else {
// sensitivity
if (analog.isSensitivitySet()) {
// adjust curve
// values < 1.f : less sensitive around neutral
// values > 1.f : more sensitive around neutral
float curve = analog.getSensitivity();
if (curve <= 0.f) {
curve = 0.01f;
}
curve = 1.f / curve;
if (analog.getType() == AnalogType::LinearCentered) {
// convert 0.0..1.0 to -1.0..+1.0
float signed_raw = (value - 0.5f) * 2.0f;
// apply curve
float sign = signed_raw < 0.0f ? -1.0f : 1.0f;
float magnitude = fabsf(signed_raw);
float curved = sign * powf(magnitude, curve);
// convert back to 0.0..1.0
value = curved * 0.5f + 0.5f;
} else {
value = powf(value, curve);
}
// sensitivity
if (analog.isSensitivitySet()) {
rads = analog.applyAngularSensitivity(rads);
value = std::clamp(value, 0.f, 1.f);
}
// multiplier / divisor
if (analog.getMultiplier() < -1) {
if (analog.getType() == AnalogType::LinearCentered) {
value = (value - 0.5f) / (-analog.getMultiplier()) + 0.5f;
} else {
value /= -analog.getMultiplier();
}
// apply to value
value = rads * (float) M_1_TAU;
value = std::clamp(value, 0.f, 1.f);
} else if (analog.getMultiplier() > 1) {
if (analog.getType() == AnalogType::LinearCentered) {
value = (value - 0.5f) * analog.getMultiplier() + 0.5f;
} else {
value *= analog.getMultiplier();
}
value = std::clamp(value, 0.f, 1.f);
}
}
// delay
if (0 < analog.getDelayBufferDepth()) {
auto& queue = analog.getDelayBuffer();
// ensure the queue isn't too long; drop old values
while (analog.getDelayBufferDepth() <= (int)queue.size()) {
queue.pop();
}
// always push new value
queue.push(value);
// get a new value to return
if ((int)queue.size() < analog.getDelayBufferDepth()) {
// not enough in the queue, stall for now, shouldn't happen often
value = analog.getLastState();
} else {
value = queue.front();
queue.pop();
}
if (analog.getDelayMs() > 0) {
value = analog.getDelayedValue(value);
}
break;
@@ -839,6 +856,42 @@ std::vector<Analog> GameAPI::Analogs::sortAnalogs(
return sorted;
}
static std::vector<Analog> sortAnalogsWithTypeInternal(
std::vector<Analog> &analogs,
const std::initializer_list<GameAPI::Analogs::AnalogWithType> list) {
std::vector<Analog> sorted;
bool analog_found;
for (auto &a : list) {
analog_found = false;
for (auto &analog : analogs) {
if (a.name == analog.getName()) {
analog_found = true;
analog.setType(a.type);
sorted.push_back(analog);
break;
}
}
if (!analog_found) {
sorted.emplace_back(a.name, a.type);
}
}
return sorted;
}
void GameAPI::Analogs::sortAnalogsWithType(
std::vector<Analog> *analogs,
const std::initializer_list<AnalogWithType> list) {
if (analogs) {
*analogs = sortAnalogsWithTypeInternal(*analogs, list);
}
}
float GameAPI::Analogs::getState(rawinput::RawInputManager *manager, Analog &analog) {
// check override
+8 -7
View File
@@ -85,14 +85,15 @@ namespace GameAPI {
const std::vector<Analog> &analogs,
const std::vector<std::string> &analog_names);
template<typename T>
void sortAnalogs(std::vector<Analog> *analogs, T t) {
const std::vector<std::string> analog_names { t };
struct AnalogWithType {
const std::string name;
const AnalogType type;
if (analogs) {
*analogs = GameAPI::Analogs::sortAnalogs(*analogs, analog_names);
}
}
AnalogWithType(std::string name, AnalogType type) :
name(std::move(name)), type(type) {}
};
void sortAnalogsWithType(std::vector<Analog> *analogs, const std::initializer_list<AnalogWithType> list);
template<typename T, typename... Rest>
void sortAnalogs(std::vector<Analog> *analogs, T t, Rest... rest) {
+4 -1
View File
@@ -306,7 +306,10 @@ std::string Button::getDisplayString(rawinput::RawInputManager* manager) {
std::string vKeyString = fmt::format("{:#x}", vKey);
// device must be existing
if (this->device_identifier.empty() && vKey == INVALID_VKEY) {
if (this->isNaive() && vKey == INVALID_VKEY) {
if (this->getInvert()) {
return "(always on)";
}
return "";
}
+16 -16
View File
@@ -28,7 +28,7 @@ Config::Config() {
this->status = false;
if (CONFIG_PATH_OVERRIDE.length() > 0) {
this->configLocation = CONFIG_PATH_OVERRIDE;
log_info("cfg", "using custom config file: {}", this->configLocation.string());
log_info("cfg", "using custom config file: {}", this->configLocation);
} else {
this->configLocation = std::filesystem::path(_wgetenv(L"APPDATA")) / L"spicetools.xml";
// avoids logging the expanded appdata path as it contains user name
@@ -57,7 +57,7 @@ Config::Config() {
this->firstFillConfigFile();
break;
case tinyxml2::XMLError::XML_ERROR_FILE_COULD_NOT_BE_OPENED:
log_fatal("cfg", "could not open config file: {}", this->configLocation.string());
log_fatal("cfg", "could not open config file: {}", this->configLocation);
break;
case tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND:
this->createConfigFile();
@@ -72,7 +72,7 @@ Config::Config() {
case tinyxml2::XMLError::XML_ERROR_PARSING_UNKNOWN:
case tinyxml2::XMLError::XML_ERROR_MISMATCHED_ELEMENT:
case tinyxml2::XMLError::XML_ERROR_PARSING:
log_warning("cfg", "Couldn't read config file: {}", this->configLocation.string());
log_warning("cfg", "Couldn't read config file: {}", this->configLocation);
this->createConfigFile();
this->firstFillConfigFile();
break;
@@ -253,7 +253,7 @@ bool Config::addGame(Game &game) {
bool smoothing = false;
int multiplier = 1;
bool relative_mode = false;
int delay_buffer_depth = 0;
uint32_t delay = 0;
tinyxml2::XMLError err1 = gameAnalogNode->QueryIntAttribute("index", &index);
gameAnalogNode->QueryFloatAttribute("sensivity", &sensitivity);
gameAnalogNode->QueryFloatAttribute("deadzone", &deadzone);
@@ -262,7 +262,7 @@ bool Config::addGame(Game &game) {
gameAnalogNode->QueryBoolAttribute("smoothing", &smoothing);
gameAnalogNode->QueryIntAttribute("multiplier", &multiplier);
gameAnalogNode->QueryBoolAttribute("relative", &relative_mode);
gameAnalogNode->QueryIntAttribute("delay", &delay_buffer_depth);
gameAnalogNode->QueryUnsignedAttribute("delay_ms", &delay);
const char *devid = gameAnalogNode->Attribute("devid");
if (err1 != tinyxml2::XMLError::XML_SUCCESS || !devid) {
@@ -278,7 +278,7 @@ bool Config::addGame(Game &game) {
gameAnalogNode->SetAttribute("smoothing", it.getSmoothing());
gameAnalogNode->SetAttribute("multiplier", it.getMultiplier());
gameAnalogNode->SetAttribute("relative", it.isRelativeMode());
gameAnalogNode->SetAttribute("delay", it.getDelayBufferDepth());
gameAnalogNode->SetAttribute("delay_ms", it.getDelayMs());
gameAnalogsNode->InsertEndChild(gameAnalogNode);
} else {
it.setIndex(static_cast<unsigned short int>(index));
@@ -290,7 +290,7 @@ bool Config::addGame(Game &game) {
it.setSmoothing(smoothing);
it.setMultiplier(multiplier);
it.setRelativeMode(relative_mode);
it.setDelayBufferDepth(delay_buffer_depth);
it.setDelayMs(delay);
}
} else {
gameAnalogNode = this->configFile.NewElement("analog");
@@ -303,7 +303,7 @@ bool Config::addGame(Game &game) {
gameAnalogNode->SetAttribute("smoothing", it.getSmoothing());
gameAnalogNode->SetAttribute("multiplier", it.getMultiplier());
gameAnalogNode->SetAttribute("relative", it.isRelativeMode());
gameAnalogNode->SetAttribute("delay", it.getDelayBufferDepth());
gameAnalogNode->SetAttribute("delay_ms", it.getDelayMs());
gameAnalogNode->SetAttribute("devid", it.getDeviceIdentifier().c_str());
gameAnalogsNode->InsertEndChild(gameAnalogNode);
}
@@ -458,7 +458,7 @@ bool Config::addGame(Game &game) {
gameAnalogNode->SetAttribute("smoothing", it.getSmoothing());
gameAnalogNode->SetAttribute("multiplier", it.getMultiplier());
gameAnalogNode->SetAttribute("relative", it.isRelativeMode());
gameAnalogNode->SetAttribute("delay", it.getDelayBufferDepth());
gameAnalogNode->SetAttribute("delay_ms", it.getDelayMs());
gameAnalogsNode->InsertEndChild(gameAnalogNode);
}
@@ -692,7 +692,7 @@ bool Config::updateBinding(const Game &game, const Analog &analog) {
gameAnalogNode->SetAttribute("smoothing", analog.getSmoothing());
gameAnalogNode->SetAttribute("multiplier", analog.getMultiplier());
gameAnalogNode->SetAttribute("relative", analog.isRelativeMode());
gameAnalogNode->SetAttribute("delay", analog.getDelayBufferDepth());
gameAnalogNode->SetAttribute("delay_ms", analog.getDelayMs());
gameAnalogNode->SetAttribute("devid", analog.getDeviceIdentifier().c_str());
} else {
gameAnalogNode = this->configFile.NewElement("analog");
@@ -704,7 +704,7 @@ bool Config::updateBinding(const Game &game, const Analog &analog) {
gameAnalogNode->SetAttribute("smoothing", analog.getSmoothing());
gameAnalogNode->SetAttribute("multiplier", analog.getMultiplier());
gameAnalogNode->SetAttribute("relative", analog.isRelativeMode());
gameAnalogNode->SetAttribute("delay", analog.getDelayBufferDepth());
gameAnalogNode->SetAttribute("delay_ms", analog.getDelayMs());
gameAnalogNode->SetAttribute("devid", analog.getDeviceIdentifier().c_str());
gameAnalogsNode->InsertEndChild(gameAnalogNode);
}
@@ -1142,7 +1142,7 @@ std::vector<Analog> Config::getAnalogs(const std::string &gameName) {
bool smoothing = false;
int multiplier = 1;
bool relative_mode = false;
int delay_buffer_depth = 0;
uint32_t delay = 0;
gameAnalogNode->QueryIntAttribute("index", &index);
gameAnalogNode->QueryFloatAttribute("sensivity", &sensitivity);
gameAnalogNode->QueryFloatAttribute("deadzone", &deadzone);
@@ -1151,7 +1151,7 @@ std::vector<Analog> Config::getAnalogs(const std::string &gameName) {
gameAnalogNode->QueryBoolAttribute("smoothing", &smoothing);
gameAnalogNode->QueryIntAttribute("multiplier", &multiplier);
gameAnalogNode->QueryBoolAttribute("relative", &relative_mode);
gameAnalogNode->QueryIntAttribute("delay", &delay_buffer_depth);
gameAnalogNode->QueryUnsignedAttribute("delay_ms", &delay);
const char *devid = gameAnalogNode->Attribute("devid");
// create analog and add to list
@@ -1164,7 +1164,7 @@ std::vector<Analog> Config::getAnalogs(const std::string &gameName) {
analog.setSmoothing(smoothing);
analog.setMultiplier(multiplier);
analog.setRelativeMode(relative_mode);
analog.setDelayBufferDepth(delay_buffer_depth);
analog.setDelayMs(delay);
if (devid) {
analog.setDeviceIdentifier(devid);
}
@@ -1327,7 +1327,7 @@ void Config::saveConfigFile() {
// create a .tmp file and write to it...
const auto xml_result = this->configFile.SaveFile(this->configLocationTemp.c_str(), false);
if (xml_result != tinyxml2::XMLError::XML_SUCCESS) {
log_info("cfg", "failed to write file: {}", this->configLocationTemp.string());
log_info("cfg", "failed to write file: {}", this->configLocationTemp);
return;
}
// copy the .tmp file to the main file...
@@ -1337,4 +1337,4 @@ void Config::saveConfigFile() {
}
// delete the .tmp file (not critical if this fails)
DeleteFileW(this->configLocationTemp.c_str());
}
}
+2 -2
View File
@@ -70,7 +70,7 @@ namespace overlay::windows {
el->SetAttribute("smoothing", analog.smoothing);
el->SetAttribute("multiplier", analog.multiplier);
el->SetAttribute("relative", analog.relative_mode);
el->SetAttribute("delay", analog.delay_buffer_depth);
el->SetAttribute("delay_ms", analog.delay_ms);
parent->InsertEndChild(el);
}
@@ -93,7 +93,7 @@ namespace overlay::windows {
el->QueryBoolAttribute("smoothing", &a.smoothing);
el->QueryIntAttribute("multiplier", &a.multiplier);
el->QueryBoolAttribute("relative", &a.relative_mode);
el->QueryIntAttribute("delay", &a.delay_buffer_depth);
el->QueryUnsignedAttribute("delay_ms", &a.delay_ms);
return a;
}
+3 -3
View File
@@ -21,7 +21,7 @@ namespace cfg {
if (SCREEN_RESIZE_CFG_PATH_OVERRIDE.has_value()) {
this->config_path = SCREEN_RESIZE_CFG_PATH_OVERRIDE.value();
if (fileutils::file_exists(this->config_path)) {
log_info("ScreenResize", "loading config from: {}", this->config_path.string());
log_info("ScreenResize", "loading config from: {}", this->config_path);
file_exists = true;
}
} else {
@@ -35,7 +35,7 @@ namespace cfg {
ScreenResize::~ScreenResize() {
}
void ScreenResize::config_load() {
std::string config = fileutils::text_read(this->config_path);
if (config.empty()) {
@@ -78,7 +78,7 @@ namespace cfg {
eamuse_get_game(),
use_game_setting,
root);
load_bool_value(doc, root + "enable_screen_resize", this->enable_screen_resize);
if (this->enable_screen_resize) {
log_misc("ScreenResize", "enabled by config file");
+1
View File
@@ -20,6 +20,7 @@ Usage:
#include <memory>
#include <string>
#include <map>
#include <cstdint>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+1
View File
@@ -39,6 +39,7 @@
#define ROBIN_HOOD_VERSION_PATCH 2 // for backwards-compatible bug fixes
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
+6 -5
View File
@@ -38,11 +38,12 @@ std::vector<Analog> &games::bc::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Busou Shinki: Armored Princess Battle Conductor");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Stick X",
"Stick Y"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Stick X", AnalogType::LinearCentered },
{ "Stick Y", AnalogType::LinearCentered }
});
}
return analogs;
+8 -7
View File
@@ -45,13 +45,14 @@ std::vector<Analog> &games::ccj::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Chase Chase Jokers");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Joystick X",
"Joystick Y",
"Trackball DX",
"Trackball DY"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Joystick X", AnalogType::LinearCentered },
{ "Joystick Y", AnalogType::LinearCentered },
{ "Trackball DX", AnalogType::LinearCentered },
{ "Trackball DY", AnalogType::LinearCentered }
});
}
return analogs;
+4 -2
View File
@@ -6,6 +6,7 @@
#include "util/logging.h"
#include "rawinput/rawinput.h"
#include "games/io.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "io.h"
@@ -112,7 +113,7 @@ namespace games::ccj {
static std::chrono::time_point<std::chrono::steady_clock> lastModified = std::chrono::steady_clock::now();
static std::chrono::milliseconds debounceDuration(100);
auto currentTime = std::chrono::steady_clock::now();
bool pressed = get_async_secondary_mouse() & 0x8000;
bool pressed = get_async_secondary_mouse();
bool focused = GetForegroundWindow() == hWnd;
if (focused && MOUSE_TRACKBALL_USE_TOGGLE && pressed && (currentTime - lastModified > debounceDuration)) {
@@ -243,6 +244,7 @@ namespace games::ccj {
log_info("trackball", "thread start, use mouse: {}, toggle: {}", MOUSE_TRACKBALL, MOUSE_TRACKBALL_USE_TOGGLE);
tbThread = new std::thread([&] {
timeutils::PreciseSleepTimer timer;
while (tbThreadRunning) {
if (hWnd && wndProc) {
wndProc(hWnd, WM_INPUT, RIM_INPUT, (LPARAM)fakeHandle);
@@ -251,7 +253,7 @@ namespace games::ccj {
if (!tbThreadRunning)
break;
std::this_thread::sleep_for(10ms);
timer.sleep(10);
}
});
}
+58 -11
View File
@@ -23,6 +23,7 @@
#include "p3io/usbmem.h"
#include "p4io/p4io.h"
#include <cstring>
using namespace acioemu;
@@ -53,9 +54,9 @@ namespace games::ddr {
return SendMessage_real(hWnd, Msg, wParam, lParam);
}
bool contains_only_ascii(const std::string& str) {
bool contains_only_ascii(const std::wstring& str) {
for (auto c: str) {
if (static_cast<unsigned char>(c) > 127) {
if (c > 127) {
return false;
}
}
@@ -80,24 +81,24 @@ namespace games::ddr {
}
if (fileutils::dir_exists(dir)) {
log_info("ddr", "looking for codecs in this directory: {}", dir.string());
log_info("ddr", "looking for codecs in this directory: {}", dir);
} else {
log_info("ddr", "codecs directory not found: {}", dir.string());
log_info("ddr", "codecs directory not found: {}", dir);
return;
}
for (const auto &file : std::filesystem::directory_iterator(dir)) {
const auto &filename = file.path().filename();
const auto extension = strtolower(filename.extension().string());
const auto extension = filename.extension().wstring();
if (extension != ".dll") {
if (wcsicmp(extension.c_str(), L".dll") != 0) {
continue;
}
log_info("ddr", "found DLL: {}, size: {} bytes", filename.string(), file.file_size());
if (filename == "k-clvsd.dll" || filename.string().find("xactengine") == 0) {
log_info("ddr", "found DLL: {}, size: {} bytes", filename, file.file_size());
if (filename == "k-clvsd.dll" || filename.wstring().find(L"xactengine") == 0) {
const std::wstring wcmd = L"regsvr32.exe /s \"" + file.path().wstring() + L"\"";
const std::string cmd = "regsvr32.exe /s \"" + file.path().string() + "\"";
const std::string cmd = fmt::format("regsvr32.exe /s \"{}\"", file.path());
int result = 0;
std::thread t([wcmd, &result]() {
@@ -111,12 +112,12 @@ namespace games::ddr {
log_warning("ddr", "`{}` failed, returned {}", cmd, result);
deferredlogs::defer_error_messages({
"DDR codec registration failure",
fmt::format(" {} failed to register with error {}", filename.string(), result)});
fmt::format(" {} failed to register with error {}", filename, result)});
}
static std::once_flag printed;
std::call_once(printed, [file]() {
if (!contains_only_ascii(file.path().string())) {
if (!contains_only_ascii(file.path().wstring())) {
log_warning(
"ddr",
"BAD PATH ERROR\n\n"
@@ -290,4 +291,50 @@ namespace games::ddr {
// dispose device hook
devicehook_dispose();
}
static void get_analog_xy_axis(Analog &analog, bool &less, bool &more) {
if (!analog.isSet()) {
return;
}
const auto value = GameAPI::Analogs::getState(RI_MGR, analog);
// stepmania linux source:
// https://github.com/stepmania/stepmania/blob/d55acb1ba26f1c5b5e3048d6d6c0bd116625216f/src/arch/InputHandler/InputHandler_Linux_Event.cpp#L410
// for example, value cap with range [0, 255]:
// 127 = 0.498, neutral
// 128 = 0.502, both
// apparently some adapters report values like above; this obviously makes a lot of
// assumptions about bit width of the HID value cap and how the adapter reports
// neutral/both values, but this is good enough for parity with stepmania and its many forks
if (0.5001f < value && value < 0.75f) {
less |= true;
more |= true;
} else if (value <= 0.25f) {
less |= true;
} else if (value >= 0.75f) {
more |= true;
}
}
void get_analog_x_axis(int player, bool &left, bool &right) {
if (player != 1 && player != 2) {
log_fatal("ddr", "invalid player number: {}, expected 1 or 2", player);
return;
}
auto &analog = get_analogs().at(player == 1 ? Analogs::P1_LEFT_RIGHT : Analogs::P2_LEFT_RIGHT);
get_analog_xy_axis(analog, left, right);
}
void get_analog_y_axis(int player, bool &up, bool &down) {
if (player != 1 && player != 2) {
log_fatal("ddr", "invalid player number: {}, expected 1 or 2", player);
return;
}
auto &analog = get_analogs().at(player == 1 ? Analogs::P1_UP_DOWN : Analogs::P2_UP_DOWN);
get_analog_xy_axis(analog, up, down);
}
}
+3
View File
@@ -23,4 +23,7 @@ namespace games::ddr {
private:
void register_codecs();
};
void get_analog_x_axis(int player, bool &left, bool &right);
void get_analog_y_axis(int player, bool &up, bool &down);
}
+44
View File
@@ -35,6 +35,50 @@ std::vector<Button> &games::ddr::get_buttons() {
return analogs;
}
std::string games::ddr::get_buttons_help() {
// keep to max 100 characters wide
return
"For DDR pad arrows, double check that simultaneous Left+Right and Up+Down can be detected.\n"
"You should boot the game, enter test menu, and use Foot Panel Check.\n\n"
"When mapping arrows, try the following in order:\n\n"
" 1. If your controller uses face buttons (A/B/X/Y), bind them here.\n"
" 2. If your controller supports XInput, use that.\n"
" 3. If your controller uses analog axis for arrows, try Analogs tab.\n"
" 4. Otherwise, you will need to use remapping software or get a better adapter."
;
}
std::vector<Analog> &games::ddr::get_analogs() {
static std::vector<Analog> analogs;
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Dance Dance Revolution");
using namespace GameAPI::Analogs;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "P1 Left-Right (Axis Fix)", AnalogType::LinearCentered },
{ "P1 Up-Down (Axis Fix)", AnalogType::LinearCentered },
{ "P2 Left-Right (Axis Fix)", AnalogType::LinearCentered },
{ "P2 Up-Down (Axis Fix)", AnalogType::LinearCentered }
});
}
return analogs;
}
std::string games::ddr::get_analogs_help() {
// keep to max 100 characters wide
return
"Only use this if your DDR pad outputs analog axis for arrows.\n\n"
"If the pad uses face buttons (A/B/X/Y), use Buttons tab instead.\n\n"
"Spice will treat values <=25% as Left, >=75% as Right, ~=50% as neutral,\n"
"and value between 50% and 75% as both arrows.\n\n"
"This is the classic Stepmania \"Axis Fix\" which may or may not work with\n"
"your dance pad or your adapter."
;
}
std::vector<Light> &games::ddr::get_lights() {
static std::vector<Light> lights;
+13
View File
@@ -33,6 +33,16 @@ namespace games::ddr {
};
}
// all analogs in correct order
namespace Analogs {
enum {
P1_LEFT_RIGHT,
P1_UP_DOWN,
P2_LEFT_RIGHT,
P2_UP_DOWN
};
}
// all lights in correct order
namespace Lights {
enum {
@@ -177,5 +187,8 @@ namespace games::ddr {
// getters
std::vector<Button> &get_buttons();
std::string get_buttons_help();
std::string get_analogs_help();
std::vector<Analog> &get_analogs();
std::vector<Light> &get_lights();
}
+52 -2
View File
@@ -3,6 +3,7 @@
#include "cfg/api.h"
#include "rawinput/rawinput.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "../ddr.h"
@@ -459,7 +460,8 @@ int games::ddr::DDRP3IOHandle::device_io(
if (nOutBufferSize >= 4) {
// cool down
Sleep(1);
static thread_local timeutils::PreciseSleepTimer timer;
timer.sleep(1);
// get controls as single variable (4 bytes)
auto &controls = *(uint32_t*) lpOutBuffer;
@@ -498,32 +500,80 @@ int games::ddr::DDRP3IOHandle::device_io(
// shift table
static size_t shift_table[] = {
30, 28, 29, 8, 9, 10, 11, 12, 24, 25, 14, 15, 16, 17, 18, 19, 20, 26, 27, 22, 23
30, 28, 29, // service, test, coin
8, // p1 start
9, 10, 11, 12, // p1 panel
24, 25, 14, 15, // p1 menu
16, // p2 start
17, 18, 19, 20, // p2 panel
26, 27, 22, 23 // p2 menu
};
static size_t button_table[] = {
Buttons::SERVICE,
Buttons::TEST,
Buttons::COIN_MECH,
Buttons::P1_START,
Buttons::P1_PANEL_UP,
Buttons::P1_PANEL_DOWN,
Buttons::P1_PANEL_LEFT,
Buttons::P1_PANEL_RIGHT,
Buttons::P1_MENU_UP,
Buttons::P1_MENU_DOWN,
Buttons::P1_MENU_LEFT,
Buttons::P1_MENU_RIGHT,
Buttons::P2_START,
Buttons::P2_PANEL_UP,
Buttons::P2_PANEL_DOWN,
Buttons::P2_PANEL_LEFT,
Buttons::P2_PANEL_RIGHT,
Buttons::P2_MENU_UP,
Buttons::P2_MENU_DOWN,
Buttons::P2_MENU_LEFT,
Buttons::P2_MENU_RIGHT,
};
// get analogs
struct {
bool up;
bool down;
bool left;
bool right;
} analog_values[2] = {};
games::ddr::get_analog_x_axis(1, analog_values[0].left, analog_values[0].right);
games::ddr::get_analog_y_axis(1, analog_values[0].up, analog_values[0].down);
games::ddr::get_analog_x_axis(2, analog_values[1].left, analog_values[1].right);
games::ddr::get_analog_y_axis(2, analog_values[1].up, analog_values[1].down);
if (analog_values[0].up) {
controls |= 1 << 9;
}
if (analog_values[0].down) {
controls |= 1 << 10;
}
if (analog_values[0].left) {
controls |= 1 << 11;
}
if (analog_values[0].right) {
controls |= 1 << 12;
}
if (analog_values[1].up) {
controls |= 1 << 17;
}
if (analog_values[1].down) {
controls |= 1 << 18;
}
if (analog_values[1].left) {
controls |= 1 << 19;
}
if (analog_values[1].right) {
controls |= 1 << 20;
}
// update states
auto &buttons = get_buttons();
size_t count = 0;
+3 -1
View File
@@ -2,6 +2,7 @@
#include "rawinput/rawinput.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "../io.h"
@@ -255,7 +256,8 @@ namespace games::ddr {
case P4IO_IOCTL_GET_INPUTS: {
// Prevents this function from being called at its normal 2000-2500 kHz cadence and overloading the CPU, instead reduces it to 250 Hz
Sleep(4);
static thread_local timeutils::PreciseSleepTimer timer;
timer.sleep(4);
memset(lpOutBuffer, 0, 16);
auto controls = (uint32_t*) lpOutBuffer;
+3 -1
View File
@@ -7,6 +7,7 @@
#include "games/game.h"
#include "util/detour.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/memutils.h"
#include "rgb_cam.h"
@@ -221,10 +222,11 @@ namespace games::drs {
void start_touch() {
std::thread t([] {
log_info("drs", "starting touch input thread");
timeutils::PreciseSleepTimer timer;
// main loop
while (TRUE) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
timer.sleep(1);
TOUCH_EVENTS.clear();
touch_get_events(TOUCH_EVENTS);
+8 -7
View File
@@ -35,13 +35,14 @@ std::vector<Analog> &games::ftt::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("FutureTomTom");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Pad 1",
"Pad 2",
"Pad 3",
"Pad 4"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Pad 1", AnalogType::LinearPositive },
{ "Pad 2", AnalogType::LinearPositive },
{ "Pad 3", AnalogType::LinearPositive },
{ "Pad 4", AnalogType::LinearPositive }
});
}
return analogs;
+12 -10
View File
@@ -86,19 +86,21 @@ std::vector<Button> &games::gitadora::get_buttons() {
std::vector<Analog> &games::gitadora::get_analogs() {
static std::vector<Analog> analogs;
using namespace GameAPI::Analogs;
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("GitaDora");
GameAPI::Analogs::sortAnalogs(&analogs,
"Guitar P1 Wail X",
"Guitar P1 Wail Y",
"Guitar P1 Wail Z",
"Guitar P1 Knob",
"Guitar P2 Wail X",
"Guitar P2 Wail Y",
"Guitar P2 Wail Z",
"Guitar P2 Knob"
);
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{"Guitar P1 Wail X", AnalogType::LinearCentered},
{"Guitar P1 Wail Y", AnalogType::LinearCentered},
{"Guitar P1 Wail Z", AnalogType::LinearCentered},
{"Guitar P1 Knob", AnalogType::Circular},
{"Guitar P2 Wail X", AnalogType::LinearCentered},
{"Guitar P2 Wail Y", AnalogType::LinearCentered},
{"Guitar P2 Wail Z", AnalogType::LinearCentered},
{"Guitar P2 Knob", AnalogType::Circular}
});
}
return analogs;
+3 -1
View File
@@ -2,6 +2,7 @@
#include "misc/eamuse.h"
#include "rawinput/rawinput.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "iidx.h"
@@ -82,7 +83,8 @@ bool games::iidx::IIDXFMSerialHandle::FMSerialDevice::parse_msg(
}
// sleep - otherwise the IO thread will go too hard on the CPU
Sleep(1);
static thread_local timeutils::PreciseSleepTimer timer;
timer.sleep(1);
// generate message
auto msg = this->create_msg(msg_in, 0x2E);
+3 -1
View File
@@ -2,6 +2,7 @@
#include "misc/eamuse.h"
#include "rawinput/rawinput.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "iidx.h"
@@ -82,7 +83,8 @@ bool games::iidx::BI2XSerialHandle::BI2XDevice::parse_msg(
}
// sleep - otherwise the IO thread will go too hard on the CPU
Sleep(1);
static thread_local timeutils::PreciseSleepTimer timer;
timer.sleep(1);
// generate message
auto msg = this->create_msg(msg_in, 0x2E);
+3 -1
View File
@@ -67,6 +67,8 @@ namespace games::iidx {
std::optional<std::string> SOUND_OUTPUT_DEVICE = std::nullopt;
std::optional<std::string> SOUND_OUTPUT_DEVICE_IN_EFFECT = std::nullopt;
std::optional<std::string> ASIO_DRIVER = std::nullopt;
uint32_t TT_DELAY_P1 = 0;
uint32_t TT_DELAY_P2 = 0;
uint8_t DIGITAL_TT_SENS = 4;
std::optional<std::string> SUBSCREEN_OVERLAY_SIZE = std::nullopt;
std::optional<std::string> SCREEN_MODE = std::nullopt;
@@ -781,7 +783,7 @@ namespace games::iidx {
}
// return higher 8 bit
return (uint8_t) (ret_value >> 2);
return (uint8_t)(ret_value >> 2);
}
unsigned char get_slider(uint8_t slider) {
+11 -10
View File
@@ -63,16 +63,17 @@ std::vector<Analog> &games::iidx::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Beatmania IIDX");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Turntable P1",
"Turntable P2",
"VEFX",
"Low-EQ",
"Hi-EQ",
"Filter",
"Play Volume"
);
using namespace GameAPI::Analogs;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Turntable P1", AnalogType::Circular },
{ "Turntable P2", AnalogType::Circular },
{ "VEFX", AnalogType::LinearPositive },
{ "Low-EQ", AnalogType::LinearPositive },
{ "Hi-EQ", AnalogType::LinearPositive },
{ "Filter", AnalogType::LinearPositive },
{ "Play Volume", AnalogType::LinearPositive }
});
}
return analogs;
}
+3 -1
View File
@@ -3,6 +3,7 @@
#if SPICE64 && !SPICE_XP
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "mf_wrappers.h"
@@ -399,6 +400,7 @@ namespace games::iidx {
void IIDXLocalCamera::CreateThread() {
// Create thread
m_drawThread = new std::thread([this]() {
timeutils::PreciseSleepTimer timer;
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
double accumulator = 0.0;
@@ -412,7 +414,7 @@ namespace games::iidx {
accumulator -= 1.0;
floorFrameTimeMicroSec += 1;
}
std::this_thread::sleep_for(std::chrono::microseconds(floorFrameTimeMicroSec));
timer.sleep(std::chrono::microseconds(floorFrameTimeMicroSec));
}
});
}
+3 -1
View File
@@ -15,6 +15,7 @@
#include "touch/touch.h"
#include "util/libutils.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#define POKE_NATIVE_TOUCH 0
@@ -200,6 +201,7 @@ namespace games::iidx::poke {
// create new thread
THREAD_RUNNING = true;
THREAD = new std::thread([] {
timeutils::PreciseSleepTimer timer;
// log
log_info("poke", "enabled");
@@ -319,7 +321,7 @@ namespace games::iidx::poke {
}
// slow down
Sleep(50);
timer.sleep(50);
}
return nullptr;
+3
View File
@@ -92,6 +92,9 @@ namespace games {
games.push_back(ddr);
buttons.insert({ ddr, ddr::get_buttons() });
lights.insert({ ddr, ddr::get_lights() });
buttons_help.insert({ ddr, ddr::get_buttons_help() });
analogs_help.insert({ ddr, ddr::get_analogs_help() });
analogs.insert({ ddr, ddr::get_analogs() });
file_hints[ddr].push_back({"ddr.dll"});
file_hints[ddr].push_back({"mdxja_945.dll"});
file_hints[ddr].push_back({"arkmdxp3.dll"});
+86 -13
View File
@@ -19,7 +19,7 @@
namespace games::jb {
// touch stuff
bool TOUCH_LEGACY_BOX = false;
JubeatTouchAlgorithm TOUCH_ALGORITHM = Improved;
static bool TOUCH_ENABLE = false;
static bool TOUCH_ATTACHED = false;
static bool IS_PORTRAIT = true;
@@ -78,7 +78,7 @@ namespace games::jb {
// note that the IO code in device.cpp will correctly compensate for orientation, depending on the model.
TOUCH_POINTS.clear();
touch_get_points(TOUCH_POINTS);
if (TOUCH_LEGACY_BOX) {
if (TOUCH_ALGORITHM == Legacy) {
auto offset = IS_PORTRAIT ? 580 : 0;
for (auto &tp : TOUCH_POINTS) {
@@ -94,6 +94,17 @@ namespace games::jb {
}
} else {
for (auto &tp : TOUCH_POINTS) {
// check window out of bounds
if (IS_PORTRAIT) {
if (tp.x > 768 || tp.y > 1360) {
continue;
}
} else {
if (tp.x > 1360 || tp.y > 768) {
continue;
}
}
int x_relative = tp.x;
int y_relative = tp.y;
@@ -110,19 +121,66 @@ namespace games::jb {
y_relative -= 8;
}
if (x_relative < 0 || y_relative < 0) {
int x_index = -1;
int x_hitbox = 0;
int y_index = -1;
int y_hitbox = 0;
// x_hitbox and y_hitbox is relative to top-left pixel of each button
if (x_relative >= 0) {
x_index = x_relative / JB_BUTTON_HITBOX;
x_hitbox = x_relative % JB_BUTTON_HITBOX;
}
if (y_relative >= 0) {
y_index = y_relative / JB_BUTTON_HITBOX;
y_hitbox = y_relative % JB_BUTTON_HITBOX;
}
// log_info("jb", "raw={}, idx={}, hitbox={}", tp.x, x_index, x_hitbox);
if (TOUCH_ALGORITHM == Improved) {
if (IS_PORTRAIT) {
// extend to left border
if (x_relative < 0) {
x_index = 0;
}
// right and bottom borders are covered by the hit box
} else {
// extend to top border
if (y_relative < 0) {
y_index = 0;
}
// extend to left border
if (x_relative < 0) {
x_index = 0;
}
// bottom border is covered by the hit box
// rightmost edge - ignore them entirely
if (x_index == 3 && JB_BUTTON_SIZE < x_hitbox) {
continue;
}
}
}
if (x_index < 0 || y_index < 0 || x_index > 3 || y_index > 3) {
continue;
}
// x_hitbox and y_hitbox is relative to top-left pixel of each button
int x_index = x_relative / JB_BUTTON_HITBOX;
int x_hitbox = x_relative % JB_BUTTON_HITBOX;
int y_index = y_relative / JB_BUTTON_HITBOX;
int y_hitbox = y_relative % JB_BUTTON_HITBOX;
// check if the gap was touched
if (x_hitbox > JB_BUTTON_SIZE || y_hitbox > JB_BUTTON_SIZE) {
continue;
if (TOUCH_ALGORITHM == AcAccurate) {
// in ac-accurate mode, touching the gap is ignored
if (x_hitbox > JB_BUTTON_SIZE || y_hitbox > JB_BUTTON_SIZE) {
continue;
}
} else if (TOUCH_ALGORITHM == Improved) {
// in improved mode, touching the gap triggers the closest button
if (x_index <= 2 && (JB_BUTTON_SIZE + JB_BUTTON_GAP / 2) < x_hitbox) {
x_index++;
}
if (y_index <= 2 && (JB_BUTTON_SIZE + JB_BUTTON_GAP / 2) < y_hitbox) {
y_index++;
}
}
// set the corresponding state
@@ -167,7 +225,7 @@ namespace games::jb {
void JBGame::pre_attach() {
if (!cfg::CONFIGURATOR_STANDALONE) {
const auto current_path = std::filesystem::current_path();
log_misc("jubeat", "current working directory: {}", current_path.string());
log_misc("jubeat", "current working directory: {}", current_path);
if (current_path.parent_path() == current_path.root_path()) {
log_warning(
"jubeat",
@@ -178,7 +236,7 @@ namespace games::jb {
" c:\\jubeat\\contents\\spice.exe <- OK\n\n"
"To fix this, create a new directory and move ALL game files there.\n\n"
"Your current working directory: {}\n",
current_path.string());
current_path);
log_fatal(
"jubeat",
@@ -193,6 +251,21 @@ namespace games::jb {
// enable touch
TOUCH_ENABLE = true;
switch (TOUCH_ALGORITHM) {
case Legacy:
log_info("jubeat", "using 'legacy' touch targets");
break;
case Improved:
log_info("jubeat", "using 'improved' touch targets");
break;
case AcAccurate:
log_info("jubeat", "using 'ac accurate' touch targets");
break;
default:
log_fatal("jubeat", "unknown touch algo detected in touch_update, this is a bug");
break;
}
// enable debug logging of gftools
HMODULE gftools = libutils::try_module("gftools.dll");
detour::inline_hook((void *) GFDbgSetReportFunc, libutils::try_proc(
+7 -1
View File
@@ -4,8 +4,14 @@
namespace games::jb {
enum JubeatTouchAlgorithm {
Legacy,
Improved,
AcAccurate
};
// touch stuff
extern bool TOUCH_LEGACY_BOX;
extern JubeatTouchAlgorithm TOUCH_ALGORITHM;
extern bool TOUCH_STATE[16];
void touch_update();
+5 -5
View File
@@ -36,11 +36,11 @@ std::vector<Analog> &games::mga::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Metal Gear");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Joy X",
"Joy Y"
);
using namespace GameAPI::Analogs;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Joy X", AnalogType::LinearCentered },
{ "Joy Y", AnalogType::LinearCentered }
});
}
return analogs;
+32 -31
View File
@@ -165,37 +165,38 @@ std::vector<Analog> &games::nost::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Nostalgia");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Key 1",
"Key 2",
"Key 3",
"Key 4",
"Key 5",
"Key 6",
"Key 7",
"Key 8",
"Key 9",
"Key 10",
"Key 11",
"Key 12",
"Key 13",
"Key 14",
"Key 15",
"Key 16",
"Key 17",
"Key 18",
"Key 19",
"Key 20",
"Key 21",
"Key 22",
"Key 23",
"Key 24",
"Key 25",
"Key 26",
"Key 27",
"Key 28"
);
using namespace GameAPI::Analogs;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Key 1", AnalogType::LinearPositive },
{ "Key 2", AnalogType::LinearPositive },
{ "Key 3", AnalogType::LinearPositive },
{ "Key 4", AnalogType::LinearPositive },
{ "Key 5", AnalogType::LinearPositive },
{ "Key 6", AnalogType::LinearPositive },
{ "Key 7", AnalogType::LinearPositive },
{ "Key 8", AnalogType::LinearPositive },
{ "Key 9", AnalogType::LinearPositive },
{ "Key 10", AnalogType::LinearPositive },
{ "Key 11", AnalogType::LinearPositive },
{ "Key 12", AnalogType::LinearPositive },
{ "Key 13", AnalogType::LinearPositive },
{ "Key 14", AnalogType::LinearPositive },
{ "Key 15", AnalogType::LinearPositive },
{ "Key 16", AnalogType::LinearPositive },
{ "Key 17", AnalogType::LinearPositive },
{ "Key 18", AnalogType::LinearPositive },
{ "Key 19", AnalogType::LinearPositive },
{ "Key 20", AnalogType::LinearPositive },
{ "Key 21", AnalogType::LinearPositive },
{ "Key 22", AnalogType::LinearPositive },
{ "Key 23", AnalogType::LinearPositive },
{ "Key 24", AnalogType::LinearPositive },
{ "Key 25", AnalogType::LinearPositive },
{ "Key 26", AnalogType::LinearPositive },
{ "Key 27", AnalogType::LinearPositive },
{ "Key 28", AnalogType::LinearPositive }
});
}
return analogs;
}
+3 -1
View File
@@ -9,6 +9,7 @@
#include "misc/eamuse.h"
#include "touch/touch.h"
#include "util/logging.h"
#include "util/precise_timer.h"
namespace games::nost::poke {
@@ -63,6 +64,7 @@ namespace games::nost::poke {
// create new thread
THREAD_RUNNING = true;
THREAD = new std::thread([] {
timeutils::PreciseSleepTimer timer;
const DWORD touch_id = (DWORD)(0xFFFFFFFE);
const int swipe_anim_total_frames = 6;
@@ -178,7 +180,7 @@ namespace games::nost::poke {
}
// slow down
Sleep(30);
timer.sleep(30);
}
return nullptr;
+6 -2
View File
@@ -4,6 +4,7 @@
#include "touchpanel.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "touch/touch.h"
using namespace std::chrono_literals;
@@ -44,6 +45,9 @@ bool games::onpara::TouchPanelHandle::open(LPCWSTR lpFileName) {
}
int games::onpara::TouchPanelHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
static thread_local timeutils::PreciseSleepTimer timer;
DWORD i;
auto buffer = reinterpret_cast<uint8_t *>(lpBuffer);
@@ -67,7 +71,7 @@ int games::onpara::TouchPanelHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesT
enqueue_packet(report);
// prevent cpu bullying
std::this_thread::sleep_for(1ms);
timer.sleep(1);
}
// copy from output queue
@@ -133,4 +137,4 @@ bool games::onpara::TouchPanelHandle::close() {
log_info("touchpanel", "Closed COM1 (Touch Panel)");
return true;
}
}
+6 -5
View File
@@ -51,11 +51,12 @@ std::vector<Analog> &games::pc::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Polaris Chord");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Fader-L",
"Fader-R"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Fader-L", AnalogType::LinearCentered },
{ "Fader-R", AnalogType::LinearCentered }
});
}
return analogs;
+10 -10
View File
@@ -4,6 +4,8 @@
#include "hooks/devicehook.h"
#include "hooks/audio/backends/dsound/dsound_backend.h"
#include "util/detour.h"
#include "util/precise_timer.h"
#include "util/logging.h"
#include "touch.h"
@@ -11,20 +13,18 @@ static decltype(SleepEx) *SleepEx_orig;
static DWORD WINAPI SleepEx_hook(DWORD dwMilliseconds, BOOL bAltertable) {
/*
* Increase touch poll from ~110 FPS to ~500 FPS
*/
// increase touch poll from ~110 FPS to ~500 FPS (Sleep) or ~1000 FPS (Win10 high-res timer)
if (dwMilliseconds == 8) {
static bool initialized = false;
if (!initialized) {
initialized = true;
// if we only sleep for 1ms we also don't need the high priority RB sets
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
dwMilliseconds = 1;
}
// most calls from rb are actually non-alertable
if (!bAltertable) {
static thread_local timeutils::PreciseSleepTimer timer;
timer.sleep(dwMilliseconds);
return 0;
}
// call original
return SleepEx_orig(dwMilliseconds, bAltertable);
}
+7 -6
View File
@@ -35,12 +35,13 @@ std::vector<Analog> &games::rf3d::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Road Fighters 3D");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Wheel",
"Accelerate",
"Brake"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Wheel", AnalogType::LinearCentered },
{ "Accelerate", AnalogType::LinearPositive },
{ "Brake", AnalogType::LinearPositive }
});
}
return analogs;
+8 -7
View File
@@ -31,13 +31,14 @@ std::vector<Analog> &games::sc::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Steel Chronicle");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Left Stick X",
"Left Stick Y",
"Right Stick X",
"Right Stick Y"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Left Stick X", AnalogType::LinearCentered },
{ "Left Stick Y", AnalogType::LinearCentered },
{ "Right Stick X", AnalogType::LinearCentered },
{ "Right Stick Y", AnalogType::LinearCentered }
});
}
return analogs;
+6 -5
View File
@@ -31,11 +31,12 @@ std::vector<Analog> &games::silentscope::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Silent Scope: Bone Eater");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Gun X",
"Gun Y"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Gun X", AnalogType::LinearCentered },
{ "Gun Y", AnalogType::LinearCentered }
});
}
return analogs;
+8 -7
View File
@@ -50,13 +50,14 @@ std::vector<Analog> &games::we::get_analogs() {
if (analogs.empty()) {
analogs = GameAPI::Analogs::getAnalogs("Winning Eleven");
GameAPI::Analogs::sortAnalogs(
&analogs,
"Pad Stick Left X",
"Pad Stick Left Y",
"Pad Stick Right X",
"Pad Stick Right Y"
);
using GameAPI::Analogs::AnalogType;
GameAPI::Analogs::sortAnalogsWithType(&analogs, {
{ "Pad Stick Left X", AnalogType::LinearCentered },
{ "Pad Stick Left Y", AnalogType::LinearCentered },
{ "Pad Stick Right X", AnalogType::LinearCentered },
{ "Pad Stick Right Y", AnalogType::LinearCentered }
});
}
return analogs;
@@ -3,6 +3,7 @@
#include "hooks/audio/audio.h"
#include "hooks/audio/backends/wasapi/audio_client.h"
#include "hooks/audio/backends/wasapi/defs.h"
#include "util/precise_timer.h"
static REFERENCE_TIME WASAPI_TARGET_REFTIME = TARGET_REFTIME;
@@ -185,6 +186,7 @@ HRESULT WaveOutBackend::on_get_buffer(uint32_t num_frames_requested, BYTE **ppDa
}
HRESULT WaveOutBackend::on_release_buffer(uint32_t num_frames_written, DWORD dwFlags) {
bool written = false;
timeutils::PreciseSleepTimer timer;
// reset the dispatcher event
ResetEvent(this->dispatcher_event);
@@ -209,7 +211,7 @@ HRESULT WaveOutBackend::on_release_buffer(uint32_t num_frames_written, DWORD dwF
// avoid pegging the CPU
if (!written) {
Sleep(1);
timer.sleep(1);
}
}
+2 -2
View File
@@ -291,7 +291,7 @@ static int avs_fs_mount(const char *mountpoint, const char *fsroot, const char *
std::filesystem::create_directories(mapped_path, err);
if (err) {
log_warning("hooks::avs", "failed to create '{}': {}", mapped_path.string(), err.message());
log_warning("hooks::avs", "failed to create '{}': {}", mapped_path, err.message());
} else {
// if this is the `e:\`, then create the special directories
@@ -305,7 +305,7 @@ static int avs_fs_mount(const char *mountpoint, const char *fsroot, const char *
log_misc("hooks::avs", "source directory '{}' remapped to '{}'",
fsroot,
mapped_path.string());
mapped_path);
}
new_fs_root = mapped_path.string();
+136 -24
View File
@@ -59,6 +59,12 @@ static CaptureData GRAPHICS_CAPTURE_BUFFER[GRAPHICS_CAPTURE_SCREEN_NO] {};
static std::mutex GRAPHICS_CAPTURE_BUFFER_M[GRAPHICS_CAPTURE_SCREEN_NO] {};
static std::condition_variable GRAPHICS_CAPTURE_CV[GRAPHICS_CAPTURE_SCREEN_NO] {};
static std::optional<graphics_orientation> target_orientation_on_boot;
static UINT target_refresh_rate_on_boot = 0;
static std::optional<std::pair<uint32_t, uint32_t>> target_resolution_on_boot;
static bool monitor_settings_changed = false;
static bool monitor_layout_needs_reset = false;
// flag settings
bool GRAPHICS_CAPTURE_CURSOR = false;
bool GRAPHICS_LOG_HRESULT = false;
@@ -104,6 +110,7 @@ static decltype(SetWindowLongA) *SetWindowLongA_orig = nullptr;
static decltype(SetWindowLongW) *SetWindowLongW_orig = nullptr;
static decltype(SetWindowPos) *SetWindowPos_orig = nullptr;
static decltype(ShowWindow) *ShowWindow_orig = nullptr;
static decltype(SetDisplayConfig) *SetDisplayConfig_addr = nullptr;
static void reset_window_hook(HWND hWnd) {
overlay::destroy(hWnd);
@@ -157,6 +164,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM l
if (wintouchemu::INJECT_MOUSE_AS_WM_TOUCH) {
// drop mouse inputs since only wintouches should be used
switch (uMsg) {
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
@@ -232,7 +240,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM l
switch (uMsg) {
case WM_MOVE:
case WM_SIZE: {
case WM_SIZE:
// Update SPICETOUCH space when the main window changes size or moves.
// The update happens regardless of whether the "fake" spicetouch window is present or not.
// This allows touches received on subscreen window to be translated correctly.
@@ -249,7 +257,16 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM l
SPICETOUCH_TOUCH_WIDTH, SPICETOUCH_TOUCH_HEIGHT,
SWP_NOZORDER | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOACTIVATE);
}
}
break;
case WM_ACTIVATEAPP:
if (wParam) {
// regained focus
// this *can* get called twice in a row when restoring, but update_monitor_at_runtime
// is idempotent (checks current display settings to see if changes are needed),
// so it shouldn't cause any issues
update_monitor_at_runtime();
}
break;
default:
break;
}
@@ -340,16 +357,24 @@ static HWND WINAPI CreateWindowExA_hook(DWORD dwExStyle, LPCSTR lpClassName, LPC
bool is_popn_sub_window = avs::game::is_model("M39") && window_name.ends_with("Sub Screen");
bool is_gfdm_sub_window = games::gitadora::is_arena_model() && window_name.ends_with("SMALL");
// hide maximize button (prevent misaligned touches)
if ((is_tdj_sub_window && GRAPHICS_IIDX_WSUB) || is_sdvx_sub_window || is_gfdm_sub_window || is_popn_sub_window) {
// update style / ex-style
if (is_tdj_sub_window || is_sdvx_sub_window || is_gfdm_sub_window || is_popn_sub_window) {
// hide maximize button (prevent misaligned touches)
dwStyle &= ~(WS_MAXIMIZEBOX);
}
// mouse clicks become misaligned when resized
if (is_gfdm_sub_window) {
// mouse clicks become misaligned when resized
dwStyle &= ~(WS_SIZEBOX);
}
if ((is_tdj_sub_window || is_sdvx_sub_window || is_popn_sub_window) && GRAPHICS_WSUB_BORDERLESS) {
dwStyle &= ~(WS_OVERLAPPEDWINDOW);
// borderless
if (GRAPHICS_WINDOWED && GRAPHICS_WSUB_BORDERLESS) {
dwStyle &= ~(WS_OVERLAPPEDWINDOW);
}
// don't show the sub window on task bar / alt-tab targets
if (!GRAPHICS_WINDOWED) {
dwExStyle &= ~(WS_EX_APPWINDOW);
dwExStyle |= WS_EX_TOOLWINDOW;
}
}
if (is_sdvx_sub_window) {
@@ -1142,7 +1167,7 @@ void change_primary_monitor(const std::string &monitor_name) {
const auto DisplayConfigGetDeviceInfo_addr =
reinterpret_cast<decltype(DisplayConfigGetDeviceInfo) *>(
GetProcAddress(user32, "DisplayConfigGetDeviceInfo"));
const auto SetDisplayConfig_addr =
SetDisplayConfig_addr =
reinterpret_cast<decltype(SetDisplayConfig) *>(
GetProcAddress(user32, "SetDisplayConfig"));
if (GetDisplayConfigBufferSizes_addr == nullptr || QueryDisplayConfig_addr == nullptr ||
@@ -1257,12 +1282,19 @@ void change_primary_monitor(const std::string &monitor_name) {
log_fatal("graphics", "SetDisplayConfig failed, check -mainmonitor option: {}", status);
}
monitor_layout_needs_reset = true;
// a little extra time for windows to settle and redraw things
Sleep(2000);
}
void update_monitor_on_boot(std::optional<graphics_orientation> target_orientation, UINT target_refresh_rate) {
// note: all of this is only being done for the primary motnior
void update_monitor(
bool is_boot,
std::optional<graphics_orientation> target_orientation,
UINT target_refresh_rate,
std::optional<std::pair<uint32_t, uint32_t>> target_resolution) {
// note: all of this is only being done for the primary monitor
// get current settings
DEVMODEA dm = {};
@@ -1330,7 +1362,7 @@ void update_monitor_on_boot(std::optional<graphics_orientation> target_orientati
}
// update refresh rate
if (target_refresh_rate > 0) {
if (target_refresh_rate > 0 && target_refresh_rate != dm.dmDisplayFrequency) {
log_misc("graphics",
"current refresh rate {} => desired refresh rate {}",
dm.dmDisplayFrequency, target_refresh_rate);
@@ -1340,27 +1372,107 @@ void update_monitor_on_boot(std::optional<graphics_orientation> target_orientati
needs_update = true;
}
if (target_resolution.has_value()) {
if (dm.dmPelsWidth != target_resolution.value().first ||
dm.dmPelsHeight != target_resolution.value().second) {
log_misc(
"graphics",
"current resolution {}, {} => desired resolution {}, {}",
dm.dmPelsWidth, dm.dmPelsHeight,
target_resolution.value().first, target_resolution.value().second);
dm.dmPelsWidth = target_resolution.value().first;
dm.dmPelsHeight = target_resolution.value().second;
needs_update = true;
}
}
if (!needs_update) {
// nothing to do
log_misc("graphics", "display settings are already up to date, no changes needed");
return;
}
const auto result = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
if (result != DISP_CHANGE_SUCCESSFUL) {
log_fatal(
"graphics",
"failed to update display settings ({}px x {}px @ {}Hz): error {}, double check options",
dm.dmPelsWidth,
dm.dmPelsHeight,
dm.dmDisplayFrequency,
result);
if (is_boot) {
log_fatal(
"graphics",
"failed to update display settings ({}px x {}px @ {}Hz): error {}, double check options",
dm.dmPelsWidth,
dm.dmPelsHeight,
dm.dmDisplayFrequency,
result);
} else {
log_warning(
"graphics",
"failed to update display settings ({}px x {}px @ {}Hz): error {}, double check options",
dm.dmPelsWidth,
dm.dmPelsHeight,
dm.dmDisplayFrequency,
result);
}
} else {
monitor_settings_changed = true;
// sleep for a little bit after changing monitor settings to delay game launch/resume
Sleep(1000);
log_info("graphics", "display settings updated successfully ({}px x {}px @ {}Hz)",
dm.dmPelsWidth,
dm.dmPelsHeight,
dm.dmDisplayFrequency);
}
// sleep for a little bit after changing monitor settings to delay game launch
Sleep(1000);
}
void update_monitor_on_boot(
std::optional<graphics_orientation> target_orientation,
UINT target_refresh_rate,
std::optional<std::pair<uint32_t, uint32_t>> target_resolution) {
target_orientation_on_boot = target_orientation;
target_refresh_rate_on_boot = target_refresh_rate;
target_resolution_on_boot = target_resolution;
log_misc("graphics", "applying monitor updates at boot...");
update_monitor(
true,
target_orientation,
target_refresh_rate,
target_resolution);
}
void update_monitor_at_runtime() {
if (!GRAPHICS_WINDOWED && monitor_settings_changed) {
log_misc("graphics", "applying monitor updates at runtime as window regained focus...");
update_monitor(
false,
target_orientation_on_boot,
target_refresh_rate_on_boot,
target_resolution_on_boot);
}
}
void reset_monitor_on_exit() {
// while CDS_FULLSCREEN is *supposed* to be temporary & the OS attempts to
// restore the original settings on exit, it can sometimes fail to do that;
// therefore, we try our best to clean things up on the way out
if (monitor_settings_changed) {
monitor_settings_changed = false;
log_misc("graphics", "resetting monitor settings on exit...");
ChangeDisplaySettingsW(nullptr, 0);
}
// same for this one.
if (monitor_layout_needs_reset) {
monitor_layout_needs_reset = false;
log_misc("graphics", "restoring primary monitor on exit...");
if (SetDisplayConfig_addr != nullptr) {
SetDisplayConfig_addr(
0,
nullptr,
0,
nullptr,
SDC_APPLY | SDC_USE_DATABASE_CURRENT);
}
}
}
+7 -1
View File
@@ -117,4 +117,10 @@ void graphics_load_windowed_subscreen_parameters();
void graphics_window_check_bounds_before_creation(int &x, int &y, const int width, const int height);
void change_primary_monitor(const std::string &monitor_name);
void update_monitor_on_boot(std::optional<graphics_orientation> target_orientation, UINT target_refresh_rate);
void update_monitor_on_boot(
std::optional<graphics_orientation> target_orientation,
UINT target_refresh_rate,
std::optional<std::pair<uint32_t, uint32_t>> target_resolution);
void update_monitor_at_runtime();
void reset_monitor_on_exit();
+49 -12
View File
@@ -98,6 +98,7 @@
#include "rawinput/rawinput.h"
#include "rawinput/touch.h"
#include "reader/reader.h"
#include "sdk/sdk.h"
#include "stubs/stubs.h"
#include "touch/touch.h"
#include "util/cpuutils.h"
@@ -107,6 +108,7 @@
#include "util/libutils.h"
#include "util/logging.h"
#include "util/peb.h"
#include "util/precise_timer.h"
#include "util/socd_cleaner.h"
#include "util/sysutils.h"
#include "util/tapeled.h"
@@ -383,6 +385,16 @@ int main_implementation(int argc, char *argv[]) {
monitor_orientation = ORIENTATION_CW;
}
std::optional<std::pair<uint32_t, uint32_t>> monitor_resolution;
if (options[launcher::Options::ChangeResolution].is_active()) {
std::pair<uint32_t, uint32_t> result;
if (parse_width_height(options[launcher::Options::ChangeResolution].value_text(), result)) {
monitor_resolution = result;
} else if (!cfg_run && !cfg::CONFIGURATOR_STANDALONE) {
log_fatal("launcher", "failed to parse -changeres");
}
}
if (options[launcher::Options::spice2x_NoD3D9DeviceHook].value_bool()) {
D3D9_DEVICE_HOOK_DISABLE = true;
// touch emulation gets disabled, might as well turn these on
@@ -1146,8 +1158,18 @@ int main_implementation(int argc, char *argv[]) {
}
if (options[launcher::Options::spice2x_JubeatLegacyTouch].value_bool()) {
games::jb::TOUCH_LEGACY_BOX = true;
games::jb::TOUCH_ALGORITHM = games::jb::JubeatTouchAlgorithm::Legacy;
}
if (options[launcher::Options::JubeatTouchAlgo].is_active()) {
if (options[launcher::Options::JubeatTouchAlgo].value_text() == "accurate") {
games::jb::TOUCH_ALGORITHM = games::jb::JubeatTouchAlgorithm::AcAccurate;
} else if (options[launcher::Options::JubeatTouchAlgo].value_text() == "legacy") {
games::jb::TOUCH_ALGORITHM = games::jb::JubeatTouchAlgorithm::Legacy;
} else {
games::jb::TOUCH_ALGORITHM = games::jb::JubeatTouchAlgorithm::Improved;
}
}
if (options[launcher::Options::spice2x_RBTouchScale].is_active()) {
games::rb::TOUCH_SCALING = options[launcher::Options::spice2x_RBTouchScale].value_uint32();
}
@@ -1272,6 +1294,10 @@ int main_implementation(int argc, char *argv[]) {
games::loveplus::CAMERA_ENABLE = true;
}
if (options[launcher::Options::DisableHighResTimer].value_bool()) {
timeutils::TIMER_HACKS_DISABLE = true;
}
// API debugging
if (api_debug && !cfg::CONFIGURATOR_STANDALONE) {
API_CONTROLLER = std::make_unique<api::Controller>(api_port, api_pass, api_pretty);
@@ -1531,16 +1557,18 @@ int main_implementation(int argc, char *argv[]) {
}
// early hooks
for (auto &hook : early_hooks) {
log_info("launcher", "loading early hook DLL {}", hook);
libutils::print_dll_info(hook);
HMODULE module;
if (!(module = libutils::try_library(hook))) {
log_warning("launcher", "failed to load early hook {}: {}", hook, get_last_error_string());
deferredlogs::defer_error_messages({
fmt::format("failed to load early hook {}:", hook),
fmt::format(" {}", get_last_error_string())
});
if (!cfg_run) {
for (auto &hook : early_hooks) {
log_info("launcher", "loading early hook DLL {}", hook);
libutils::print_dll_info(hook);
HMODULE module;
if (!(module = libutils::try_library(hook))) {
log_warning("launcher", "failed to load early hook {}: {}", hook, get_last_error_string());
deferredlogs::defer_error_messages({
fmt::format("failed to load early hook {}:", hook),
fmt::format(" {}", get_last_error_string())
});
}
}
}
@@ -2171,7 +2199,7 @@ int main_implementation(int argc, char *argv[]) {
if (options[launcher::Options::PrimaryMonitor].is_active()) {
change_primary_monitor(options[launcher::Options::PrimaryMonitor].value_text());
}
update_monitor_on_boot(monitor_orientation, GRAPHICS_FORCE_REFRESH);
update_monitor_on_boot(monitor_orientation, GRAPHICS_FORCE_REFRESH, monitor_resolution);
// initialize raw input
RI_MGR = std::make_unique<rawinput::RawInputManager>();
@@ -2224,6 +2252,9 @@ int main_implementation(int argc, char *argv[]) {
hooks::lang::early_init();
}
// use high resolution timer for this process
timeutils::set_timer_resolution();
// load DLLs
avs::core::load_dll();
avs::ea3::load_dll();
@@ -2358,6 +2389,7 @@ int main_implementation(int argc, char *argv[]) {
});
} else {
bt5api_hook(module);
sdk::register_sdk_hooks(hook, module);
}
}
@@ -2392,6 +2424,9 @@ int main_implementation(int argc, char *argv[]) {
bt5api_init();
}
// init SDK
sdk::init_sdk_modules();
// API
if (api_enable || std::min(api_serial_port.size(), api_serial_baud.size()) > 0) {
API_CONTROLLER = std::make_unique<api::Controller>(api_port, api_pass, api_pretty);
@@ -2499,6 +2534,8 @@ int main_implementation(int argc, char *argv[]) {
bt5api_dispose();
}
sdk::fini_sdk_modules();
// stop raw input
RI_MGR.reset();
+39 -4
View File
@@ -1920,6 +1920,15 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = {
{"3", "Landscape, Flipped"}
},
},
{
// ChangeResolution
.title = "Change Monitor Resolution",
.name = "changeres",
.desc = "Changes monitor resolution before booting the game.",
.type = OptionType::Text,
.setting_name = "1280,720",
.category = "Monitor"
},
{
.title = "AVS Log Level",
.name = "loglevel",
@@ -2279,16 +2288,32 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = {
},
{
// spice2x_JubeatLegacyTouch
.title = "JB Legacy Touch Targets",
.title = "JB Legacy Touch Targets (Deprecated - use -jubeattouchalgo instead)",
.name = "sp2x-jubeatlegacytouch",
.display_name = "jubeatlegacytouch",
.aliases= "jubeatlegacytouch",
.desc = "For touch screen players - use the legacy & less accurate grid-based layout for touch recognition, "
"instead of the new & more accurate touch targets. Default: off.",
.desc = "Deprecated - use -jubeattouchalgo instead.",
.type = OptionType::Bool,
.hidden = true,
.game_name = "Jubeat",
.category = "Game Options",
},
{
.title = "JB Touch Algorithm",
.name = "jubeattouchalgo",
.desc = "For touch screen players - choose the touch algorithm to use.\n\n"
"legacy - evenly divide the grid into 16 squares; old spicetools behavior, slightly inaccurate in gaps\n\n"
"improved (default) - squares register as-is, gaps will trigger the closest square\n\n"
"accurate - only touches within squares will trigger; gaps do nothing (for AC size touch screens)",
.type = OptionType::Enum,
.game_name = "Jubeat",
.category = "Game Options",
.elements = {
{"legacy", ""},
{"improved", ""},
{"accurate", ""},
},
},
{
// spice2x_RBTouchScale
.title = "RB Scale Touch Input",
@@ -2769,7 +2794,17 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = {
.type = OptionType::Bool,
.game_name = "Otoca D'or",
.category = "Game Options (Peripherals)",
}
},
{
// DisableHighResTimer
.title = "Use Legacy Timers",
.name = "notimerhacks",
.desc = "Disables high resolution timers, reverting to legacy behavior. "
"Recommended that you leave this OFF for optimal input latency, "
"unless you're on a resource-constrained system (e.g., old cabinet PC)",
.type = OptionType::Bool,
.category = "Development"
},
};
const std::vector<std::string> &launcher::get_categories(Options::OptionsCategory category) {
+3
View File
@@ -199,6 +199,7 @@ namespace launcher {
LoadStubs,
AdjustOrientation,
spice2x_AutoOrientation,
ChangeResolution,
LogLevel,
EAAutomap,
EANetdump,
@@ -239,6 +240,7 @@ namespace launcher {
IIDXWindowedSubscreenBorderless,
IIDXWindowedSubscreenAlwaysOnTop,
spice2x_JubeatLegacyTouch,
JubeatTouchAlgo,
spice2x_RBTouchScale,
spice2x_AsioForceUnload,
spice2x_IIDXNoESpec,
@@ -279,6 +281,7 @@ namespace launcher {
LovePlusPrinterJPGQuality,
OptionConflictResolution,
OtocaCamHook,
DisableHighResTimer,
};
enum class OptionsCategory {
+7
View File
@@ -7,12 +7,14 @@
#include "easrv/easrv.h"
#include "rawinput/rawinput.h"
#include "hooks/audio/audio.h"
#include "hooks/graphics/graphics.h"
#include "util/deferlog.h"
#include "util/logging.h"
#include "launcher.h"
#include "logger.h"
#include "nvapi/nvapi.h"
#include "sdk/sdk.h"
namespace launcher {
@@ -22,6 +24,11 @@ namespace launcher {
// therefore, subsystems need to be guarded against multiple unload attempts
log_info("launcher", "stopping subsystems");
sdk::fini_sdk_modules();
// reset monitor settings
reset_monitor_on_exit();
// before shutting down logger, dump any deferred log messages
deferredlogs::dump_to_logger();
+3 -1
View File
@@ -67,7 +67,9 @@ namespace superexit {
}
}
bool async_key_exit = GetAsyncKeyState(VK_MENU) && GetAsyncKeyState(VK_F4);
bool async_key_exit =
(GetAsyncKeyState(VK_MENU) & 0x8000) != 0 &&
(GetAsyncKeyState(VK_F4) & 0x8000) != 0;
bool overlay_exit = false;
auto buttons = games::get_buttons_overlay(eamuse_get_game());
+15 -12
View File
@@ -9,6 +9,7 @@
#include "rawinput/rawinput.h"
#include "games/sdvx/sdvx.h"
#include "util/logging.h"
#include "util/precise_timer.h"
#include "util/time.h"
#include "util/utils.h"
#include "overlay/overlay.h"
@@ -87,7 +88,7 @@ bool eamuse_get_card(const std::filesystem::path &path, uint8_t *card, int index
std::unique_lock<std::mutex> lock(CARD_OVERRIDES_LOCK);
const auto card_override = CARD_OVERRIDES[index];
lock.unlock();
// Check if card overrides are present
if (!card_override.empty()) {
@@ -131,7 +132,7 @@ bool eamuse_get_card_from_file(const std::filesystem::path &path, uint8_t *card,
// open file
std::ifstream f(path);
if (!f) {
log_warning("eamuse", "{} can not be opened!", path.string());
log_warning("eamuse", "{} can not be opened!", path);
return false;
}
@@ -142,7 +143,7 @@ bool eamuse_get_card_from_file(const std::filesystem::path &path, uint8_t *card,
// check size
if (length < 16) {
log_warning("eamuse", "{} is too small (must be at least 16 characters)", path.string());
log_warning("eamuse", "{} is too small (must be at least 16 characters)", path);
return false;
}
@@ -160,14 +161,14 @@ bool eamuse_get_card_from_file(const std::filesystem::path &path, uint8_t *card,
if (!digit && !character_big && !character_small) {
log_warning("eamuse",
"{} contains an invalid character sequence at byte {} (16 characters, 0-9/A-F only)",
path.string(), n);
path, n);
return false;
}
}
// info
log_info("eamuse", "[P{}] Inserted {}: {}", index+1, path.string(), buffer);
log_info("eamuse", "[P{}] Inserted {}: {}", index+1, path, buffer);
// convert hex to bytes
hex2bin(buffer, card);
@@ -286,6 +287,7 @@ void eamuse_coin_start_thread() {
COIN_INPUT_THREAD = new std::thread([]() {
auto overlay_buttons = games::get_buttons_overlay(eamuse_get_game());
static bool COIN_INPUT_KEY_STATE = false;
timeutils::PreciseSleepTimer timer;
while (COIN_INPUT_THREAD_ACTIVE) {
// check input key
@@ -305,7 +307,7 @@ void eamuse_coin_start_thread() {
}
// once every two frames
Sleep(1000 / 30);
timer.sleep(1000 / 30);
}
});
}
@@ -340,6 +342,7 @@ void eamuse_pin_macro_start_thread() {
size_t pin_index[2] = {PIN_MACRO_VALUES[0].length(), PIN_MACRO_VALUES[1].length()};
std::optional<uint8_t> active_unit = std::nullopt;
timeutils::PreciseSleepTimer timer;
while (PIN_MACRO_THREAD_ACTIVE) {
// wait for key press
@@ -359,7 +362,7 @@ void eamuse_pin_macro_start_thread() {
}
if (!active_unit.has_value()) {
Sleep(20);
timer.sleep(20);
continue;
}
}
@@ -375,22 +378,22 @@ void eamuse_pin_macro_start_thread() {
eamuse_set_keypad_overrides(unit, keypad_overrides[char_index]);
}
pin_index[unit]++;
Sleep(100);
timer.sleep(100);
// clear
eamuse_set_keypad_overrides(unit, 0);
Sleep(50);
timer.sleep(50);
// end of PIN
if (pin_index[unit] == PIN_MACRO_VALUES[unit].length()) {
active_unit = std::nullopt;
Sleep(120);
timer.sleep(120);
}
continue;
}
Sleep(200);
timer.sleep(200);
}
});
}
@@ -454,7 +457,7 @@ uint16_t eamuse_get_keypad_state(size_t unit) {
if (unit >= std::size(KEYPAD_STATE)) {
return 0;
}
// reset
KEYPAD_STATE[unit] = KEYPAD_STATE_OVERRIDES[unit];
KEYPAD_STATE[unit] |= KEYPAD_STATE_OVERRIDES_BT5[unit];
+16 -2
View File
@@ -38,6 +38,9 @@ namespace wintouchemu {
bool INJECT_MOUSE_AS_WM_TOUCH = false;
bool LOG_FPS = false;
bool ADD_TOUCH_FLAG_PRIMARY = false;
// state
double last_touch_event = 0.0;
static inline bool is_emu_enabled() {
return FORCE || !is_touch_available("wintouchemu::is_emu_enabled") || GRAPHICS_SHOW_CURSOR;
@@ -248,7 +251,10 @@ namespace wintouchemu {
touch_input->y -= SPICETOUCH_TOUCH_Y;
}
// log_misc("wintouchemu", "mouse state ({}, {})", to_string(touch_input->x), to_string(touch_input->y));
// log_misc(
// "wintouchemu",
// "mouse state ({}, {}) event={}",
// to_string(touch_input->x), to_string(touch_input->y), mouse_state.touch_event);
auto valid = true;
if (overlay::OVERLAY) {
@@ -439,6 +445,8 @@ namespace wintouchemu {
}
}
const auto now = get_performance_milliseconds();
// update touch events
if (hWnd != nullptr) {
@@ -458,6 +466,7 @@ namespace wintouchemu {
// check if new events are available
if (event_count > 0) {
last_touch_event = now;
// send fake event to make the game update it's touch inputs
auto wndProc = (WNDPROC) GetWindowLongPtr(hWnd, GWLP_WNDPROC);
@@ -484,7 +493,12 @@ namespace wintouchemu {
// value from GetTouchInputInfo or fail to read dwFlags for valid events, so it's not OK to
// send empty events when the mouse button is not clicked/released
if (hWnd != nullptr && USE_MOUSE) {
bool button_pressed = ((GetKeyState(VK_LBUTTON) & 0x100) != 0);
bool button_pressed = get_async_primary_mouse();
// if there was a touch event in the last 500 ms, don't insert new button presses
if (button_pressed && (now - last_touch_event) < 500) {
button_pressed = false;
}
// figure out what kind of touch event to simulate
if (button_pressed && !mouse_state.last_button_pressed) {
+40 -29
View File
@@ -351,7 +351,8 @@ void ImGui_ImplSpice_NewFrame() {
// only process new input from devices if window is in focus
// (when not in focus, all mouse/keyboard events are treated as released)
const auto accept_new_input = superexit::has_focus() && !rawinput::OS_WINDOW_ACTIVE;
const auto overlay_visible = overlay::OVERLAY && overlay::OVERLAY->get_active();
const auto accept_new_input = superexit::has_focus() && !rawinput::OS_WINDOW_ACTIVE && overlay_visible;
// remember old state
std::array<BYTE, VKEY_MAX> KeysDownOld;
@@ -366,14 +367,16 @@ void ImGui_ImplSpice_NewFrame() {
g_KeysDown.fill(false);
// apply windows mouse buttons
g_MouseDown[ImGuiMouseButton_Left] |= (get_async_primary_mouse()) != 0;
g_MouseDown[ImGuiMouseButton_Right] |= (get_async_secondary_mouse()) != 0;
g_MouseDown[ImGuiMouseButton_Middle] |= (GetAsyncKeyState(VK_MBUTTON)) != 0;
if (accept_new_input) {
g_MouseDown[ImGuiMouseButton_Left] |= get_async_primary_mouse();
g_MouseDown[ImGuiMouseButton_Right] |= get_async_secondary_mouse();
g_MouseDown[ImGuiMouseButton_Middle] |= (GetAsyncKeyState(VK_MBUTTON) & 0x8000) != 0;
}
// read new keys state
static long mouse_wheel_last = 0;
long mouse_wheel = 0;
if (RI_MGR != nullptr && accept_new_input) {
if (RI_MGR != nullptr) {
auto devices = RI_MGR->devices_get();
for (auto &device : devices) {
switch (device.type) {
@@ -381,40 +384,46 @@ void ImGui_ImplSpice_NewFrame() {
auto &mouse = device.mouseInfo;
// mouse button triggers
if (GetSystemMetrics(SM_SWAPBUTTON)) {
if (mouse->key_states[rawinput::MOUSEBTN_RIGHT]) {
g_MouseDown[ImGuiMouseButton_Left] = true;
if (accept_new_input) {
if (GetSystemMetrics(SM_SWAPBUTTON)) {
if (mouse->key_states[rawinput::MOUSEBTN_RIGHT]) {
g_MouseDown[ImGuiMouseButton_Left] = true;
}
if (mouse->key_states[rawinput::MOUSEBTN_LEFT]) {
g_MouseDown[ImGuiMouseButton_Right] = true;
}
} else {
if (mouse->key_states[rawinput::MOUSEBTN_LEFT]) {
g_MouseDown[ImGuiMouseButton_Left] = true;
}
if (mouse->key_states[rawinput::MOUSEBTN_RIGHT]) {
g_MouseDown[ImGuiMouseButton_Right] = true;
}
}
if (mouse->key_states[rawinput::MOUSEBTN_LEFT]) {
g_MouseDown[ImGuiMouseButton_Right] = true;
if (mouse->key_states[rawinput::MOUSEBTN_MIDDLE]) {
g_MouseDown[ImGuiMouseButton_Middle] = true;
}
} else {
if (mouse->key_states[rawinput::MOUSEBTN_LEFT]) {
g_MouseDown[ImGuiMouseButton_Left] = true;
}
if (mouse->key_states[rawinput::MOUSEBTN_RIGHT]) {
g_MouseDown[ImGuiMouseButton_Right] = true;
}
}
if (mouse->key_states[rawinput::MOUSEBTN_MIDDLE]) {
g_MouseDown[ImGuiMouseButton_Middle] = true;
}
// final mouse wheel value should be all devices combined
// need to continuously calculate mouse wheel position even when not in focus
// to avoid values jumping (since mouse wheel values are absolute not relative)
mouse_wheel += mouse->pos_wheel;
break;
}
case rawinput::KEYBOARD: {
// iterate all virtual key codes
for (size_t vKey = 0; vKey < VKEY_MAX; vKey++) {
// get state (combined from all pages)
auto &key_states = device.keyboardInfo->key_states;
for (size_t page_index = 0; page_index < 1024; page_index += 256) {
g_KeysDown[vKey] |= key_states[page_index + vKey];
if (accept_new_input) {
// iterate all virtual key codes
for (size_t vKey = 0; vKey < VKEY_MAX; vKey++) {
// get state (combined from all pages)
auto &key_states = device.keyboardInfo->key_states;
for (size_t page_index = 0; page_index < 1024; page_index += 256) {
g_KeysDown[vKey] |= key_states[page_index + vKey];
}
}
}
break;
}
default:
@@ -464,9 +473,11 @@ void ImGui_ImplSpice_NewFrame() {
}
// set mouse wheel
auto wheel_diff = mouse_wheel - mouse_wheel_last;
long wheel_diff = mouse_wheel - mouse_wheel_last;
mouse_wheel_last = mouse_wheel;
io.AddMouseWheelEvent(0, wheel_diff);
if (wheel_diff != 0 && accept_new_input) {
io.AddMouseWheelEvent(0, wheel_diff);
}
// update OS mouse position
const auto old_mouse_pos = io.MousePos;
+2 -2
View File
@@ -733,13 +733,13 @@ void overlay::SpiceOverlay::add_font(const char* font, ImFontConfig* config, con
full_path += font;
if (fileutils::file_exists(full_path)) {
log_misc("overlay", "loading font: {}", full_path.string());
log_misc("overlay", "loading font: {}", full_path);
ImGui::GetIO().Fonts->AddFontFromFileTTF(
full_path.string().c_str(),
13.0f,
config,
glyphs);
} else {
log_misc("overlay", "font not found: {}", full_path.string());
log_misc("overlay", "font not found: {}", full_path);
}
}
+199 -154
View File
@@ -948,7 +948,7 @@ namespace overlay::windows {
// grab current keyboard state
for (unsigned short int i = 0x01; i < 0xFF; i++) {
buttons_keyboard_state[i] = GetAsyncKeyState(i) != 0;
buttons_keyboard_state[i] = (GetAsyncKeyState(i) & 0x8000) != 0;
}
}
if (ImGui::IsItemHovered(ImGui::TOOLTIP_FLAGS)) {
@@ -1206,6 +1206,16 @@ namespace overlay::windows {
case rawinput::HID: {
auto hid = device->hidInfo;
struct temp_button {
std::string device_name;
unsigned short vkey;
ButtonAnalogType analog_type;
};
// use this to prioritize button binding over value types
// (for controllers that output both)
std::optional<temp_button> button_to_bind;
// ignore touchscreen and digitizer button inputs
// digitizer has funky stuff like "Touch Valid" "Data Valid" always held high
if (!rawinput::touch::is_touchscreen(device) &&
@@ -1219,18 +1229,11 @@ namespace overlay::windows {
// check if button is down
if (button_states[i]) {
// bind key
button->setDeviceIdentifier(device->name);
button->setVKey(static_cast<unsigned short>(button_index + i));
button->setAnalogType(BAT_NONE);
::Config::getInstance().updateBinding(
games_list[games_selected], *button,
alt_index - 1);
ImGui::CloseCurrentPopup();
buttons_bind_active = false;
inc_buttons_many_index(button_it_max);
RI_MGR->devices_midi_freeze(false);
button_to_bind = {
device->name,
static_cast<unsigned short>(button_index + i),
BAT_NONE
};
break;
}
}
@@ -1239,95 +1242,100 @@ namespace overlay::windows {
}
// value caps
auto value_states = &hid->value_states;
auto bind_value_states = &hid->bind_value_states;
auto value_names = &hid->value_caps_names;
for (size_t i = 0; i < value_states->size(); i++) {
auto &state = value_states->at(i);
auto &bind_state = bind_value_states->at(i);
auto &value_name = value_names->at(i);
if (!button_to_bind.has_value()) {
auto value_states = &hid->value_states;
auto bind_value_states = &hid->bind_value_states;
auto value_names = &hid->value_caps_names;
for (size_t i = 0; i < value_states->size(); i++) {
auto &state = value_states->at(i);
auto &bind_state = bind_value_states->at(i);
auto &value_name = value_names->at(i);
// check for valid axis names
if (value_name == "X" ||
value_name == "Y" ||
value_name == "Rx" ||
value_name == "Ry" ||
value_name == "Z")
{
// check if axis is in activation area
float normalized = (state - 0.5f) * 2.f;
float diff = std::fabs(state - bind_state);
if (std::fabs(normalized) > 0.9f && diff > 0.1f) {
auto bat = normalized > 0 ? BAT_POSITIVE : BAT_NEGATIVE;
// check for valid axis names
if (value_name == "X" ||
value_name == "Y" ||
value_name == "Rx" ||
value_name == "Ry" ||
value_name == "Z")
{
// check if axis is in activation area
float normalized = (state - 0.5f) * 2.f;
float diff = std::fabs(state - bind_state);
if (std::fabs(normalized) > 0.9f && diff > 0.1f) {
auto bat = normalized > 0 ? BAT_POSITIVE : BAT_NEGATIVE;
// bind value
button->setDeviceIdentifier(device->name);
button->setVKey(static_cast<unsigned short>(i));
button->setAnalogType(bat);
button->setDebounceUp(0.0);
button->setDebounceDown(0.0);
button->setBatThreshold(0);
button->setVelocityThreshold(0);
::Config::getInstance().updateBinding(
games_list[games_selected], *button,
alt_index - 1);
ImGui::CloseCurrentPopup();
buttons_bind_active = false;
inc_buttons_many_index(button_it_max);
RI_MGR->devices_midi_freeze(false);
// bind value
button_to_bind = {
device->name,
static_cast<unsigned short>(i),
bat
};
// usually, turntables are X, knobs are X and Y
// gamepad triggers are Z, and Rx/Ry are right thumb stick
// one day we will label all I/O modules and flag which one are button-as-analog
// so that we don't have to do string comparions like below
if ((value_name == "X" || value_name == "Y") &&
(button->getName().find("Press") == std::string::npos) && // museca
(button->getName().find("Slowdown") == std::string::npos) && // bishibashi
(button->getName().find("TT+") != std::string::npos ||
button->getName().find("TT-") != std::string::npos || // iidx
button->getName().find("Knob") != std::string::npos || // gitadora guitar
button->getName().find("Disk") != std::string::npos || // museca, bishibashi
button->getName().find("VOL-") != std::string::npos)) { // sdvx
this->analog_as_button_warning_show_next_frame =
std::make_pair(button->getName(), alt_index);
// usually, turntables are X, knobs are X and Y
// gamepad triggers are Z, and Rx/Ry are right thumb stick
// one day we will label all I/O modules and flag which one are button-as-analog
// so that we don't have to do string comparions like below
if ((value_name == "X" || value_name == "Y") &&
(button->getName().find("Press") == std::string::npos) && // museca
(button->getName().find("Slowdown") == std::string::npos) && // bishibashi
(button->getName().find("TT+") != std::string::npos ||
button->getName().find("TT-") != std::string::npos || // iidx
button->getName().find("Knob") != std::string::npos || // gitadora guitar
button->getName().find("Disk") != std::string::npos || // museca, bishibashi
button->getName().find("P1 Panel") != std::string::npos || // ddr
button->getName().find("P2 Panel") != std::string::npos || // ddr
button->getName().find("VOL-") != std::string::npos)) { // sdvx
this->analog_as_button_warning_show_next_frame =
std::make_pair(button->getName(), alt_index);
}
break;
} else if (diff > 0.3f) {
bind_state = state;
}
break;
} else if (diff > 0.3f) {
bind_state = state;
}
}
// hat switch
if (value_name == "Hat switch") {
// hat switch
if (value_name == "Hat switch") {
// get hat switch values
ButtonAnalogType buffer[3], buffer_bind[3];
Button::getHatSwitchValues(state, buffer);
Button::getHatSwitchValues(bind_state, buffer_bind);
// get hat switch values
ButtonAnalogType buffer[3], buffer_bind[3];
Button::getHatSwitchValues(state, buffer);
Button::getHatSwitchValues(bind_state, buffer_bind);
// check the first entry only
if (buffer[0] != BAT_NONE && buffer[0] != buffer_bind[0]) {
// check the first entry only
if (buffer[0] != BAT_NONE && buffer[0] != buffer_bind[0]) {
// bind value
button->setDeviceIdentifier(device->name);
button->setVKey(static_cast<unsigned short>(i));
button->setAnalogType(buffer[0]);
button->setDebounceUp(0.0);
button->setDebounceDown(0.0);
button->setBatThreshold(0);
button->setVelocityThreshold(0);
::Config::getInstance().updateBinding(
games_list[games_selected], *button,
alt_index - 1);
ImGui::CloseCurrentPopup();
buttons_bind_active = false;
inc_buttons_many_index(button_it_max);
RI_MGR->devices_midi_freeze(false);
break;
// bind value
button_to_bind = {
device->name,
static_cast<unsigned short>(i),
buffer[0]
};
break;
}
}
}
}
if (button_to_bind.has_value()) {
const auto &b = button_to_bind.value();
button->setDeviceIdentifier(b.device_name);
button->setVKey(b.vkey);
button->setAnalogType(b.analog_type);
button->setDebounceUp(0.0);
button->setDebounceDown(0.0);
button->setBatThreshold(0);
button->setVelocityThreshold(0);
::Config::getInstance().updateBinding(
games_list[games_selected], *button,
alt_index - 1);
ImGui::CloseCurrentPopup();
buttons_bind_active = false;
inc_buttons_many_index(button_it_max);
RI_MGR->devices_midi_freeze(false);
}
break;
}
case rawinput::MIDI: {
@@ -1607,7 +1615,7 @@ namespace overlay::windows {
// use care when iterating over the result (could result in torn reads)
bool keyboard_state_new[sizeof(buttons_keyboard_state)];
for (size_t i = 0; i < sizeof(keyboard_state_new); i++) {
keyboard_state_new[i] = GetAsyncKeyState(i) != 0;
keyboard_state_new[i] = (GetAsyncKeyState(i) & 0x8000) != 0;
}
// detect key presses
@@ -1995,6 +2003,7 @@ namespace overlay::windows {
int vKey = button->getVKey();
if (ImGui::InputInt(button->isNaive() ? "Virtual Key" : "Index", &vKey, 1, 1)) {
button->setVKey(vKey);
button->setInvert(false);
}
if (ImGui::IsItemDeactivatedAfterEdit()) {
dirty = true;
@@ -2062,15 +2071,31 @@ namespace overlay::windows {
"This setting will add noticable input lag.");
}
// invert
bool invert = button->getInvert();
if (ImGui::Checkbox("Invert Resulting Value", &invert)) {
button->setInvert(invert);
dirty = true;
// invert (widget hidden for naive + 0xff)
if (!(button->isNaive() && button->getVKey() == INVALID_VKEY)) {
bool invert = button->getInvert();
if (ImGui::Checkbox("Invert Resulting Value", &invert)) {
button->setInvert(invert);
dirty = true;
}
}
// always on (naive + vkey 0xff + invert)
if (button->isNaive() && alt_index == 0) {
bool always_on = button->isNaive() && button->getVKey() == INVALID_VKEY && button->getInvert();
if (ImGui::Checkbox("Always On", &always_on)) {
if (always_on) {
button->setVKey(INVALID_VKEY);
button->setInvert(true);
} else {
button->setInvert(false);
}
dirty = true;
}
}
// bat threshold
if (device->type == rawinput::HID &&
if (device != nullptr && device->type == rawinput::HID &&
(button->getAnalogType() == BAT_POSITIVE || button->getAnalogType() == BAT_NEGATIVE)) {
int bat_threshold = button->getBatThreshold();
@@ -2184,9 +2209,9 @@ namespace overlay::windows {
ImGui::Separator();
if (ImGui::BeginTable("AnalogsTable", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, overlay::apply_scaling(220));
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, overlay::apply_scaling(240));
ImGui::TableSetupColumn("Binding", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_WidthFixed, overlay::apply_scaling(100));
ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_WidthFixed, overlay::apply_scaling(80));
// check if empty
if (!analogs || analogs->empty()) {
@@ -2245,8 +2270,9 @@ namespace overlay::windows {
}
// analog binding
const std::string title = "Analog Binding (" + analog.getName() + ")";
if (ImGui::Button("Set")) {
ImGui::OpenPopup("Analog Binding");
ImGui::OpenPopup(title.c_str());
// get devices
this->analogs_devices.clear();
@@ -2276,7 +2302,7 @@ namespace overlay::windows {
}
}
edit_analog_popup(analog);
edit_analog_popup(analog, title);
// row hover detection (invisible selectable that spans entire row)
ImGui::InvisibleTableRowSelectable();
@@ -2290,8 +2316,8 @@ namespace overlay::windows {
}
}
void Config::edit_analog_popup(Analog &analog) {
if (ImGui::BeginPopupModal("Analog Binding", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
void Config::edit_analog_popup(Analog &analog, std::string title) {
if (ImGui::BeginPopupModal(title.c_str(), NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
// device selector
auto analog_device_changed = ImGui::Combo(
@@ -2498,31 +2524,45 @@ namespace overlay::windows {
const bool value_changed =
ImGui::SliderFloat("Sensitivity", &sensitivity, 0.f, 2.f, "%.3f");
ImGui::SameLine();
ImGui::HelpMarker(
"Adjust floating point multiplier to relative movement.\n\n"
"Value is squared before being multiplied (e.g., 1.44 is 2x sensitivity, 2.00 is 4x).\n\n"
"Dependent on how often the game polls for input. Intended for angular input (knobs, turntables)");
if (device->type == rawinput::HID && analog.getType() != GameAPI::Analogs::AnalogType::Circular) {
ImGui::HelpMarker(
"Adjust the analog sensitivity curve; "
"values <1.0 are less sensitive around neutral, "
"values >1.0 are more sensitive.");
} else {
ImGui::HelpMarker(
"Adjust floating point multiplier to relative movement.\n\n"
"Value is squared before being multiplied (e.g., 1.44 is 2x sensitivity, 2.00 is 4x).");
}
if (value_changed) {
analog.setSensitivity(sensitivity * sensitivity);
}
}
if (device->type == rawinput::HID || device->type == rawinput::MIDI) {
// hide deadzone for circular analog since it doesn't make any sense (unless in relative mode)
if ((device->type == rawinput::HID || device->type == rawinput::MIDI) &&
((analog.getType() != GameAPI::Analogs::AnalogType::Circular) || analog.isRelativeMode())) {
auto deadzone = analog.getDeadzone();
// for back compat (before each analog had a type)
if (deadzone < 0.f) {
deadzone = -deadzone;
analog.setDeadzone(deadzone);
}
const bool value_changed =
ImGui::SliderFloat("Deadzone", &deadzone, -0.999f, 0.999f, "%.3f");
ImGui::SliderFloat("Deadzone", &deadzone, 0.f, 0.999f, "%.3f");
if (value_changed) {
analog.setDeadzone(deadzone);
}
ImGui::SameLine();
ImGui::HelpMarker("Positive values specify a deadzone around the middle.\n"
"Negative values specify a deadzone from the minimum value.");
ImGui::HelpMarker("Specify the deadzone that gets applied to at-rest (neutral) value.");
// deadzone mirror
bool deadzone_mirror = analog.getDeadzoneMirror();
ImGui::Checkbox("Deadzone Mirror", &deadzone_mirror);
ImGui::SameLine();
ImGui::HelpMarker("Positive deadzone values cut off at edges instead.\n"
"Negative deadzone values cut off at maximum value instead.");
ImGui::HelpMarker("Apply deadzone to extreme value(s) instead of neutral.");
if (deadzone_mirror != analog.getDeadzoneMirror()) {
analog.setDeadzoneMirror(deadzone_mirror);
}
@@ -2541,47 +2581,50 @@ namespace overlay::windows {
if (this->analogs_devices_selected >= 0) {
const auto device = this->analogs_devices.at(this->analogs_devices_selected);
if (device->type == rawinput::HID) {
// smoothing
bool smoothing = analog.getSmoothing();
ImGui::BeginDisabled(analog.isRelativeMode());
ImGui::Checkbox("Smooth Axis (adds latency)", &smoothing);
ImGui::SameLine();
ImGui::HelpMarker(
"Apply a moving average algorithm; intended for angular input (knobs, turntables). "
"Adds a slight bit of latency to input as the algorithm averages out recent input. "
"Only use in dire situations where the input is too jittery for the game.");
ImGui::EndDisabled();
if (smoothing != analog.getSmoothing()) {
analog.setSmoothing(smoothing);
if (analog.getType() == GameAPI::Analogs::AnalogType::Circular) {
// smoothing
bool smoothing = analog.getSmoothing();
ImGui::BeginDisabled(analog.isRelativeMode());
ImGui::Checkbox("Smooth Axis (adds latency)", &smoothing);
ImGui::SameLine();
ImGui::HelpMarker(
"Apply a moving average algorithm; intended for angular input (knobs, turntables). "
"Adds a slight bit of latency to input as the algorithm averages out recent input. "
"Only use in dire situations where the input is too jittery for the game.");
ImGui::EndDisabled();
if (smoothing != analog.getSmoothing()) {
analog.setSmoothing(smoothing);
}
// relative input mode
bool relative_analog = analog.isRelativeMode();
ImGui::Checkbox("Relative Axis", &relative_analog);
ImGui::SameLine();
ImGui::HelpMarker(
"Use relative directional input instead of positional values. "
"Can be used to translate analog sticks to knob input.\n\n"
"At default settings, max speed is one revolution per second.\n\n"
"Adjust sensitivity to increase/decrease max speed, and deadzone to prevent jitter.");
if (relative_analog != analog.isRelativeMode()) {
analog.setRelativeMode(relative_analog);
}
}
// relative input mode
bool relative_analog = analog.isRelativeMode();
ImGui::Checkbox("Relative Axis (experimental)", &relative_analog);
ImGui::SameLine();
ImGui::HelpMarker(
"Use relative directional input instead of positional values.\n\n"
"Can be used to translate analog sticks to knob input, for example.\n\n"
"WARNING: speed depends on how often the game polls for input! "
"Strongly recommended that you go into the game's test menu instead "
"of adjusting in spicecfg.");
if (relative_analog != analog.isRelativeMode()) {
analog.setRelativeMode(relative_analog);
}
// delay buffer
int delay = analog.getDelayBufferDepth();
ImGui::InputInt("Delay (experimental)", &delay, 1, 10);
if (ImGui::IsItemDeactivatedAfterEdit()) {
delay = CLAMP(delay, 0, 256);
analog.setDelayBufferDepth(delay);
// delay
int delay = analog.getDelayMs();
if (ImGui::InputInt("Delay (ms)", &delay, 1, 1)) {
delay = std::clamp(delay, 0, 250);
analog.setDelayMs(delay);
}
ImGui::SameLine();
ImGui::HelpMarker(
"Adds a delay to input. This is poll-based, not time-based.\n\n"
"WARNING: delay depends on how often the game polls for input! "
"Strongly recommended that you go into the game's test menu instead "
"of adjusting in spicecfg.");
"Adds an artificial delay, in milliseconds.\n\n"
"Value read by the game engine will be delayed AT MOST this amount of time (could be slightly less).\n\n"
"To minimize quantization error, delay value should be a multiple of the game's poll rate, "
"add 0.5ms of buffer, and then round up to the nearest millisecond.\n\n"
"If you aren't sure, assume the game polls for input at the same rate as the display FPS."
);
}
}
@@ -2592,10 +2635,12 @@ namespace overlay::windows {
ImGui::ProgressBar(value);
// centered knob preview
const float knob_size = 64.f;
auto width = ImGui::GetContentRegionAvail().x - knob_size;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (width / 2));
ImGui::Knob(value, knob_size);
if (analog.getType() == GameAPI::Analogs::AnalogType::Circular) {
const float knob_size = 64.f;
auto width = ImGui::GetContentRegionAvail().x - knob_size;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (width / 2));
ImGui::Knob(value, knob_size);
}
// update analog
if (analogs_devices_selected >= 0 && analogs_devices_selected < (int) analogs_devices.size()) {
@@ -5392,7 +5437,7 @@ namespace overlay::windows {
a.setSmoothing(ta.smoothing);
a.setMultiplier(ta.multiplier);
a.setRelativeMode(ta.relative_mode);
a.setDelayBufferDepth(ta.delay_buffer_depth);
a.setDelayMs(ta.delay_ms);
::Config::getInstance().updateBinding(game, a);
break;
}
+1 -1
View File
@@ -162,7 +162,7 @@ namespace overlay::windows {
unsigned int get_keypad_top_row(const Button &button);
void build_analogs(const std::string &name, std::vector<Analog> *analogs);
void edit_analog_popup(Analog &analog);
void edit_analog_popup(Analog &analog, std::string title);
void update() override;
void stop_lights_test();
@@ -72,7 +72,7 @@ namespace overlay::windows {
bool smoothing = false;
int multiplier = 1;
bool relative_mode = false;
int delay_buffer_depth = 0;
uint32_t delay_ms = 0;
bool is_device() const { return !device_identifier.empty(); }
bool is_unbound() const { return device_identifier.empty() && index == 0xFF; }
@@ -90,7 +90,7 @@ namespace overlay::windows {
smoothing = a.getSmoothing();
multiplier = a.getMultiplier();
relative_mode = a.isRelativeMode();
delay_buffer_depth = a.getDelayBufferDepth();
delay_ms = a.getDelayMs();
}
};
@@ -74,6 +74,23 @@ namespace overlay::windows {
{"Nostroller (Lights 15-28)", "Nostalgia", 0, 0, "LED_27", "", "", true, "Key 27", ""},
{"Nostroller (Lights 15-28)", "Nostalgia", 0, 0, "LED_28", "", "", true, "Key 28", ""},
// icedragon.io snek board, ddr mode
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "neon", "", "", false, "Neon", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "mar p1 upper", "", "", false, "P1 Halogen Upper", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "mar p1 lower", "", "", false, "P1 Halogen Lower", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "mar p2 upper", "", "", false, "P2 Halogen Upper", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "mar p2 lower", "", "", false, "P2 Halogen Lower", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p1 buttons", "", "", false, "P1 Button", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p2 buttons", "", "", false, "P2 Button", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p1 up", "", "", false, "P1 Foot Up", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p1 down", "", "", false, "P1 Foot Down", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p1 left", "", "", false, "P1 Foot Left", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p1 right", "", "", false, "P1 Foot Right", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p2 up", "", "", false, "P2 Foot Up", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p2 down", "", "", false, "P2 Foot Down", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p2 left", "", "", false, "P2 Foot Left", ""},
{"snek lights", "Dance Dance Revolution", 0x2e8a, 0x10a8, "p2 right", "", "", false, "P2 Foot Right", ""},
};
static const int LIGHT_MATCH_MAP_COUNT =
+29 -24
View File
@@ -95,6 +95,10 @@ namespace overlay::windows {
}
// utility
std::string displayPath(const std::filesystem::path &path) {
return fmt::format(FMT_STRING("{}"), path);
}
std::string getFromUrl(const std::string& dll_name, const std::string& url) {
log_info("patchmanager", "getting patches from URL: {}, for file: {}", url, dll_name);
std::string result;
@@ -226,7 +230,7 @@ namespace overlay::windows {
if (PATCH_MANAGER_CFG_PATH_OVERRIDE.has_value()) {
this->config_path = PATCH_MANAGER_CFG_PATH_OVERRIDE.value();
log_info("patchmanager", "using custom config file path: {}", this->config_path.string().c_str());
log_info("patchmanager", "using custom config file path: {}", this->config_path);
} else {
this->config_path =
fileutils::get_config_file_path("patchmanager", "spicetools_patch_manager.json");
@@ -330,7 +334,7 @@ namespace overlay::windows {
"Wrong path? Run spicecfg from the correct directory, or fix your modules parameter before launching spicecfg.\n"
"Make sure you're not using a different one when launching the game.");
ImGui::SameLine();
ImGui::Text("Modules Path: %s", MODULE_PATH.string().c_str());
ImGui::Text("Modules Path: %s", displayPath(MODULE_PATH).c_str());
ImGui::AlignTextToFramePadding();
ImGui::DummyMarker();
@@ -878,7 +882,7 @@ namespace overlay::windows {
}
void PatchManager::hard_apply_patches() {
std::vector<std::string> written_list;
std::vector<std::filesystem::path> written_list;
for (auto& patch : patches) {
switch (patch.type) {
case PatchType::Memory:
@@ -1218,7 +1222,7 @@ namespace overlay::windows {
log_info(
"patchmanager",
"file: {}, patch id: {}, build timestamp of dll: {:%Y-%m-%d %H:%M}",
dll_path.has_filename() ? dll_path.filename().string() : dll_path.string(),
dll_path.has_filename() ? dll_path.filename() : dll_path,
identifier,
time);
}
@@ -1623,7 +1627,7 @@ namespace overlay::windows {
// save to file
std::filesystem::path save_path = LOCAL_PATCHES_PATH / (identifier + ".json");
fileutils::text_write(save_path, patches_json);
log_info("patchmanager", "remotely fetched JSON saved to: {}", save_path.string());
log_info("patchmanager", "remotely fetched JSON saved to: {}", save_path);
return true;
} else {
log_warning("patchmanager", "failed to fetch patches JSON for {}", dll_name);
@@ -1675,19 +1679,19 @@ namespace overlay::windows {
const size_t patches_size_previous = patches.size();
for (const std::filesystem::path& patches_json_path: LOCAL_PATCHES_JSON_PATHS) {
if (!fileutils::file_exists(patches_json_path)) {
log_misc("patchmanager", "file does not exist, skipping: {}", patches_json_path.string());
log_misc("patchmanager", "file does not exist, skipping: {}", patches_json_path);
continue;
}
log_misc("patchmanager", "reading from patches.json: {}", patches_json_path.string());
log_misc("patchmanager", "reading from patches.json: {}", patches_json_path);
std::string content = fileutils::text_read(patches_json_path);
append_patches(content, apply_patches, filter);
const auto new_patches = patches.size() - patches_size_previous;
log_info("patchmanager", "loaded {} patches from: {}", new_patches, patches_json_path.string());
log_info("patchmanager", "loaded {} patches from: {}", new_patches, patches_json_path);
if (0 < new_patches) {
ret = true;
ACTIVE_JSON_FILE = patches_json_path.string();
ACTIVE_JSON_FILE = displayPath(patches_json_path);
break;
}
}
@@ -1723,21 +1727,21 @@ namespace overlay::windows {
if (fileutils::file_exists(firstPath) || !extraDlls.empty()) {
if (fileutils::file_exists(firstPath)) {
log_info("patchmanager", "loaded patches for {} from {}", firstDll, firstPath.string());
log_info("patchmanager", "loaded patches for {} from {}", firstDll, firstPath);
std::string content = fileutils::text_read(firstPath);
append_patches(content, apply_patches, nullptr, first_id);
ACTIVE_JSON_FILE = firstPath.string();
ACTIVE_JSON_FILE = displayPath(firstPath);
}
for (const std::string& dll : extraDlls) {
auto extraId = get_game_identifier(MODULE_PATH / dll);
auto extraPath = std::filesystem::path(fmt::format("patches/{}.json", extraId));
log_info("patchmanager", "loaded patches for {} from {}", dll, extraPath.string());
log_info("patchmanager", "loaded patches for {} from {}", dll, extraPath);
std::string content = fileutils::text_read(extraPath);
append_patches(content, apply_patches, nullptr, extraId);
if (ACTIVE_JSON_FILE.empty()) {
ACTIVE_JSON_FILE = extraPath.string();
ACTIVE_JSON_FILE = displayPath(extraPath);
} else {
ACTIVE_JSON_FILE += ", " + extraPath.string();
ACTIVE_JSON_FILE += ", " + displayPath(extraPath);
}
}
} else {
@@ -3024,22 +3028,23 @@ namespace overlay::windows {
}
void create_dll_backup(
std::vector<std::string>& written_list, const std::filesystem::path& dll_path) {
std::vector<std::filesystem::path>& written_list, const std::filesystem::path& dll_path) {
// if dll_path is not in written_list, create a file backup.
if (std::find(written_list.begin(), written_list.end(), dll_path.string()) == written_list.end()) {
written_list.push_back(dll_path.string());
auto dll_bak_path = std::filesystem::path(dll_path.string() + ".bak");
if (std::find(written_list.begin(), written_list.end(), dll_path) == written_list.end()) {
written_list.push_back(dll_path);
auto dll_bak_path = dll_path;
dll_bak_path += ".bak";
try {
if (!fileutils::file_exists(dll_bak_path)) {
std::filesystem::copy(dll_path, dll_bak_path);
}
log_info("patchmanager", "created DLL backup for: {}", dll_path.string());
log_info("patchmanager", "created DLL backup for: {}", dll_path);
} catch (const std::filesystem::filesystem_error& e) {
log_warning(
"patchmanager",
"filesystem error while creating DLL backup for {}, error: {}",
dll_path.string(), e.what());
dll_path, e.what());
}
}
}
@@ -3065,14 +3070,14 @@ namespace overlay::windows {
/// check if file exists
auto dll_path = MODULE_PATH / dll_name;
if (!fileutils::file_exists(dll_path)) {
log_warning("patchmanager", "{} does not exist", dll_path.string());
log_warning("patchmanager", "{} does not exist", dll_path);
return nullptr;
}
// get module
auto module = libutils::try_module(dll_path);
if (!module) {
log_warning("patchmanager", "cannot get module: {}", dll_path.string());
log_warning("patchmanager", "cannot get module: {}", dll_path);
return nullptr;
}
@@ -3081,7 +3086,7 @@ namespace overlay::windows {
if (offset == -1) {
log_warning(
"patchmanager", "cannot convert offset to RVA: {}, {}",
dll_path.string(), data_offset);
dll_path, data_offset);
return nullptr;
}
@@ -3095,7 +3100,7 @@ namespace overlay::windows {
log_warning(
"patchmanager", "GetModuleInformation failed for {}, gle: {}",
dll_path.string(), GetLastError());
dll_path, GetLastError());
return nullptr;
}
+2 -2
View File
@@ -162,11 +162,11 @@ namespace overlay::windows {
uint8_t* destination, const std::string& dll_name, size_t offset, size_t size);
void create_dll_backup(
std::vector<std::string>& written_list, const std::filesystem::path& dll_path);
std::vector<std::filesystem::path>& written_list, const std::filesystem::path& dll_path);
std::string fix_up_dll_name(const std::string& dll_name);
uint8_t* get_dll_offset_for_patch_apply(
const std::string& dll_name, const uint64_t data_offset, const size_t size_in_bytes);
uint64_t parse_json_data_offset(
const std::string &patch_name, const rapidjson::Value &value);
+22 -2
View File
@@ -9,6 +9,7 @@
#include "util/logging.h"
#include "external/robin_hood.h"
#include "util/precise_timer.h"
#include "util/time.h"
#include "util/utils.h"
@@ -155,8 +156,9 @@ void rawinput::RawInputManager::input_hwnd_create() {
});
// wait for window creation being done
timeutils::PreciseSleepTimer timer;
while (!this->input_hwnd) {
Sleep(1);
timer.sleep(1);
}
}
@@ -605,6 +607,24 @@ void rawinput::RawInputManager::devices_scan_rawinput(RAWINPUTDEVICELIST *device
value_caps.LogicalMax = 255;
}
// fix up invalid max values (seen on xbox controllers where max is 0xffffffff despite being 16-bit)
if (value_caps.LogicalMin == 0 && value_caps.BitSize > 0 && value_caps.BitSize < 32) {
const uint32_t field_max = (1u << value_caps.BitSize) - 1u;
const uint32_t logical_max = static_cast<uint32_t>(value_caps.LogicalMax);
if (logical_max > field_max) {
log_info(
"rawinput",
"value cap {} LogicalMax exceeds bit width, fixing it up: {} -> {}",
value_cap_num,
value_caps.LogicalMax,
field_max
);
value_caps.LogicalMax = static_cast<LONG>(field_max);
}
}
// fix up hat switch to initially report as neutral position
if (value_caps.UsagePage == 0x1 && value_caps.Range.UsageMin == 0x39) {
value_states[value_cap_num] = -1.f;
@@ -2965,4 +2985,4 @@ void rawinput::RawInputManager::remove_callback_midi(void * data, const std::fun
[data, callback](MidiCallback const &cb) {
return cb.data == data && cb.f.target<void>() == callback.target<void>();
}), this->callback_midi.end());
}
}
+133 -75
View File
@@ -1,6 +1,11 @@
#include "rawinput/xinput.h"
#include "util/logging.h"
// std::min
#ifdef min
#undef min
#endif
namespace xinput {
// this is all we need to emulate xinput.h which we avoid including here...
@@ -24,6 +29,10 @@ namespace xinput {
#define XINPUT_GAMEPAD_X 0x4000
#define XINPUT_GAMEPAD_Y 0x8000
// custom
static constexpr float GAMEPAD_THUMB_DIGITAL_THRESHOLD = 0.2f;
typedef struct {
uint32_t dwPacketNumber;
XINPUT_GAMEPAD_STATE Gamepad;
@@ -153,7 +162,7 @@ XInputSetState(
float XInputManager::get_analog_state(uint8_t player, XInputAnalogEnum analog) {
return 0.5f;
}
bool XInputManager::is_button_pressed(uint8_t player, XInputButtonEnum button) {
bool XInputManager::is_button_pressed(uint8_t player, XInputButtonEnum button, XINPUT_GAMEPAD_STATE_NORMALIZED *state_in) {
return false;
}
bool XInputManager::get_any_button_pressed(XINPUT_NEW_BUTTON &button) {
@@ -223,6 +232,40 @@ XInputSetState(
return players;
}
static void normalize_stick(
SHORT raw_x,
SHORT raw_y,
float deadzone,
float &out_x,
float &out_y) {
const int x_i = static_cast<int>(raw_x);
const int y_i = -static_cast<int>(raw_y);
const float x_f = static_cast<float>(x_i);
const float y_f = static_cast<float>(y_i);
const float magnitude = std::sqrt(x_f * x_f + y_f * y_f);
// within deadzone; ignore
if (magnitude <= deadzone) {
out_x = 0.5f;
out_y = 0.5f;
return;
}
// scale value starting with 0 from deadzone border
const float magnitude_clamped = std::min(magnitude, 32767.0f);
const float scaled = (magnitude_clamped - deadzone) / (32767.0f - deadzone);
// normalize
const float normalized_x = (x_f / magnitude) * scaled;
const float normalized_y = (y_f / magnitude) * scaled;
// convert range to [0, 1] with 0.5 as center
out_x = std::clamp((normalized_x + 1.f) / 2.f, 0.f, 1.f);
out_y = std::clamp((normalized_y + 1.f) / 2.f, 0.f, 1.f);
}
void XInputManager::get_state(uint8_t player, XINPUT_GAMEPAD_STATE_NORMALIZED &state) {
state = {};
state.sThumbLX = 0.5f;
@@ -233,7 +276,7 @@ XInputSetState(
return;
}
XINPUT_STATE x;
XINPUT_STATE x = {};
if (XInputGetState_addr(player, &x) != ERROR_SUCCESS) {
return;
}
@@ -242,106 +285,83 @@ XInputSetState(
state.bLeftTrigger = x.Gamepad.bLeftTrigger / 255.0f;
state.bRightTrigger = x.Gamepad.bRightTrigger / 255.0f;
// left stick circular dead zone
{
const auto x_raw = x.Gamepad.sThumbLX;
const auto y_raw = -x.Gamepad.sThumbLY; // flip to make [down = positive]
const float magnitude = sqrtf(x_raw * x_raw + y_raw * y_raw);
if (magnitude > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) {
const float scaled =
(magnitude - XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) /
(32767.0f - XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
// apply circular deadzone logic to left stick
normalize_stick(
x.Gamepad.sThumbLX,
x.Gamepad.sThumbLY,
static_cast<float>(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE),
state.sThumbLX,
state.sThumbLY);
state.sThumbLX = (x_raw / magnitude) * scaled;
state.sThumbLY = (y_raw / magnitude) * scaled;
// normalize to [0, 1]
state.sThumbLX = std::clamp((state.sThumbLX + 1.f) / 2.f, 0.f, 1.f);
state.sThumbLY = std::clamp((state.sThumbLY + 1.f) / 2.f, 0.f, 1.f);
} else {
// within deadzone
state.sThumbLX = 0.5f;
state.sThumbLY = 0.5f;
}
}
// right stick circular dead zone
{
const auto x_raw = x.Gamepad.sThumbRX;
const auto y_raw = -x.Gamepad.sThumbRY; // flip to make [down = positive]
const float magnitude = sqrtf(x_raw * x_raw + y_raw * y_raw);
if (magnitude > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) {
const float scaled =
(magnitude - XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) /
(32767.0f - XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE);
state.sThumbRX = (x_raw / magnitude) * scaled;
state.sThumbRY = (y_raw / magnitude) * scaled;
// normalize to [0, 1]
state.sThumbRX = std::clamp((state.sThumbRX + 1.f) / 2.f, 0.f, 1.f);
state.sThumbRY = std::clamp((state.sThumbRY + 1.f) / 2.f, 0.f, 1.f);
} else {
// within deadzone
state.sThumbRX = 0.5f;
state.sThumbRY = 0.5f;
}
}
// apply circular deadzone logic to right stick
normalize_stick(
x.Gamepad.sThumbRX,
x.Gamepad.sThumbRY,
static_cast<float>(XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE),
state.sThumbRX,
state.sThumbRY);
}
bool XInputManager::is_button_pressed(uint8_t player, XInputButtonEnum button) {
XINPUT_GAMEPAD_STATE_NORMALIZED state;
bool XInputManager::is_button_pressed(uint8_t player, XInputButtonEnum button, XINPUT_GAMEPAD_STATE_NORMALIZED *state_in) {
XINPUT_GAMEPAD_STATE_NORMALIZED state_on_stack;
XINPUT_GAMEPAD_STATE_NORMALIZED *state;
get_state(player, state);
if (state_in) {
state = state_in;
} else {
state = &state_on_stack;
get_state(player, *state);
}
switch (button) {
case XInputButtonEnum::DPAD_UP:
return (state.wButtons & XINPUT_GAMEPAD_DPAD_UP) != 0;
return (state->wButtons & XINPUT_GAMEPAD_DPAD_UP) != 0;
case XInputButtonEnum::DPAD_DOWN:
return (state.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) != 0;
return (state->wButtons & XINPUT_GAMEPAD_DPAD_DOWN) != 0;
case XInputButtonEnum::DPAD_LEFT:
return (state.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) != 0;
return (state->wButtons & XINPUT_GAMEPAD_DPAD_LEFT) != 0;
case XInputButtonEnum::DPAD_RIGHT:
return (state.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0;
return (state->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0;
case XInputButtonEnum::START:
return (state.wButtons & XINPUT_GAMEPAD_START) != 0;
return (state->wButtons & XINPUT_GAMEPAD_START) != 0;
case XInputButtonEnum::BACK:
return (state.wButtons & XINPUT_GAMEPAD_BACK) != 0;
return (state->wButtons & XINPUT_GAMEPAD_BACK) != 0;
case XInputButtonEnum::LEFT_STICK:
return (state.wButtons & XINPUT_GAMEPAD_LEFT_THUMB) != 0;
return (state->wButtons & XINPUT_GAMEPAD_LEFT_THUMB) != 0;
case XInputButtonEnum::RIGHT_STICK:
return (state.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0;
return (state->wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0;
case XInputButtonEnum::LEFT_SHOULDER:
return (state.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0;
return (state->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0;
case XInputButtonEnum::RIGHT_SHOULDER:
return (state.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0;
return (state->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0;
case XInputButtonEnum::BUTTON_A:
return (state.wButtons & XINPUT_GAMEPAD_A) != 0;
return (state->wButtons & XINPUT_GAMEPAD_A) != 0;
case XInputButtonEnum::BUTTON_B:
return (state.wButtons & XINPUT_GAMEPAD_B) != 0;
return (state->wButtons & XINPUT_GAMEPAD_B) != 0;
case XInputButtonEnum::BUTTON_X:
return (state.wButtons & XINPUT_GAMEPAD_X) != 0;
return (state->wButtons & XINPUT_GAMEPAD_X) != 0;
case XInputButtonEnum::BUTTON_Y:
return (state.wButtons & XINPUT_GAMEPAD_Y) != 0;
return (state->wButtons & XINPUT_GAMEPAD_Y) != 0;
case XInputButtonEnum::LEFT_TRIGGER:
return state.bLeftTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
return state->bLeftTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
case XInputButtonEnum::RIGHT_TRIGGER:
return state.bRightTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
return state->bRightTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
case XInputButtonEnum::LEFT_STICK_UP:
return state.sThumbLY > 0.6f;
return state->sThumbLY < (0.5f - GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::LEFT_STICK_DOWN:
return state.sThumbLY < 0.4f;
return state->sThumbLY > (0.5f + GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::LEFT_STICK_LEFT:
return state.sThumbLX < 0.4f;
return state->sThumbLX < (0.5f - GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::LEFT_STICK_RIGHT:
return state.sThumbLX > 0.6f;
return state->sThumbLX > (0.5f + GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::RIGHT_STICK_UP:
return state.sThumbRY > 0.6f;
return state->sThumbRY < (0.5f - GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::RIGHT_STICK_DOWN:
return state.sThumbRY < 0.4f;
return state->sThumbRY > (0.5f + GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::RIGHT_STICK_LEFT:
return state.sThumbRX < 0.4f;
return state->sThumbRX < (0.5f - GAMEPAD_THUMB_DIGITAL_THRESHOLD);
case XInputButtonEnum::RIGHT_STICK_RIGHT:
return state.sThumbRX > 0.6f;
return state->sThumbRX > (0.5f + GAMEPAD_THUMB_DIGITAL_THRESHOLD);
default:
break;
}
@@ -374,11 +394,49 @@ XInputSetState(
}
bool XInputManager::get_any_button_pressed(XINPUT_NEW_BUTTON &button) {
constexpr std::array<XInputButtonEnum, static_cast<size_t>(XInputButtonEnum::COUNT)> button_priority = {
// the ordering here is important; we want to check buttons first, then dpad, then analog
// this is to help with cases like DDR pads that output multiple at the same time for arrows
// actual buttons
XInputButtonEnum::BUTTON_A,
XInputButtonEnum::BUTTON_B,
XInputButtonEnum::BUTTON_X,
XInputButtonEnum::BUTTON_Y,
XInputButtonEnum::START,
XInputButtonEnum::BACK,
XInputButtonEnum::LEFT_STICK,
XInputButtonEnum::RIGHT_STICK,
XInputButtonEnum::LEFT_SHOULDER,
XInputButtonEnum::RIGHT_SHOULDER,
// dpad
XInputButtonEnum::DPAD_UP,
XInputButtonEnum::DPAD_DOWN,
XInputButtonEnum::DPAD_LEFT,
XInputButtonEnum::DPAD_RIGHT,
// analog values that can be used as buttons
XInputButtonEnum::LEFT_TRIGGER,
XInputButtonEnum::RIGHT_TRIGGER,
XInputButtonEnum::LEFT_STICK_UP,
XInputButtonEnum::LEFT_STICK_DOWN,
XInputButtonEnum::LEFT_STICK_LEFT,
XInputButtonEnum::LEFT_STICK_RIGHT,
XInputButtonEnum::RIGHT_STICK_UP,
XInputButtonEnum::RIGHT_STICK_DOWN,
XInputButtonEnum::RIGHT_STICK_LEFT,
XInputButtonEnum::RIGHT_STICK_RIGHT,
};
for (uint8_t player = 0; player < XUSER_MAX_COUNT; player++) {
XINPUT_GAMEPAD_STATE_NORMALIZED state;
get_state(player, state);
for (uint16_t b = 0; b < static_cast<uint16_t>(XInputButtonEnum::COUNT); b++) {
if (is_button_pressed(player, static_cast<XInputButtonEnum>(b))) {
if (is_button_pressed(player, button_priority[b], &state)) {
button.player = player;
button.button = static_cast<XInputButtonEnum>(b);
button.button = button_priority[b];
return true;
}
}
+3 -1
View File
@@ -31,6 +31,8 @@ namespace xinput {
float sThumbRY;
};
// the order of this enum is used for vkey mapping (saved in config file)
// therefore it can never be changed
enum class XInputButtonEnum : uint16_t {
// actual buttons
DPAD_UP,
@@ -102,7 +104,7 @@ namespace xinput {
~XInputManager();
void stop();
std::vector<uint8_t> get_available_players();
bool is_button_pressed(uint8_t player, XInputButtonEnum button);
bool is_button_pressed(uint8_t player, XInputButtonEnum button, XINPUT_GAMEPAD_STATE_NORMALIZED *state_in=nullptr);
float get_analog_state(uint8_t player, XInputAnalogEnum analog);
bool get_any_button_pressed(XINPUT_NEW_BUTTON &button);
void set_output_state(uint8_t player, XInputOutputEnum output, float value);
+9 -5
View File
@@ -7,6 +7,7 @@
#include "util/logging.h"
#include "misc/eamuse.h"
#include "util/precise_timer.h"
#include "util/utils.h"
#include "structuredmessage.h"
@@ -217,6 +218,7 @@ bool Reader::set_comm_state(DWORD BaudRate) {
}
bool Reader::wait_for_handshake() {
timeutils::PreciseSleepTimer timer;
// baud rates
DWORD baud_rates[] = { CBR_57600, CBR_38400, CBR_19200, CBR_9600 };
@@ -268,7 +270,7 @@ bool Reader::wait_for_handshake() {
}
// sleep
Sleep(50);
timer.sleep(50);
}
log_warning("reader", "{}: no handshake received for {} baud", this->port, baud_rates[i]);
@@ -405,6 +407,7 @@ void start_reader_thread(const std::string &port, int id) {
READER_THREAD_RUNNING = true;
READER_THREADS.push_back(new std::thread([port, id]() {
log_info("reader", "{}: starting reader thread", port);
timeutils::PreciseSleepTimer timer;
while (READER_THREAD_RUNNING) {
@@ -442,21 +445,22 @@ void start_reader_thread(const std::string &port, int id) {
}
if (did_read_card) {
Sleep(2500);
timer.sleep(2500);
}
Sleep(20);
timer.sleep(20);
}
}
// sleep between reader connection retries
if (READER_THREAD_RUNNING)
Sleep(5000);
timer.sleep(5000);
}
}));
// wait for thread to start
Sleep(10);
timeutils::PreciseSleepTimer timer;
timer.sleep(10);
}
void stop_reader_thread() {
+273
View File
@@ -0,0 +1,273 @@
#pragma once
#ifndef SPICE_SDK_H
#define SPICE_SDK_H
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
#define SPICE_SDK_ENTRY_POINT extern "C" __declspec(dllexport) int __cdecl
#else
#define SPICE_SDK_ENTRY_POINT __declspec(dllexport) int __cdecl
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef enum SPICE_SDK_STATUS_CODE {
SPICE_SDK_STATUS_SUCCESS = 0,
// 000: generic
SPICE_SDK_STATUS_GENERIC_ERROR = 1,
SPICE_SDK_STATUS_NOT_INITIALIZED = 2,
SPICE_SDK_STATUS_NOT_SUPPORTED = 3,
SPICE_SDK_STATUS_TOO_SMALL = 4,
SPICE_SDK_STATUS_TOO_LATE = 5,
// 1000: invalid args
SPICE_SDK_STATUS_INVALID_ARGUMENT_1 = 1001,
SPICE_SDK_STATUS_INVALID_ARGUMENT_2 = 1002,
SPICE_SDK_STATUS_INVALID_ARGUMENT_3 = 1003,
SPICE_SDK_STATUS_INVALID_ARGUMENT_4 = 1004,
SPICE_SDK_STATUS_INVALID_ARGUMENT_5 = 1005,
} SPICE_SDK_STATUS_CODE;
typedef enum SPICE_SDK_LOG_LEVEL {
SPICE_SDK_LOG_LEVEL_MISC = 0,
SPICE_SDK_LOG_LEVEL_INFO = 1,
SPICE_SDK_LOG_LEVEL_WARNING = 2,
SPICE_SDK_LOG_LEVEL_FATAL = 3,
} SPICE_SDK_LOG_LEVEL;
typedef struct SPICE_SDK_TOUCH_POINT {
uint32_t id;
int x;
int y;
} SPICE_SDK_TOUCH_POINT;
typedef struct SPICE_SDK_GAME_INFO {
char name[64]; // null-terminated
} SPICE_SDK_GAME_INFO;
typedef struct SPICE_SDK_AVS_INFO {
char model[4]; // "MDX", null-terminated
char dest; // J
char spec; // A
char rev; // A
char ext[11]; // "2025061002", null-terminated
} SPICE_SDK_AVS_INFO;
// get_game_info (v0.1 and up)
//
// get info about the currently running game
//
// info: receives game info
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_get_game_info_func)(
SPICE_SDK_GAME_INFO *info
);
// get_avs_info (v0.1 and up)
//
// get AVS info (model, dest, spec, rev, ext)
//
// info: receives AVS info
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_get_avs_info_func)(
SPICE_SDK_AVS_INFO *info
);
// log (v0.1 and up)
// logs a message to the log
// writing a FATAL message will terminate spice, only use in catastrophic failure
//
// level: see log level enum
// module: short string that identifies the facility / module / submodule
// message: the message to log
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_log_func)(
SPICE_SDK_LOG_LEVEL level,
const char *module,
const char *message
);
// get_button (v0.1 and up)
// gets the button state
//
// button_id: ID of the button; see spicesdk_io.h for named values
// pressed: (optional) is the button pressed?
// velocity: (optional) MIDI velocity of the button
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_get_button_func)(
uint32_t button_id,
bool *pressed,
float *velocity
);
// set_button (v0.1 and up)
// sets or clears the button override
//
// make sure to hold the button long enough for the game's I/O engine to pick up
// usually, one or two frames
//
// button_id: ID of the button; see spicesdk_io.h for named values
// pressed: true to set the button override (permanently set the button to be ON until cleared),
// false to clear the override (allow user's controller to provide input again)
// velocity: MIDI velocity of the button; only valid when pressed is true
// can be between 0.0 and 1.0, inclusive
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_set_button_func)(
uint32_t button_id,
bool pressed,
float velocity
);
// get_analog (v0.1 and up)
// gets the analog state
//
// button_id: ID of the button; see spicesdk_io.h for named values
// value: receives the state of the analog
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_get_analog_func)(
uint32_t analog_id,
float *value
);
// set_analog (v0.1 and up)
// sets or clears the analog override
//
// analog_id: ID of the analog; see spicesdk_io.h for named values
// override_active: true to set override (gain exclusive control)
// false to clear it (allow user's controller provide input again)
// value: value of the analog; only valid when override_active is true
// can be between 0.0 and 1.0, inclusive
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_set_analog_func)(
uint32_t analog_id,
bool override_active,
float value
);
// get_light (v0.1 and up)
// gets the last observed value of a light
//
// light_id: ID of the light; see spicesdk_io.h for named values
// value: output parameter for the light value; 0.0 to 1.0
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_get_light_func)(
uint32_t light_id,
float *value
);
// set_light (v0.1 and up)
// sets or clears the light override
//
// light_id: ID of the light; see spicesdk_io.h for named values
// light_value: output parameter for the light value; 0.0 to 1.0
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_set_light_func)(
uint32_t light_id,
bool override_active,
float light_value
);
// set_touch (v0.1 and up)
// adds or updates touch points
//
// points: array of touch points to add or update
// count: number of touch points in the array
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_set_touch_func)(
const SPICE_SDK_TOUCH_POINT *points,
uint32_t count
);
// clear_touch (v0.1 and up)
// clears touch points (i.e., no longer being touched)
//
// ids: array of touch point IDs to clear
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_clear_touch_func)(
const uint32_t *ids,
uint32_t count
);
// insert_card (v0.1 and up)
// simulates inserting an e-amuse card with the given ID
//
// unit: 0 for player 1, 1 for player 2
// card_id: null-terminated string of the card ID
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_insert_card_func)(
uint8_t unit,
const char *card_id
);
// set_keypad (v0.1 and up)
// sets keypad state
//
// make sure to hold the button long enough for the game to pick up
// 70ms is usually sufficient, except for DDR which needs 150ms
//
// unit: 0 for player 1, 1 for player 2
// key: '0' to '9' for numbers, 'A' for 00, 'D' for decimal point, 0 or '\0' to release all keys
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_set_keypad_func)(
uint8_t unit,
char key
);
typedef struct SPICE_SDK_V0 {
uint32_t size;
spice_sdk_log_func *log;
spice_sdk_get_game_info_func *get_game_info;
spice_sdk_get_avs_info_func *get_avs_info;
spice_sdk_get_button_func *get_button;
spice_sdk_set_button_func *set_button;
spice_sdk_get_analog_func *get_analog;
spice_sdk_set_analog_func *set_analog;
spice_sdk_get_light_func *get_light;
spice_sdk_set_light_func *set_light;
spice_sdk_set_touch_func *set_touch;
spice_sdk_clear_touch_func *clear_touch;
spice_sdk_insert_card_func *insert_card;
spice_sdk_set_keypad_func *set_keypad;
} SPICE_SDK_V0;
typedef void (__cdecl spice_sdk_destroy_callback_func)(
void
);
// init (v0.1 and up)
//
// version: supply 0
// destroy_callback: supply a function pointer that will be called when spice
// is shutting down
// sdk_functions: supply a pointer to SPICE_SDK_V0; ensure size field is initialized
// to sizeof(SPICE_SDK_V0) before calling this function
typedef SPICE_SDK_STATUS_CODE (__cdecl spice_sdk_init_func)(
uint32_t version,
spice_sdk_destroy_callback_func *destroy_callback,
void *sdk_functions
);
typedef int (__cdecl spice_sdk_entry_point_func)(
spice_sdk_init_func *init
);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // SPICE_SDK_H
File diff suppressed because it is too large Load Diff
+98
View File
@@ -0,0 +1,98 @@
#include <format>
#include <chrono>
#include <thread>
#include <windows.h>
#include "sdk/include/spicesdk.h"
#include "sdk/include/spicesdk_io.h"
// this sample assumes that the game is DDR
// convenience wrapper for logging; feel free to add other levels
#define LOG_INFO(message) spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0_cpp", message)
static SPICE_SDK_V0 spice = {};
static spice_sdk_destroy_callback_func destroy_callback;
static std::jthread worker_thread;
static void worker_thread_main(std::stop_token stop_token);
// main entry point into the DLL
// spice executable will call into this shortly after the game is partially
// initialized (but not quite fully booted just yet)
SPICE_SDK_ENTRY_POINT
spice_sdk_entry_point(
spice_sdk_init_func *init
)
{
SPICE_SDK_STATUS_CODE status;
// SPICE_SDK_V0 must be zeroed AND the size field must be set
spice.size = sizeof(spice);
// initialize the SDK - can be called any time, but we'll do it here
status = init(0, destroy_callback, &spice);
// always check for return value; failure could be usage error,
// or the spice executable doesn't support this SDK version
// check the log messages from sdk:
if (status != SPICE_SDK_STATUS_SUCCESS) {
return 0;
}
LOG_INFO("plugin loaded");
// spin up a worker thread
worker_thread = std::jthread(worker_thread_main);
return 1;
}
void
__cdecl
destroy_callback(
void
)
{
LOG_INFO("plugin unloading");
if (worker_thread.joinable()) {
worker_thread.request_stop();
worker_thread.join();
}
}
struct ArrowButton {
int key;
SPICE_SDK_DDR_BUTTONS button;
const char* name;
bool previous_state;
};
static ArrowButton arrow_buttons[] = {
{ VK_UP, DDR_Button_P1_PANEL_UP, "UP", false },
{ VK_DOWN, DDR_Button_P1_PANEL_DOWN, "DOWN", false },
{ VK_LEFT, DDR_Button_P1_PANEL_LEFT, "LEFT", false },
{ VK_RIGHT, DDR_Button_P1_PANEL_RIGHT, "RIGHT", false },
};
// worker thread for I/O
static void worker_thread_main(std::stop_token stop_token) {
while (!stop_token.stop_requested()) {
for (auto& arrow : arrow_buttons) {
// check for ctrl + arrow keys and trigger p1 pad arrows
if (((GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0) &&
((GetAsyncKeyState(arrow.key) & 0x8000) != 0)) {
spice.set_button(arrow.button, true, 1.f);
if (!arrow.previous_state) {
LOG_INFO(std::format("let me hear you say: {}", arrow.name).c_str());
arrow.previous_state = true;
}
} else {
spice.set_button(arrow.button, false, 0.f);
arrow.previous_state = false;
}
}
Sleep(1);
}
}
+4
View File
@@ -0,0 +1,4 @@
LIBRARY sdk_sample_v0_cpp
EXPORTS
spice_sdk_entry_point
@@ -0,0 +1,318 @@
#include <string.h>
#include <stdio.h>
#include <windows.h>
#include <process.h>
#include "sdk/include/spicesdk.h"
#include "sdk/include/spicesdk_io.h"
static SPICE_SDK_V0 spice;
static spice_sdk_destroy_callback_func destroy_callback;
static void test_logging();
static void test_game_info();
static void test_avs_info();
static void get_buttons();
static void set_buttons();
static void clear_buttons();
static void get_analogs();
static void set_analogs();
static void clear_analogs();
static void get_lights();
static void set_lights();
static void clear_lights();
static void set_touch();
static void clear_touch();
static void insert_card();
static void set_keypad();
static void clear_keypad();
static HANDLE worker_stop_event;
static HANDLE worker_handle;
static unsigned __stdcall worker_thread(void *arg);
// this sample assumes that the game is IIDX, but it doesn't check for it.
SPICE_SDK_ENTRY_POINT
spice_sdk_entry_point(
spice_sdk_init_func *init
)
{
SPICE_SDK_STATUS_CODE status;
memset(&spice, 0, sizeof(spice));
spice.size = sizeof(spice);
status = init(0, destroy_callback, &spice);
if (status != SPICE_SDK_STATUS_SUCCESS) {
return 0;
}
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "plugin loaded");
test_logging();
test_game_info();
test_avs_info();
worker_stop_event = CreateEventA(NULL, TRUE, FALSE, NULL);
if (!worker_stop_event) {
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "failed to create worker stop event");
return 0;
}
worker_handle = (HANDLE)_beginthreadex(
NULL, // security
0, // stack size
worker_thread, // function
NULL, // argument
0, // flags
NULL // thread id
);
if (!worker_handle) {
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "failed to create worker thread");
CloseHandle(worker_stop_event);
worker_stop_event = NULL;
return 0;
}
return 1;
}
void
__cdecl
destroy_callback(
void
)
{
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "plugin unloaded");
if (worker_stop_event) {
SetEvent(worker_stop_event);
}
if (worker_handle) {
WaitForSingleObject(worker_handle, INFINITE);
CloseHandle(worker_handle);
worker_handle = NULL;
}
if (worker_stop_event) {
CloseHandle(worker_stop_event);
worker_stop_event = NULL;
}
}
static unsigned __stdcall worker_thread(void *arg) {
int phase = 0;
while (WaitForSingleObject(worker_stop_event, 0) == WAIT_TIMEOUT) {
phase += 1;
switch (phase) {
case 1:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "get buttons...");
get_buttons();
break;
case 2:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "set buttons...");
set_buttons();
break;
case 3:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "clear buttons...");
clear_buttons();
break;
case 4:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "get analogs...");
get_analogs();
break;
case 5:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "set analogs...");
set_analogs();
break;
case 6:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "clear analogs...");
clear_analogs();
break;
case 7:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "get lights...");
get_lights();
break;
case 8:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "set lights...");
set_lights();
break;
case 9:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "clear lights...");
clear_lights();
break;
case 10:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "set touch...");
set_touch();
break;
case 11:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "clear touch...");
clear_touch();
break;
case 12:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "insert card...");
insert_card();
break;
case 13:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "set keypad...");
set_keypad();
break;
case 14:
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "clear keypad...");
clear_keypad();
break;
default:
phase = 0;
break;
}
if (phase != 0) {
WaitForSingleObject(worker_stop_event, 3000);
}
}
return 0;
}
static void test_logging() {
spice.log(SPICE_SDK_LOG_LEVEL_MISC, "sample_v0", "this is a misc message");
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", "this is an info message");
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "this is a warning message");
}
static void test_game_info() {
SPICE_SDK_GAME_INFO info;
SPICE_SDK_STATUS_CODE status;
status = spice.get_game_info(&info);
if (status != SPICE_SDK_STATUS_SUCCESS) {
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "get_game_info failed");
return;
}
char log_message[128];
snprintf(log_message, sizeof(log_message), "game info - name: %s", info.name);
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", log_message);
}
static void test_avs_info() {
SPICE_SDK_AVS_INFO info;
SPICE_SDK_STATUS_CODE status;
status = spice.get_avs_info(&info);
if (status != SPICE_SDK_STATUS_SUCCESS) {
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "get_avs_info failed");
return;
}
char log_message[128];
snprintf(
log_message,
sizeof(log_message),
"avs - model: %s, dest: %c, spec: %c, rev: %c, ext: %s",
info.model, info.dest, info.spec, info.rev, info.ext);
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", log_message);
}
static void get_buttons() {
bool pressed;
float velocity;
spice.get_button(IIDX_Button_P1_Headphone, &pressed, &velocity);
char log_message[128];
snprintf(
log_message,
sizeof(log_message),
"button P1_Headphone pressed: %s, velocity: %.2f",
pressed ? "ON" : "off", velocity);
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", log_message);
}
static void set_buttons() {
spice.set_button(IIDX_Button_P1_1, true, 0.3f);
spice.set_button(IIDX_Button_P1_3, true, 0.5f);
spice.set_button(IIDX_Button_P1_5, true, 0.7f);
}
static void clear_buttons() {
spice.set_button(IIDX_Button_P1_1, false, 0.f);
spice.set_button(IIDX_Button_P1_3, false, 0.f);
spice.set_button(IIDX_Button_P1_5, false, 0.f);
}
static void get_analogs() {
float value;
spice.get_analog(IIDX_Analog_TT_P1, &value);
char log_message[128];
snprintf(
log_message,
sizeof(log_message),
"analog TT_P1: %.2f",
value);
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", log_message);
}
static void set_analogs() {
spice.set_analog(IIDX_Analog_TT_P1, true, 0.25f);
spice.set_analog(IIDX_Analog_TT_P2, true, 0.75f);
}
static void clear_analogs() {
spice.set_analog(IIDX_Analog_TT_P1, false, 0.f);
spice.set_analog(IIDX_Analog_TT_P2, false, 0.f);
}
static void get_lights() {
float value;
SPICE_SDK_STATUS_CODE status;
status = spice.get_light(IIDX_Light_TT_P1_Resistance, &value);
if (status == SPICE_SDK_STATUS_SUCCESS) {
char log_message[64];
snprintf(log_message, sizeof(log_message), "P1 TT resistance value: %.2f", value);
spice.log(SPICE_SDK_LOG_LEVEL_INFO, "sample_v0", log_message);
} else {
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", "get_light failed");
}
}
static void set_lights() {
spice.set_light(IIDX_Light_P1_Start, true, 1.f);
}
static void clear_lights() {
spice.set_light(IIDX_Light_P1_Start, false, 0.f);
}
static void set_touch() {
SPICE_SDK_TOUCH_POINT points[2] = {
{ .id = 1, .x = 100, .y = 200 },
{ .id = 2, .x = 300, .y = 400 },
};
spice.set_touch(points, 2);
}
static void clear_touch() {
uint32_t ids[2] = { 1, 2 };
spice.clear_touch(ids, 2);
}
static void insert_card() {
spice.insert_card(0, "E004010000001234");
}
static void set_keypad() {
SPICE_SDK_STATUS_CODE ret = spice.set_keypad(0, '3');
if (ret != SPICE_SDK_STATUS_SUCCESS) {
char log_message[64];
snprintf(log_message, sizeof(log_message), "set_keypad failed: %d", ret);
spice.log(SPICE_SDK_LOG_LEVEL_WARNING, "sample_v0", log_message);
}
}
static void clear_keypad() {
spice.set_keypad(0, 0);
}
@@ -0,0 +1,4 @@
LIBRARY sdk_sample_v0_flat_c
EXPORTS
spice_sdk_entry_point
+598
View File
@@ -0,0 +1,598 @@
#include <vector>
#include <mutex>
#include <shared_mutex>
#include "sdk.h"
#include "avs/game.h"
#include "games/io.h"
#include "launcher/launcher.h"
#include "misc/eamuse.h"
#include "sdk/include/spicesdk.h"
#include "touch/touch.h"
#include "util/logging.h"
#include "util/utils.h"
#include "acio/mdxf/mdxf_poll.h"
namespace sdk {
static spice_sdk_init_func sdk_init;
static spice_sdk_log_func sdk_log;
static spice_sdk_get_avs_info_func sdk_get_avs_info;
static spice_sdk_get_game_info_func sdk_get_game_info;
static spice_sdk_get_button_func sdk_get_button;
static spice_sdk_set_button_func sdk_set_button;
static spice_sdk_get_analog_func sdk_get_analog;
static spice_sdk_set_analog_func sdk_set_analog;
static spice_sdk_get_light_func sdk_get_light;
static spice_sdk_set_light_func sdk_set_light;
static spice_sdk_set_touch_func sdk_set_touch;
static spice_sdk_clear_touch_func sdk_clear_touch;
static spice_sdk_insert_card_func sdk_insert_card;
static spice_sdk_set_keypad_func sdk_set_keypad;
struct SdkModule {
std::string dll;
HINSTANCE module;
};
// DLLs
static int sdk_modules_count = 0;
static std::vector<SdkModule> sdk_modules_list;
static std::shared_mutex sdk_global_mutex;
// internal
static bool sdk_initialized = false;
static bool sdk_shutting_down = false;
static std::vector<Button> *buttons;
static std::vector<Analog> *analogs;
static std::vector<Light> *lights;
// callbacks
static std::mutex sdk_callback_registration_mutex;
static std::vector<spice_sdk_destroy_callback_func *> callbacks_destroy;
void register_sdk_hooks(std::string dll, HINSTANCE module) {
sdk_modules_list.emplace_back(std::move(dll), module);
sdk_modules_count += 1;
}
void init_sdk_modules() {
if (sdk_modules_count == 0) {
return;
}
// prepare
buttons = games::get_buttons(eamuse_get_game());
analogs = games::get_analogs(eamuse_get_game());
lights = games::get_lights(eamuse_get_game());
// under exclusive lock, mark the SDK helpers as being available
{
std::unique_lock lock(sdk_global_mutex);
sdk_initialized = true;
}
// without any locks, call into each DLL; this may call back into SDK functions
for (auto &module : sdk_modules_list) {
// get a pointer to dll's spice_sdk_entry_point
const auto entry_point = reinterpret_cast<spice_sdk_entry_point_func *>(
GetProcAddress(module.module, "spice_sdk_entry_point"));
if (!entry_point) {
continue;
}
// call into it on this thread
log_info("sdk", "registering SDK hooks for {}", module.dll);
const auto ret = entry_point(sdk_init);
log_info("sdk", "spice_sdk_entry_point returned {}", ret);
}
}
void fini_sdk_modules() {
// prevent multiple calls and further calls into sdk_init
{
std::unique_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return;
}
sdk_shutting_down = true;
}
// call into destroy callback of each DLL
// this may call back into SDK functions (e.g., for logging)
// so we leave sdk_initialized as-is
{
log_info("sdk", "calling destroy callbacks...");
std::lock_guard lock(sdk_callback_registration_mutex);
for (const auto& destroy : callbacks_destroy) {
destroy();
}
}
// under exclusive lock, mark the SDK functions as no longer available
{
std::unique_lock lock(sdk_global_mutex);
sdk_initialized = false;
}
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_init(
uint32_t version,
spice_sdk_destroy_callback_func *destroy_callback,
void *sdk_functions
)
{
std::shared_lock lock(sdk_global_mutex);
if (sdk_shutting_down || !sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
uint32_t size;
if (version != 0) {
log_warning("sdk", "sdk_init returning NOT_SUPPORTED due to invalid version: {}", version);
return SPICE_SDK_STATUS_NOT_SUPPORTED;
}
if (!destroy_callback) {
log_warning("sdk", "sdk_init returning INVALID_ARGUMENT_2 due to invalid destroy_callback pointer");
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
if (!sdk_functions) {
log_warning("sdk", "sdk_init returning INVALID_ARGUMENT_3 due to invalid sdk_functions pointer");
return SPICE_SDK_STATUS_INVALID_ARGUMENT_3;
}
auto *v0 = reinterpret_cast<SPICE_SDK_V0 *>(sdk_functions);
if (v0->size < RTL_SIZEOF_THROUGH_FIELD(SPICE_SDK_V0, set_keypad)) {
log_warning("sdk", "sdk_init returning TOO_SMALL due to size field of SPICE_SDK_V0 not being set");
return SPICE_SDK_STATUS_TOO_SMALL;
}
// we are trusting the size passed in by the caller
size = v0->size;
memset(v0, 0, size);
v0->size = size;
v0->log = sdk_log;
v0->get_game_info = sdk_get_game_info;
v0->get_avs_info = sdk_get_avs_info;
v0->get_button = sdk_get_button;
v0->set_button = sdk_set_button;
v0->get_analog = sdk_get_analog;
v0->set_analog = sdk_set_analog;
v0->get_light = sdk_get_light;
v0->set_light = sdk_set_light;
v0->set_touch = sdk_set_touch;
v0->clear_touch = sdk_clear_touch;
v0->insert_card = sdk_insert_card;
v0->set_keypad = sdk_set_keypad;
// end of 0.1
// any newer minor iterations will need to check the size
{
// destroy callbacks are only called upon successful return from this routine
std::lock_guard lock(sdk_callback_registration_mutex);
callbacks_destroy.push_back(destroy_callback);
}
log_info("sdk", "sdk_init returning SUCCESS");
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_log(
SPICE_SDK_LOG_LEVEL level,
const char *facility,
const char *message
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (facility == nullptr) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
const std::string facility_str = fmt::format("sdk::{}", facility);
switch (level) {
case SPICE_SDK_LOG_LEVEL_MISC:
log_misc(facility_str.c_str(), "{}", message);
break;
case SPICE_SDK_LOG_LEVEL_INFO:
log_info(facility_str.c_str(), "{}", message);
break;
case SPICE_SDK_LOG_LEVEL_WARNING:
log_warning(facility_str.c_str(), "{}", message);
break;
case SPICE_SDK_LOG_LEVEL_FATAL:
log_fatal(facility_str.c_str(), "{}", message);
break;
default:
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_get_avs_info(
SPICE_SDK_AVS_INFO *info
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!info) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
// MDXJAA2025061002
strncpy(info->model, avs::game::MODEL, sizeof(info->model));
info->dest = avs::game::DEST[0];
info->spec = avs::game::SPEC[0];
info->rev = avs::game::REV[0];
strncpy(info->ext, avs::game::EXT, sizeof(info->ext));
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_get_game_info(
SPICE_SDK_GAME_INFO *info
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!info) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
*info = {};
const std::string game_name = eamuse_get_game();
strncpy(info->name, game_name.c_str(), sizeof(info->name));
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_get_button (
uint32_t button_id,
bool *pressed,
float *velocity
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!buttons) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (button_id >= buttons->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
Button &button = (*buttons)[button_id];
if (pressed) {
*pressed = (GameAPI::Buttons::getState(RI_MGR, button) == GameAPI::Buttons::BUTTON_PRESSED);
}
if (velocity) {
*velocity = GameAPI::Buttons::getVelocity(RI_MGR, button);
}
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_set_button (
uint32_t button_id,
bool pressed,
float velocity
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!buttons) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (button_id >= buttons->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (pressed) {
velocity = std::clamp(velocity, 0.f, 1.f);
}
Button &button = (*buttons)[button_id];
if (pressed) {
button.override_state = pressed ? GameAPI::Buttons::BUTTON_PRESSED : GameAPI::Buttons::BUTTON_NOT_PRESSED;
button.override_velocity = velocity;
}
button.override_enabled = pressed;
mdxf_poll(true);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_get_analog (
uint32_t analog_id,
float *value
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!analogs) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (analog_id >= analogs->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (!value) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
Analog &analog = (*analogs)[analog_id];
*value = GameAPI::Analogs::getState(RI_MGR, analog);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_set_analog (
uint32_t analog_id,
bool override_active,
float value
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!analogs) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (analog_id >= analogs->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (override_active) {
value = std::clamp(value, 0.f, 1.f);
}
Analog &analog = (*analogs)[analog_id];
if (override_active) {
analog.override_state = value;
}
analog.override_enabled = override_active;
mdxf_poll(true);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_get_light(
uint32_t light_id,
float *value
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!lights) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (light_id >= lights->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (!value) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
Light &light = (*lights)[light_id];
*value = GameAPI::Lights::readLight(RI_MGR, light);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_set_light(
uint32_t light_id,
bool override_active,
float value
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (!lights) {
return SPICE_SDK_STATUS_NOT_INITIALIZED;
}
if (light_id >= lights->size()) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (override_active) {
value = std::clamp(value, 0.f, 1.f);
}
Light &light = (*lights)[light_id];
if (override_active) {
light.override_state = value;
}
light.override_enabled = override_active;
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_set_touch(
const SPICE_SDK_TOUCH_POINT *points,
uint32_t count
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (count == 0 || !points) {
return SPICE_SDK_STATUS_TOO_SMALL;
}
std::vector<TouchPoint> touch_points;
for (uint32_t i = 0; i < count; i++) {
const SPICE_SDK_TOUCH_POINT &point = points[i];
touch_points.emplace_back(TouchPoint {
.id = point.id,
.x = point.x,
.y = point.y,
.mouse = false,
});
}
touch_write_points(&touch_points);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_clear_touch(
const uint32_t *ids,
uint32_t count
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (count == 0 || !ids) {
return SPICE_SDK_STATUS_TOO_SMALL;
}
std::vector<DWORD> touch_point_ids;
for (uint32_t i = 0; i < count; i++) {
touch_point_ids.push_back(ids[i]);
}
touch_remove_points(&touch_point_ids);
return SPICE_SDK_STATUS_SUCCESS;
}
SPICE_SDK_STATUS_CODE
__cdecl
sdk_insert_card(
uint8_t unit,
const char *card_id
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (unit >= 2) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (!card_id) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
if (strlen(card_id) != 16) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
// convert to binary
uint8_t card_bin[8] {};
if (!hex2bin(card_id, card_bin)) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
// insert
eamuse_card_insert(unit & 1, card_bin);
return SPICE_SDK_STATUS_SUCCESS;
}
struct KeypadMapping {
char character;
uint16_t state;
};
static KeypadMapping KEYPAD_MAPPINGS[] = {
{ '0', 1 << EAM_IO_KEYPAD_0 },
{ '1', 1 << EAM_IO_KEYPAD_1 },
{ '2', 1 << EAM_IO_KEYPAD_2 },
{ '3', 1 << EAM_IO_KEYPAD_3 },
{ '4', 1 << EAM_IO_KEYPAD_4 },
{ '5', 1 << EAM_IO_KEYPAD_5 },
{ '6', 1 << EAM_IO_KEYPAD_6 },
{ '7', 1 << EAM_IO_KEYPAD_7 },
{ '8', 1 << EAM_IO_KEYPAD_8 },
{ '9', 1 << EAM_IO_KEYPAD_9 },
{ 'A', 1 << EAM_IO_KEYPAD_00 },
{ 'D', 1 << EAM_IO_KEYPAD_DECIMAL },
};
SPICE_SDK_STATUS_CODE
__cdecl
sdk_set_keypad(
uint8_t unit,
char key
)
{
std::shared_lock lock(sdk_global_mutex);
if (!sdk_initialized) {
return SPICE_SDK_STATUS_TOO_LATE;
}
if (unit >= 2) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_1;
}
if (key == 0) {
eamuse_set_keypad_overrides(unit, 0);
return SPICE_SDK_STATUS_SUCCESS;
}
// find mapping
uint16_t state = 0;
bool mapping_found = false;
for (auto &mapping : KEYPAD_MAPPINGS) {
if (mapping.character == key) {
state |= mapping.state;
mapping_found = true;
break;
}
}
// check for error
if (!mapping_found) {
return SPICE_SDK_STATUS_INVALID_ARGUMENT_2;
}
// set
eamuse_set_keypad_overrides(unit, state);
return SPICE_SDK_STATUS_SUCCESS;
}
} // namespace sdk
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <string>
#include <windows.h>
namespace sdk {
void register_sdk_hooks(std::string dll, HINSTANCE module);
void init_sdk_modules();
void fini_sdk_modules();
}
+66 -49
View File
@@ -67,6 +67,8 @@ static const char *LOG_MODULE_NAME = "touch";
static TouchHandler *TOUCH_HANDLER = nullptr;
static bool is_mouse_message_from_touchscreen();
TouchHandler::TouchHandler(std::string name) {
log_info("touch", "Using touch handler: {}", name);
}
@@ -215,6 +217,30 @@ void update_card_button() {
}
}
static void release_all_mouse_touch_points() {
std::lock_guard<std::mutex> lock_points(TOUCH_POINTS_M);
std::lock_guard<std::mutex> lock_events(TOUCH_EVENTS_M);
for (size_t x = 0; x < TOUCH_POINTS.size();) {
TouchPoint *tp = &TOUCH_POINTS[x];
if (tp->id == 0u) {
TouchEvent te {
.id = tp->id,
.x = tp->x,
.y = tp->y,
.type = TOUCH_UP,
.mouse = tp->mouse,
};
add_touch_event(&te);
TOUCH_POINTS.erase(TOUCH_POINTS.begin() + x);
} else {
x++;
}
}
}
static LRESULT CALLBACK SpiceTouchWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
// check if touch was registered
@@ -490,35 +516,22 @@ static LRESULT CALLBACK SpiceTouchWndProc(HWND hWnd, UINT msg, WPARAM wParam, LP
// parse mouse messages
switch (msg) {
case WM_LBUTTONDOWN: {
// check if mouse is enabled
if (SPICETOUCH_ENABLE_MOUSE) {
if (is_mouse_message_from_touchscreen()) {
return 0;
}
// subscribe to mouse messages even when the cursor leaves the window
SetCapture(hWnd);
// release all old events before inserting a new one
release_all_mouse_touch_points();
// lock touch points
std::lock_guard<std::mutex> lock_points(TOUCH_POINTS_M);
std::lock_guard<std::mutex> lock_events(TOUCH_EVENTS_M);
// remove all points with ID 0
for (size_t x = 0; x < TOUCH_POINTS.size(); x++) {
TouchPoint *tp = &TOUCH_POINTS[x];
if (tp->id == 0u) {
// generate touch up event
TouchEvent te {
.id = tp->id,
.x = tp->x,
.y = tp->y,
.type = TOUCH_UP,
.mouse = tp->mouse,
};
add_touch_event(&te);
// erase touch point
TOUCH_POINTS.erase(TOUCH_POINTS.begin() + x);
}
}
// create touch point
TouchPoint tp {
.id = 0,
@@ -545,9 +558,11 @@ static LRESULT CALLBACK SpiceTouchWndProc(HWND hWnd, UINT msg, WPARAM wParam, LP
break;
}
case WM_MOUSEMOVE: {
// check if mouse is enabled
if (SPICETOUCH_ENABLE_MOUSE) {
if (is_mouse_message_from_touchscreen()) {
return 0;
}
// lock touch points
std::lock_guard<std::mutex> lock_points(TOUCH_POINTS_M);
@@ -582,40 +597,31 @@ static LRESULT CALLBACK SpiceTouchWndProc(HWND hWnd, UINT msg, WPARAM wParam, LP
break;
}
case WM_LBUTTONUP: {
// check if mouse is enabled
if (SPICETOUCH_ENABLE_MOUSE) {
if (is_mouse_message_from_touchscreen()) {
return 0;
}
// lock touch points
std::lock_guard<std::mutex> lock_points(TOUCH_POINTS_M);
std::lock_guard<std::mutex> lock_events(TOUCH_EVENTS_M);
// remove all points with ID 0
for (size_t x = 0; x < TOUCH_POINTS.size(); x++) {
TouchPoint *tp = &TOUCH_POINTS[x];
if (tp->id == 0u) {
// generate touch up event
TouchEvent te {
.id = tp->id,
.x = tp->x,
.y = tp->y,
.type = TOUCH_UP,
.mouse = tp->mouse,
};
add_touch_event(&te);
// remove touch point
TOUCH_POINTS.erase(TOUCH_POINTS.begin() + x);
}
release_all_mouse_touch_points();
if (GetCapture() == hWnd) {
ReleaseCapture();
}
}
break;
}
default:
case WM_CAPTURECHANGED:
case WM_CANCELMODE: {
// to deal with window losing the capture after SetCapture
release_all_mouse_touch_points();
if (msg == WM_CANCELMODE && GetCapture() == hWnd) {
ReleaseCapture();
}
break;
}
default:
// call original function
if (SPICETOUCH_CALL_OLD_PROC && SPICETOUCH_OLD_PROC != nullptr) {
return SPICETOUCH_OLD_PROC(hWnd, msg, wParam, lParam);
@@ -663,6 +669,8 @@ void touch_attach_dx_hook() {
// initialize touch handler
touch_initialize();
log_info("touch", "touch_attach_dx_hook: attaching SpiceTouchWndProc...");
// add dx hook
graphics_add_wnd_proc(SpiceTouchWndProc);
@@ -681,6 +689,8 @@ void touch_create_wnd(HWND hWnd, bool overlay) {
// initialize touch handler
touch_initialize();
log_info("touch", "touch_create_wnd: creating SPICETOUCH_TOUCH_THREAD...");
// create thread
SPICETOUCH_TOUCH_THREAD = new std::thread([hWnd, overlay]() {
@@ -956,4 +966,11 @@ void update_spicetouch_window_dimensions(HWND hWnd) {
SPICETOUCH_TOUCH_Y = topleft.y;
SPICETOUCH_TOUCH_WIDTH = bottomright.x - topleft.x;
SPICETOUCH_TOUCH_HEIGHT = bottomright.y - topleft.y;
}
}
// https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
static bool is_mouse_message_from_touchscreen() {
constexpr ULONG_PTR MI_WP_SIGNATURE = 0xFF515700;
constexpr ULONG_PTR SIGNATURE_MASK = 0xFFFFFF00;
return (GetMessageExtraInfo() & SIGNATURE_MASK) == MI_WP_SIGNATURE;
}
+14 -37
View File
@@ -82,14 +82,14 @@ bool fileutils::verify_header_pe(const std::filesystem::path &file_path) {
if (!valid) {
log_fatal("fileutils",
"{} (32 bit) can't be loaded using spice64.exe - please use spice.exe for this game.",
file_path.string());
file_path);
}
#else
valid = dll_file_header->Machine == IMAGE_FILE_MACHINE_I386;
if (!valid) {
log_fatal("fileutils",
"{} (64 bit) can't be loaded using spice.exe - please use spice64.exe for this game.",
file_path.string());
file_path);
}
#endif
}
@@ -156,9 +156,9 @@ bool fileutils::dir_create_log(const std::string_view &module, const std::filesy
auto ret = std::filesystem::create_directory(dir_path, err);
if (err) {
log_warning(module, "failed to create directory '{}': {}", dir_path.string(), err.message());
log_warning(module, "failed to create directory '{}': {}", dir_path, err.message());
} else if (ret) {
log_misc(module, "created directory '{}'", dir_path.string());
log_misc(module, "created directory '{}'", dir_path);
}
return ret && !err;
@@ -178,39 +178,14 @@ bool fileutils::dir_create_recursive_log(const std::string_view &module, const s
auto ret = std::filesystem::create_directories(dir_path, err);
if (err) {
log_warning(module, "failed to create directory (recursive) '{}': {}", dir_path.string(), err.message());
log_warning(module, "failed to create directory (recursive) '{}': {}", dir_path, err.message());
} else if (ret) {
log_misc(module, "created directory (recursive) '{}'", dir_path.string());
log_misc(module, "created directory (recursive) '{}'", dir_path);
}
return ret && !err;
}
void fileutils::dir_scan(const std::string &path, std::vector<std::string> &vec, bool recursive) {
// check directory
if (std::filesystem::exists(path) && std::filesystem::is_directory(path)) {
if (recursive) {
for (const auto &entry : std::filesystem::recursive_directory_iterator(path)) {
if (!std::filesystem::is_directory(entry)) {
auto path = entry.path().string();
vec.emplace_back(std::move(path));
}
}
} else {
for (const auto &entry : std::filesystem::directory_iterator(path)) {
if (!std::filesystem::is_directory(entry)) {
auto path = entry.path().string();
vec.emplace_back(std::move(path));
}
}
}
}
// determinism
std::sort(vec.begin(), vec.end());
}
bool fileutils::text_write(const std::filesystem::path &file_path, std::string text) {
std::ofstream out(file_path, std::ios::out | std::ios::binary);
if (out) {
@@ -296,22 +271,24 @@ std::filesystem::path fileutils::get_config_file_path(const std::string module,
bool fileutils::write_config_file(const std::string_view &module, const std::filesystem::path path, std::string text) {
// attempt to undo %appdata% expansion to hide user name
const auto appdata = std::filesystem::path(_wgetenv(L"APPDATA")).string();
auto censored = path.string();
const auto appdata = std::filesystem::path(_wgetenv(L"APPDATA")).wstring();
auto censored = path.wstring();
const auto substr_offset = censored.find(appdata);
if (substr_offset != std::string::npos) {
censored.replace(substr_offset, appdata.length(), "%appdata%");
censored.replace(substr_offset, appdata.length(), L"%appdata%");
}
auto censored_display = fmt::detail::to_utf8<wchar_t>(censored, fmt::detail::to_utf8_error_policy::replace);
// create directory path up to where the config file lives
if (!path.parent_path().empty() && !std::filesystem::exists(path.parent_path())) {
log_misc(module, "creating directory path to config file: {}", censored);
log_misc(module, "creating directory path to config file: {}", censored_display);
if (!fileutils::dir_create_recursive(path.parent_path())) {
return false;
}
}
// save file
log_info(module, "saving config file: {}", censored);
log_info(module, "saving config file: {}", censored_display);
return fileutils::text_write(path, text);
}
}
-1
View File
@@ -26,7 +26,6 @@ namespace fileutils {
bool dir_create_log(const std::string_view &module, const std::filesystem::path &dir_path);
bool dir_create_recursive(const std::filesystem::path &dir_path);
bool dir_create_recursive_log(const std::string_view &module, const std::filesystem::path &dir_path);
void dir_scan(const std::string &path, std::vector<std::string> &vec, bool recursive);
// IO
bool text_write(const std::filesystem::path &file_path, std::string text);
+21 -20
View File
@@ -1,5 +1,6 @@
#include "libutils.h"
#include <cstring>
#include <windows.h>
#include <psapi.h>
#include <shlwapi.h>
@@ -38,7 +39,7 @@ std::filesystem::path libutils::module_file_name(HMODULE module) {
return std::filesystem::path(std::move(buf));
}
static inline void load_library_fail(const std::string &file_name, bool fatal) {
static inline void load_library_fail(const std::filesystem::path &file_name, bool fatal) {
std::string info_str { fmt::format(
"DLL failed to load - this is a common error. Please carefully read ALL of the following steps for a fix:\n"
" 1. Confirm if the file ({}) exists on the disk and check the file permissions.\n"
@@ -76,9 +77,9 @@ HMODULE libutils::load_library(const std::filesystem::path &path, bool fatal) {
HMODULE module = LoadLibraryW(path.c_str());
if (!module) {
log_warning("libutils", "'{}' couldn't be loaded: {}", path.string(), get_last_error_string());
log_warning("libutils", "'{}' couldn't be loaded: {}", path, get_last_error_string());
dependencies::walk(path);
load_library_fail(path.filename().string(), fatal);
load_library_fail(path.filename(), fatal);
}
return module;
@@ -236,7 +237,7 @@ intptr_t libutils::rva2offset(const std::filesystem::path &path, intptr_t rva) {
HANDLE dll_mapping = CreateFileMappingW(dll_file, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!dll_mapping) {
CloseHandle(dll_file);
log_warning("libutils", "could not create file mapping for {}", path.string());
log_warning("libutils", "could not create file mapping for {}", path);
return -1;
}
@@ -245,7 +246,7 @@ intptr_t libutils::rva2offset(const std::filesystem::path &path, intptr_t rva) {
if (!dll_file_base) {
CloseHandle(dll_file);
CloseHandle(dll_mapping);
log_warning("libutils", "could not map view of file for {}", path.string());
log_warning("libutils", "could not map view of file for {}", path);
return -1;
}
@@ -306,7 +307,7 @@ intptr_t libutils::offset2rva(const std::filesystem::path &path, intptr_t offset
// create file mapping
HANDLE dll_mapping = CreateFileMappingW(dll_file, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!dll_mapping) {
log_warning("libutils", "could not create file mapping for {}: {}", path.string(), get_last_error_string());
log_warning("libutils", "could not create file mapping for {}: {}", path, get_last_error_string());
CloseHandle(dll_file);
return -1;
}
@@ -314,7 +315,7 @@ intptr_t libutils::offset2rva(const std::filesystem::path &path, intptr_t offset
// map view of file
LPVOID dll_file_base = MapViewOfFile(dll_mapping, FILE_MAP_READ, 0, 0, 0);
if (!dll_file_base) {
log_warning("libutils", "could not map view of file for {}: {}", path.string(), get_last_error_string());
log_warning("libutils", "could not map view of file for {}: {}", path, get_last_error_string());
CloseHandle(dll_file);
CloseHandle(dll_mapping);
return -1;
@@ -344,9 +345,9 @@ void libutils::check_duplicate_dlls() {
for (const auto &file : std::filesystem::directory_iterator(MODULE_PATH)) {
const auto &filename = file.path().filename();
const auto extension = strtolower(filename.extension().string());
const auto extension = filename.extension().wstring();
if (extension == ".dll" &&
if (wcsicmp(extension.c_str(), L".dll") == 0 &&
fileutils::file_exists(spice_bin_path / filename)) {
log_warning(
"libutils",
@@ -361,9 +362,9 @@ void libutils::check_duplicate_dlls() {
"this has unintended consequences and may crash your game!\n"
"resolve the conflict by deleting the stale copy of the DLL\n"
"-------------------------------------------------------------------\n\n\n",
filename.string(),
(spice_bin_path / filename).string(),
(MODULE_PATH / filename).string());
filename,
(spice_bin_path / filename),
(MODULE_PATH / filename));
}
}
}
@@ -384,22 +385,22 @@ void libutils::warn_if_dll_exists(const std::string &file_name) {
void libutils::print_dll_info(std::filesystem::path filename) {
DWORD handle;
const auto size = GetFileVersionInfoSizeA(filename.string().c_str(), &handle);
const auto size = GetFileVersionInfoSizeW(filename.wstring().c_str(), &handle);
if (size == 0) {
log_debug(
"libutils",
"GetFileVersionInfoSizeA failed for {}: {}",
filename.filename().string(),
filename.filename(),
get_last_error_string());
return;
}
auto data = util::make_unique_plain<VOID>(size);
if (!GetFileVersionInfoA(filename.string().c_str(), handle, size, data.get())) {
if (!GetFileVersionInfoW(filename.wstring().c_str(), handle, size, data.get())) {
log_debug(
"libutils",
"GetFileVersionInfoA failed for {}: {}",
filename.filename().string(),
filename.filename(),
get_last_error_string());
return;
}
@@ -414,7 +415,7 @@ void libutils::print_dll_info(std::filesystem::path filename) {
log_debug(
"libutils",
"VerQueryValueA failed for {}: {}",
filename.filename().string(),
filename.filename(),
get_last_error_string());
return;
}
@@ -422,7 +423,7 @@ void libutils::print_dll_info(std::filesystem::path filename) {
log_debug(
"libutils",
"VerQueryValueA returned invalid results for {}",
filename.filename().string());
filename.filename());
return;
}
@@ -457,7 +458,7 @@ void libutils::print_dll_info(std::filesystem::path filename) {
"libutils",
"VerQueryValueA({}) failed for {}: {}",
subBlock,
filename.filename().string(),
filename.filename(),
get_last_error_string());
return "";
};
@@ -469,7 +470,7 @@ void libutils::print_dll_info(std::filesystem::path filename) {
log_info(
"libutils",
"DLL info for {}: CompanyName = {}, ProductName = {}, Version = {}",
filename.filename().string(),
filename.filename(),
company_name.empty() ? "?" : company_name,
product_name.empty() ? "?" : product_name,
version_str.empty() ? "?" : version_str);
+2 -1
View File
@@ -10,6 +10,7 @@
#include "external/fmt/include/fmt/format.h"
#include "external/fmt/include/fmt/compile.h"
#include "external/fmt/include/fmt/std.h"
#include "launcher/launcher.h"
#include "launcher/logger.h"
@@ -75,7 +76,7 @@ void show_popup_for_fatal_error(std::string message);
// misc log
#define LOG_FORMAT(level, module, fmt_str, ...) fmt::format(FMT_COMPILE("{}" fmt_str "\n"), \
fmt_log { std::time(nullptr), level, module }, ## __VA_ARGS__)
#define LOG_FORMAT_POPUP(module, fmt_str, ...) fmt::format(FMT_COMPILE("{}: " fmt_str "\n"), module, ## __VA_ARGS__)
#define log_misc(module, format_str, ...) logger::push( \
+188
View File
@@ -0,0 +1,188 @@
#define _WIN32_WINNT 0x0602
#include "precise_timer.h"
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#include <timeapi.h>
#if !SPICE_XP
#include <processthreadsapi.h>
#endif
#include <chrono>
#include <cmath>
#include <limits>
#include "util/logging.h"
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#define PERIOD 1
#define TOLERANCE 0.02
#ifndef PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION
#define PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION 0x4
#endif
namespace timeutils {
bool TIMER_HACKS_DISABLE = false;
static TimerHandle get_precise_sleep_timer();
static void destroy_precise_sleep_timer(TimerHandle timer);
static void precise_sleep(TimerHandle timer, double seconds);
void set_timer_resolution() {
if (TIMER_HACKS_DISABLE) {
return;
}
#if !SPICE_XP
// make a call to opt out of power throttling
// (requested timer resolution being ignored when window is occluded or minimized)
// SetProcessInformation is win8+
const auto kernel32 = GetModuleHandleA("kernel32.dll");
if (kernel32) {
const auto SetProcessInformation_addr =
reinterpret_cast<decltype(SetProcessInformation) *>(
GetProcAddress(kernel32, "SetProcessInformation"));
if (SetProcessInformation_addr) {
PROCESS_POWER_THROTTLING_STATE state {};
state.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
state.ControlMask = PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION;
state.StateMask = 0;
const auto ret = SetProcessInformation_addr(
GetCurrentProcess(),
ProcessPowerThrottling,
&state,
sizeof(state));
log_info(
"timeutils",
"SetProcessInformation called to disable timer resolution throttling, returned {}",
ret);
}
}
#endif
const auto ret = timeBeginPeriod(PERIOD);
log_info(
"timeutils",
"timeBeginPeriod({}) called, returned {}",
PERIOD,
ret);
// and then we never call timeEndPeriod();
// the game will also call this but the OS will honor the lowest value (1 above)
}
#if !SPICE_XP
// timerSleep from https://blog.bearcats.nl/perfect-sleep-function/
static void timerSleep(HANDLE timer, double seconds) {
using namespace std::chrono;
auto t = high_resolution_clock::now();
const auto target = t + nanoseconds(int64_t(seconds * 1e9));
const int64_t maxTicks = PERIOD * 9'500;
for (;;) {
const int64_t remaining = (target - t).count();
int64_t ticks = (remaining - TOLERANCE) / 100;
if (ticks <= 0) {
break;
}
if (ticks > maxTicks) {
ticks = maxTicks;
}
LARGE_INTEGER due;
due.QuadPart = -ticks;
SetWaitableTimerEx(timer, &due, 0, NULL, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
t = high_resolution_clock::now();
}
while (high_resolution_clock::now() < target) {
YieldProcessor();
}
}
#endif
static TimerHandle get_precise_sleep_timer() {
TimerHandle timer = nullptr;
if (TIMER_HACKS_DISABLE) {
return timer;
}
// CreateWaitableTimerExW is Vista+
// CREATE_WAITABLE_TIMER_HIGH_RESOLUTION win10 1803+
#if !SPICE_XP
timer = CreateWaitableTimerExW(
NULL,
NULL,
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
TIMER_ALL_ACCESS);
#endif
return timer;
}
static void destroy_precise_sleep_timer(TimerHandle timer) {
if (timer) {
CloseHandle(timer);
}
}
static void precise_sleep(TimerHandle timer, double seconds) {
if (!std::isfinite(seconds) || seconds <= 0.0) {
return;
}
#if !SPICE_XP
if (timer) {
timerSleep(timer, seconds);
return;
}
#endif
// robustSleep is too CPU heavy so we will stick to Sleep() with
// timeBeginPeriod, which has an error at most 1ms
const auto milliseconds = std::ceil(seconds * 1000.0);
if (milliseconds >= std::numeric_limits<DWORD>::max()) {
Sleep(std::numeric_limits<DWORD>::max());
return;
}
Sleep(static_cast<DWORD>(milliseconds));
}
// RAII wrapper
PreciseSleepTimer::PreciseSleepTimer() : timer(get_precise_sleep_timer()) {}
PreciseSleepTimer::~PreciseSleepTimer() {
destroy_precise_sleep_timer(timer);
}
void PreciseSleepTimer::sleep(uint32_t ms) const {
sleep(std::chrono::milliseconds(ms));
}
void PreciseSleepTimer::sleep_seconds(double seconds) const {
precise_sleep(timer, seconds);
}
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <chrono>
#include <cstdint>
namespace timeutils {
extern bool TIMER_HACKS_DISABLE;
void set_timer_resolution();
using TimerHandle = void *;
class PreciseSleepTimer {
public:
PreciseSleepTimer();
~PreciseSleepTimer();
PreciseSleepTimer(const PreciseSleepTimer &) = delete;
PreciseSleepTimer &operator=(const PreciseSleepTimer &) = delete;
PreciseSleepTimer(PreciseSleepTimer &&) = delete;
PreciseSleepTimer &operator=(PreciseSleepTimer &&) = delete;
void sleep(uint32_t ms) const;
template <typename Rep, typename Period>
void sleep(std::chrono::duration<Rep, Period> duration) const {
sleep_seconds(std::chrono::duration<double>(duration).count());
}
private:
void sleep_seconds(double seconds) const;
TimerHandle timer;
};
}
+3 -3
View File
@@ -275,7 +275,7 @@ intptr_t replace_pattern(HMODULE module, const std::string &signature,
bool get_pe_identifier(const std::filesystem::path& dll_path, uint32_t* time_date_stamp, uint32_t* address_of_entry_point) {
std::ifstream file(dll_path, std::ios::binary);
if (!file) {
log_warning("sigscan", "Failed to open file: {}", dll_path.string().c_str());
log_warning("sigscan", "Failed to open file: {}", dll_path);
return false;
}
@@ -283,7 +283,7 @@ bool get_pe_identifier(const std::filesystem::path& dll_path, uint32_t* time_dat
IMAGE_DOS_HEADER dos_header;
file.read(reinterpret_cast<char*>(&dos_header), sizeof(dos_header));
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE) {
log_warning("sigscan", "Invalid DOS signature: {}", dll_path.string().c_str());
log_warning("sigscan", "Invalid DOS signature: {}", dll_path);
return false;
}
@@ -294,7 +294,7 @@ bool get_pe_identifier(const std::filesystem::path& dll_path, uint32_t* time_dat
IMAGE_NT_HEADERS nt_headers;
file.read(reinterpret_cast<char*>(&nt_headers), sizeof(nt_headers));
if (nt_headers.Signature != IMAGE_NT_SIGNATURE) {
log_warning("sigscan", "Invalid NT signature: {}", dll_path.string().c_str());
log_warning("sigscan", "Invalid NT signature: {}", dll_path);
return false;
}
+4 -4
View File
@@ -319,14 +319,14 @@ bool acquire_shutdown_privs();
void generate_ea_card(char card[17]);
static inline int get_async_primary_mouse() {
static inline bool get_async_primary_mouse() {
int vk = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON;
return GetAsyncKeyState(vk);
return (GetAsyncKeyState(vk) & 0x8000) != 0;
}
static inline int get_async_secondary_mouse() {
static inline bool get_async_secondary_mouse() {
int vk = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON;
return GetAsyncKeyState(vk);
return (GetAsyncKeyState(vk) & 0x8000) != 0;
}
static inline bool parse_width_height(const std::string wh, std::pair<uint32_t, uint32_t> &result) {