Compare commits

...
19 Commits
Author SHA1 Message Date
WillandClaude Opus 5.5 c371a45b91 options: store Hex values passed on the command line (#944)
Ye olde classic case of "review this code" and the robot saying "this is
also broken".

Only two hex options and both kinda rare so makes sense they've not been
seen as a bug before. Looks like it's been there some time.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:44:48 -08:00
bicarus-devandCopilot 69585ac43d clean up screen resize
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-12-05 19:49:06 -08:00
Elthiee 3d530bfee0 feat: add per player battle/DP zoom (#943)
## Link to GitHub Issue or related Pull Request, if one exists
[#0](https://github.com/spice2x/spice2x.github.io/issues/402)

## Description of change
*what does this code do?*
Simply modifing existing zoom feature with split zoom funcionality.

## Testing
*how was the code tested?*
There were no desyncs while I was playing with a friend of mine on my
setup (3700x, rtx 3060 12gb), performance was no different to regular
zoom.
2026-12-05 18:19:01 -08:00
bicarus af66dd5b50 misc: various boot optimizations (#942)
## Link to GitHub Issue or related Pull Request, if one exists
Various fixes copied from https://github.com/l4kr/spicefast

## Description of change
* make local Windows event logs appear empty to game DLLs, avoiding
startup scans without modifying system logs or remote reads.
* when -nvprofile is on, skip writes and profile saves when settings
already match
* defer SetupAPI device name lookups during HID enumeration until it's
absolutely needed
* remove the fixed 100 ms delay after AVS boot

## Testing
2026-12-05 03:37:32 -08:00
Will 1e0de890bc Clang: use the same optimisation/stripping as gcc (#940)
Some gcc flags were only applied to gcc, but a lot of em really belong
on clang too.
It's the reason xp builds were 11 meg compared to gcc's 4. This brings
them down to ~6 (mainly due to stripping).

Clang complained that `-s` was a link-only flag so that's been changed
too.
2026-11-29 18:11:24 -08:00
bicarus ae433ccb1d iidx: movie decoder workaround for dxvk (#939)
## Link to GitHub Issue or related Pull Request, if one exists
https://github.com/eamuse/sp2xpatcher/pull/12

## Description of change
Subsumes https://github.com/eamuse/sp2xpatcher/pull/12 into a hook-based
fix that is automatically applied when Vulcan is detected.

## Testing
2026-11-28 20:21:33 -08:00
bicarus 57c083e7ad audio: workaround audio buffer issue in wine (#937)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #931

## Description of change
Implement workaround for audio bug in Wine which caused loud static with
`-wasapishared` due to the way wine maps 24-bit PCM into 32-bit
container when handing off to PulseAudio.

## Testing
tbd
2026-11-28 18:41:41 -08:00
Will e2fd48953e update XP LLVM to 23.1.5, DLL compatibility checker to 1.6 (#938)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Typical toolchain churn, but also fixes an issue with Win7 compat
checking where API set DLLs weren't mapped right

## Testing
Builds
2026-11-27 22:55:21 -08:00
bicarus a4850165bb net: improve TLS handshake (#936)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #928

## Description of change
Before: hardcoded 100ms timeout on TLS reply, if timed out, drop the
handshake

After: wait for reply, process right away. Use default (10s) socket
receive timeout as fallback.

## Testing
Tested EA on a server that supports SSL.
2026-11-27 20:08:56 -08:00
bicarus ae7d169b3f cfg: trim surrounding whitespace in options tab (#935)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
Remove leading and trailing whitespace for some commonly used options
(EA server URL, pcbid, etc) to prevent users copy-pasting wrong text.

## Testing
cfg only
2026-11-26 02:17:52 -08:00
bicarus-dev ce87d20f25 sdvx: cache result from K32GetPerformanceInfo to avoid performance issues on some PCs 2026-11-19 23:35:28 -08:00
鲸流 3e3db7a411 bc: add light support and unity player arguments injection (#932)
## Link to GitHub Issue or related Pull Request, if one exists
#0

## Description of change

_Just imitation of the existing implementations of CCJ, MFG or QKS._

- Add BI2X hook and lighting support.
- Align Unity launch argument handling and cursor visibility with other
Unity games in spice2x using `unity_utils::force_show_cursor` and
`unity_utils::set_args`.
- Add `-bcargs` command-line option to pass custom arguments directly to
the Unity player.
- Upgrade I/O initialization to `devicehook_init_trampoline()` and
ensure the raw log directory is created recursively.

## Testing
- Verified build on GitHub Actions with no compiler warnings.
- Tested with the CI compiled executable.
   - HID lighting worked fine on aic_pico and iidx_pico.
- Display arguments such as `-w`, `-windowborder` and `-windowsize` are
correctly passed.
_(However, once the game launches, it reinitializes the window and
switches to fullscreen before the checking phase begins. To maintain
these arguments, an additional hook is required. I resolved this issue
using a BepInEx plugin.)_
2026-10-31 15:02:12 -07:00
bicarus 37f947b57f increase default heap size for nabla 2026-10-29 21:00:51 -07:00
bicarus 63bfef7c69 fix sdvx windowed mode mouse emulation double register 2026-10-29 20:05:26 -07:00
bicarus c83496776e cc: option for artificially delaying printer (#925)
## Link to GitHub Issue or related Pull Request, if one exists
#0

## Description of change
Add an option to artificially delay the printing process (70 seconds or
so, more for holo cards) so that the minigame is triggered on the
screen.

## Testing
2026-10-12 10:25:34 -07:00
bicarusandCopilot fdc7adff7f add card connect support (#923)
There are no servers to test this, but:

* touch, touch with mouse
* in theory card reader should work
* printer works (RGB, front and back)
* test/service button, lights

What is (painfully) missing:
* windowed mode

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-11 01:04:14 -07:00
bicarus cf5d87d4d5 Update bug report template description 2026-10-07 20:13:47 -07:00
bicarus 175245333d Fix formatting in bug report issue template 2026-10-07 20:12:45 -07:00
bicarus 9c8f7f551d Update bug_report.md 2026-10-07 20:12:25 -07:00
52 changed files with 2627 additions and 362 deletions

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
---
name: Bug report
about: Create a report to help us improve
name: Bug report (NOT for troubleshooting or asking for help)
about: 'File a bug in spice2x'
title: ''
labels: bug
assignees: ''
+1
View File
@@ -6,6 +6,7 @@
*.iws
# CMake
/build/
cmake-build*
# user config
+15 -6
View File
@@ -141,6 +141,12 @@ else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-local-typedefs") # for our logging system
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-attributes") # fmtlib workaround
# static linking
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -static -static-libgcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static -static-libgcc -static-libstdc++")
endif()
if(NOT MSVC)
# release flags
if(CMAKE_BUILD_TYPE MATCHES "Release")
@@ -160,8 +166,8 @@ else()
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden -fvisibility-inlines-hidden")
# remove symbol table and relocation information
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -s")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -s")
set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -s")
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -s")
# performance
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O2 -pipe")
@@ -223,10 +229,6 @@ else()
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Og -pipe")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Og -pipe")
endif()
# static linking
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -static -static-libgcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static -static-libgcc -static-libstdc++")
endif()
# default defines
@@ -453,6 +455,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
games/hpm/hpm.cpp
games/hpm/io.cpp
games/iidx/iidx.cpp
games/iidx/dxva2.cpp
games/iidx/io.cpp
games/iidx/poke.cpp
games/iidx/bi2a.cpp
@@ -541,6 +544,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
games/onpara/touchpanel.cpp
games/bc/bc.cpp
games/bc/io.cpp
games/bc/bi2x_hook.cpp
games/ccj/ccj.cpp
games/ccj/io.cpp
games/ccj/bi2x_hook.cpp
@@ -557,6 +561,10 @@ set(SOURCE_FILES ${SOURCE_FILES}
games/udn/udn.cpp
games/udn/io.cpp
games/udn/bi2x_hook.cpp
games/cardconnect/cardconnect.cpp
games/cardconnect/io.cpp
games/cardconnect/bi2x_hook.cpp
games/cardconnect/printer.cpp
# hooks
hooks/audio/acm.cpp
@@ -591,6 +599,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
hooks/cfgmgr32hook.cpp
hooks/debughook.cpp
hooks/devicehook.cpp
hooks/eventlog.cpp
hooks/graphics/graphics.cpp
hooks/graphics/graphics_windowed.cpp
hooks/graphics/jpeg_encoder.cpp
+2 -5
View File
@@ -46,17 +46,14 @@ MessageData *ACIODeviceEmu::create_msg(uint8_t addr, uint16_t code, uint8_t pid,
}
// allocate data
auto data_raw = new uint8_t[MSG_HEADER_SIZE + data_size];
auto msg = new MessageData {};
// set header
auto msg = (MessageData *) &data_raw[0];
set_header(msg, addr, code, pid, (uint8_t) data_size);
// set data
if (data) {
memcpy(data_raw + MSG_HEADER_SIZE, data, data_size);
} else {
memset(data_raw + MSG_HEADER_SIZE, 0, data_size);
memcpy(msg->cmd.raw, data, data_size);
}
// return prepared message
+8 -1
View File
@@ -14,15 +14,20 @@ bool acioemu::ACIOHandle::open(LPCWSTR lpFileName) {
return false;
}
std::lock_guard<std::mutex> lock(mutex);
log_info("acioemu", "Opened {} (ACIO)", ws2s(com_port));
// ACIO device
acio_emu.add_device(new acioemu::ICCADevice(false, true, icca_node_count));
if (!initialized) {
acio_emu.add_device(new acioemu::ICCADevice(false, true, icca_node_count));
initialized = true;
}
return true;
}
int acioemu::ACIOHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
std::lock_guard<std::mutex> lock(mutex);
auto buffer = reinterpret_cast<uint8_t *>(lpBuffer);
// read from emu
@@ -42,6 +47,7 @@ int acioemu::ACIOHandle::read(LPVOID lpBuffer, DWORD nNumberOfBytesToRead) {
}
int acioemu::ACIOHandle::write(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite) {
std::lock_guard<std::mutex> lock(mutex);
auto buffer = reinterpret_cast<const uint8_t *>(lpBuffer);
// write to emu
@@ -64,6 +70,7 @@ int acioemu::ACIOHandle::device_io(
}
size_t acioemu::ACIOHandle::bytes_available() {
std::lock_guard<std::mutex> lock(mutex);
return acio_emu.bytes_available();
}
+4
View File
@@ -1,5 +1,7 @@
#pragma once
#include <mutex>
#include "acioemu/acioemu.h"
#include "hooks/devicehook.h"
@@ -12,6 +14,8 @@ namespace acioemu {
uint8_t icca_node_count;
acioemu::ACIOEmu acio_emu;
std::mutex mutex;
bool initialized = false;
public:
ACIOHandle(LPCWSTR lpCOMPort, uint8_t iccaNodeCount = 2);
+15 -9
View File
@@ -46,9 +46,9 @@ 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]() {
this->keypad_thread = std::jthread([this](std::stop_token stop_token) {
timeutils::PreciseSleepTimer timer;
while (this->cards) {
while (!stop_token.stop_requested()) {
for (int unit = 0; unit < this->node_count; unit++) {
this->update_keypad(unit, false);
}
@@ -61,11 +61,15 @@ ICCADevice::ICCADevice(bool flip_order, bool keypad_thread, uint8_t node_count)
ICCADevice::~ICCADevice() {
// stop thread
delete keypad_thread;
if (keypad_thread.joinable()) {
keypad_thread.request_stop();
keypad_thread.join();
}
// delete cards in array
for (int i = 0; i < node_count; i++) {
delete cards[i];
delete[] cards[i];
delete[] keypad_last[i];
}
// delete the rest
@@ -107,7 +111,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
if (avs::game::is_model({"LDJ", "TBS", "UJK", "XIF"}) ||
games::sdvx::is_valkyrie_model()) {
this->set_version(msg, 0x3, 0, 1, 7, 0, "ICCA");
} else if (avs::game::is_model("VFG")) {
} else if (avs::game::is_model({"VFG", "TCS"})) {
this->set_version(msg, 0x3, 0, 1, 7, 0, "ICCB");
} else {
this->set_version(msg, 0x3, 0, 1, 6, 0, "ICCA");
@@ -160,7 +164,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
break;
case 0x12: // EJECT
if (this->cards[unit] != nullptr) {
delete this->cards[unit];
delete[] this->cards[unit];
}
this->cards[unit] = nullptr;
this->hold[unit] = false;
@@ -267,7 +271,7 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
memcpy(msg->cmd.raw, this->cards[unit], 8);
// delete card
delete this->cards[unit];
delete[] this->cards[unit];
this->cards[unit] = nullptr;
this->hold[unit] = false;
}
@@ -326,7 +330,9 @@ bool ICCADevice::parse_msg(MessageData *msg_in,
}
//log_info("icca", "counter[{}] = {}", unit, this->counter[unit]);
auto msg = this->create_msg_status(msg_in, this->counter[unit]);
// Card Connect waits for a successful reply without retrying this command.
auto msg = this->create_msg_status(
msg_in, avs::game::is_model("TCS") ? 0 : this->counter[unit]);
write_msg(msg, response_buffer);
delete msg;
break;
@@ -363,7 +369,7 @@ void ICCADevice::update_card(int unit) {
if (difftime(t_now, this->cards_time[unit]) >= 10.f) {
if (this->cards[unit] != nullptr) {
delete this->cards[unit];
delete[] this->cards[unit];
}
this->cards[unit] = nullptr;
this->hold[unit] = false;
+1 -1
View File
@@ -17,7 +17,7 @@ namespace acioemu {
private:
bool type_new;
bool flip_order;
std::thread *keypad_thread;
std::jthread keypad_thread;
std::mutex keypad_mutex;
uint8_t **cards;
time_t *cards_time;
+2
View File
@@ -2,6 +2,8 @@
#include "external/rapidjson/document.h"
#include "cfg/screen_resize.h"
#include <vector>
using namespace std::placeholders;
using namespace rapidjson;
+15 -3
View File
@@ -1,11 +1,14 @@
#include "core.h"
#include <climits>
#include <cstring>
#include <mutex>
#include <optional>
#include <vector>
#include <stdint.h>
#include "avs/game.h"
#include "external/robin_hood.h"
#include "games/popn/popn.h"
#include "launcher/logger.h"
@@ -1181,6 +1184,18 @@ namespace avs {
return;
}
#ifdef SPICE64
// nabla increased heap size a few months into service (June 2026?)
if (dll_name == "soundvoltex.dll" &&
avs::game::is_ext(2025121501, INT_MAX)) {
auto old_size = HEAP_SIZE;
HEAP_SIZE = 0x18000000;
DEFAULT_HEAP_SIZE_SET = true;
log_info("avs-core", "updated heap size: {} -> {} (nabla)", old_size, avs::core::HEAP_SIZE);
return;
}
#endif
// hack, both hello! popn and popn hc using popn.dll
if (games::popn::is_pikapika_model()) {
auto old_size = HEAP_SIZE;
@@ -2101,9 +2116,6 @@ namespace avs {
log_fatal("avs-core", "unknown AVS boot procedure");
}
// wait a bit for output
Sleep(100);
// destroy config
config_destroy(config);
}
+59 -94
View File
@@ -1,5 +1,8 @@
#define SECURITY_WIN32
#include <algorithm>
#include <chrono>
#include <climits>
#include <cstring>
#include <iostream>
#include <vector>
@@ -91,6 +94,7 @@ namespace avs {
};
static constexpr size_t alignment = 16;
using handshake_clock = std::chrono::steady_clock;
static int io_buf_init(struct io_buf *buf, size_t initial_capacity) {
uint8_t *tmp_bytes = nullptr;
@@ -261,89 +265,35 @@ arg_fail:
return 0;
}
static int impl_socket_recv_all(
static int tls_recv_handshake(
struct avs_net_sock_desc_work *work,
struct io_buf *buf,
uint32_t recv_timeout)
handshake_clock::time_point deadline)
{
uint8_t old_non_blocking_value = 0;
uint8_t non_blocking = 0;
avs_net_size_t old_non_blocking_value_size = 0;
struct avs_net_poll_fd poll_fds[1] {};
int ret = 0;
if (work == nullptr || work->sock_fd < 0) {
return -1;
}
auto err = io_buf_validate(buf);
if (err != 0) {
return -1;
}
if (buf->pos == buf->limit) {
return -1;
}
poll_fds[0].socket = work->sock_fd;
poll_fds[0].events = AVS_NET_POLL_POLLIN;
non_blocking = 1;
old_non_blocking_value_size = sizeof(old_non_blocking_value);
core::avs_net_getsockopt(work->sock_fd, AVS_SO_NONBLOCK, &old_non_blocking_value, &old_non_blocking_value_size);
core::avs_net_setsockopt(work->sock_fd, AVS_SO_NONBLOCK, &non_blocking, sizeof(non_blocking));
while (true) {
auto result = core::avs_net_poll(poll_fds, std::size(poll_fds), recv_timeout);
const auto now = handshake_clock::now();
if (now < deadline) {
const auto remaining = std::chrono::ceil<std::chrono::milliseconds>(deadline - now);
avs_net_poll_fd poll_fd {};
poll_fd.socket = work->sock_fd;
poll_fd.events = AVS_NET_POLL_POLLIN;
const auto result = core::avs_net_poll(&poll_fd, 1,
static_cast<int>(remaining.count()));
if (result < 0) {
log_warning("avs::ssl", "avs_net_poll failed: 0x{:08x}", result);
ret = -1;
goto out;
log_warning("avs::ssl", "avs_net_poll failed during TLS handshake: 0x{:08x}", result);
return result;
}
if (!result) {
#if 0
log_warning("avs::ssl", "socket timeout, no data received after {} milliseconds", recv_timeout);
#endif
goto poll_succeeded_or_empty;
}
if (poll_fds[0].r_events & AVS_NET_POLL_POLLIN) {
result = core::avs_net_recv(work->sock_fd, &buf->bytes[buf->pos], buf->limit - buf->pos);
if (result < 0) {
break;
if (result > 0) {
if (poll_fd.r_events & AVS_NET_POLL_POLLIN) {
return impl_socket_recv(work, &work->recv_buf);
}
if (result == 0) {
log_misc("avs::ssl", "connection closed");
ret = -1;
goto out;
}
#if 0
log_warning("avs::ssl", "socket({}) got {} bytes during handshake", work->sock_fd, result);
#endif
buf->pos += result;
log_warning("avs::ssl", "unexpected TLS handshake poll events: 0x{:04x}",
poll_fd.r_events);
return core::avs_error_make(AVS_ERROR_CLASS_NET, AVS_ERROR_SUBCLASS_SC_BADMSG);
}
}
poll_succeeded_or_empty:
ret = 0;
out:
core::avs_net_setsockopt(work->sock_fd, AVS_SO_NONBLOCK, &old_non_blocking_value, sizeof(old_non_blocking_value));
return ret;
log_warning("avs::ssl", "timed out waiting for TLS handshake data");
return core::avs_error_make(AVS_ERROR_CLASS_NET, AVS_ERROR_SUBCLASS_NET_TIMEOUT);
}
static int impl_socket_send(struct avs_net_sock_desc_work *work, struct io_buf *buf) {
@@ -897,6 +847,7 @@ out:
uint32_t address,
avs_net_port_t port)
{
constexpr uint32_t default_handshake_timeout_ms = 10000;
constexpr uint32_t security_context_flags = ISC_REQ_CONFIDENTIALITY |
ISC_REQ_INTEGRITY |
ISC_REQ_STREAM |
@@ -912,6 +863,7 @@ out:
SECURITY_STATUS status = SEC_E_OK;
int result = 0;
int err = 0;
handshake_clock::time_point handshake_deadline;
char hostname[256];
@@ -987,6 +939,11 @@ out:
goto first_isc_fail;
}
// share one receive budget across all TLS flights and partial reads
handshake_deadline = handshake_clock::now() + std::chrono::milliseconds(work->recv_timeout
? std::min<uint32_t>(work->recv_timeout, INT_MAX)
: default_handshake_timeout_ms);
while (status != SEC_E_OK) {
switch (status) {
case SEC_I_CONTINUE_NEEDED:
@@ -1002,33 +959,26 @@ out:
}
}
work->recv_buf.pos = 0;
work->recv_buf.limit = work->recv_buf.capacity;
err = impl_socket_recv_all(work, &work->recv_buf, 100);
if (err != 0) {
goto loop_fail;
if (work->recv_buf.pos == 0) {
err = tls_recv_handshake(work, handshake_deadline);
if (err != 0) {
goto loop_fail;
}
}
break;
case SEC_E_INCOMPLETE_MESSAGE:
if (recv_bufs[1].BufferType != SECBUFFER_MISSING) {
err = core::avs_error_make(AVS_ERROR_CLASS_NET, AVS_ERROR_SUBCLASS_SC_BADMSG);
goto loop_fail;
if (work->recv_buf.pos == work->recv_buf.capacity) {
err = io_buf_grow(&work->recv_buf);
if (err != 0) {
log_warning("avs::ssl", "failed to grow TLS handshake receive buffer");
goto loop_fail;
}
work->recv_buf.limit = work->recv_buf.capacity;
}
err = io_buf_grow_to(&work->recv_buf, work->recv_buf.pos + recv_bufs[1].cbBuffer);
if (err != 0) {
goto loop_fail;
}
work->recv_buf.limit = work->recv_buf.capacity;
err = impl_socket_recv(work, &work->recv_buf);
err = tls_recv_handshake(work, handshake_deadline);
if (err != 0) {
goto loop_fail;
@@ -1093,6 +1043,21 @@ out:
&send_vec,
&attributes,
nullptr);
if (status == SEC_I_CONTINUE_NEEDED || status == SEC_E_OK) {
const auto extra = recv_bufs[1].BufferType == SECBUFFER_EXTRA
? recv_bufs[1].cbBuffer : 0;
if (extra > 0) {
const auto tail = work->recv_buf.bytes + (work->recv_buf.pos - extra);
if (status == SEC_E_OK) {
work->recv_ciphertext_tail = tail;
work->recv_ciphertext_count = extra;
} else {
memmove(work->recv_buf.bytes, tail, extra);
}
}
work->recv_buf.pos = extra;
}
}
log_misc("avs::ssl", "TLS handshake complete");
+2
View File
@@ -48,6 +48,8 @@ struct OptionDefinition {
std::string file_extension = "";
std::string quick_setting_category = "";
bool trim_whitespace = false;
};
class Option {
+75 -1
View File
@@ -1,5 +1,7 @@
#include "screen_resize.h"
#include <algorithm>
#include <cmath>
#include "avs/game.h"
#include "external/rapidjson/document.h"
#include "external/rapidjson/pointer.h"
@@ -97,7 +99,10 @@ namespace cfg {
int duplicate = 0;
load_int_value(doc, root + prefix + "duplicate", duplicate);
scene.duplicate = static_cast<cfg::ScreenDuplicateMode>(duplicate);
load_split_config(doc, root + prefix, scene.split);
}
this->need_surface_clean = true;
// windowed settings are always under game settings
root = "/sp2x_games/" + eamuse_get_game() + "/";
@@ -179,6 +184,70 @@ namespace cfg {
return false;
}
static void load_split_scale(
const rapidjson::Document &doc, const std::string &path, float &scale) {
const auto value = rapidjson::Pointer(path).Get(doc);
if (!value) {
return;
}
if (value->IsNumber()) {
const double number = value->GetDouble();
if (std::isfinite(number) && number >= split_region_setting::min_scale &&
number <= split_region_setting::max_scale) {
scale = static_cast<float>(number);
return;
}
}
log_warning("ScreenResize", "{} must be a number from {} to {}; using default",
path, split_region_setting::min_scale, split_region_setting::max_scale);
scale = split_region_setting::default_scale;
}
void ScreenResize::load_split_region(
rapidjson::Document &doc, const std::string &path, split_region_setting &region) {
load_int_value(doc, path + "offset_x", region.offset_x);
load_int_value(doc, path + "offset_y", region.offset_y);
load_split_scale(doc, path + "scale_x", region.scale_x);
load_split_scale(doc, path + "scale_y", region.scale_y);
load_bool_value(doc, path + "keep_aspect_ratio", region.keep_aspect_ratio);
}
void ScreenResize::load_split_config(
rapidjson::Document &doc, const std::string &path, split_screen_setting &split) {
load_bool_value(doc, path + "split_mode", split.enabled);
const auto ratio = rapidjson::Pointer(path + "split_ratio").Get(doc);
if (ratio) {
if (ratio->IsNumber() && std::isfinite(ratio->GetDouble())) {
split.ratio = static_cast<float>(std::clamp(
ratio->GetDouble(), split_screen_setting::min_ratio,
split_screen_setting::max_ratio));
} else {
log_warning("ScreenResize", "{}split_ratio must be a finite number", path);
}
}
load_bool_value(doc, path + "split_swap_sides", split.swap_sides);
load_split_region(doc, path + "split_left/", split.left);
load_split_region(doc, path + "split_right/", split.right);
}
static void save_split_region(
rapidjson::Document &doc, const std::string &path, const split_region_setting &region) {
rapidjson::Pointer(path + "offset_x").Set(doc, region.offset_x);
rapidjson::Pointer(path + "offset_y").Set(doc, region.offset_y);
rapidjson::Pointer(path + "scale_x").Set(doc, region.scale_x);
rapidjson::Pointer(path + "scale_y").Set(doc, region.scale_y);
rapidjson::Pointer(path + "keep_aspect_ratio").Set(doc, region.keep_aspect_ratio);
}
static void save_split_config(
rapidjson::Document &doc, const std::string &path, const split_screen_setting &split) {
rapidjson::Pointer(path + "split_mode").Set(doc, split.enabled);
rapidjson::Pointer(path + "split_ratio").Set(doc, split.ratio);
rapidjson::Pointer(path + "split_swap_sides").Set(doc, split.swap_sides);
save_split_region(doc, path + "split_left/", split.left);
save_split_region(doc, path + "split_right/", split.right);
}
void ScreenResize::config_save() {
rapidjson::Document doc;
std::string config = fileutils::text_read(this->config_path);
@@ -212,6 +281,8 @@ namespace cfg {
rapidjson::Pointer(root + prefix + "scale_y").Set(doc, scene.scale_y);
rapidjson::Pointer(root + prefix + "keep_aspect_ratio").Set(doc, scene.keep_aspect_ratio);
rapidjson::Pointer(root + prefix + "duplicate").Set(doc, scene.duplicate);
save_split_config(doc, root + prefix, scene.split);
}
// windowed mode settings
@@ -227,7 +298,10 @@ namespace cfg {
// build JSON
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
if (!doc.Accept(writer)) {
log_warning("ScreenResize", "unable to serialize config; existing file left unchanged");
return;
}
// save to file
if (fileutils::write_config_file("ScreenResize", this->config_path, buffer.GetString())) {
+29
View File
@@ -21,6 +21,29 @@ namespace cfg {
CopyRight = 2,
};
struct split_region_setting {
static constexpr double min_scale = 0.6;
static constexpr double max_scale = 3.0;
static constexpr float default_scale = 1.0f;
int offset_x = 0;
int offset_y = 0;
float scale_x = default_scale;
float scale_y = default_scale;
bool keep_aspect_ratio = true;
};
struct split_screen_setting {
static constexpr double min_ratio = 0.1;
static constexpr double max_ratio = 0.9;
bool enabled = false;
float ratio = 0.5f;
bool swap_sides = false;
split_region_setting left;
split_region_setting right;
};
struct fullscreen_setting {
int offset_x = 0;
int offset_y = 0;
@@ -28,6 +51,8 @@ namespace cfg {
float scale_y = 1.0;
bool keep_aspect_ratio = true;
ScreenDuplicateMode duplicate = ScreenDuplicateMode::None;
split_screen_setting split;
};
extern std::optional<std::string> SCREEN_RESIZE_CFG_PATH_OVERRIDE;
@@ -41,6 +66,10 @@ namespace cfg {
bool load_int_value(rapidjson::Document& doc, std::string path, int& value);
bool load_uint32_value(rapidjson::Document& doc, std::string path, uint32_t& value);
bool load_float_value(rapidjson::Document& doc, std::string path, float& value);
void load_split_config(
rapidjson::Document &doc, const std::string &path, split_screen_setting &split);
void load_split_region(
rapidjson::Document &doc, const std::string &path, split_region_setting &region);
public:
ScreenResize();
+2 -2
View File
@@ -18,11 +18,11 @@ RUN useradd user -m && echo "ALL ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
RUN su user -c "cd /tmp/ && git clone https://aur.archlinux.org/yay-bin.git --depth=1 && cd yay-bin && makepkg --noconfirm -si && yay --noconfirm -S mingw-w64-cmake"
RUN mkdir -p /opt/llvm-mingw-xp \
&& curl -fsSL "https://github.com/mon/llvm-mingw-xp/releases/download/llvm-mingw-xp-22.1.0/llvm-mingw-llvm-mingw-xp-22.1.0-msvcrt-ubuntu-22.04-x86_64.tar.xz" \
&& curl -fsSL "https://github.com/mon/llvm-mingw-xp/releases/download/llvm-mingw-xp-23.1.5/llvm-mingw-xp-23.1.5-msvcrt-ubuntu-22.04-x86_64.tar.xz" \
| tar -xJ --strip-components=1 -C /opt/llvm-mingw-xp
ENV PATH="$PATH:/opt/llvm-mingw-xp/bin"
RUN curl -fsSL "https://github.com/mon/windows-dll-compat-checker/releases/download/v1.3/windows_dll_compat_checker-linux-x86_64.tar.xz" \
RUN curl -fsSL "https://github.com/mon/windows-dll-compat-checker/releases/download/v1.6/windows_dll_compat_checker-linux-x86_64.tar.xz" \
| tar -xJ -C /usr/local/bin
# Stock makepkg.conf builds serially; this makes the AUR compiles below parallel.
+27 -13
View File
@@ -1,25 +1,30 @@
#include "bc.h"
#include <format>
#include "hooks/setupapihook.h"
#include "util/fileutils.h"
#include "util/libutils.h"
#include "acio2emu/handle.h"
#include "acioemu/handle.h"
#include "hooks/graphics/graphics.h"
#include "util/detour.h"
#include "util/unity_player.h"
#include "node.h"
#include "bi2x_hook.h"
namespace games::bc {
static decltype(ShowCursor) *ShowCursor_orig = nullptr;
static int WINAPI ShowCursor_hook(BOOL bShow) {
// log_misc("bsac", "ShowCursor {}", bShow);
return 1;
}
std::string BC_INJECT_ARGS = "";
void BCGame::attach() {
Game::attach();
// create required directories
fileutils::dir_create_recursive("dev/raw/log");
// preload libraries
libutils::load_library("libaio.dll");
libutils::load_library("libaio-iob2_video.dll");
setupapihook_init(libutils::load_library("libaio.dll"));
SETUPAPI_SETTINGS settings {};
@@ -32,15 +37,24 @@ namespace games::bc {
auto iob = new acio2emu::IOBHandle(L"COM3");
iob->register_node(std::make_unique<TBSNode>());
if (GRAPHICS_SHOW_CURSOR) {
detour::trampoline_try(
"user32.dll", "ShowCursor",
(void*)ShowCursor_hook, (void**)&ShowCursor_orig);
}
#if SPICE64
// insert BI2X hooks
bi2x_hook_init();
#endif
devicehook_init();
devicehook_init_trampoline();
devicehook_add(iob);
devicehook_add(new acioemu::ACIOHandle(L"COM1"));
if (GRAPHICS_SHOW_CURSOR) {
unity_utils::force_show_cursor(true);
}
unity_utils::set_args(
std::format("{} {}{}",
GetCommandLineA(),
BC_INJECT_ARGS,
unity_utils::get_unity_player_args()));
}
void BCGame::detach() {
+3
View File
@@ -1,8 +1,11 @@
#pragma once
#include <string>
#include "games/game.h"
namespace games::bc {
extern std::string BC_INJECT_ARGS;
class BCGame : public games::Game {
public:
BCGame() : Game("Busou Shinki: Armored Princess Battle Conductor") {}
+163
View File
@@ -0,0 +1,163 @@
#include "bi2x_hook.h"
#if SPICE64
#include <cstdint>
#include <iterator>
#include "util/detour.h"
#include "util/logging.h"
#include "rawinput/rawinput.h"
#include "games/io.h"
#include "io.h"
#include "util/tapeled.h"
namespace games::bc {
struct AIO_IOB2_BI2X_TBS;
/*
* typedefs
*/
typedef void (__fastcall *aioIob2Bi2xTBS_GetDeviceStatus_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, void *o_DevStatus);
typedef void (__fastcall *aioIob2Bi2xTBS_SetButton0Lamp_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn);
typedef void (__fastcall *aioIob2Bi2xTBS_SetIrLed_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn);
typedef void (__fastcall *aioIob2Bi2xTBS_SetIccrLed_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB);
typedef void (__fastcall *aioIob2Bi2xTBS_SetStickLed_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB);
typedef void (__fastcall *aioIob2Bi2xTBS_SetTapeLedData_t)(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_TapeLed, uint8_t *i_pData);
static aioIob2Bi2xTBS_GetDeviceStatus_t aioIob2Bi2xTBS_GetDeviceStatus_orig = nullptr;
static aioIob2Bi2xTBS_SetButton0Lamp_t aioIob2Bi2xTBS_SetButton0Lamp_orig = nullptr;
static aioIob2Bi2xTBS_SetIrLed_t aioIob2Bi2xTBS_SetIrLed_orig = nullptr;
static aioIob2Bi2xTBS_SetIccrLed_t aioIob2Bi2xTBS_SetIccrLed_orig = nullptr;
static aioIob2Bi2xTBS_SetStickLed_t aioIob2Bi2xTBS_SetStickLed_orig = nullptr;
static aioIob2Bi2xTBS_SetTapeLedData_t aioIob2Bi2xTBS_SetTapeLedData_orig = nullptr;
/*
* hooks
*/
static void write_light_rgb(
Lights::bc_lights_t r, Lights::bc_lights_t g, Lights::bc_lights_t b, uint32_t color) {
auto &lights = get_lights();
GameAPI::Lights::writeLight(RI_MGR, lights.at(r), ((color >> 16) & 0xFF) / 255.f);
GameAPI::Lights::writeLight(RI_MGR, lights.at(g), ((color >> 8) & 0xFF) / 255.f);
GameAPI::Lights::writeLight(RI_MGR, lights.at(b), (color & 0xFF) / 255.f);
}
static void __fastcall aioIob2Bi2xTBS_GetDeviceStatus(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, void *o_DevStatus) {
RI_MGR->devices_flush_output();
if (aioIob2Bi2xTBS_GetDeviceStatus_orig) {
aioIob2Bi2xTBS_GetDeviceStatus_orig(i_pNodeCtl, o_DevStatus);
}
}
static void __fastcall aioIob2Bi2xTBS_SetButton0Lamp(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn) {
auto &lights = get_lights();
GameAPI::Lights::writeLight(RI_MGR, lights.at(Lights::Button), (i_bOn ? 1.f : 0.f));
if (aioIob2Bi2xTBS_SetButton0Lamp_orig) {
aioIob2Bi2xTBS_SetButton0Lamp_orig(i_pNodeCtl, i_bOn);
}
}
static void __fastcall aioIob2Bi2xTBS_SetIrLed(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, bool i_bOn) {
auto &lights = get_lights();
GameAPI::Lights::writeLight(RI_MGR, lights.at(Lights::IrLed), (i_bOn ? 1.f : 0.f));
if (aioIob2Bi2xTBS_SetIrLed_orig) {
aioIob2Bi2xTBS_SetIrLed_orig(i_pNodeCtl, i_bOn);
}
}
static void __fastcall aioIob2Bi2xTBS_SetIccrLed(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB) {
write_light_rgb(Lights::CardReader_R, Lights::CardReader_G, Lights::CardReader_B, i_RGB);
if (aioIob2Bi2xTBS_SetIccrLed_orig) {
aioIob2Bi2xTBS_SetIccrLed_orig(i_pNodeCtl, i_RGB);
}
}
static void __fastcall aioIob2Bi2xTBS_SetStickLed(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_RGB) {
write_light_rgb(Lights::Joystick_R, Lights::Joystick_G, Lights::Joystick_B, i_RGB);
if (aioIob2Bi2xTBS_SetStickLed_orig) {
aioIob2Bi2xTBS_SetStickLed_orig(i_pNodeCtl, i_RGB);
}
}
static void __fastcall aioIob2Bi2xTBS_SetTapeLedData(
AIO_IOB2_BI2X_TBS *i_pNodeCtl, uint32_t i_TapeLed, uint8_t *i_pData) {
static struct TapeLedMapping {
size_t data_size;
int r, g, b;
TapeLedMapping(size_t data_size, int r, int g, int b)
: data_size(data_size), r(r), g(g), b(b) {}
} mapping[] = {
{ 48, Lights::TitlePanel_R, Lights::TitlePanel_G, Lights::TitlePanel_B },
{ 49, Lights::SidePanel_R, Lights::SidePanel_G, Lights::SidePanel_B },
};
if (tapeledutils::is_enabled() && i_TapeLed < std::size(mapping)) {
auto &map = mapping[i_TapeLed];
const auto rgb = tapeledutils::pick_color_from_led_tape(i_pData, map.data_size);
auto &lights = get_lights();
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.r), rgb.r);
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.g), rgb.g);
GameAPI::Lights::writeLight(RI_MGR, lights.at(map.b), rgb.b);
}
if (aioIob2Bi2xTBS_SetTapeLedData_orig) {
aioIob2Bi2xTBS_SetTapeLedData_orig(i_pNodeCtl, i_TapeLed, i_pData);
}
}
void bi2x_hook_init() {
static bool initialized = false;
if (initialized) {
return;
} else {
initialized = true;
}
log_info("bc_bi2x_hook", "init");
const auto libaioIob2VideoDll = "libaio-iob2_video.dll";
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_GetDeviceStatus",
aioIob2Bi2xTBS_GetDeviceStatus, &aioIob2Bi2xTBS_GetDeviceStatus_orig);
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetButton0Lamp",
aioIob2Bi2xTBS_SetButton0Lamp, &aioIob2Bi2xTBS_SetButton0Lamp_orig);
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetIrLed",
aioIob2Bi2xTBS_SetIrLed, &aioIob2Bi2xTBS_SetIrLed_orig);
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetIccrLed",
aioIob2Bi2xTBS_SetIccrLed, &aioIob2Bi2xTBS_SetIccrLed_orig);
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetStickLed",
aioIob2Bi2xTBS_SetStickLed, &aioIob2Bi2xTBS_SetStickLed_orig);
detour::trampoline_try(libaioIob2VideoDll, "aioIob2Bi2xTBS_SetTapeLedData",
aioIob2Bi2xTBS_SetTapeLedData, &aioIob2Bi2xTBS_SetTapeLedData_orig);
}
}
#endif
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#if SPICE64
namespace games::bc {
void bi2x_hook_init();
}
#endif
+28
View File
@@ -48,3 +48,31 @@ std::vector<Analog> &games::bc::get_analogs() {
return analogs;
}
std::vector<Light> &games::bc::get_lights() {
static std::vector<Light> lights;
if (lights.empty()) {
lights = GameAPI::Lights::getLights("Busou Shinki: Armored Princess Battle Conductor");
GameAPI::Lights::sortLights(
&lights,
"Title Panel R",
"Title Panel G",
"Title Panel B",
"Side Panel R",
"Side Panel G",
"Side Panel B",
"Card Reader R",
"Card Reader G",
"Card Reader B",
"Joystick R",
"Joystick G",
"Joystick B",
"Button",
"IR LED"
);
}
return lights;
}
+20
View File
@@ -30,7 +30,27 @@ namespace games::bc {
};
}
namespace Lights {
typedef enum {
TitlePanel_R,
TitlePanel_G,
TitlePanel_B,
SidePanel_R,
SidePanel_G,
SidePanel_B,
CardReader_R,
CardReader_G,
CardReader_B,
Joystick_R,
Joystick_G,
Joystick_B,
Button,
IrLed,
} bc_lights_t;
}
std::vector<Button> &get_buttons();
std::string get_buttons_help();
std::vector<Analog> &get_analogs();
std::vector<Light> &get_lights();
}
+371
View File
@@ -0,0 +1,371 @@
#include "bi2x_hook.h"
#if SPICE64
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include "io.h"
#include "misc/eamuse.h"
#include "rawinput/rawinput.h"
#include "util/detour.h"
#include "util/logging.h"
#include "util/tapeled.h"
namespace games::cardconnect {
struct AIO_SCI_COMM {
uint8_t data[0xf8];
};
struct AIO_NMGR_IOB2 {
uint8_t data[0x9f8];
};
struct AIO_IOB2_BI2X_TCS {
uint8_t data[0x350];
};
struct AIO_IOB2_BI2X_WRFIRM {
uint8_t data[0x20f48];
};
#pragma pack(push, 1)
struct AIO_IOB2_BI2X_TCS__INPUT {
uint8_t DevIoCounter;
uint8_t bTest;
uint8_t bService;
uint8_t bCoinSw;
uint8_t bCoinJam;
uint8_t CoinCount;
};
struct AIO_IOB2_BI2X_TCS__DEVSTATUS {
uint8_t InputCounter;
uint8_t OutputCounter;
uint8_t TapeLedCounter;
AIO_IOB2_BI2X_TCS__INPUT Input;
uint8_t reserved[17];
};
#pragma pack(pop)
// The supplied native DLL copies 26 bytes, even though the managed wrapper requests 27.
static_assert(sizeof(AIO_IOB2_BI2X_TCS__DEVSTATUS) == 26);
static_assert(offsetof(AIO_IOB2_BI2X_TCS__DEVSTATUS, Input) == 3);
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bTest) == 1);
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bService) == 2);
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, bCoinSw) == 3);
static_assert(offsetof(AIO_IOB2_BI2X_TCS__INPUT, CoinCount) == 5);
static AIO_IOB2_BI2X_TCS *(__fastcall *aioIob2Bi2xTCS_Create_orig)(
AIO_NMGR_IOB2 *, uint32_t) = nullptr;
static uint32_t (__fastcall *aioIob2Bi2xTCS_GetDeviceStatus_orig)(
AIO_IOB2_BI2X_TCS *, AIO_IOB2_BI2X_TCS__DEVSTATUS *, uint32_t) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_IoReset_orig)(
AIO_IOB2_BI2X_TCS *, uint32_t) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_SetWatchDogTimer_orig)(
AIO_IOB2_BI2X_TCS *, uint8_t) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_ControlCoinBlocker_orig)(
AIO_IOB2_BI2X_TCS *, uint32_t, bool) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_AddCounter_orig)(
AIO_IOB2_BI2X_TCS *, uint32_t, uint32_t) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_SetPhotoLight_orig)(
AIO_IOB2_BI2X_TCS *, bool) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_SetIccrLed_orig)(
AIO_IOB2_BI2X_TCS *, uint32_t) = nullptr;
static void (__fastcall *aioIob2Bi2xTCS_SetTapeLedData_orig)(
AIO_IOB2_BI2X_TCS *, uint32_t, uint8_t *) = nullptr;
static AIO_SCI_COMM *(__fastcall *aioIob2Bi2x_OpenSciUsbCdc_orig)(uint32_t) = nullptr;
static AIO_IOB2_BI2X_WRFIRM *(__fastcall *aioIob2Bi2x_CreateWriteFirmContext_orig)(
uint32_t, uint32_t) = nullptr;
static void (__fastcall *aioIob2Bi2x_DestroyWriteFirmContext_orig)(
AIO_IOB2_BI2X_WRFIRM *) = nullptr;
static int32_t (__fastcall *aioIob2Bi2x_WriteFirmGetState_orig)(
AIO_IOB2_BI2X_WRFIRM *) = nullptr;
static AIO_NMGR_IOB2 *(__fastcall *aioNMgrIob2_Create_orig)(
AIO_SCI_COMM *, uint32_t) = nullptr;
static void (__fastcall *aioNMgrIob_BeginManage_orig)(AIO_NMGR_IOB2 *) = nullptr;
static void (__fastcall *aioNodeMgr_Destroy_orig)(AIO_NMGR_IOB2 *) = nullptr;
static int32_t (__fastcall *aioNodeMgr_GetState_orig)(AIO_NMGR_IOB2 *) = nullptr;
static bool (__fastcall *aioNodeMgr_IsReady_orig)(AIO_NMGR_IOB2 *, int32_t) = nullptr;
static void (__fastcall *aioNodeCtl_Destroy_orig)(AIO_IOB2_BI2X_TCS *) = nullptr;
static int32_t (__fastcall *aioNodeCtl_GetState_orig)(AIO_IOB2_BI2X_TCS *) = nullptr;
static bool (__fastcall *aioNodeCtl_IsReady_orig)(AIO_IOB2_BI2X_TCS *, int32_t) = nullptr;
static void (__fastcall *aioSci_Destroy_orig)(AIO_SCI_COMM *) = nullptr;
static std::unique_ptr<AIO_SCI_COMM> aio_sci;
static std::unique_ptr<AIO_NMGR_IOB2> aio_manager;
static std::unique_ptr<AIO_IOB2_BI2X_TCS> aio_board;
static std::unique_ptr<AIO_IOB2_BI2X_WRFIRM> aio_firmware;
static uint8_t input_counter = 0;
static bool coin_pressed = false;
static void write_light(size_t index, float value) {
auto &lights = get_lights();
GameAPI::Lights::writeLight(RI_MGR, lights[index], value);
}
static AIO_IOB2_BI2X_TCS *__fastcall aioIob2Bi2xTCS_Create(
AIO_NMGR_IOB2 *manager, uint32_t device_id) {
if (!aio_manager || manager != aio_manager.get()) {
return aioIob2Bi2xTCS_Create_orig(manager, device_id);
}
if (!aio_board) {
aio_board = std::make_unique<AIO_IOB2_BI2X_TCS>();
input_counter = 0;
coin_pressed = false;
log_info("cardconnect::bi2x", "created emulated BI2X-TCS board");
}
return aio_board.get();
}
static uint32_t __fastcall aioIob2Bi2xTCS_GetDeviceStatus(
AIO_IOB2_BI2X_TCS *board, AIO_IOB2_BI2X_TCS__DEVSTATUS *status,
uint32_t status_size) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_GetDeviceStatus_orig(board, status, status_size);
}
if (!status && status_size > 0) {
log_warning("cardconnect::bi2x", "GetDeviceStatus called with a null output buffer");
return 0;
}
auto &buttons = get_buttons();
const bool coin = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::CoinMech]);
if (coin && !coin_pressed) {
eamuse_coin_insert();
}
coin_pressed = coin;
AIO_IOB2_BI2X_TCS__DEVSTATUS current {};
current.InputCounter = ++input_counter;
current.Input.DevIoCounter = input_counter;
current.Input.bTest = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Test]) ? 1 : 0;
current.Input.bService = GameAPI::Buttons::getState(RI_MGR, buttons[Buttons::Service]) ? 1 : 0;
current.Input.bCoinSw = coin ? 1 : 0;
current.Input.CoinCount = static_cast<uint8_t>(eamuse_coin_get_stock());
RI_MGR->devices_flush_output();
const auto copy_size = std::min<uint32_t>(status_size, sizeof(current));
if (copy_size > 0) {
std::memcpy(status, &current, copy_size);
}
return copy_size;
}
static void __fastcall aioIob2Bi2xTCS_IoReset(AIO_IOB2_BI2X_TCS *board, uint32_t bits) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_IoReset_orig(board, bits);
}
}
static void __fastcall aioIob2Bi2xTCS_SetWatchDogTimer(
AIO_IOB2_BI2X_TCS *board, uint8_t count) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_SetWatchDogTimer_orig(board, count);
}
}
static void __fastcall aioIob2Bi2xTCS_ControlCoinBlocker(
AIO_IOB2_BI2X_TCS *board, uint32_t slot, bool open) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_ControlCoinBlocker_orig(board, slot, open);
}
if (slot != 0) {
log_warning("cardconnect::bi2x", "unknown coin blocker slot {}", slot);
return;
}
eamuse_coin_set_block(!open);
}
static void __fastcall aioIob2Bi2xTCS_AddCounter(
AIO_IOB2_BI2X_TCS *board, uint32_t counter, uint32_t count) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_AddCounter_orig(board, counter, count);
}
// This drives the physical bookkeeping meter, not the input coin counter.
}
static void __fastcall aioIob2Bi2xTCS_SetPhotoLight(AIO_IOB2_BI2X_TCS *board, bool on) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_SetPhotoLight_orig(board, on);
}
write_light(Lights::PhotoLight, on ? 1.f : 0.f);
}
static void __fastcall aioIob2Bi2xTCS_SetIccrLed(AIO_IOB2_BI2X_TCS *board, uint32_t rgb) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_SetIccrLed_orig(board, rgb);
}
write_light(Lights::CardReaderR, ((rgb >> 16) & 0xff) / 255.f);
write_light(Lights::CardReaderG, ((rgb >> 8) & 0xff) / 255.f);
write_light(Lights::CardReaderB, (rgb & 0xff) / 255.f);
}
static void __fastcall aioIob2Bi2xTCS_SetTapeLedData(
AIO_IOB2_BI2X_TCS *board, uint32_t tape, uint8_t *data) {
if (!aio_board || board != aio_board.get()) {
return aioIob2Bi2xTCS_SetTapeLedData_orig(board, tape, data);
}
if (!data || tape >= 2) {
log_warning("cardconnect::bi2x", "invalid tape LED data for channel {}", tape);
return;
}
if (tapeledutils::is_enabled()) {
const auto color = tapeledutils::pick_color_from_led_tape(data, 15);
const auto first = tape == 0 ? Lights::SideLeftR : Lights::SideRightR;
write_light(first, color.r);
write_light(first + 1, color.g);
write_light(first + 2, color.b);
}
}
static AIO_SCI_COMM *__fastcall aioIob2Bi2x_OpenSciUsbCdc(uint32_t serial_number) {
if (!aio_sci) {
aio_sci = std::make_unique<AIO_SCI_COMM>();
}
return aio_sci.get();
}
static AIO_IOB2_BI2X_WRFIRM *__fastcall aioIob2Bi2x_CreateWriteFirmContext(
uint32_t serial_number, uint32_t iob_mask) {
if (!aio_firmware) {
aio_firmware = std::make_unique<AIO_IOB2_BI2X_WRFIRM>();
}
return aio_firmware.get();
}
static void __fastcall aioIob2Bi2x_DestroyWriteFirmContext(AIO_IOB2_BI2X_WRFIRM *context) {
if (!aio_firmware || context != aio_firmware.get()) {
return aioIob2Bi2x_DestroyWriteFirmContext_orig(context);
}
aio_firmware.reset();
}
static int32_t __fastcall aioIob2Bi2x_WriteFirmGetState(AIO_IOB2_BI2X_WRFIRM *context) {
if (!aio_firmware || context != aio_firmware.get()) {
return aioIob2Bi2x_WriteFirmGetState_orig(context);
}
return 8;
}
static AIO_NMGR_IOB2 *__fastcall aioNMgrIob2_Create(AIO_SCI_COMM *sci, uint32_t mode) {
if (!aio_sci || sci != aio_sci.get()) {
return aioNMgrIob2_Create_orig(sci, mode);
}
if (!aio_manager) {
aio_manager = std::make_unique<AIO_NMGR_IOB2>();
}
return aio_manager.get();
}
static void __fastcall aioNMgrIob_BeginManage(AIO_NMGR_IOB2 *manager) {
if (!aio_manager || manager != aio_manager.get()) {
return aioNMgrIob_BeginManage_orig(manager);
}
}
static void __fastcall aioNodeMgr_Destroy(AIO_NMGR_IOB2 *manager) {
if (!aio_manager || manager != aio_manager.get()) {
return aioNodeMgr_Destroy_orig(manager);
}
aio_manager.reset();
}
static int32_t __fastcall aioNodeMgr_GetState(AIO_NMGR_IOB2 *manager) {
if (!aio_manager || manager != aio_manager.get()) {
return aioNodeMgr_GetState_orig(manager);
}
return 1;
}
static bool __fastcall aioNodeMgr_IsReady(AIO_NMGR_IOB2 *manager, int32_t state) {
if (!aio_manager || manager != aio_manager.get()) {
return aioNodeMgr_IsReady_orig(manager, state);
}
return state >= 1;
}
static void __fastcall aioNodeCtl_Destroy(AIO_IOB2_BI2X_TCS *board) {
if (!aio_board || board != aio_board.get()) {
return aioNodeCtl_Destroy_orig(board);
}
aio_board.reset();
}
static int32_t __fastcall aioNodeCtl_GetState(AIO_IOB2_BI2X_TCS *board) {
if (!aio_board || board != aio_board.get()) {
return aioNodeCtl_GetState_orig(board);
}
return 1;
}
static bool __fastcall aioNodeCtl_IsReady(AIO_IOB2_BI2X_TCS *board, int32_t state) {
if (!aio_board || board != aio_board.get()) {
return aioNodeCtl_IsReady_orig(board, state);
}
return state >= 1;
}
static void __fastcall aioSci_Destroy(AIO_SCI_COMM *sci) {
if (!aio_sci || sci != aio_sci.get()) {
return aioSci_Destroy_orig(sci);
}
aio_sci.reset();
}
void bi2x_hook_init() {
log_info("cardconnect::bi2x", "initializing native BI2X-TCS hooks");
const auto video = "libaio-iob2_video.dll";
detour::trampoline(video, "aioIob2Bi2xTCS_Create",
aioIob2Bi2xTCS_Create, &aioIob2Bi2xTCS_Create_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_GetDeviceStatus",
aioIob2Bi2xTCS_GetDeviceStatus, &aioIob2Bi2xTCS_GetDeviceStatus_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_IoReset",
aioIob2Bi2xTCS_IoReset, &aioIob2Bi2xTCS_IoReset_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_SetWatchDogTimer",
aioIob2Bi2xTCS_SetWatchDogTimer, &aioIob2Bi2xTCS_SetWatchDogTimer_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_ControlCoinBlocker",
aioIob2Bi2xTCS_ControlCoinBlocker, &aioIob2Bi2xTCS_ControlCoinBlocker_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_AddCounter",
aioIob2Bi2xTCS_AddCounter, &aioIob2Bi2xTCS_AddCounter_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_SetPhotoLight",
aioIob2Bi2xTCS_SetPhotoLight, &aioIob2Bi2xTCS_SetPhotoLight_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_SetIccrLed",
aioIob2Bi2xTCS_SetIccrLed, &aioIob2Bi2xTCS_SetIccrLed_orig);
detour::trampoline(video, "aioIob2Bi2xTCS_SetTapeLedData",
aioIob2Bi2xTCS_SetTapeLedData, &aioIob2Bi2xTCS_SetTapeLedData_orig);
const auto iob = "libaio-iob.dll";
detour::trampoline(iob, "aioIob2Bi2x_OpenSciUsbCdc",
aioIob2Bi2x_OpenSciUsbCdc, &aioIob2Bi2x_OpenSciUsbCdc_orig);
detour::trampoline(iob, "aioIob2Bi2x_CreateWriteFirmContext",
aioIob2Bi2x_CreateWriteFirmContext, &aioIob2Bi2x_CreateWriteFirmContext_orig);
detour::trampoline(iob, "aioIob2Bi2x_DestroyWriteFirmContext",
aioIob2Bi2x_DestroyWriteFirmContext, &aioIob2Bi2x_DestroyWriteFirmContext_orig);
detour::trampoline(iob, "aioIob2Bi2x_WriteFirmGetState",
aioIob2Bi2x_WriteFirmGetState, &aioIob2Bi2x_WriteFirmGetState_orig);
detour::trampoline(iob, "aioNMgrIob2_Create",
aioNMgrIob2_Create, &aioNMgrIob2_Create_orig);
detour::trampoline(iob, "aioNMgrIob_BeginManage",
aioNMgrIob_BeginManage, &aioNMgrIob_BeginManage_orig);
const auto aio = "libaio.dll";
detour::trampoline(aio, "aioNodeMgr_Destroy", aioNodeMgr_Destroy, &aioNodeMgr_Destroy_orig);
detour::trampoline(aio, "aioNodeMgr_GetState", aioNodeMgr_GetState, &aioNodeMgr_GetState_orig);
detour::trampoline(aio, "aioNodeMgr_IsReady", aioNodeMgr_IsReady, &aioNodeMgr_IsReady_orig);
detour::trampoline(aio, "aioNodeCtl_Destroy", aioNodeCtl_Destroy, &aioNodeCtl_Destroy_orig);
detour::trampoline(aio, "aioNodeCtl_GetState", aioNodeCtl_GetState, &aioNodeCtl_GetState_orig);
detour::trampoline(aio, "aioNodeCtl_IsReady", aioNodeCtl_IsReady, &aioNodeCtl_IsReady_orig);
detour::trampoline(aio, "aioSci_Destroy", aioSci_Destroy, &aioSci_Destroy_orig);
}
}
#endif
@@ -0,0 +1,5 @@
#pragma once
namespace games::cardconnect {
void bi2x_hook_init();
}
@@ -0,0 +1,58 @@
#include "cardconnect.h"
#include <format>
#include "acioemu/handle.h"
#include "bi2x_hook.h"
#include "printer.h"
#include "hooks/graphics/graphics.h"
#include "util/execexe.h"
#include "util/fileutils.h"
#include "util/libutils.h"
#include "util/logging.h"
#include "util/unity_player.h"
namespace games::cardconnect {
std::string CARDCONNECT_INJECT_ARGS = "";
static const std::wstring reader_port = L"\\\\.\\COM2";
void CardConnectGame::attach() {
Game::attach();
fileutils::dir_create_recursive_log("cardconnect", "dev/raw/log");
if (!fileutils::bin_write("dev/raw/log/output_log.txt", nullptr, 0)) {
log_warning("cardconnect", "failed to create Unity output log");
}
auto *reader = new acioemu::ACIOHandle(reader_port.c_str(), 1);
devicehook_init_trampoline();
devicehook_add(reader);
execexe::init();
execexe::init_port_hook(reader_port, reader);
#if SPICE64
libutils::load_library("libaio.dll");
libutils::load_library("libaio-iob.dll");
libutils::load_library("libaio-iob2_video.dll");
bi2x_hook_init();
printer_attach();
#endif
if (GRAPHICS_SHOW_CURSOR) {
unity_utils::force_show_cursor(true);
}
unity_utils::set_args(
std::format("{} {}{}",
GetCommandLineA(),
CARDCONNECT_INJECT_ARGS,
unity_utils::get_unity_player_args()));
}
void CardConnectGame::detach() {
Game::detach();
devicehook_dispose();
}
}
@@ -0,0 +1,15 @@
#pragma once
#include "games/game.h"
namespace games::cardconnect {
extern std::string CARDCONNECT_INJECT_ARGS;
class CardConnectGame : public games::Game {
public:
CardConnectGame() : Game("Card Connect") {}
virtual void attach() override;
virtual void detach() override;
};
}
+40
View File
@@ -0,0 +1,40 @@
#include "io.h"
std::vector<Button> &games::cardconnect::get_buttons() {
static std::vector<Button> buttons;
if (buttons.empty()) {
buttons = GameAPI::Buttons::getButtons("Card Connect");
GameAPI::Buttons::sortButtons(
&buttons,
"Test",
"Service",
"Coin Mech"
);
}
return buttons;
}
std::vector<Light> &games::cardconnect::get_lights() {
static std::vector<Light> lights;
if (lights.empty()) {
lights = GameAPI::Lights::getLights("Card Connect");
GameAPI::Lights::sortLights(
&lights,
"Photo Light",
"Card Reader R",
"Card Reader G",
"Card Reader B",
"Side Left R",
"Side Left G",
"Side Left B",
"Side Right R",
"Side Right G",
"Side Right B"
);
}
return lights;
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <vector>
#include "cfg/api.h"
namespace games::cardconnect {
namespace Buttons {
enum {
Test,
Service,
CoinMech,
};
}
namespace Lights {
enum {
PhotoLight,
CardReaderR,
CardReaderG,
CardReaderB,
SideLeftR,
SideLeftG,
SideLeftB,
SideRightR,
SideRightG,
SideRightB,
};
}
std::vector<Button> &get_buttons();
std::vector<Light> &get_lights();
}
+617
View File
@@ -0,0 +1,617 @@
#include "printer.h"
#if SPICE64
#include <algorithm>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <optional>
#include <vector>
#include "games/shared/printer.h"
#include "util/detour.h"
#include "util/libutils.h"
#include "util/logging.h"
namespace games::cardconnect {
// Settings and native protocol values.
bool PRINTER_DISABLED = false;
bool PRINTER_SIMULATE_DELAY = false;
static constexpr uint16_t READY = 0;
static constexpr uint16_t INVALID_PARAMETER = 1006;
static constexpr uint16_t BUSY = 1500;
static constexpr uint16_t PRINTING = 2100;
static constexpr uint16_t OUTPUT_ERROR = 2504;
enum PrinterInfoTag : uint16_t {
INFO_PAPER = 0,
INFO_FIRMWARE = 3,
INFO_PRINT_COUNT = 4,
INFO_HOLO_REMAINING = 6,
INFO_MEMORY = 16,
INFO_FRONT_MODE = 19,
INFO_BACK_MODE = 20,
INFO_IR_CORRECTION = 22,
};
enum PrinterMode : uint8_t {
MODE_YMC_MAT = 2,
MODE_YMC_LAM = 3,
MODE_YMC_MAT_HOLO = 5,
MODE_YMC_LAM_HOLO = 6,
MODE_IR_R_YMAC_MAT = 8,
MODE_IR_R_YMAC_LAM = 9,
MODE_R_YMAC_MAT = 10,
MODE_R_YMAC_LAM = 11,
MODE_YMC_GROSS = 18,
MODE_YMC_GROSS_HOLO = 21,
MODE_IR_R_YMAC_GROSS = 24,
MODE_R_YMAC_GROSS = 25,
};
static constexpr uint16_t FORMAT_RGB = 3;
static constexpr uint16_t FORMAT_BGR = 4;
static constexpr uint16_t COLOR_COMPONENTS = 3;
static constexpr uint16_t COLOR_DEPTH = 8;
static constexpr uint16_t CARD_WIDTH = 662;
static constexpr uint16_t CARD_HEIGHT = 1024;
static constexpr uint32_t RIBBON_REMAINING = 4096;
static constexpr auto PRINT_TIME = std::chrono::seconds(5);
static constexpr std::optional<std::chrono::seconds> get_mode_delay(uint8_t mode) {
// Printer::GetPrintTime adds 10s for holo and 8s per finished side.
if (mode == MODE_YMC_GROSS || mode == MODE_IR_R_YMAC_GROSS || mode == MODE_R_YMAC_GROSS) {
return std::chrono::seconds(0);
}
if (mode == MODE_YMC_MAT || mode == MODE_YMC_LAM ||
mode == MODE_IR_R_YMAC_MAT || mode == MODE_IR_R_YMAC_LAM ||
mode == MODE_R_YMAC_MAT || mode == MODE_R_YMAC_LAM) {
return std::chrono::seconds(8);
}
if (mode == MODE_YMC_GROSS_HOLO) {
return std::chrono::seconds(10);
}
if (mode == MODE_YMC_MAT_HOLO || mode == MODE_YMC_LAM_HOLO) {
return std::chrono::seconds(18);
}
return std::nullopt;
}
// Native reply layouts.
#pragma pack(push, 1)
struct FirmwareRecord {
std::array<uint8_t, 34> reserved;
uint8_t major;
uint8_t minor;
std::array<uint8_t, 2> reserved_tail;
};
struct FirmwareReply {
uint8_t count;
std::array<FirmwareRecord, 4> records;
};
struct PrintCountReply {
uint32_t total_count;
std::array<uint8_t, 16> reserved;
uint32_t ribbon_remaining;
std::array<uint8_t, 8> reserved_tail;
};
struct HoloRemainingReply {
uint32_t remaining;
std::array<uint8_t, 28> reserved;
};
struct MemoryReply {
uint16_t reserved;
uint16_t remaining;
uint16_t completed;
uint16_t copies;
std::array<uint8_t, 10> reserved_tail;
};
struct PrintIDReply {
uint16_t remaining;
std::array<uint8_t, 4> reserved;
uint16_t status;
};
#pragma pack(pop)
static_assert(sizeof(FirmwareRecord) == 38);
static_assert(offsetof(FirmwareRecord, major) == 34);
static_assert(offsetof(FirmwareRecord, minor) == 35);
static_assert(sizeof(FirmwareReply) == 153);
static_assert(offsetof(FirmwareReply, records) == 1);
static_assert(sizeof(PrintCountReply) == 32);
static_assert(offsetof(PrintCountReply, ribbon_remaining) == 20);
static_assert(sizeof(HoloRemainingReply) == 32);
static_assert(sizeof(MemoryReply) == 18);
static_assert(offsetof(MemoryReply, remaining) == 2);
static_assert(offsetof(MemoryReply, completed) == 4);
static_assert(offsetof(MemoryReply, copies) == 6);
static_assert(sizeof(PrintIDReply) == 8);
static_assert(offsetof(PrintIDReply, status) == 6);
// One printer, shared by the game's threads.
struct PrintJob {
uint16_t id = 0;
uint16_t copies = 1;
uint16_t remaining = 0;
uint16_t width = 0;
uint16_t height = 0;
uint16_t format = FORMAT_RGB;
std::array<std::vector<uint8_t>, 2> sides;
uint16_t error = READY;
bool receiving = false;
// Submitted jobs stay busy while waiting for this baseline.
bool awaiting_counter_baseline = false;
std::array<std::chrono::seconds, 2> mode_delays {};
std::chrono::seconds print_time = PRINT_TIME;
std::chrono::steady_clock::time_point next_copy;
};
static std::mutex printer_mutex;
static PrintJob job;
static uint16_t next_page_id = 0;
static uint32_t total_count = 0;
static uint32_t cutter_offset = 0;
// Write the result; non-ready codes return FALSE.
static BOOL set_result(uint16_t *result, uint16_t code = READY) {
if (!result) {
log_warning("cardconnect::printer", "missing result buffer");
return FALSE;
}
*result = code;
return code == READY;
}
static BOOL invalid_parameter(uint16_t *result, const char *operation) {
log_warning("cardconnect::printer", "{}: invalid parameter or job state", operation);
return set_result(result, INVALID_PARAMETER);
}
// Caller holds printer_mutex. The baseline gates completion.
static void update_printing() {
if (job.awaiting_counter_baseline) {
return;
}
const auto now = std::chrono::steady_clock::now();
while (job.remaining && now >= job.next_copy) {
++total_count;
--job.remaining;
job.next_copy += job.print_time;
log_info("cardconnect::printer", "job {}: total count={}, remaining={}",
job.id, total_count, job.remaining);
}
}
// Caller holds printer_mutex.
static uint16_t poll_status() {
update_printing();
if (job.error) {
return job.error;
}
return job.remaining ? PRINTING : READY;
}
// Driver lifetime.
static void __stdcall chcusb_MakeThread(uint16_t count) {
log_info("cardconnect::printer", "initializing printer with {} thread slots", count);
}
static BOOL __stdcall chcusb_open(uint16_t *result) {
return set_result(result);
}
static void __stdcall chcusb_close() {
// Closing a worker must not cancel a submitted job.
std::lock_guard lock(printer_mutex);
if (job.receiving) {
log_warning("cardconnect::printer", "discarding incomplete print job {}", job.id);
job = {};
}
}
static BOOL __stdcall chcusb_ReleaseThread(uint16_t *result) {
std::lock_guard lock(printer_mutex);
job = {};
return set_result(result);
}
// Status and printer information.
static BOOL __stdcall chcusb_status(uint16_t *result) {
std::lock_guard lock(printer_mutex);
return set_result(result, poll_status());
}
static BOOL __stdcall chcusb_getPrinterInfo(uint16_t tag, void *buffer, uint16_t *length) {
std::lock_guard lock(printer_mutex);
update_printing();
// Build the requested reply.
std::array<uint8_t, sizeof(FirmwareReply)> data {};
uint16_t size;
switch (tag) {
case INFO_FIRMWARE: {
FirmwareReply reply {};
reply.count = static_cast<uint8_t>(reply.records.size());
for (auto &record : reply.records) {
record.major = 1;
}
size = sizeof(reply);
std::memcpy(data.data(), &reply, size);
break;
}
case INFO_PRINT_COUNT: {
PrintCountReply reply {};
reply.total_count = total_count;
reply.ribbon_remaining = RIBBON_REMAINING;
size = sizeof(reply);
std::memcpy(data.data(), &reply, size);
break;
}
case INFO_HOLO_REMAINING: {
HoloRemainingReply reply {};
reply.remaining = RIBBON_REMAINING;
size = sizeof(reply);
std::memcpy(data.data(), &reply, size);
break;
}
case INFO_MEMORY: {
MemoryReply reply {};
reply.remaining = job.remaining;
reply.completed = static_cast<uint16_t>(job.copies - job.remaining);
reply.copies = job.copies;
size = sizeof(reply);
std::memcpy(data.data(), &reply, size);
break;
}
default:
log_warning("cardconnect::printer", "unsupported printer info tag {}", tag);
return FALSE;
}
// Check capacity before writing.
if (!buffer || !length || *length < size) {
log_warning("cardconnect::printer", "invalid buffer for printer info tag {}", tag);
if (length) {
*length = size;
}
return FALSE;
}
std::memcpy(buffer, data.data(), size);
*length = size;
// CoMain needs its post-cleanup baseline before any copy finishes.
if (tag == INFO_PRINT_COUNT && job.awaiting_counter_baseline) {
job.awaiting_counter_baseline = false;
job.next_copy = std::chrono::steady_clock::now() + job.print_time;
log_info("cardconnect::printer",
"job {}: counter baseline={}, starting print timer ({}s per copy)",
job.id, total_count, job.print_time.count());
}
return TRUE;
}
// Paper and coating settings do not alter saved RGB data.
static BOOL __stdcall chcusb_setPrinterInfo(
uint16_t tag, const void *buffer, uint16_t *length, uint16_t *result) {
uint16_t expected = 0;
switch (tag) {
case INFO_PAPER:
expected = 10;
break;
case INFO_FRONT_MODE:
case INFO_BACK_MODE:
case INFO_IR_CORRECTION:
// The managed caller sends one byte, not two.
expected = 1;
break;
}
if (!expected || !buffer || !length || *length != expected) {
log_warning("cardconnect::printer",
"setPrinterInfo: tag={}, length={}, expected={}, buffer={}, length pointer={}",
tag, length ? *length : 0, expected, buffer != nullptr, length != nullptr);
return invalid_parameter(result, "setPrinterInfo");
}
if (PRINTER_SIMULATE_DELAY && (tag == INFO_FRONT_MODE || tag == INFO_BACK_MODE)) {
const auto mode = *static_cast<const uint8_t *>(buffer);
const auto delay = get_mode_delay(mode);
if (!delay) {
log_warning("cardconnect::printer", "cannot estimate delay for print mode {}", mode);
return invalid_parameter(result, "setPrinterInfo print mode");
}
if (!result) {
return set_result(result);
}
std::lock_guard lock(printer_mutex);
if (tag == INFO_FRONT_MODE) {
job.mode_delays[0] = *delay;
} else {
job.mode_delays[1] = *delay;
}
}
return set_result(result);
}
// Configure the next job.
static BOOL __stdcall chcusb_imageformat(
uint16_t format, uint16_t components, uint16_t depth,
uint16_t width, uint16_t height, uint16_t *result) {
std::lock_guard lock(printer_mutex);
update_printing();
if ((format != FORMAT_RGB && format != FORMAT_BGR) ||
components != COLOR_COMPONENTS || depth != COLOR_DEPTH ||
width != CARD_WIDTH || height != CARD_HEIGHT || job.receiving || job.remaining) {
return invalid_parameter(result, "imageformat");
}
job.width = width;
job.height = height;
job.format = format;
return set_result(result);
}
static BOOL __stdcall chcusb_copies(uint16_t copies, uint16_t *result) {
std::lock_guard lock(printer_mutex);
update_printing();
if (!copies || job.receiving || job.remaining) {
return invalid_parameter(result, "copies");
}
job.copies = copies;
return set_result(result);
}
// Receive front and back image data.
static BOOL __stdcall chcusb_startpage(uint16_t mode, uint16_t *page_id, uint16_t *result) {
std::lock_guard lock(printer_mutex);
update_printing();
if (job.receiving || job.remaining) {
log_warning("cardconnect::printer", "startpage while printer is busy");
return set_result(result, BUSY);
}
if (mode != 0 || !page_id || !result || !job.width || !job.height) {
return invalid_parameter(result, "startpage");
}
// Keep zero reserved for "no job".
if (++next_page_id == 0) {
++next_page_id;
}
job.id = next_page_id;
job.print_time = PRINT_TIME;
if (PRINTER_SIMULATE_DELAY) {
job.print_time = std::chrono::seconds(73) + job.mode_delays[0] + job.mode_delays[1];
}
job.error = READY;
job.receiving = true;
job.sides = {};
*page_id = job.id;
log_info("cardconnect::printer", "receiving job {} ({} copies)", job.id, job.copies);
return set_result(result);
}
static BOOL __stdcall chcusb_write(
const uint8_t *data, uint32_t *size, uint16_t *result) {
std::lock_guard lock(printer_mutex);
const size_t expected = static_cast<size_t>(job.width) * job.height * COLOR_COMPONENTS;
if (!job.receiving || !data || !size || !result || !*size) {
return invalid_parameter(result, "write");
}
// Fill the front before accepting the back.
auto &side = job.sides[job.sides[0].size() == expected ? 1 : 0];
if (*size > expected - side.size()) {
return invalid_parameter(result, "write size");
}
side.insert(side.end(), data, data + *size);
return set_result(result);
}
// Accept coating masks without saving them.
static BOOL __stdcall discard_mask(
const uint8_t *data, uint32_t *size, uint16_t *result) {
std::lock_guard lock(printer_mutex);
if (!job.receiving || !data || !size ||
*size != static_cast<uint32_t>(job.width) * job.height) {
return invalid_parameter(result, "mask write");
}
return set_result(result);
}
static BOOL __stdcall chcusb_endpage(uint16_t *result) {
std::lock_guard lock(printer_mutex);
const size_t expected = static_cast<size_t>(job.width) * job.height * COLOR_COMPONENTS;
// Both sides must be complete.
if (!result || !job.receiving ||
job.sides[0].size() != expected || job.sides[1].size() != expected) {
return invalid_parameter(result, "endpage");
}
// Image files use RGB channel order.
if (job.format == FORMAT_BGR) {
for (auto &side : job.sides) {
for (size_t i = 0; i < side.size(); i += COLOR_COMPONENTS) {
std::swap(side[i], side[i + 2]);
}
}
}
// Save every copy before reporting success.
job.receiving = false;
for (uint16_t i = 0; i < job.copies; ++i) {
if (!games::shared::printer_write_images({
{job.sides[0].data(), job.width, job.height, COLOR_COMPONENTS, "_front"},
{job.sides[1].data(), job.width, job.height, COLOR_COMPONENTS, "_back"}})) {
job.error = OUTPUT_ERROR;
job.sides = {};
log_warning("cardconnect::printer", "failed to save job {}", job.id);
return set_result(result, job.error);
}
}
// Wait for the game's counter baseline.
job.sides = {};
job.remaining = job.copies;
job.awaiting_counter_baseline = true;
log_info("cardconnect::printer", "submitted job {}, waiting for counter baseline", job.id);
return set_result(result);
}
// Job progress and cancellation.
static BOOL __stdcall chcusb_getPrintIDStatus(
uint16_t page_id, void *buffer, uint16_t *result) {
std::lock_guard lock(printer_mutex);
const auto status = poll_status();
if (!buffer || page_id != job.id) {
return invalid_parameter(result, "getPrintIDStatus");
}
PrintIDReply reply {};
reply.remaining = job.remaining;
reply.status = status;
std::memcpy(buffer, &reply, sizeof(reply));
return set_result(result);
}
static BOOL __stdcall chcusb_cancelCopies(uint16_t page_id, uint16_t *result) {
std::lock_guard lock(printer_mutex);
if (page_id != job.id) {
return invalid_parameter(result, "cancelCopies");
}
update_printing();
job.remaining = 0;
job.receiving = false;
job.awaiting_counter_baseline = false;
job.sides = {};
return set_result(result);
}
static BOOL __stdcall chcusb_resetPrinter(uint16_t *result) {
std::lock_guard lock(printer_mutex);
update_printing();
job = {};
return set_result(result);
}
// Physical-printer controls.
static BOOL __stdcall chcusb_setIcctable(
[[maybe_unused]] const char *input_profile,
[[maybe_unused]] const char *output_profile,
[[maybe_unused]] uint16_t rendering_intents,
[[maybe_unused]] const void *input_tone_r,
[[maybe_unused]] const void *input_tone_g,
[[maybe_unused]] const void *input_tone_b,
[[maybe_unused]] const void *output_tone_r,
[[maybe_unused]] const void *output_tone_g,
[[maybe_unused]] const void *output_tone_b,
uint16_t *result) {
// Keep the original RGB colors.
return set_result(result);
}
static void __stdcall chcusb_setCutterOffset(uint32_t offset, uint16_t *result) {
std::lock_guard lock(printer_mutex);
cutter_offset = offset;
set_result(result);
}
static BOOL __stdcall chcusb_getCutterOffset(uint32_t *offset, uint16_t *result) {
std::lock_guard lock(printer_mutex);
if (!offset) {
return invalid_parameter(result, "getCutterOffset");
}
*offset = cutter_offset;
return set_result(result);
}
static BOOL __stdcall chcusb_getErrorLog(uint16_t index, void *buffer, uint16_t *result) {
if (!buffer || index != 0) {
return invalid_parameter(result, "getErrorLog");
}
std::memset(buffer, 0, 16);
return set_result(result);
}
template<typename T>
static void hook(const char *name, T function) {
T original = nullptr;
detour::trampoline("C320Dusb.dll", name, function, &original);
}
void printer_attach() {
if (PRINTER_DISABLED) {
return;
}
log_info("cardconnect::printer", "enabling C320D printer emulation");
games::shared::printer_init_output({"_front", "_back"});
libutils::load_library("game\\tcs_data\\Plugins\\C320Dusb.dll");
// Connections and status.
hook("chcusb_MakeThread", chcusb_MakeThread);
hook("chcusb_open", chcusb_open);
hook("chcusb_close", chcusb_close);
hook("chcusb_ReleaseThread", chcusb_ReleaseThread);
hook("chcusb_status", chcusb_status);
hook("chcusb_getPrinterInfo", chcusb_getPrinterInfo);
hook("chcusb_setPrinterInfo", chcusb_setPrinterInfo);
// Job setup and image transfer.
hook("chcusb_imageformat", chcusb_imageformat);
hook("chcusb_copies", chcusb_copies);
hook("chcusb_startpage", chcusb_startpage);
hook("chcusb_write", chcusb_write);
hook("chcusb_writeLaminate", discard_mask);
hook("chcusb_writeHolo", discard_mask);
hook("chcusb_writeIred", discard_mask);
hook("chcusb_endpage", chcusb_endpage);
// Completion and device controls.
hook("chcusb_getPrintIDStatus", chcusb_getPrintIDStatus);
hook("chcusb_cancelCopies", chcusb_cancelCopies);
hook("chcusb_resetPrinter", chcusb_resetPrinter);
hook("chcusb_setIcctable", chcusb_setIcctable);
hook("chcusb_setCutterOffset", chcusb_setCutterOffset);
hook("chcusb_getCutterOffset", chcusb_getCutterOffset);
hook("chcusb_getErrorLog", chcusb_getErrorLog);
}
}
#else
namespace games::cardconnect {
bool PRINTER_DISABLED = false;
bool PRINTER_SIMULATE_DELAY = false;
}
#endif
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace games::cardconnect {
extern bool PRINTER_DISABLED;
extern bool PRINTER_SIMULATE_DELAY;
void printer_attach();
}
+114
View File
@@ -0,0 +1,114 @@
#include "dxva2.h"
#include <algorithm>
#include <atomic>
#include <cstring>
#include <windows.h>
#include <d3d9.h>
#include <dxva2api.h>
#include "avs/game.h"
#include "hooks/graphics/backends/d3d9/d3d9_backend.h"
#include "util/detour.h"
#include "util/logging.h"
namespace games::iidx {
static decltype(DXVA2CreateDirect3DDeviceManager9) *create_dxva2_manager_orig = nullptr;
static bool force_dxva2_workaround = false;
static bool has_video_player_with_dxva2_fallback(HMODULE module) {
// iidx34+ tries AVMfVideoPlayerWithDxva and falls back to MF-based software decoder
// (can install dxva2 hooks to trigger the fallback)
//
// older iidx (003 variants of iidx29-30?) uses MfVideo::DxvaDeviceImpl and does not automatically fallback
// (requires a DLL patch to trigger the fallback)
//
// this function detects the AVMfVideoPlayerWithDxva case and returns true
constexpr char player_type[] = ".?AVMfVideoPlayerWithDxva@Video@Graphics@@";
const auto *image = reinterpret_cast<const char *>(module);
const auto *dos_header = reinterpret_cast<const IMAGE_DOS_HEADER *>(image);
const auto *nt_headers =
reinterpret_cast<const IMAGE_NT_HEADERS *>(image + dos_header->e_lfanew);
const auto *section = IMAGE_FIRST_SECTION(nt_headers);
for (WORD i = 0; i < nt_headers->FileHeader.NumberOfSections; i++, section++) {
if (std::memcmp(section->Name, ".data", sizeof(".data")) != 0) {
continue;
}
const auto size = std::min(section->Misc.VirtualSize, section->SizeOfRawData);
const std::string_view data(image + section->VirtualAddress, size);
const std::string_view marker(player_type, sizeof(player_type));
return data.find(marker) != std::string_view::npos;
}
return false;
}
static HRESULT WINAPI create_dxva2_manager_hook(UINT *reset_token, IDirect3DDeviceManager9 **manager) {
if (!force_dxva2_workaround && !graphics_d3d9_is_dxvk()) {
return create_dxva2_manager_orig(reset_token, manager);
}
// dxvk can create the manager without providing a usable decoder; failing creation
// lets iidx fall back to software decoding on builds that support it.
static std::atomic_bool logged = false;
if (!logged.exchange(true, std::memory_order_relaxed)) {
log_info(
"iidx",
"DXVA2 workaround active ({}): returning E_FAIL from DXVA2CreateDirect3DDeviceManager9",
force_dxva2_workaround ? "forced on by user" : "automatically for DXVK");
}
return E_FAIL;
}
void init_dxva2_workaround(std::string_view mode) {
// default (no selection) is auto
if (mode.empty()) {
mode = "auto";
}
// forced off by user
if (mode == "off") {
return;
}
const bool forced_on_by_user = (mode == "on");
// invalid option value
if (!forced_on_by_user && mode != "auto") {
log_warning("iidx", "invalid DXVA2 workaround mode '{}'; expected auto, on, or off", mode);
return;
}
const auto module = avs::game::DLL_INSTANCE;
if (!module) {
if (forced_on_by_user) {
log_warning("iidx", "DXVA2 workaround requested, but the game DLL is not loaded");
}
return;
}
if (!forced_on_by_user && !has_video_player_with_dxva2_fallback(module)) {
return;
}
force_dxva2_workaround = forced_on_by_user;
// install hook
create_dxva2_manager_orig = detour::iat_try(
"DXVA2CreateDirect3DDeviceManager9", create_dxva2_manager_hook, module, "dxva2.dll");
if (!create_dxva2_manager_orig) {
if (forced_on_by_user) {
log_warning("iidx", "DXVA2 workaround requested, but the DXVA2 import was not found");
}
return;
}
if (forced_on_by_user) {
log_info("iidx", "DXVA2 disabled by user");
}
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <string_view>
namespace games::iidx {
void init_dxva2_workaround(std::string_view mode);
}
+7 -1
View File
@@ -39,6 +39,7 @@
#include "bi2a.h"
#include "bi2x_hook.h"
#include "dxva2.h"
#include "ezusb.h"
#include "io.h"
#include "poke.h"
@@ -311,8 +312,9 @@ namespace games::iidx {
void IIDXGame::attach() {
Game::attach();
// IO boards
auto options = games::get_options(eamuse_get_game());
// IO boards
if (!options->at(launcher::Options::IIDXBIO2FW).value_bool()) {
// reduce boot wait time
@@ -452,6 +454,10 @@ namespace games::iidx {
#if SPICE64
// dxvk workaround for movie decoder
init_dxva2_workaround(
options->at(launcher::Options::IIDXNoDxva2).value_text());
if (TDJ_MODE) {
sysutils::hook_EnumDisplayDevicesA();
}
+9
View File
@@ -38,6 +38,7 @@
#include "mfg/io.h"
#include "pc/io.h"
#include "udn/io.h"
#include "cardconnect/io.h"
namespace games {
@@ -300,6 +301,7 @@ namespace games {
buttons.insert({ bc, bc::get_buttons() });
buttons_help.insert({ bc, bc::get_buttons_help() });
analogs.insert({ bc, bc::get_analogs() });
lights.insert({ bc, bc::get_lights() });
file_hints[bc].push_back({"game/bsac_app.exe"});
// ccj
@@ -341,6 +343,13 @@ namespace games {
buttons_help.insert({ udn, udn::get_buttons_help() });
lights.insert({ udn, udn::get_lights() });
file_hints[udn].push_back({"game/dancearound_Data"});
// Card Connect
const std::string cardconnect("Card Connect");
games.push_back(cardconnect);
buttons.insert({ cardconnect, cardconnect::get_buttons() });
lights.insert({ cardconnect, cardconnect::get_lights() });
file_hints[cardconnect].push_back({"game/tcs.exe"});
}
const std::vector<std::string> &get_games() {
+42
View File
@@ -9,6 +9,8 @@
#include "hooks/devicehook.h"
#include "hooks/libraryhook.h"
#ifdef SPICE64
#include <mutex>
#include <psapi.h>
#include "hooks/graphics/nvapi_impl.h"
#endif
#include "hooks/graphics/nvapi_hook.h"
@@ -40,6 +42,9 @@ static decltype(RegEnumKeyA) *RegEnumKeyA_orig = nullptr;
static decltype(RegOpenKeyA) *RegOpenKeyA_orig = nullptr;
static decltype(RegOpenKeyExA) *RegOpenKeyExA_orig = nullptr;
static decltype(RegQueryValueExA) *RegQueryValueExA_orig = nullptr;
#ifdef SPICE64
static decltype(K32GetPerformanceInfo) *K32GetPerformanceInfo_orig = nullptr;
#endif
namespace games::sdvx {
@@ -200,6 +205,35 @@ namespace games::sdvx {
}
#ifdef SPICE64
static BOOL WINAPI K32GetPerformanceInfo_hook(PPERFORMANCE_INFORMATION info, DWORD cb) {
if (info == nullptr) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (cb < sizeof(*info)) {
SetLastError(ERROR_BAD_LENGTH);
return FALSE;
}
// store a cached copy of the first successful call to K32GetPerformanceInfo
static std::mutex cache_mutex;
static PERFORMANCE_INFORMATION cached {};
static bool cached_valid = false;
std::lock_guard<std::mutex> lock(cache_mutex);
if (!cached_valid) {
if (!K32GetPerformanceInfo_orig(info, cb)) {
return FALSE;
}
cached = *info;
cached_valid = true;
}
// return the cached copy to avoid performance issues with the game calling this every frame
*info = cached;
return TRUE;
}
static bool sdvx64_spam_remover(void *user, const std::string &data, logger::Style style, std::string &out) {
if (data.empty() || data[0] != '[') {
return false;
@@ -534,6 +568,14 @@ namespace games::sdvx {
if (is_valkyrie_model()) {
sysutils::hook_EnumDisplayDevicesA();
}
// keep one real snapshot for the session instead of querying statistics every frame
K32GetPerformanceInfo_orig = detour::iat_try(
"K32GetPerformanceInfo", K32GetPerformanceInfo_hook, avs::game::DLL_INSTANCE);
if (K32GetPerformanceInfo_orig != nullptr) {
log_info("sdvx", "installed cached hook for K32GetPerformanceInfo");
}
#endif
}
+102 -60
View File
@@ -2,6 +2,7 @@
#include <vector>
#include <thread>
#include <limits>
#include "avs/game.h"
#include "hooks/sleephook.h"
@@ -264,7 +265,9 @@ namespace games::shared {
typedef void (CALLBACK *PFNACBfunc)(DWORD dwErr, short PrintFlag, short PrintUsbNo, long nJid, int CopyNumber);
static inline std::string get_image_out_path(bool clear, std::string path, const std::string &format) {
static std::vector<std::string> get_image_out_paths(
bool clear, std::string path, const std::string &format,
const std::vector<std::string> &suffixes, bool overwrite = false) {
// check path
if (path.empty()) {
@@ -277,28 +280,99 @@ namespace games::shared {
path = std::string(path.c_str(), path.length() - 1);
// find non-existing filename
static std::string prefix = "printer_";
for (int n = 0; n < 4096; n++) {
std::ostringstream filename_s;
filename_s << path << "\\" << prefix << n << "." << format;
std::string filename = filename_s.str();
if (clear && fileutils::file_exists(filename.c_str())) {
log_info("printer", "deleting {}...", filename);
DeleteFile(filename.c_str());
if (PRINTER_OVERWRITE_FILE) {
return filename;
std::vector<std::string> filenames;
bool exists = false;
for (const auto &suffix : suffixes) {
auto filename = fmt::format("{}\\printer_{}{}.{}", path, n, suffix, format);
if (fileutils::file_exists(filename.c_str())) {
exists = true;
if (clear) {
log_info("printer", "deleting {}...", filename);
if (!DeleteFileA(filename.c_str())) {
log_warning("printer", "could not delete {}: {}", filename, GetLastError());
return {};
}
}
}
filenames.push_back(std::move(filename));
}
if ((!clear && !exists) || overwrite) {
return filenames;
}
}
if (!clear) {
log_warning("printer", "could not find an unused printer output filename");
}
return {};
}
bool printer_write_image(const uint8_t *data, int width, int height, int components,
const std::string &suffix) {
return printer_write_images({{data, width, height, components, suffix}});
}
bool printer_write_images(std::initializer_list<PrinterImage> images) {
if (images.size() == 0 || PRINTER_PATH.empty() || PRINTER_FORMAT.empty()) {
log_warning("printer", "printer output is uninitialized or contains no images");
return false;
}
std::vector<std::string> suffixes;
for (const auto &image : images) {
if (!image.data || image.width <= 0 || image.height <= 0 ||
(image.components != 1 && image.components != 3) ||
image.width > std::numeric_limits<int>::max() / image.components / image.height) {
log_warning("printer", "invalid image supplied for printer output");
return false;
}
suffixes.push_back(image.suffix);
}
bool all_saved = true;
for (const auto &path : PRINTER_PATH) {
for (const auto &format : PRINTER_FORMAT) {
const auto image_paths = get_image_out_paths(
PRINTER_OVERWRITE_FILE, path, format, suffixes, PRINTER_OVERWRITE_FILE);
if (image_paths.size() != images.size()) {
log_warning("printer", "could not allocate printer output paths in {}", path);
all_saved = false;
continue;
}
size_t index = 0;
for (const auto &image : images) {
const auto &image_path = image_paths[index++];
bool success = false;
if (format == "png") {
success = stbi_write_png(
image_path.c_str(), image.width, image.height, image.components,
image.data, image.width * image.components);
} else if (format == "bmp") {
success = stbi_write_bmp(image_path.c_str(), image.width, image.height,
image.components, image.data);
} else if (format == "tga") {
success = stbi_write_tga(image_path.c_str(), image.width, image.height,
image.components, image.data);
} else if (format == "jpg") {
success = stbi_write_jpg(
image_path.c_str(), image.width, image.height, image.components,
image.data, PRINTER_JPG_QUALITY);
}
if (success) {
log_info("printer", "printer emulation has written an image to {}", image_path);
overlay::notifications::add(
overlay::notifications::Severity::Success,
fmt::format("Printer: saved {}", fileutils::basename(image_path)));
} else {
all_saved = false;
log_warning("printer", "printer emulation failed to write image to {}", image_path);
overlay::notifications::add(
overlay::notifications::Severity::Error,
fmt::format("Printer: failed to write {}", fileutils::basename(image_path)));
}
}
}
else if (!fileutils::file_exists(filename.c_str()))
return filename;
}
// error
if (!clear) {
log_fatal("printer", "could not find path");
}
return "DUMMY";
return all_saved;
}
static inline bool process_image_print(const CPDBandImageParams *pBandImage) {
@@ -372,43 +446,8 @@ namespace games::shared {
}
}
// iterate folders
log_misc("printer", "writing files...");
for (const auto &path : PRINTER_PATH) {
for (const auto &format : PRINTER_FORMAT) {
// get image path
std::string image_path = get_image_out_path(PRINTER_OVERWRITE_FILE, path, format);
bool success = false;
// call write function depending on format
if (format == "png" && stbi_write_png(
image_path.c_str(), image_width, image_height, 3, image_data, image_width * 3))
success = true;
if (format == "bmp" && stbi_write_bmp(
image_path.c_str(), image_width, image_height, 3, image_data))
success = true;
if (format == "tga" && stbi_write_tga(
image_path.c_str(), image_width, image_height, 3, image_data))
success = true;
if (format == "jpg" && stbi_write_jpg(
image_path.c_str(), image_width, image_height, 3, image_data, PRINTER_JPG_QUALITY))
success = true;
// logging
if (success) {
log_info("printer", "printer emulation has written an image to {}", image_path);
overlay::notifications::add(
overlay::notifications::Severity::Success,
fmt::format("Printer: saved {}", fileutils::basename(image_path)));
} else {
log_warning("printer", "printer emulation failed to write image to {}", image_path);
overlay::notifications::add(
overlay::notifications::Severity::Error,
fmt::format("Printer: failed to write {}", fileutils::basename(image_path)));
}
}
}
// preserve the legacy caller's success behavior after reporting file errors
printer_write_image(image_data, image_width, image_height, 3);
// clean up
delete[] image_data;
@@ -555,9 +594,7 @@ namespace games::shared {
log_info("printer", "CPUXInit called");
}
void printer_attach() {
log_info("printer", "SpiceTools Printer");
void printer_init_output(std::initializer_list<std::string> suffixes) {
// default parameters
if (PRINTER_PATH.empty()) {
PRINTER_PATH.emplace_back(".");
@@ -588,10 +625,15 @@ namespace games::shared {
PRINTER_CLEAR = false;
for (const auto &path : PRINTER_PATH) {
for (const auto &format : PRINTER_FORMAT) {
get_image_out_path(true, path, format);
get_image_out_paths(true, path, format, suffixes);
}
}
}
}
void printer_attach() {
log_info("printer", "SpiceTools Printer");
printer_init_output();
// IAT hooks
detour::iat_try("CPU9CheckPaperRemain", CPU9CheckPaperRemain);
+14
View File
@@ -2,6 +2,8 @@
#include <vector>
#include <string>
#include <cstdint>
#include <initializer_list>
#include <windows.h>
@@ -15,4 +17,16 @@ namespace games::shared {
extern bool PRINTER_OVERWRITE_FILE;
void printer_attach();
struct PrinterImage {
const uint8_t *data;
int width;
int height;
int components;
std::string suffix;
};
void printer_init_output(std::initializer_list<std::string> suffixes = {""});
bool printer_write_images(std::initializer_list<PrinterImage> images);
bool printer_write_image(const uint8_t *data, int width, int height, int components,
const std::string &suffix = "");
}
@@ -183,6 +183,30 @@ HRESULT STDMETHODCALLTYPE WrappedIAudioClient::Initialize(
WAVEFORMATEXTENSIBLE resample_storage = {};
const WAVEFORMATEX *device_format = pFormat;
#if SPICE_LINUX
WAVEFORMATEXTENSIBLE full_width_storage = {};
if (this->shared.redirected_from_exclusive &&
pFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
pFormat->cbSize == sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) &&
pFormat->wBitsPerSample == 32) {
const auto *ext = reinterpret_cast<const WAVEFORMATEXTENSIBLE *>(pFormat);
if (ext->SubFormat == GUID_KSDATAFORMAT_SUBTYPE_PCM &&
ext->Samples.wValidBitsPerSample == 24) {
// workaround for bug in wine
//
// Windows reads audio data in the **top** 24 bits, but Wine's PulseAudio mapping
// for this format reads the **bottom** 24 bits, causing static.
// report 32 valid bits so Wine selects s32le and reads the whole sample.
// the bottom 8 bits are zero padding, so the audio data and volume stay the same.
full_width_storage = *ext;
full_width_storage.Samples.wValidBitsPerSample = 32;
device_format = &full_width_storage.Format;
log_info("audio::wasapi", "using 32-bit PCM for Linux shared-mode 24-in-32 audio");
}
}
#endif
if (!this->shared.redirected_from_exclusive) {
// when downmixing, open the real device as stereo while the game keeps writing its native
+153
View File
@@ -0,0 +1,153 @@
#include "eventlog.h"
#include <mutex>
#include <set>
#include "util/detour.h"
#include "util/logging.h"
namespace hooks::eventlog {
static decltype(OpenEventLogA) *OpenEventLogA_orig = nullptr;
static decltype(OpenEventLogW) *OpenEventLogW_orig = nullptr;
static decltype(CloseEventLog) *CloseEventLog_orig = nullptr;
static decltype(GetNumberOfEventLogRecords) *GetNumberOfEventLogRecords_orig = nullptr;
static decltype(ReadEventLogA) *ReadEventLogA_orig = nullptr;
static decltype(ReadEventLogW) *ReadEventLogW_orig = nullptr;
// count and read calls only receive a handle, not the server name used at open
static std::mutex handles_mutex;
static std::set<HANDLE> local_log_handles;
static HANDLE record_open(HANDLE handle, bool local) {
// bookkeeping must not change the last error left by OpenEventLog
auto error = GetLastError();
{
std::lock_guard lock(handles_mutex);
if (local) {
local_log_handles.insert(handle);
} else {
// another DLL may have closed a local handle without going through our hook
local_log_handles.erase(handle);
}
}
SetLastError(error);
return handle;
}
static bool is_local_log(HANDLE handle) {
std::lock_guard lock(handles_mutex);
return local_log_handles.count(handle) != 0;
}
static HANDLE WINAPI OpenEventLogA_hook(LPCSTR server, LPCSTR source) {
auto handle = OpenEventLogA_orig(server, source);
return handle ? record_open(handle, !server || !*server) : nullptr;
}
static HANDLE WINAPI OpenEventLogW_hook(LPCWSTR server, LPCWSTR source) {
auto handle = OpenEventLogW_orig(server, source);
return handle ? record_open(handle, !server || !*server) : nullptr;
}
static BOOL WINAPI CloseEventLog_hook(HANDLE handle) {
// finish removing this handle before another open can register its reused value
std::unique_lock lock(handles_mutex);
auto result = CloseEventLog_orig(handle);
auto error = GetLastError();
if (result) {
local_log_handles.erase(handle);
}
lock.unlock();
SetLastError(error);
return result;
}
static BOOL WINAPI GetNumberOfEventLogRecords_hook(HANDLE handle, PDWORD count) {
// let Windows validate the request; only replace a successful local count
auto result = GetNumberOfEventLogRecords_orig(handle, count);
auto error = GetLastError();
if (result && is_local_log(handle)) {
*count = 0;
}
SetLastError(error);
return result;
}
static bool valid_read_flags(DWORD flags) {
// exactly one positioning mode and one direction; pass unknown bits through to Windows
switch (flags) {
case EVENTLOG_SEQUENTIAL_READ | EVENTLOG_FORWARDS_READ:
case EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ:
case EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ:
case EVENTLOG_SEEK_READ | EVENTLOG_BACKWARDS_READ:
return true;
default:
return false;
}
}
static BOOL read_event_log(decltype(ReadEventLogA) *original, HANDLE handle, DWORD flags,
DWORD offset, LPVOID buffer, DWORD size, DWORD *bytes_read, DWORD *needed) {
if (!valid_read_flags(flags) || !is_local_log(handle)) {
return original(handle, flags, offset, buffer, size, bytes_read, needed);
}
if (!buffer || !bytes_read || !needed) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
// callers that read without checking the count should also see an empty log
*bytes_read = 0;
*needed = 0;
SetLastError(ERROR_HANDLE_EOF);
return FALSE;
}
static BOOL WINAPI ReadEventLogA_hook(HANDLE handle, DWORD flags, DWORD offset, LPVOID buffer,
DWORD size, DWORD *bytes_read, DWORD *needed) {
return read_event_log(ReadEventLogA_orig, handle, flags, offset, buffer, size, bytes_read, needed);
}
static BOOL WINAPI ReadEventLogW_hook(HANDLE handle, DWORD flags, DWORD offset, LPVOID buffer,
DWORD size, DWORD *bytes_read, DWORD *needed) {
return read_event_log(ReadEventLogW_orig, handle, flags, offset, buffer, size, bytes_read, needed);
}
void init(HMODULE module) {
// some games like SDVX read the Application event log, one record at a time, looking for
// Windows activation timestamps; present local logs as empty to avoid these scans.
if (!module) {
return;
}
constexpr auto dll = "advapi32.dll";
if (!detour::iat_find("OpenEventLogA", module, dll) &&
!detour::iat_find("OpenEventLogW", module, dll)) {
return;
}
CloseEventLog_orig = detour::iat_try("CloseEventLog", CloseEventLog_hook, module, dll);
if (!CloseEventLog_orig) {
log_misc("eventlog", "no CloseEventLog import; leaving event log access unchanged");
return;
}
GetNumberOfEventLogRecords_orig = detour::iat_try(
"GetNumberOfEventLogRecords", GetNumberOfEventLogRecords_hook, module, dll);
ReadEventLogA_orig = detour::iat_try("ReadEventLogA", ReadEventLogA_hook, module, dll);
ReadEventLogW_orig = detour::iat_try("ReadEventLogW", ReadEventLogW_hook, module, dll);
if (!GetNumberOfEventLogRecords_orig && !ReadEventLogA_orig && !ReadEventLogW_orig) {
return;
}
// start tracking opens only after we can intercept reads or counts and observe closes
OpenEventLogA_orig = detour::iat_try("OpenEventLogA", OpenEventLogA_hook, module, dll);
OpenEventLogW_orig = detour::iat_try("OpenEventLogW", OpenEventLogW_hook, module, dll);
if (OpenEventLogA_orig || OpenEventLogW_orig) {
log_info("eventlog", "hooks installed");
}
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <windows.h>
namespace hooks::eventlog {
void init(HMODULE module);
}
@@ -286,8 +286,37 @@ static bool is_dx9_on_12_enabled() {
return result;
}
static bool detect_dxvk(HMODULE d3d9) {
// **mostly** reliable detection for dxvk; these are used internally for debugging
constexpr WORD register_annotation = 28257;
constexpr WORD unregister_annotation = 28258;
if (!d3d9 ||
!GetProcAddress(d3d9, MAKEINTRESOURCEA(register_annotation)) ||
!GetProcAddress(d3d9, MAKEINTRESOURCEA(unregister_annotation))) {
return false;
}
// log once
static std::atomic_bool logged = false;
if (!logged.exchange(true, std::memory_order_relaxed)) {
log_info("graphics::d3d9", "DXVK detected");
deferredlogs::defer_error_messages({
"dxvk detected",
" Vulkan-based renderer may cause graphical issues or crashes",
" it should only be used if necessary on your PC",
});
}
return true;
}
bool graphics_d3d9_is_dxvk() {
return detect_dxvk(libutils::try_module("d3d9.dll"));
}
static IDirect3D9 *WINAPI Direct3DCreate9_hook(UINT SDKVersion) {
log_misc("graphics::d3d9", "Direct3DCreate9 hook hit");
graphics_d3d9_is_dxvk();
// remove hook
if (D3D9_DIRECT3D_CREATE9_ADR) {
@@ -330,6 +359,7 @@ static IDirect3D9 *WINAPI Direct3DCreate9_hook(UINT SDKVersion) {
static HRESULT WINAPI Direct3DCreate9Ex_hook(UINT SDKVersion, IDirect3D9Ex **d3d9ex) {
log_misc("graphics::d3d9", "Direct3DCreate9Ex hook hit");
graphics_d3d9_is_dxvk();
// call original
HRESULT result;
@@ -366,6 +396,7 @@ void graphics_d3d9_init() {
if (!d3d9) {
log_info("graphics::d3d9", "skipping inline hooks");
} else {
detect_dxvk(d3d9);
// 9 on 12
Direct3DCreate9On12_orig = (Direct3DCreate9On12_t) libutils::try_proc(d3d9, "Direct3DCreate9On12");
@@ -12,6 +12,7 @@ static const GUID IID_WrappedIDirect3D9 = {
};
void graphics_d3d9_init();
bool graphics_d3d9_is_dxvk();
void graphics_d3d9_on_present(
HWND hFocusWindow,
IDirect3DDevice9 *device,
@@ -3,6 +3,7 @@
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <mutex>
#include <unordered_map>
#include <vector>
@@ -1088,6 +1089,76 @@ static float topSurface_aspect_ratio = 1.f;
static UINT backbuffer_width = 0;
static UINT backbuffer_height = 0;
static RECT compute_split_src_rect(
const RECT &origin_rect,
LONG player_width,
LONG player_height,
bool is_right_source,
const cfg::split_region_setting &region) {
float w_new = static_cast<float>(player_width) / region.scale_x;
float h_new = static_cast<float>(player_height) / region.scale_y;
const float max_w = static_cast<float>(topSurface_width);
const float max_h = static_cast<float>(topSurface_height);
if (region.keep_aspect_ratio) {
const float limit = std::min({1.0f, max_w / w_new, max_h / h_new});
w_new *= limit;
h_new *= limit;
} else {
w_new = std::min(w_new, max_w);
h_new = std::min(h_new, max_h);
}
const LONG src_w = std::clamp<LONG>(
static_cast<LONG>(std::lround(w_new)), 1, static_cast<LONG>(topSurface_width));
const LONG src_h = std::clamp<LONG>(
static_cast<LONG>(std::lround(h_new)), 1, static_cast<LONG>(topSurface_height));
const float anchor_x = is_right_source
? (static_cast<float>(origin_rect.right) - static_cast<float>(player_width) * 0.5f)
: (static_cast<float>(origin_rect.left) + static_cast<float>(player_width) * 0.5f);
const float anchor_y =
(static_cast<float>(origin_rect.top) + static_cast<float>(origin_rect.bottom)) * 0.5f;
// widen before applying offsets so even extreme settings stay within the surface
const auto left = static_cast<int64_t>(std::lround(anchor_x - src_w * 0.5f)) - region.offset_x;
const auto top = static_cast<int64_t>(std::lround(anchor_y - src_h * 0.5f)) - region.offset_y;
const auto x = static_cast<LONG>(std::clamp<int64_t>(left, 0, topSurface_width - src_w));
const auto y = static_cast<LONG>(std::clamp<int64_t>(top, 0, topSurface_height - src_h));
return {x, y, x + src_w, y + src_h};
}
static void draw_split_region(
IDirect3DDevice9 *device, const RECT &src, const RECT &dest,
D3DTEXTUREFILTERTYPE filter, const char *player) {
if (device->StretchRect(topSurface, &src, backbuffer, &dest, filter) != D3D_OK) {
log_warning(
"graphics::d3d9",
"SurfaceHook - StretchRect split {} failed, src: {} {} {} {}, dst: {} {} {} {}",
player, src.left, src.top, src.right, src.bottom,
dest.left, dest.top, dest.right, dest.bottom);
}
}
static void draw_split_screen(
IDirect3DDevice9 *device, const RECT &origin, LONG width, LONG height,
const cfg::split_screen_setting &split, D3DTEXTUREFILTERTYPE filter) {
const LONG left_width = std::clamp<LONG>(
std::lround(static_cast<float>(width) * split.ratio), 1, width - 1);
const LONG right_width = width - left_width;
const RECT left_src = compute_split_src_rect(origin, left_width, height, false, split.left);
const RECT right_src = compute_split_src_rect(origin, right_width, height, true, split.right);
// move each viewport with its original width, without changing its source crop
const LONG left_x = split.swap_sides ? right_width : 0;
const LONG right_x = split.swap_sides ? 0 : left_width;
const RECT left_dest {left_x, 0, left_x + left_width, height};
const RECT right_dest {right_x, 0, right_x + right_width, height};
draw_split_region(device, left_src, left_dest, filter, "1P");
draw_split_region(device, right_src, right_dest, filter, "2P");
}
void SurfaceHook(IDirect3DDevice9 *pReal) {
// phase 0 - create a surface that has the same aspect ratio as the original back buffer
@@ -1121,7 +1192,12 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
"graphics::d3d9", "SurfaceHook - Backbuffer: {} {} {}",
param.BackBufferWidth, param.BackBufferHeight, param.BackBufferCount);
tex->GetSurfaceLevel(0, &topSurface);
if (tex) {
tex->GetSurfaceLevel(0, &topSurface);
}
if (topSurface) {
pReal->ColorFill(topSurface, nullptr, D3DCOLOR_XRGB(0, 0, 0));
}
if (swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backbuffer) != D3D_OK) {
log_warning("graphics::d3d9", "SurfaceHook - GetBackBuffer failed");
}
@@ -1129,19 +1205,35 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
swapChain->Release();
}
if (!topSurface || !backbuffer) {
return;
}
// pre-calculate dimensions used for phase 1
const int rectLeft = backbuffer_width;
const int rectTop = backbuffer_height;
const int w = backbuffer_width;
const int h = backbuffer_height;
const auto &resize = *cfg::SCREENRESIZE;
const auto &scene = resize.scene_settings[resize.screen_resize_current_scene];
const bool use_split_mode = resize.enable_screen_resize && scene.split.enabled &&
w >= 2 && h >= 1;
const auto effective_duplicate =
(resize.enable_screen_resize && !use_split_mode)
? scene.duplicate
: cfg::ScreenDuplicateMode::None;
// this code used to clear the surface using ColorFill on every call, but
// this turned out to be very expensive, leading to major frame drops in
// SDVX Live2D scenario
if (cfg::SCREENRESIZE->need_surface_clean) {
static auto last_duplicate_mode = cfg::ScreenDuplicateMode::None;
if (cfg::SCREENRESIZE->need_surface_clean || last_duplicate_mode != effective_duplicate) {
pReal->ColorFill(topSurface, nullptr, D3DCOLOR_XRGB(0, 0, 0));
cfg::SCREENRESIZE->need_surface_clean = false;
}
last_duplicate_mode = effective_duplicate;
HRESULT hr;
@@ -1167,17 +1259,14 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
bool duplicate = false;
RECT originRect2 = originRect;
if (cfg::SCREENRESIZE->enable_screen_resize) {
auto& scene = cfg::SCREENRESIZE->scene_settings[cfg::SCREENRESIZE->screen_resize_current_scene];
if (scene.duplicate == cfg::ScreenDuplicateMode::CopyLeft) {
duplicate = true;
originRect2.right = originRect.left;
originRect2.left = (LONG)(originRect2.left - (originRect.right - originRect.left));
} else if (scene.duplicate == cfg::ScreenDuplicateMode::CopyRight) {
duplicate = true;
originRect2.left = originRect.right;
originRect2.right = (LONG)(originRect2.left + (originRect.right - originRect.left));
}
if (effective_duplicate == cfg::ScreenDuplicateMode::CopyLeft) {
duplicate = true;
originRect2.right = originRect.left;
originRect2.left = (LONG)(originRect2.left - (originRect.right - originRect.left));
} else if (effective_duplicate == cfg::ScreenDuplicateMode::CopyRight) {
duplicate = true;
originRect2.left = originRect.right;
originRect2.right = (LONG)(originRect2.left + (originRect.right - originRect.left));
}
// log_misc(
@@ -1207,6 +1296,14 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
}
}
const bool use_linear_filter = !resize.enable_screen_resize || resize.enable_linear_filter;
const auto filter = use_linear_filter ? D3DTEXF_LINEAR : D3DTEXF_NONE;
if (use_split_mode) {
draw_split_screen(pReal, originRect, w, h, scene.split, filter);
return;
}
// phase 2 - viewport calculation - do the actual zoom / offset math
// figure out what region of the surface to copy back to the back buffer.
RECT targetRect {
@@ -1215,8 +1312,7 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
(LONG)(rectLeft + w),
(LONG)(rectTop + h),
};
if (cfg::SCREENRESIZE->enable_screen_resize) {
auto& scene = cfg::SCREENRESIZE->scene_settings[cfg::SCREENRESIZE->screen_resize_current_scene];
if (resize.enable_screen_resize) {
auto w_new = w / scene.scale_x;
auto h_new = h / scene.scale_y;
@@ -1280,14 +1376,10 @@ void SurfaceHook(IDirect3DDevice9 *pReal) {
// targetRect.left, targetRect.top, targetRect.right, targetRect.bottom);
// phase 3 - draw the surface to back buffer
bool use_linear_filter = true;
if (cfg::SCREENRESIZE->enable_screen_resize) {
use_linear_filter = cfg::SCREENRESIZE->enable_linear_filter;
}
hr = pReal->StretchRect(
topSurface, &targetRect,
backbuffer, nullptr,
use_linear_filter ? D3DTEXF_LINEAR : D3DTEXF_NONE);
filter);
if (hr != D3D_OK) {
log_warning(
"graphics::d3d9",
+46 -2
View File
@@ -73,6 +73,8 @@
#include "games/mfg/mfg.h"
#include "games/pc/pc.h"
#include "games/udn/udn.h"
#include "games/cardconnect/cardconnect.h"
#include "games/cardconnect/printer.h"
#include "games/museca/museca.h"
#include "hooks/avshook.h"
#include "hooks/audio/audio.h"
@@ -80,6 +82,7 @@
#include "hooks/audio/backends/wasapi/downmix.h"
#include "hooks/debughook.h"
#include "hooks/devicehook.h"
#include "hooks/eventlog.h"
#include "hooks/graphics/nvenc_hook.h"
#include "hooks/input/dinput8/hook.h"
#include "hooks/graphics/graphics.h"
@@ -248,6 +251,7 @@ int main_implementation(int argc, char *argv[]) {
bool attach_mfg = false;
bool attach_pc = false;
bool attach_udn = false;
bool attach_cardconnect = false;
bool attach_museca = false;
bool show_cursor_if_no_touch = false;
@@ -787,6 +791,9 @@ int main_implementation(int argc, char *argv[]) {
if (options[launcher::Options::LoadUDNModule].value_bool()) {
attach_udn = true;
}
if (options[launcher::Options::LoadCardConnectModule].value_bool()) {
attach_cardconnect = true;
}
if (options[launcher::Options::LoadMusecaModule].value_bool()) {
attach_museca = true;
}
@@ -879,7 +886,8 @@ int main_implementation(int argc, char *argv[]) {
// printer overwrite
if (options[launcher::Options::SDVXPrinterOutputOverwrite].value_bool() ||
options[launcher::Options::LovePlusPrinterOutputOverwrite].value_bool()) {
options[launcher::Options::LovePlusPrinterOutputOverwrite].value_bool() ||
options[launcher::Options::CardConnectPrinterOutputOverwrite].value_bool()) {
games::shared::PRINTER_OVERWRITE_FILE = true;
}
@@ -890,6 +898,9 @@ int main_implementation(int argc, char *argv[]) {
for (auto &path : options[launcher::Options::LovePlusPrinterOutputPath].values_text()) {
games::shared::PRINTER_PATH.push_back(path);
}
for (auto &path : options[launcher::Options::CardConnectPrinterOutputPath].values_text()) {
games::shared::PRINTER_PATH.push_back(path);
}
// printer file format
for (auto &path : options[launcher::Options::SDVXPrinterOutputFormat].values_text()) {
@@ -898,17 +909,24 @@ int main_implementation(int argc, char *argv[]) {
for (auto &path : options[launcher::Options::LovePlusPrinterOutputFormat].values_text()) {
games::shared::PRINTER_FORMAT.push_back(path);
}
for (auto &format : options[launcher::Options::CardConnectPrinterOutputFormat].values_text()) {
games::shared::PRINTER_FORMAT.push_back(format);
}
// printer JPG quality
if (options[launcher::Options::SDVXPrinterJPGQuality].is_active()) {
games::shared::PRINTER_JPG_QUALITY = options[launcher::Options::SDVXPrinterJPGQuality].value_uint32();
} else if (options[launcher::Options::LovePlusPrinterJPGQuality].is_active()) {
games::shared::PRINTER_JPG_QUALITY = options[launcher::Options::LovePlusPrinterJPGQuality].value_uint32();
} else if (options[launcher::Options::CardConnectPrinterJPGQuality].is_active()) {
games::shared::PRINTER_JPG_QUALITY =
options[launcher::Options::CardConnectPrinterJPGQuality].value_uint32();
}
// printer output clear
if (options[launcher::Options::SDVXPrinterOutputClear].value_bool() ||
options[launcher::Options::LovePlusPrinterOutputClear].value_bool()) {
options[launcher::Options::LovePlusPrinterOutputClear].value_bool() ||
options[launcher::Options::CardConnectPrinterOutputClear].value_bool()) {
games::shared::PRINTER_CLEAR = true;
}
@@ -1468,6 +1486,9 @@ int main_implementation(int argc, char *argv[]) {
if (options[launcher::Options::CCJMouseTrackballWithToggle].value_bool()) {
games::ccj::MOUSE_TRACKBALL_USE_TOGGLE = true;
}
if (options[launcher::Options::BCArgs].is_active()) {
games::bc::BC_INJECT_ARGS = options[launcher::Options::BCArgs].value_text();
}
if (options[launcher::Options::CCJArgs].is_active()) {
games::ccj::CCJ_INJECT_ARGS = options[launcher::Options::CCJArgs].value_text();
}
@@ -1498,6 +1519,15 @@ int main_implementation(int argc, char *argv[]) {
if (options[launcher::Options::UDNNoIO].is_active()) {
games::udn::UDN_NO_IO = options[launcher::Options::UDNNoIO].value_bool();
}
if (options[launcher::Options::CardConnectArgs].is_active()) {
games::cardconnect::CARDCONNECT_INJECT_ARGS =
options[launcher::Options::CardConnectArgs].value_text();
}
games::cardconnect::PRINTER_DISABLED =
options[launcher::Options::CardConnectNoPrinter].value_bool();
if (options[launcher::Options::CardConnectPrinterDelay].value_bool()) {
games::cardconnect::PRINTER_SIMULATE_DELAY = true;
}
if (options[launcher::Options::spice2x_EnableSMXStage].value_bool()) {
rawinput::ENABLE_SMX_STAGE = true;
}
@@ -2322,6 +2352,14 @@ int main_implementation(int argc, char *argv[]) {
break;
}
// Card Connect
if (check_dll("kamunity.dll") && fileutils::file_exists("game/tcs.exe")) {
avs::game::DLL_NAME = "kamunity.dll";
attach_io = true;
attach_cardconnect = true;
break;
}
// Busou Shinki: Armored Princess Battle Conductor
if (check_dll("kamunity.dll") && fileutils::file_exists("game/bsac_app.exe")) {
avs::game::DLL_NAME = "kamunity.dll";
@@ -2491,6 +2529,11 @@ int main_implementation(int argc, char *argv[]) {
avs::core::HEAP_SIZE = 1073741824; // 1GB
games.push_back(new games::udn::UDNGame());
}
if (attach_cardconnect) {
show_cursor_if_no_touch = true;
avs::core::set_default_heap_size("kamunity.dll");
games.push_back(new games::cardconnect::CardConnectGame());
}
// apply user heap size, if defined
if (user_heap_size > 0) {
@@ -2667,6 +2710,7 @@ int main_implementation(int argc, char *argv[]) {
// load game
avs::game::load_dll();
hooks::eventlog::init(avs::game::DLL_INSTANCE);
// attach games
for (auto game : games) {
+106
View File
@@ -138,6 +138,7 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.setting_name = "example.com:8083",
.category = "Network",
.quick_setting_category = "Network",
.trim_whitespace = true,
};
c[launcher::Options::PCBID] = {
.title = "PCBID",
@@ -148,6 +149,7 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.category = "Network",
.sensitive = true,
.quick_setting_category = "Network",
.trim_whitespace = true,
};
c[launcher::Options::Player1Card] = {
.title = "Player 1 Card",
@@ -159,6 +161,7 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.sensitive = true,
.picker = OptionPickerType::EACard,
.quick_setting_category = "Network",
.trim_whitespace = true,
};
c[launcher::Options::Player2Card] = {
.title = "Player 2 Card",
@@ -170,6 +173,7 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.sensitive = true,
.picker = OptionPickerType::EACard,
.quick_setting_category = "Network",
.trim_whitespace = true,
};
c[launcher::Options::Player1PinMacro] = {
.title = "Player 1 PIN Macro",
@@ -842,6 +846,21 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.game_name = "Beatmania IIDX",
.category = "Game Overlay",
};
c[launcher::Options::IIDXNoDxva2] = {
.title = "IIDX Disable DXVA2 Decoder",
.name = "iidxnodxva2",
.desc =
"Forcibly disables the DXVA2 decoder, causing the game to use the software decoder instead "
"on some versions of IIDX",
.type = OptionType::Enum,
.game_name = "Beatmania IIDX",
.category = "Advanced Game Options",
.elements = {
{"auto", ""},
{"on", ""},
{"off", ""},
},
};
c[launcher::Options::LoadSoundVoltexModule] = {
.title = "Force Load Sound Voltex Module",
.name = "sdvx",
@@ -1527,6 +1546,14 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.game_name = "Museca",
.category = "Advanced Game Options",
};
c[launcher::Options::LoadCardConnectModule] = {
.title = "Force Load Card Connect Module",
.name = "cardconnect",
.desc = "Manually enable Card Connect module.",
.type = OptionType::Bool,
.game_name = "Card Connect",
.category = "Advanced Game Options",
};
c[launcher::Options::PathToModules] = {
.title = "Modules Folder Override",
.name = "modules",
@@ -2354,6 +2381,15 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
{"all", "basic + HID devices"},
},
};
c[launcher::Options::BCArgs] = {
.title = "BC Arguments Override",
.name = "bcargs",
.desc = "Command line arguments passed to the game.",
.type = OptionType::Text,
.setting_name = "",
.game_name = "Busou Shinki: Armored Princess Battle Conductor",
.category = "Advanced Game Options",
};
c[launcher::Options::QKSArgs] = {
.title = "QKS Arguments Override",
.name = "qksargs",
@@ -2477,6 +2513,75 @@ static const std::vector<OptionDefinition> OPTION_DEFINITIONS = std::invoke([]()
.game_name = "DANCE aROUND",
.category = "Advanced Game Options",
};
c[launcher::Options::CardConnectArgs] = {
.title = "Card Connect Arguments Override",
.name = "cardconnectargs",
.desc = "Command line arguments passed to the game.",
.type = OptionType::Text,
.setting_name = "",
.game_name = "Card Connect",
.category = "Advanced Game Options",
};
c[launcher::Options::CardConnectNoPrinter] = {
.title = "Card Connect Disable Printer Emulation",
.name = "cardconnectnoprinter",
.desc = "Leave the native printer driver unhooked for use with a real printer.",
.type = OptionType::Bool,
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::CardConnectPrinterDelay] = {
.title = "Card Connect Simulate Printer Delay",
.name = "cardconnectprinterdelay",
.desc = "Simulate real printing time: 73 seconds per card, plus hologram and coating delays "
"(up to 99 seconds). Off by default (5 seconds per card).",
.type = OptionType::Bool,
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::CardConnectPrinterOutputPath] = {
.title = "Card Connect Printer Output Path",
.name = "cardconnectprinterpath",
.desc = "Folder for front/back color images. Defaults to the working directory.",
.type = OptionType::Text,
.game_name = "Card Connect",
.category = "Cab Peripherals",
.picker = OptionPickerType::DirectoryPath,
};
c[launcher::Options::CardConnectPrinterOutputClear] = {
.title = "Card Connect Printer Output Clear",
.name = "cardconnectprinterclear",
.desc = "Delete saved front/back images in the output directory on startup.",
.type = OptionType::Bool,
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::CardConnectPrinterOutputOverwrite] = {
.title = "Card Connect Printer Output Overwrite",
.name = "cardconnectprinteroverwrite",
.desc = "Always overwrite the same front/back image pair.",
.type = OptionType::Bool,
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::CardConnectPrinterOutputFormat] = {
.title = "Card Connect Printer Output Format",
.name = "cardconnectprinterformat",
.desc = "File format for printer output. Defaults to PNG.",
.type = OptionType::Text,
.setting_name = "(png/bmp/tga/jpg)",
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::CardConnectPrinterJPGQuality] = {
.title = "Card Connect Printer JPG Quality",
.name = "cardconnectprinterjpgquality",
.desc = "Quality setting in percent if JPG format is used.",
.type = OptionType::Integer,
.setting_name = "(1-100)",
.game_name = "Card Connect",
.category = "Cab Peripherals",
};
c[launcher::Options::spice2x_LightsOverallBrightness] = {
.title = "Lights Brightness Adjustment",
.name = "sp2x-lights-brightness",
@@ -3477,6 +3582,7 @@ std::unique_ptr<std::vector<Option>> launcher::parse_options(int argc, char *arg
// validate it is an integer
try {
auto _ = std::stoull(argv[i], nullptr, 16);
option.value_add(argv[i]);
} catch (const std::exception &ex) {
log_fatal("options", "parameter for -{} is not a hex number: {}", alias, argv[i]);
}
+11
View File
@@ -83,6 +83,7 @@ namespace launcher {
spice2x_IIDXLEDColor,
spice2x_IIDXLEDPos,
IIDXLEDBorderless,
IIDXNoDxva2,
LoadSoundVoltexModule,
SDVXForce720p,
SDVXPrinterEmulation,
@@ -151,6 +152,7 @@ namespace launcher {
LoadMFGModule,
LoadPCModule,
LoadUDNModule,
LoadCardConnectModule,
LoadMusecaModule,
PathToModules,
ScreenshotFolder,
@@ -240,6 +242,7 @@ namespace launcher {
DisableAvsCache,
OutputPEB,
DumpSystemInfo,
BCArgs,
QKSArgs,
CCJArgs,
CCJMouseTrackball,
@@ -253,6 +256,14 @@ namespace launcher {
PCKnobMode,
UDNArgs,
UDNNoIO,
CardConnectArgs,
CardConnectNoPrinter,
CardConnectPrinterDelay,
CardConnectPrinterOutputPath,
CardConnectPrinterOutputClear,
CardConnectPrinterOutputOverwrite,
CardConnectPrinterOutputFormat,
CardConnectPrinterJPGQuality,
spice2x_LightsOverallBrightness,
spice2x_WindowBorder,
spice2x_WindowSize,
+2
View File
@@ -736,6 +736,8 @@ void eamuse_autodetect_game() {
eamuse_set_game("DANCE aROUND");
else if (avs::game::is_model("NDD"))
eamuse_set_game("Silent Scope: Bone Eater");
else if (avs::game::is_model("TCS"))
eamuse_set_game("Card Connect");
else {
log_warning("eamuse", "unknown game model: {}", avs::game::MODEL);
eamuse_set_game("unknown");
+49 -78
View File
@@ -155,7 +155,8 @@ namespace nvapi {
log_misc("nvapi", "NVAPI module initialized");
}
NvAPI_Status create_profile_if_needed(NvDRSSessionHandle h_session, NvDRSProfileHandle *h_profile) {
static NvAPI_Status create_profile_if_needed(NvDRSSessionHandle h_session,
NvDRSProfileHandle *h_profile, bool &changed) {
NvAPI_UnicodeString app_name;
#ifdef SPICE64
memcpy_s(app_name, sizeof(app_name), L"spice64.exe", 12 * sizeof(wchar_t));
@@ -203,57 +204,38 @@ namespace nvapi {
return status;
}
changed = true;
return NVAPI_OK;
}
NvAPI_Status set_gpu_power_state(NvDRSSessionHandle h_session, NvDRSProfileHandle h_profile) {
auto drs_setting = NVDRS_SETTING {};
drs_setting.version = NVDRS_SETTING_VER;
drs_setting.settingId = PREFERRED_PSTATE_ID;
drs_setting.settingType = NVDRS_DWORD_TYPE;
drs_setting.u32PredefinedValue = PREFERRED_PSTATE_PREFER_MAX;
drs_setting.u32CurrentValue = PREFERRED_PSTATE_PREFER_MAX;
return NvAPI_DRS_SetSetting(h_session, h_profile, &drs_setting);
}
static void apply_dword_setting(NvDRSSessionHandle session, NvDRSProfileHandle profile,
NvU32 id, NvU32 value, const char *name, bool &changed) {
NVDRS_SETTING setting {};
setting.version = NVDRS_SETTING_VER;
auto status = NvAPI_DRS_GetSetting(session, profile, id, &setting);
if (status == NVAPI_OK) {
// an inherited or predefined value is not an explicit application override
if (setting.settingLocation == NVDRS_CURRENT_PROFILE_LOCATION &&
!setting.isCurrentPredefined && setting.settingType == NVDRS_DWORD_TYPE &&
setting.u32CurrentValue == value) {
return;
}
} else if (status != NVAPI_SETTING_NOT_FOUND) {
log_warning("nvapi", "could not read {}: {}", name, get_error_message(status));
}
NvAPI_Status set_gsync_mode(NvDRSSessionHandle h_session, NvDRSProfileHandle h_profile) {
auto drs_setting = NVDRS_SETTING {};
drs_setting.version = NVDRS_SETTING_VER;
drs_setting.settingId = VRR_APP_OVERRIDE_ID;
drs_setting.settingType = NVDRS_DWORD_TYPE;
drs_setting.u32PredefinedValue = VRR_APP_OVERRIDE_FIXED_REFRESH;
drs_setting.u32CurrentValue = VRR_APP_OVERRIDE_FIXED_REFRESH;
return NvAPI_DRS_SetSetting(h_session, h_profile, &drs_setting);
}
NvAPI_Status set_vsync_mode(NvDRSSessionHandle h_session, NvDRSProfileHandle h_profile) {
auto drs_setting = NVDRS_SETTING {};
drs_setting.version = NVDRS_SETTING_VER;
drs_setting.settingId = VSYNCMODE_ID;
drs_setting.settingType = NVDRS_DWORD_TYPE;
drs_setting.u32PredefinedValue = VSYNCMODE_PASSIVE;
drs_setting.u32CurrentValue = VSYNCMODE_PASSIVE;
return NvAPI_DRS_SetSetting(h_session, h_profile, &drs_setting);
}
NvAPI_Status set_refresh_rate(NvDRSSessionHandle h_session, NvDRSProfileHandle h_profile) {
auto drs_setting = NVDRS_SETTING {};
drs_setting.version = NVDRS_SETTING_VER;
drs_setting.settingId = REFRESH_RATE_OVERRIDE_ID;
drs_setting.settingType = NVDRS_DWORD_TYPE;
drs_setting.u32PredefinedValue = REFRESH_RATE_OVERRIDE_APPLICATION_CONTROLLED;
drs_setting.u32CurrentValue = REFRESH_RATE_OVERRIDE_APPLICATION_CONTROLLED;
return NvAPI_DRS_SetSetting(h_session, h_profile, &drs_setting);
}
NvAPI_Status set_max_fps(NvDRSSessionHandle h_session, NvDRSProfileHandle h_profile) {
auto drs_setting = NVDRS_SETTING {};
drs_setting.version = NVDRS_SETTING_VER;
drs_setting.settingId = FRL_FPS_ID;
drs_setting.settingType = NVDRS_DWORD_TYPE;
drs_setting.u32PredefinedValue = FRL_FPS_DISABLED;
drs_setting.u32CurrentValue = FRL_FPS_DISABLED;
return NvAPI_DRS_SetSetting(h_session, h_profile, &drs_setting);
setting = {};
setting.version = NVDRS_SETTING_VER;
setting.settingId = id;
setting.settingType = NVDRS_DWORD_TYPE;
setting.u32PredefinedValue = value;
setting.u32CurrentValue = value;
status = NvAPI_DRS_SetSetting(session, profile, &setting);
if (status == NVAPI_OK) {
changed = true;
} else {
log_warning("nvapi", "could not set {}: {}", name, get_error_message(status));
}
}
void set_profile_settings() {
@@ -278,41 +260,30 @@ namespace nvapi {
NvDRSProfileHandle h_profile = nullptr;
log_info("nvapi", "creating NVIDIA profile for spice(64).exe...");
if (create_profile_if_needed(h_session, &h_profile) != NVAPI_OK) {
bool changed = false;
if (create_profile_if_needed(h_session, &h_profile, changed) != NVAPI_OK) {
NvAPI_DRS_DestroySession(h_session);
return;
}
log_info("nvapi", "setting VSync to Application Controlled...");
if ((status = set_vsync_mode(h_session, h_profile)) != NVAPI_OK) {
log_warning("nvapi", "could not set VSync mode: {}", get_error_message(status));
}
apply_dword_setting(h_session, h_profile, VSYNCMODE_ID, VSYNCMODE_PASSIVE,
"VSync mode", changed);
apply_dword_setting(h_session, h_profile, PREFERRED_PSTATE_ID, PREFERRED_PSTATE_PREFER_MAX,
"preferred PState", changed);
apply_dword_setting(h_session, h_profile, VRR_APP_OVERRIDE_ID, VRR_APP_OVERRIDE_FIXED_REFRESH,
"G-SYNC mode", changed);
apply_dword_setting(h_session, h_profile, REFRESH_RATE_OVERRIDE_ID,
REFRESH_RATE_OVERRIDE_APPLICATION_CONTROLLED, "preferred refresh rate", changed);
apply_dword_setting(h_session, h_profile, FRL_FPS_ID, FRL_FPS_DISABLED,
"max framerate", changed);
log_info("nvapi", "applying preferred PState to Maximum Performance...");
if ((status = set_gpu_power_state(h_session, h_profile)) != NVAPI_OK) {
log_warning("nvapi", "could not set preferred PState: {}", get_error_message(status));
}
log_info("nvapi", "disabling G-SYNC...");
if ((status = set_gsync_mode(h_session, h_profile)) != NVAPI_OK) {
log_warning("nvapi", "could not set G-Sync mode: {}", get_error_message(status));
}
log_info("nvapi", "setting preferred refresh rate to Application Controlled...");
if ((status = set_refresh_rate(h_session, h_profile)) != NVAPI_OK) {
log_warning("nvapi", "could not set preferred refresh rate: {}", get_error_message(status));
}
log_info("nvapi", "disabling max framerate...");
if ((status = set_max_fps(h_session, h_profile)) != NVAPI_OK) {
log_warning("nvapi", "could not disable max framerate: {}", get_error_message(status));
}
log_info("nvapi", "saving settings for DRS session...");
if ((status = NvAPI_DRS_SaveSettings(h_session)) != NVAPI_OK) {
log_warning("nvapi", "could not save driver settings: {}", get_error_message(status));
NvAPI_DRS_DestroySession(h_session);
return;
if (changed) {
log_info("nvapi", "saving settings for DRS session...");
if ((status = NvAPI_DRS_SaveSettings(h_session)) != NVAPI_OK) {
log_warning("nvapi", "could not save driver settings: {}", get_error_message(status));
}
} else {
log_misc("nvapi", "no driver profile changes to save");
}
log_info("nvapi", "destroying DRS session...");
+10 -3
View File
@@ -5282,9 +5282,16 @@ namespace overlay::windows {
ImGui::InputTextWithHint("", hint, buffer, sizeof(buffer) - 1);
// would like to use IsItemDeactivatedAfterEdit but can't handle the case when window is closed while editing
if (ImGui::IsItemEdited()) {
this->options_dirty = true;
option.value = buffer;
::Config::getInstance().updateBinding(games_list[games_selected], option);
// trim whitespace to prevent copy/paste errors
auto value = definition.trim_whitespace ?
strtrim(buffer) : std::string(buffer);
if (option.value != value) {
this->options_dirty = true;
option.value = std::move(value);
::Config::getInstance().updateBinding(games_list[games_selected], option);
}
}
if (ImGui::IsItemHovered(ImGui::TOOLTIP_FLAGS)) {
ImGui::HelpTooltip(definition.desc.c_str());
+135 -51
View File
@@ -1,3 +1,6 @@
#include <algorithm>
#include <climits>
#include <games/io.h>
#include "screen_resize.h"
@@ -55,15 +58,10 @@ namespace overlay::windows {
cfg::SCREENRESIZE->enable_screen_resize = false;
cfg::SCREENRESIZE->screen_resize_current_scene = 0;
cfg::SCREENRESIZE->enable_linear_filter = true;
for (size_t i = 0; i < std::size(cfg::SCREENRESIZE->scene_settings); i++) {
auto& scene = cfg::SCREENRESIZE->scene_settings[i];
scene.keep_aspect_ratio = true;
scene.offset_x = 0;
scene.offset_y = 0;
scene.scale_x = 1.f;
scene.scale_y = 1.f;
scene.duplicate = cfg::ScreenDuplicateMode::None;
for (auto &scene : cfg::SCREENRESIZE->scene_settings) {
scene = {};
}
cfg::SCREENRESIZE->need_surface_clean = true;
cfg::SCREENRESIZE->enable_window_resize = false;
cfg::SCREENRESIZE->window_always_on_top = false;
@@ -101,6 +99,78 @@ namespace overlay::windows {
build_footer();
}
static bool split_scale_slider(const char *label, float &scale) {
return ImGui::SliderFloat(
label, &scale, cfg::split_region_setting::min_scale,
cfg::split_region_setting::max_scale, "%.3f", ImGuiSliderFlags_AlwaysClamp);
}
static void build_split_region_config(const char *label, cfg::split_region_setting &region) {
if (!ImGui::TreeNodeEx(label, ImGuiTreeNodeFlags_DefaultOpen)) {
return;
}
ImGui::InputInt("X Offset", &region.offset_x);
ImGui::InputInt("Y Offset", &region.offset_y);
if (ImGui::Checkbox("Keep Aspect Ratio", &region.keep_aspect_ratio) &&
region.keep_aspect_ratio) {
region.scale_y = region.scale_x;
}
if (region.keep_aspect_ratio) {
if (split_scale_slider("Scale", region.scale_x)) {
region.scale_y = region.scale_x;
}
} else {
split_scale_slider("Width Scale", region.scale_x);
split_scale_slider("Height Scale", region.scale_y);
}
ImGui::TreePop();
}
static cfg::split_region_setting mirror_split_region(cfg::split_region_setting region) {
region.offset_x = static_cast<int>(
std::min<int64_t>(-static_cast<int64_t>(region.offset_x), INT_MAX));
return region;
}
static void build_split_config(cfg::split_screen_setting &split) {
float divider = split.swap_sides ? 1.0f - split.ratio : split.ratio;
if (ImGui::SliderFloat(
"Split Position", &divider, cfg::split_screen_setting::min_ratio,
cfg::split_screen_setting::max_ratio, "%.2f", ImGuiSliderFlags_AlwaysClamp)) {
split.ratio = split.swap_sides ? 1.0f - divider : divider;
}
ImGui::SameLine();
ImGui::HelpMarker("Position of the divider from the left edge (0.50 = center).");
ImGui::Checkbox("Swap Sides", &split.swap_sides);
ImGui::SameLine();
ImGui::HelpMarker("Swap the playfields without changing their widths, zoom, or offsets.");
if (ImGui::Button("Mirror 1P -> 2P")) {
split.right = mirror_split_region(split.left);
}
ImGui::SameLine();
if (ImGui::Button("Mirror 2P -> 1P")) {
split.left = mirror_split_region(split.right);
}
ImGui::SameLine();
if (ImGui::Button("Reset Split")) {
split = {};
split.enabled = true;
}
ImGui::SameLine();
ImGui::HelpMarker("Mirror copies zoom and offsets, but reverses the X offset.");
build_split_region_config(split.swap_sides
? "1P Playfield (Displayed Right)###split_left"
: "1P Playfield (Left)###split_left", split.left);
build_split_region_config(split.swap_sides
? "2P Playfield (Displayed Left)###split_right"
: "2P Playfield (Right)###split_right", split.right);
}
void ScreenResize::build_fullscreen_config() {
ImGui::TextColored(ImVec4(1, 0.5f, 0.5f, 1.f),
@@ -138,53 +208,67 @@ namespace overlay::windows {
auto& scene = cfg::SCREENRESIZE->scene_settings[cfg::SCREENRESIZE->screen_resize_current_scene];
// general settings
ImGui::InputInt("X Offset", &scene.offset_x);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on +/- buttons to move quickly.");
ImGui::InputInt("Y Offset", &scene.offset_y);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on +/- buttons to move quickly.");
// aspect ratio
ImGui::Checkbox("Keep Aspect Ratio", &scene.keep_aspect_ratio);
if (scene.keep_aspect_ratio) {
// we want to avoid zooming out below 0.6 as it will cause StretchRect calls to
// go on a slow sync path with the GPU, leading to frame drops in some situations
// (e.g., SDVX Live2D)
if (ImGui::SliderFloat("Scale", &scene.scale_x, 0.6f, 2.5f)) {
scene.scale_y = scene.scale_x;
}
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
} else {
ImGui::SliderFloat("Width Scale", &scene.scale_x, 0.6f, 2.5f);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
ImGui::SliderFloat("Height Scale", &scene.scale_y, 0.6f, 2.5f);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
}
static const char* dupe_items[] = { "None", "Copy Left", "Copy Right" };
const bool duplicate_changed = ImGui::Combo(
"Duplicate",
reinterpret_cast<int *>(&scene.duplicate),
dupe_items,
ARRAYSIZE(dupe_items));
const bool split_changed =
ImGui::Checkbox("Split Screen (Dual Playfield)", &scene.split.enabled);
ImGui::SameLine();
ImGui::HelpMarker(
"Show an identical copy of the image on the left or right, allowing you to achieve "
"wrap-around effect when an offset is set.");
ImGui::EndDisabled();
// tell d3d9 device to clear surface to get rid of ghost image
if (duplicate_changed) {
"Split the screen into independent Left (1P) and Right (2P) zoom viewports, "
"allowing separate zoom and offset per playfield (e.g. Battle mode).");
if (split_changed) {
cfg::SCREENRESIZE->need_surface_clean = true;
}
if (scene.split.enabled) {
build_split_config(scene.split);
} else {
// general settings
ImGui::InputInt("X Offset", &scene.offset_x);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on +/- buttons to move quickly.");
ImGui::InputInt("Y Offset", &scene.offset_y);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on +/- buttons to move quickly.");
// aspect ratio
ImGui::Checkbox("Keep Aspect Ratio", &scene.keep_aspect_ratio);
if (scene.keep_aspect_ratio) {
// we want to avoid zooming out below 0.6 as it will cause StretchRect calls to
// go on a slow sync path with the GPU, leading to frame drops in some situations
// (e.g., SDVX Live2D)
if (ImGui::SliderFloat("Scale", &scene.scale_x, 0.6f, 2.5f)) {
scene.scale_y = scene.scale_x;
}
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
} else {
ImGui::SliderFloat("Width Scale", &scene.scale_x, 0.6f, 2.5f);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
ImGui::SliderFloat("Height Scale", &scene.scale_y, 0.6f, 2.5f);
ImGui::SameLine();
ImGui::HelpMarker("Hint: ctrl + click on the slider to type in a numeric value.");
}
static const char* dupe_items[] = { "None", "Copy Left", "Copy Right" };
const bool duplicate_changed = ImGui::Combo(
"Duplicate",
reinterpret_cast<int *>(&scene.duplicate),
dupe_items,
ARRAYSIZE(dupe_items));
ImGui::SameLine();
ImGui::HelpMarker(
"Show an identical copy of the image on the left or right, allowing you to achieve "
"wrap-around effect when an offset is set.");
// tell d3d9 device to clear surface to get rid of ghost image
if (duplicate_changed) {
cfg::SCREENRESIZE->need_surface_clean = true;
}
}
ImGui::EndDisabled();
}
void ScreenResize::build_windowed_config() {
+8 -9
View File
@@ -275,7 +275,6 @@ void rawinput::RawInputManager::devices_scan_rawinput(RAWINPUTDEVICELIST *device
// extract information out of name
auto device_info = rawinput::RawInputManager::get_device_info(device_name);
auto device_description = rawinput::RawInputManager::rawinput_get_device_description(device_info, device_name);
// get device information
RID_DEVICE_INFO rawinput_device_info {};
@@ -301,15 +300,16 @@ void rawinput::RawInputManager::devices_scan_rawinput(RAWINPUTDEVICELIST *device
new_device.id = unique_id;
new_device.handle = device->hDevice;
new_device.name = device_name;
new_device.desc = device_description;
new_device.info = device_info;
new_device.input_time = get_performance_seconds();
switch (device->dwType) {
case RIM_TYPEMOUSE:
new_device.desc = rawinput_get_device_description(device_info, device_name);
new_device.type = MOUSE;
new_device.mouseInfo = new DeviceMouseInfo();
break;
case RIM_TYPEKEYBOARD:
new_device.desc = rawinput_get_device_description(device_info, device_name);
new_device.type = KEYBOARD;
new_device.keyboardInfo = new DeviceKeyboardInfo();
break;
@@ -402,13 +402,6 @@ void rawinput::RawInputManager::devices_scan_rawinput(RAWINPUTDEVICELIST *device
prod_ws = wchar_to_u8(prod_str_buffer);
}
// For Bluetooth LE HID devices (e.g., newer Xbox controllers) HidD_GetProductString
// and HidD_GetManufacturerString will return blank strings.
// https://docs.microsoft.com/en-us/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html
if (man_ws.empty() && prod_ws.empty()) {
prod_ws = device_description;
}
// build desc string
std::string desc_ws;
if (string_begins_with(prod_ws, man_ws)) {
@@ -427,6 +420,12 @@ void rawinput::RawInputManager::devices_scan_rawinput(RAWINPUTDEVICELIST *device
log_warning("rawinput", "failed to get HID device attributes for {}", device_name);
}
}
// For Bluetooth LE HID devices (e.g., newer Xbox controllers) HidD_GetProductString
// and HidD_GetManufacturerString will return blank strings.
// https://docs.microsoft.com/en-us/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html
if (new_device.desc.empty()) {
new_device.desc = rawinput_get_device_description(device_info, device_name);
}
// get button caps
USHORT button_cap_length = caps.NumberInputButtonCaps;
@@ -7,6 +7,7 @@
#include "settings.h"
#include "transform.h"
#include "hooks/graphics/graphics.h"
#include "touch/touch.h"
#include "util/logging.h"
@@ -141,6 +142,13 @@ namespace nativetouch::inject {
end_mouse_contact(window);
}
// SDVX accepts both mouse and touch on its windowed subscreen, causing duplicate input.
if (GRAPHICS_WINDOWED &&
window == SDVX_SUBSCREEN_WINDOW &&
message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) {
return true;
}
return false;
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ namespace execexe {
static HANDLE WINAPI execexe_CreateFileW_hook(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
if (lpFileName == port_name && acio->open(lpFileName)) {
if (lpFileName == port_name) {
if (!port_opened) {
port_opened = acio->open(port_name.c_str());
} else {