From e91de54badf6394eae50f4c8bf6a0a7294abb0ba Mon Sep 17 00:00:00 2001 From: shen Date: Sat, 12 Sep 2026 13:40:19 +0800 Subject: [PATCH] feat: implement M4 controller input foundation --- README.md | 5 +- THIRD_PARTY_NOTICES.md | 3 +- app/build.gradle.kts | 5 +- app/src/main/cpp/core_session.cpp | 40 +- app/src/main/cpp/core_session.h | 1 + app/src/main/cpp/jni_bridge.cpp | 5 + app/src/main/cpp/session_rules.cpp | 7 + app/src/main/cpp/session_rules.h | 1 + app/src/main/cpp/tests/native_smoke_test.cpp | 15 + .../main/java/org/neslite/app/MainActivity.kt | 580 ++++++++++++++++-- .../main/java/org/neslite/app/NativeBridge.kt | 4 +- .../neslite/app/input/ControllerProfile.kt | 124 ++++ .../app/input/ControllerProfileJson.kt | 55 ++ .../app/input/ControllerProfileStore.kt | 42 ++ .../java/org/neslite/app/input/InputRouter.kt | 121 ++++ .../java/org/neslite/app/BuildIdentityTest.kt | 4 +- .../app/input/ControllerProfileTest.kt | 57 ++ .../org/neslite/app/input/InputRouterTest.kt | 88 +++ docs/architecture.md | 22 +- docs/build.md | 6 +- docs/controller-x5lite.md | 12 +- docs/dependencies.md | 2 +- docs/identity.md | 2 +- docs/reports/m4-controller.md | 42 ++ docs/toolchain.md | 2 +- todo.md | 5 + 26 files changed, 1172 insertions(+), 78 deletions(-) create mode 100644 app/src/main/java/org/neslite/app/input/ControllerProfile.kt create mode 100644 app/src/main/java/org/neslite/app/input/ControllerProfileJson.kt create mode 100644 app/src/main/java/org/neslite/app/input/ControllerProfileStore.kt create mode 100644 app/src/main/java/org/neslite/app/input/InputRouter.kt create mode 100644 app/src/test/java/org/neslite/app/input/ControllerProfileTest.kt create mode 100644 app/src/test/java/org/neslite/app/input/InputRouterTest.kt create mode 100644 docs/reports/m4-controller.md diff --git a/README.md b/README.md index e5494f7..9c17bfd 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ # NESLite NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。它使用固定版本的 -FCEUmm libretro 内核。当前仓库已完成 M3 的隔离实现和本地验证,包括 Oboe 输出、重采样、 -音频焦点/路由恢复和 2× 快进;由于前序真机门槛尚未通过,M2/G2 与 M3/G3 的实机验收仍待补齐。 +FCEUmm libretro 内核。当前仓库已完成 M4 的隔离实现和本地验证,包括通用手柄映射、自定义绑定、 +输入来源合成、死区、连发、暂停菜单和档案持久化;由于前序真机门槛尚未通过,M2~M4 的实机 +验收仍待补齐。 ## 快速构建 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index eba602e..256370a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -10,6 +10,7 @@ | AndroidX Core KTX | `androidx.core:core-ktx:1.17.0` | Apache-2.0 | 分发时保留许可和 NOTICE(如上游提供)。 | | AndroidX Activity KTX | `androidx.activity:activity-ktx:1.12.0` | Apache-2.0 | 分发时保留许可和 NOTICE(如上游提供)。 | | Room | `androidx.room:room-runtime/room-ktx:2.7.2` | Apache-2.0 | 分发时保留许可和 NOTICE(如上游提供)。 | +| DataStore Preferences | `androidx.datastore:datastore-preferences:1.1.7` | Apache-2.0 | 分发时保留许可和 NOTICE(如上游提供)。 | | FCEUmm | `236ccdfc911e84c60fea6b9d0699c2d440a8de14` | GPL-2.0-only | 对应完整源码、GPL v2 文本、原始版权/Authors、所有补丁和获取说明。 | | libretro.h | `0c9622896333ee62dc4326bbe8784a210ddeb03c` | MIT | 原始版权和 MIT 许可文本。 | | Oboe | 1.10.0 / `a81bb9f87d4105b84b682685d3bfbb5beca371d1` | Apache-2.0 | Apache 2.0 文本及上游 NOTICE(如有)。 | @@ -18,7 +19,7 @@ | 组件 | 固定来源 | 许可证 | 发布时的必需材料 | | --- | --- | --- | --- | -| DataStore | 1.1.7 | Apache-2.0 | 实际引入时保留许可/NOTICE。 | +| (无) | — | — | 当前锁定的生产依赖均已按阶段引入。 | 测试依赖 JUnit 4.13.2(EPL-1.0)和 AndroidX Test/Espresso(Apache-2.0)不打入生产 APK, 但随测试源码分发时仍需保留其各自的许可证信息。 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e3d84bb..504c2d7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "org.neslite.app" minSdk = 28 targetSdk = 36 - versionCode = 3004 - versionName = "0.3.4" + versionCode = 4004 + versionName = "0.4.4" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { @@ -73,6 +73,7 @@ dependencies { implementation(libs.androidx.activity.ktx) implementation(libs.androidx.room.runtime) implementation(libs.androidx.room.ktx) + implementation(libs.androidx.datastore.preferences) annotationProcessor(libs.androidx.room.compiler) testImplementation(libs.junit) diff --git a/app/src/main/cpp/core_session.cpp b/app/src/main/cpp/core_session.cpp index 80e568d..71dc0ff 100644 --- a/app/src/main/cpp/core_session.cpp +++ b/app/src/main/cpp/core_session.cpp @@ -70,6 +70,8 @@ struct Host { std::deque commands; std::thread worker; std::atomic joypad{0}; + std::atomic turbo{0}; + std::atomic effective_joypad{0}; std::atomic issued_session{0}; std::atomic state{SessionState::Idle}; std::atomic session_id{0}; @@ -93,6 +95,8 @@ struct Host { TimingMetrics timing; std::atomic fast_forward{false}; std::atomic audio_target_frames{800}; + double turbo_simulated_seconds = 0.0; + std::uint16_t previous_turbo_mask = 0; Host() : worker([this] { run(); }) {} ~Host() { @@ -209,6 +213,10 @@ struct Host { } rom.clear(); joypad.store(0, std::memory_order_relaxed); + turbo.store(0, std::memory_order_relaxed); + effective_joypad.store(0, std::memory_order_relaxed); + turbo_simulated_seconds = 0.0; + previous_turbo_mask = 0; return battery_saved; } @@ -309,6 +317,10 @@ struct Host { complete(active_id, command.name == "mute:on" ? "muted" : "unmuted"); } else if (command.name == "audio_rebuild" && loaded) { set_state(SessionState::Pausing); + turbo.store(0, std::memory_order_relaxed); + effective_joypad.store(0, std::memory_order_relaxed); + turbo_simulated_seconds = 0.0; + previous_turbo_mask = 0; timing.transition(TimingMode::Paused, monotonic_now_ns()); fast_forward = false; audio.set_fast_muted(false); @@ -349,6 +361,10 @@ struct Host { complete(active_id, "running"); } else if (command.name == "pause" && loaded && command_allowed(state.load(), command.name)) { set_state(SessionState::Pausing); + turbo.store(0, std::memory_order_relaxed); + effective_joypad.store(0, std::memory_order_relaxed); + turbo_simulated_seconds = 0.0; + previous_turbo_mask = 0; fast_forward = false; audio.set_fast_muted(false); audio.stop(); @@ -406,9 +422,22 @@ struct Host { next_frame = clock::now(); continue; } + const double fps = std::clamp(av.timing.fps, 10.0, 240.0); + const std::uint16_t requested_turbo = turbo.load(std::memory_order_relaxed); + if (requested_turbo == 0) { + turbo_simulated_seconds = 0.0; + } else if (previous_turbo_mask == 0) { + turbo_simulated_seconds = 0.0; + } + const bool turbo_on = requested_turbo != 0 && turbo_gate(turbo_simulated_seconds); + effective_joypad.store( + static_cast(joypad.load(std::memory_order_relaxed) | + (turbo_on ? requested_turbo : 0)), + std::memory_order_relaxed); + previous_turbo_mask = requested_turbo; const auto work_started = clock::now(); retro_run(); - const double fps = std::clamp(av.timing.fps, 10.0, 240.0); + if (requested_turbo != 0) turbo_simulated_seconds += 1.0 / fps; timing.record_frame(1.0 / fps, std::chrono::duration_cast( clock::now() - work_started).count()); const std::size_t target = audio_target_frames.load(); @@ -537,7 +566,7 @@ struct Host { static void input_poll_callback() {} static std::int16_t input_state_callback(unsigned port, unsigned device, unsigned, unsigned id) { if (port != 0 || device != RETRO_DEVICE_JOYPAD) return 0; - const std::uint16_t mask = instance().joypad.load(std::memory_order_relaxed); + const std::uint16_t mask = instance().effective_joypad.load(std::memory_order_relaxed); if (id == RETRO_DEVICE_ID_JOYPAD_MASK) return static_cast(mask); return id < 16U && (mask & (1U << id)) != 0U ? 1 : 0; } @@ -575,6 +604,10 @@ void set_joypad_mask(std::uint16_t mask) { Host::instance().joypad.store(mask, std::memory_order_relaxed); } +void set_turbo_mask(std::uint16_t mask) { + Host::instance().turbo.store(mask, std::memory_order_relaxed); +} + std::string session_status_json() { Host& host = Host::instance(); std::lock_guard lock(host.mutex); @@ -588,6 +621,9 @@ std::string session_status_json() { << ",\"completion\":\"" << json_escape(host.completion) << "\",\"error\":\"" << json_escape(host.error) << "\",\"fastForward\":" << (host.fast_forward.load() ? "true" : "false") + << ",\"input\":{\"baseMask\":" << host.joypad.load(std::memory_order_relaxed) + << ",\"turboMask\":" << host.turbo.load(std::memory_order_relaxed) + << ",\"effectiveMask\":" << host.effective_joypad.load(std::memory_order_relaxed) << "}" << ",\"audio\":{\"open\":" << (audio.open ? "true" : "false") << ",\"active\":" << (audio.active ? "true" : "false") << ",\"muted\":" << (audio.muted ? "true" : "false") diff --git a/app/src/main/cpp/core_session.h b/app/src/main/cpp/core_session.h index 08e97f5..270cedb 100644 --- a/app/src/main/cpp/core_session.h +++ b/app/src/main/cpp/core_session.h @@ -15,6 +15,7 @@ std::uint64_t load_rom(const std::string& rom_path, const std::string& rom_hash); bool session_command(std::uint64_t session_id, const std::string& command); void set_joypad_mask(std::uint16_t mask); +void set_turbo_mask(std::uint16_t mask); std::string session_status_json(); bool latest_video_frame(VideoFrame* frame); diff --git a/app/src/main/cpp/jni_bridge.cpp b/app/src/main/cpp/jni_bridge.cpp index 25e40b1..2c3daba 100644 --- a/app/src/main/cpp/jni_bridge.cpp +++ b/app/src/main/cpp/jni_bridge.cpp @@ -60,6 +60,11 @@ Java_org_neslite_app_NativeBridge_setJoypadMask(JNIEnv*, jclass, jint mask) { neslite::set_joypad_mask(static_cast(mask)); } +extern "C" JNIEXPORT void JNICALL +Java_org_neslite_app_NativeBridge_setTurboMask(JNIEnv*, jclass, jint mask) { + neslite::set_turbo_mask(static_cast(mask)); +} + extern "C" JNIEXPORT jstring JNICALL Java_org_neslite_app_NativeBridge_sessionStatus(JNIEnv* env, jclass) { const std::string status = neslite::session_status_json(); diff --git a/app/src/main/cpp/session_rules.cpp b/app/src/main/cpp/session_rules.cpp index 478a74e..0073e6f 100644 --- a/app/src/main/cpp/session_rules.cpp +++ b/app/src/main/cpp/session_rules.cpp @@ -1,6 +1,7 @@ #include "session_rules.h" #include +#include namespace neslite { @@ -46,4 +47,10 @@ double scheduler_period_scale(std::size_t buffer_level, std::size_t target_level return 1.0 + std::clamp(normalized_error * 0.01, -0.02, 0.02); } +bool turbo_gate(double simulated_seconds, double pulses_per_second) { + if (!std::isfinite(simulated_seconds) || !std::isfinite(pulses_per_second) || + simulated_seconds < 0.0 || pulses_per_second <= 0.0) return false; + return std::fmod(simulated_seconds * pulses_per_second, 1.0) < 0.5; +} + } // namespace neslite diff --git a/app/src/main/cpp/session_rules.h b/app/src/main/cpp/session_rules.h index 0b22e2c..20741dd 100644 --- a/app/src/main/cpp/session_rules.h +++ b/app/src/main/cpp/session_rules.h @@ -15,5 +15,6 @@ bool required_host_capabilities_available(unsigned core_api_version, unsigned ex bool directories_available); double scheduler_period_scale(std::size_t buffer_level, std::size_t target_level, bool audio_active, bool fast_forward); +bool turbo_gate(double simulated_seconds, double pulses_per_second = 15.0); } // namespace neslite diff --git a/app/src/main/cpp/tests/native_smoke_test.cpp b/app/src/main/cpp/tests/native_smoke_test.cpp index 5900325..12e77f9 100644 --- a/app/src/main/cpp/tests/native_smoke_test.cpp +++ b/app/src/main/cpp/tests/native_smoke_test.cpp @@ -84,5 +84,20 @@ int main() { if (neslite::scheduler_period_scale(0, 100, true, false) >= 1.0) return 36; if (neslite::scheduler_period_scale(200, 100, true, false) <= 1.0) return 37; if (std::abs(neslite::scheduler_period_scale(100, 100, true, true) - 0.5) > 0.0001) return 38; + int ntsc_pulses = 0; + int pal_pulses = 0; + bool previous_ntsc = false; + bool previous_pal = false; + for (int frame_index = 0; frame_index < 60; ++frame_index) { + const bool gate = neslite::turbo_gate(static_cast(frame_index) / 60.0); + if (gate && !previous_ntsc) ++ntsc_pulses; + previous_ntsc = gate; + } + for (int frame_index = 0; frame_index < 50; ++frame_index) { + const bool gate = neslite::turbo_gate(static_cast(frame_index) / 50.0); + if (gate && !previous_pal) ++pal_pulses; + previous_pal = gate; + } + if (ntsc_pulses != 15 || pal_pulses != 15 || neslite::turbo_gate(-1.0)) return 40; return 0; } diff --git a/app/src/main/java/org/neslite/app/MainActivity.kt b/app/src/main/java/org/neslite/app/MainActivity.kt index af3447f..3baa591 100644 --- a/app/src/main/java/org/neslite/app/MainActivity.kt +++ b/app/src/main/java/org/neslite/app/MainActivity.kt @@ -24,8 +24,14 @@ import android.widget.ScrollView import android.widget.SeekBar import android.widget.TextView import android.widget.Toast +import android.app.AlertDialog import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch import org.json.JSONArray import org.json.JSONObject import org.neslite.app.diagnostics.ControllerSnapshot @@ -37,6 +43,20 @@ import org.neslite.app.library.GameDatabase import org.neslite.app.library.GameEntity import org.neslite.app.library.LibraryRecovery import org.neslite.app.library.RomImporter +import org.neslite.app.input.AxisHysteresis +import org.neslite.app.input.BindingKind +import org.neslite.app.input.ControllerIdentity +import org.neslite.app.input.ControllerProfile +import org.neslite.app.input.ControllerProfileJson +import org.neslite.app.input.ControllerProfileResolver +import org.neslite.app.input.ControllerProfileStore +import org.neslite.app.input.GameAction +import org.neslite.app.input.InputBinding +import org.neslite.app.input.InputRouter +import org.neslite.app.input.InputSource +import org.neslite.app.input.InputSourceKind +import org.neslite.app.input.ProfileOrigin +import org.neslite.app.input.RoutedInputState import java.io.File import java.text.SimpleDateFormat import java.util.Date @@ -54,18 +74,34 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private lateinit var eventText: TextView private var controllers: List = emptyList() private val libraryExecutor = Executors.newSingleThreadExecutor() + private val controllerScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val mainHandler = Handler(Looper.getMainLooper()) private lateinit var database: GameDatabase private lateinit var gameList: LinearLayout private lateinit var emulatorSurface: EmulatorSurface private lateinit var emulatorStatus: TextView private lateinit var audioStatus: TextView + private lateinit var pauseMenu: LinearLayout + private lateinit var controllerSettingsPanel: LinearLayout private lateinit var audioManager: AudioManager private lateinit var audioFocusRequest: AudioFocusRequest private var activeSessionId = 0L private var joypadMask = 0 private var muted = false private var audioDeviceCallbackRegistered = false + private var lastSessionState = "Idle" + private val inputRouter = InputRouter() + private val axisHysteresis = AxisHysteresis() + private val profileResolver = ControllerProfileResolver() + private lateinit var profileStore: ControllerProfileStore + private val controllerProfiles = mutableMapOf() + private val controllerIdentities = mutableMapOf() + private val controllerProfileRevisions = mutableMapOf() + private var selectedControllerId: Int? = null + private var draftProfile: ControllerProfile? = null + private var pendingBindingAction: GameAction? = null + private var controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。" + private var settingsReturnToPause = false private val audioFocusListener = AudioManager.OnAudioFocusChangeListener { focusChange -> if (focusChange != AudioManager.AUDIOFOCUS_GAIN) { @@ -104,6 +140,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { nativeProbe = probeNative() baseline = DeviceDiagnostics.collectBaseline(this, nativeProbe.pageSizeBytes) database = GameDatabase.get(this) + profileStore = ControllerProfileStore(this, profileResolver) activeSessionId = savedInstanceState?.getLong(STATE_SESSION_ID) ?: 0L setContentView(createContentView()) refreshControllers() @@ -127,8 +164,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { audioManager.unregisterAudioDeviceCallback(audioDeviceCallback) audioDeviceCallbackRegistered = false } - NativeBridge.setJoypadMask(0) - joypadMask = 0 + clearControllerState() if (::emulatorSurface.isInitialized) emulatorSurface.onPause() inputDiagnostics.clearAll("activity_stopped", SystemClock.uptimeMillis()) inputManager.unregisterInputDeviceListener(this) @@ -138,6 +174,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onDestroy() { mainHandler.removeCallbacksAndMessages(null) libraryExecutor.shutdownNow() + controllerScope.cancel() super.onDestroy() } @@ -167,6 +204,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } override fun onInputDeviceRemoved(deviceId: Int) { + inputRouter.clearDevice(deviceId) + axisHysteresis.clearDevice(deviceId) + controllerProfiles.remove(deviceId) + controllerIdentities.remove(deviceId) + controllerProfileRevisions.remove(deviceId) pauseForExternalReason("controller_removed") inputDiagnostics.clearDevice( deviceId, @@ -193,16 +235,41 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { keyName = KeyEvent.keyCodeToString(event.keyCode), repeatCount = event.repeatCount, ) - joypadBitForKey(event.keyCode)?.let { bit -> - joypadMask = if (event.action == KeyEvent.ACTION_UP) { - joypadMask and (1 shl bit).inv() - } else { - joypadMask or (1 shl bit) + if (pendingBindingAction != null && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + captureBinding(InputBinding(BindingKind.KEY, event.keyCode)) + renderInputState() + return true + } + if (!gameplayInputActive() && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 && + event.keyCode == KeyEvent.KEYCODE_BUTTON_B + ) { + when { + controllerSettingsPanel.visibility == View.VISIBLE -> closeControllerSettings() + pauseMenu.visibility == View.VISIBLE -> sendControlCommand("run") + else -> return false } - NativeBridge.setJoypadMask(joypadMask) + return true + } + val profile = profileForDevice(event.deviceId) + val binding = InputBinding(BindingKind.KEY, event.keyCode) + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount > 0) { + renderInputState() + return profile.actionsFor(binding).isNotEmpty() + } + val pressed = event.action != KeyEvent.ACTION_UP + val routedActions = profile.actionsFor(binding) + .filter { gameplayInputActive() || it == GameAction.PAUSE_MENU } + routedActions.forEach { action -> + applyRoutedInput( + inputRouter.update( + InputSource(event.deviceId, InputSourceKind.KEY, event.keyCode), + action, + pressed, + ), + ) } renderInputState() - return true + return routedActions.isNotEmpty() } return false } @@ -210,26 +277,56 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private fun handleMotionEvent(event: MotionEvent): Boolean { val device = event.device if (device != null && DeviceDiagnostics.isControllerSource(event.source)) { - device.motionRanges - .filter { range -> range.source and event.source == range.source } - .forEach { range -> - inputDiagnostics.recordAxis( - deviceId = event.deviceId, - eventTimeMs = event.eventTime, - source = event.source, - axis = range.axis, - axisName = MotionEvent.axisToString(range.axis) ?: "AXIS_${range.axis}", - value = event.getAxisValue(range.axis), + val ranges = device.motionRanges.filter { range -> range.source and event.source == range.source } + val profile = profileForDevice(event.deviceId) + ranges.forEach { range -> + inputDiagnostics.recordAxis( + deviceId = event.deviceId, + eventTimeMs = event.eventTime, + source = event.source, + axis = range.axis, + axisName = MotionEvent.axisToString(range.axis) ?: "AXIS_${range.axis}", + value = event.getAxisValue(range.axis), + ) + } + if (pendingBindingAction != null) { + ranges + .map { range -> range to event.getAxisValue(range.axis) } + .filter { (_, value) -> kotlin.math.abs(value) >= profile.pressThreshold } + .maxByOrNull { (_, value) -> kotlin.math.abs(value) } + ?.let { (range, value) -> + captureBinding( + InputBinding( + if (value < 0f) BindingKind.AXIS_NEGATIVE else BindingKind.AXIS_POSITIVE, + range.axis, + ), + ) + renderInputState() + return true + } + } + ranges.forEach { range -> + val value = event.getAxisValue(range.axis) + axisHysteresis.update( + event.deviceId, + range.axis, + value, + profile.pressThreshold, + profile.releaseThreshold, + ).forEach { transition -> + val binding = InputBinding( + if (transition.source.direction < 0) BindingKind.AXIS_NEGATIVE else BindingKind.AXIS_POSITIVE, + range.axis, ) + profile.actionsFor(binding) + .filter { gameplayInputActive() || it == GameAction.PAUSE_MENU } + .forEach { action -> + applyRoutedInput(inputRouter.update(transition.source, action, transition.pressed)) + } } - joypadMask = joypadMask - .withBit(6, event.getAxisValue(MotionEvent.AXIS_X) < -0.5f || event.getAxisValue(MotionEvent.AXIS_HAT_X) < -0.5f) - .withBit(7, event.getAxisValue(MotionEvent.AXIS_X) > 0.5f || event.getAxisValue(MotionEvent.AXIS_HAT_X) > 0.5f) - .withBit(4, event.getAxisValue(MotionEvent.AXIS_Y) < -0.5f || event.getAxisValue(MotionEvent.AXIS_HAT_Y) < -0.5f) - .withBit(5, event.getAxisValue(MotionEvent.AXIS_Y) > 0.5f || event.getAxisValue(MotionEvent.AXIS_HAT_Y) > 0.5f) - NativeBridge.setJoypadMask(joypadMask) + } renderInputState() - return true + return gameplayInputActive() } return false } @@ -246,7 +343,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { setPadding(32, 32, 32, 48) addView(title(getString(R.string.diagnostics_title))) addView(body(getString(R.string.diagnostics_instructions))) - addView(section("M3 游戏库、音画与快进")) + addView(section("M4 游戏库、完整手柄操作与音画")) addView( Button(context).apply { text = "从文件导入 iNES / NES 2.0 ROM" @@ -262,6 +359,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) emulatorStatus = body("状态:Idle") addView(emulatorStatus) + pauseMenu = createPauseMenu() + addView(pauseMenu) addView( LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL @@ -336,6 +435,15 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { addView(section(getString(R.string.section_controllers))) controllerText = body("") addView(controllerText) + addView(Button(context).apply { + text = "手柄映射与设置" + setOnClickListener { showControllerSettings(returnToPause = false) } + }) + controllerSettingsPanel = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + visibility = View.GONE + } + addView(controllerSettingsPanel) addView(section(getString(R.string.section_input_state))) stateText = body("") addView(stateText) @@ -359,6 +467,317 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) } + private fun createPauseMenu() = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + visibility = View.GONE + addView(section("暂停菜单")) + addView(Button(context).apply { + text = "继续" + setOnClickListener { sendControlCommand("run") } + }) + addView(Button(context).apply { + text = "重置游戏" + setOnClickListener { sendControlCommand("reset") } + }) + addView(Button(context).apply { + text = "手柄设置" + setOnClickListener { showControllerSettings(returnToPause = true) } + }) + addView(Button(context).apply { + text = "退出游戏" + setOnClickListener { sendControlCommand("stop") } + }) + } + + private fun showPauseMenu() { + closeControllerSettings(showPreviousMenu = false) + pauseMenu.visibility = View.VISIBLE + (pauseMenu.getChildAt(1) as? Button)?.requestFocus() + } + + private fun hidePauseMenu() { + if (::pauseMenu.isInitialized) pauseMenu.visibility = View.GONE + } + + private fun showControllerSettings(returnToPause: Boolean) { + val shouldReturnToPause = returnToPause || lastSessionState == "Running" + if (lastSessionState == "Running" && !sendControlCommand("pause")) return + settingsReturnToPause = shouldReturnToPause + hidePauseMenu() + controllerSettingsPanel.visibility = View.VISIBLE + draftProfile = selectedControllerId?.let(controllerProfiles::get) + pendingBindingAction = null + controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。" + renderControllerSettings() + } + + private fun closeControllerSettings(showPreviousMenu: Boolean = true) { + pendingBindingAction = null + draftProfile = null + if (::controllerSettingsPanel.isInitialized) controllerSettingsPanel.visibility = View.GONE + clearControllerState() + if (showPreviousMenu && settingsReturnToPause && ::pauseMenu.isInitialized) showPauseMenu() + settingsReturnToPause = false + } + + private fun renderControllerSettings() { + if (!::controllerSettingsPanel.isInitialized || controllerSettingsPanel.visibility != View.VISIBLE) return + controllerSettingsPanel.removeAllViews() + controllerSettingsPanel.addView(section("手柄映射与死区")) + val deviceId = selectedControllerId + val controller = controllers.firstOrNull { it.deviceId == deviceId } + val profile = draftProfile ?: deviceId?.let(controllerProfiles::get) + if (controller == null || profile == null) { + controllerSettingsPanel.addView(body("当前没有已连接的手柄;设置入口保持可达,连接后即可编辑。")) + controllerSettingsPanel.addView(Button(this).apply { + text = "关闭" + setOnClickListener { closeControllerSettings() } + }) + focusFirstButton(controllerSettingsPanel) + return + } + controllerSettingsPanel.addView( + body("${controller.name}\n档案:${profile.origin} · ${profile.fingerprint.take(12)};不使用临时 deviceId 持久化"), + ) + if (controllers.size > 1) { + controllerSettingsPanel.addView(Button(this).apply { + text = "切换到下一个手柄" + setOnClickListener { + val index = controllers.indexOfFirst { it.deviceId == selectedControllerId } + selectedControllerId = controllers[(index + 1).mod(controllers.size)].deviceId + draftProfile = selectedControllerId?.let(controllerProfiles::get) + pendingBindingAction = null + renderControllerSettings() + } + }) + } + controllerSettingsPanel.addView(body(controllerSettingsMessage)) + controllerSettingsPanel.addView(Button(this).apply { + text = if (profile.swapAB) "A/B 交换:开" else "A/B 交换:关" + setOnClickListener { + draftProfile = profile.toggleAB() + controllerSettingsMessage = "已交换 NES A/B;保存后生效。" + renderControllerSettings() + } + }) + controllerSettingsPanel.addView(body("轴按下阈值:${formatThreshold(profile.pressThreshold)}")) + controllerSettingsPanel.addView(SeekBar(this).apply { + min = 20 + max = 95 + progress = (profile.pressThreshold * 100).toInt() + setOnSeekBarChangeListener(thresholdListener { value -> + val press = value.coerceAtLeast(profile.releaseThreshold + 0.05f).coerceAtMost(0.95f) + draftProfile = profile.copy(origin = ProfileOrigin.CUSTOM, pressThreshold = press) + renderControllerSettings() + }) + }) + controllerSettingsPanel.addView(body("轴释放阈值:${formatThreshold(profile.releaseThreshold)}")) + controllerSettingsPanel.addView(SeekBar(this).apply { + min = 5 + max = 90 + progress = (profile.releaseThreshold * 100).toInt() + setOnSeekBarChangeListener(thresholdListener { value -> + val release = value.coerceAtMost(profile.pressThreshold - 0.05f).coerceAtLeast(0.05f) + draftProfile = profile.copy(origin = ProfileOrigin.CUSTOM, releaseThreshold = release) + renderControllerSettings() + }) + }) + GameAction.entries.forEach { action -> + val description = profile.bindings[action].orEmpty().joinToString { binding -> + binding.displayName(KeyEvent::keyCodeToString) { axis -> + MotionEvent.axisToString(axis) ?: "AXIS_$axis" + } + }.ifEmpty { "未绑定" } + controllerSettingsPanel.addView(Button(this).apply { + text = "${action.label}:$description" + setOnClickListener { + clearControllerState() + pendingBindingAction = action + controllerSettingsMessage = "正在捕获“${action.label}”;按键、推动轴,或点击取消。" + renderControllerSettings() + } + }) + } + if (pendingBindingAction != null) { + controllerSettingsPanel.addView(Button(this).apply { + text = "取消捕获" + setOnClickListener { + pendingBindingAction = null + controllerSettingsMessage = "已取消捕获,当前映射未改变。" + clearControllerState() + renderControllerSettings() + } + }) + } + controllerSettingsPanel.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + addView(Button(context).apply { + text = "保存" + setOnClickListener { saveControllerProfile() } + }) + addView(Button(context).apply { + text = "取消" + setOnClickListener { closeControllerSettings() } + }) + addView(Button(context).apply { + text = "恢复默认" + setOnClickListener { resetControllerProfile() } + }) + }) + focusFirstButton(controllerSettingsPanel) + } + + private fun focusFirstButton(container: ViewGroup) { + for (index in 0 until container.childCount) { + val child = container.getChildAt(index) + if (child is Button && child.visibility == View.VISIBLE && child.isEnabled) { + child.requestFocus() + return + } + if (child is ViewGroup) { + focusFirstButton(child) + if (child.hasFocus()) return + } + } + } + + private fun thresholdListener(onFinished: (Float) -> Unit) = object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {} + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + override fun onStopTrackingTouch(seekBar: SeekBar?) { + onFinished((seekBar?.progress ?: 50) / 100f) + } + } + + private fun captureBinding(binding: InputBinding) { + val action = pendingBindingAction ?: return + val profile = draftProfile ?: return + pendingBindingAction = null + val conflicts = profile.actionsFor(binding) - action + if (conflicts.isNotEmpty()) { + AlertDialog.Builder(this) + .setTitle("绑定冲突") + .setMessage("该输入已用于 ${conflicts.joinToString { it.label }}。是否移除旧绑定并改为 ${action.label}?") + .setPositiveButton("替换") { _, _ -> finishBinding(profile, action, binding, replace = true) } + .setNegativeButton("取消") { _, _ -> + controllerSettingsMessage = "冲突未替换,映射保持不变。" + clearControllerState() + renderControllerSettings() + } + .show() + } else { + finishBinding(profile, action, binding, replace = false) + } + } + + private fun finishBinding( + profile: ControllerProfile, + action: GameAction, + binding: InputBinding, + replace: Boolean, + ) { + val withoutConflict = if (replace) profile.removeBinding(binding, action) else profile + draftProfile = withoutConflict.replaceBinding(action, binding) + controllerSettingsMessage = "已捕获 ${action.label};点击保存后生效。" + clearControllerState() + renderControllerSettings() + } + + private fun saveControllerProfile() { + val deviceId = selectedControllerId ?: return + val profile = draftProfile?.copy(origin = ProfileOrigin.CUSTOM) ?: return + controllerProfileRevisions[deviceId] = (controllerProfileRevisions[deviceId] ?: 0) + 1 + controllerProfiles[deviceId] = profile + pendingBindingAction = null + clearControllerState() + controllerScope.launch { + val result = runCatching { profileStore.save(profile) } + runOnUiThread { + if (selectedControllerId != deviceId) return@runOnUiThread + controllerSettingsMessage = if (result.isSuccess) { + "设置已保存;重连和重启后按设备特征恢复。" + } else { + "保存失败:${result.exceptionOrNull()?.message ?: "未知错误"}" + } + draftProfile = profile + renderControllerSettings() + } + } + } + + private fun resetControllerProfile() { + val deviceId = selectedControllerId ?: return + val identity = controllerIdentities[deviceId] ?: return + val defaultProfile = profileResolver.resolve(identity) + controllerProfileRevisions[deviceId] = (controllerProfileRevisions[deviceId] ?: 0) + 1 + controllerProfiles[deviceId] = defaultProfile + draftProfile = defaultProfile + pendingBindingAction = null + clearControllerState() + controllerScope.launch { + val result = runCatching { profileStore.reset(identity) } + runOnUiThread { + if (selectedControllerId != deviceId) return@runOnUiThread + controllerSettingsMessage = if (result.isSuccess) { + "已恢复安全的通用默认配置。" + } else { + "恢复默认失败:${result.exceptionOrNull()?.message ?: "未知错误"}" + } + renderControllerSettings() + } + } + } + + private fun syncControllerProfiles() { + val connected = controllers.mapTo(mutableSetOf()) { it.deviceId } + controllerProfiles.keys.retainAll(connected) + controllerIdentities.keys.retainAll(connected) + controllerProfileRevisions.keys.retainAll(connected) + controllers.forEach { controller -> + val identity = controller.toIdentity() + if (controllerIdentities[controller.deviceId]?.fingerprint() == identity.fingerprint()) return@forEach + controllerIdentities[controller.deviceId] = identity + controllerProfiles[controller.deviceId] = profileResolver.resolve(identity) + val revision = (controllerProfileRevisions[controller.deviceId] ?: 0) + 1 + controllerProfileRevisions[controller.deviceId] = revision + controllerScope.launch { + val restored = runCatching { profileStore.load(identity) } + .getOrElse { profileResolver.resolve(identity) } + runOnUiThread { + if (controllerIdentities[controller.deviceId]?.fingerprint() == identity.fingerprint() && + controllerProfileRevisions[controller.deviceId] == revision + ) { + val cleared = inputRouter.clearDevice(controller.deviceId) + axisHysteresis.clearDevice(controller.deviceId) + controllerProfiles[controller.deviceId] = restored + applyRoutedInput(cleared) + if (selectedControllerId == controller.deviceId && draftProfile == null) { + renderControllerSettings() + } + } + } + } + } + if (selectedControllerId !in connected) { + selectedControllerId = controllers.firstOrNull()?.deviceId + draftProfile = null + pendingBindingAction = null + } + renderControllerSettings() + } + + private fun profileForDevice(deviceId: Int): ControllerProfile = controllerProfiles[deviceId] + ?: InputDevice.getDevice(deviceId)?.let { device -> + profileResolver.resolve( + ControllerIdentity(device.vendorId, device.productId, device.descriptor.orEmpty(), device.name.orEmpty()), + ) + } + ?: profileResolver.resolve(ControllerIdentity(0, 0, "unavailable", "unavailable")) + + private fun ControllerSnapshot.toIdentity() = ControllerIdentity(vendorId, productId, descriptor, name) + + private fun formatThreshold(value: Float) = String.format(Locale.ROOT, "%.2f", value) + private fun refreshControllers() { val connectedIds = DeviceDiagnostics.controllerDeviceIds() inputDiagnostics.attachedDeviceIds() @@ -372,6 +791,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) } controllers = DeviceDiagnostics.controllers(inputDiagnostics) + syncControllerProfiles() if (::controllerText.isInitialized) { controllerText.text = if (controllers.isEmpty()) { getString(R.string.no_controller) @@ -501,7 +921,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (::emulatorStatus.isInitialized && activeSessionId != 0L) { val raw = NativeBridge.sessionStatus() runCatching { JSONObject(raw) }.onSuccess { status -> - emulatorStatus.text = "状态:${status.optString("state")} · ${status.optString("completion")}" + + val nextState = status.optString("state") + if (lastSessionState == "Running" && nextState != "Running") clearControllerState() + lastSessionState = nextState + emulatorStatus.text = "状态:$nextState · ${status.optString("completion")}" + if (status.optBoolean("fastForward")) " · 2×" else "" val audio = status.optJSONObject("audio") ?: JSONObject() val timing = status.optJSONObject("timing") ?: JSONObject() @@ -513,48 +936,82 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { mainHandler.postDelayed(::pollSessionStatus, 250) } - private fun sendControlCommand(command: String) { - if (activeSessionId == 0L) return + private fun sendControlCommand(command: String): Boolean { + if (activeSessionId == 0L) return false if (command == "run" && audioManager.requestAudioFocus(audioFocusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { emulatorStatus.text = "音频焦点未获准,游戏保持暂停" - return + return false + } + if (command == "pause" || command == "stop") clearControllerState() + if (!NativeBridge.command(activeSessionId, command)) { + emulatorStatus.text = "命令队列已满:$command" + if (command == "run") audioManager.abandonAudioFocusRequest(audioFocusRequest) + return false + } + when (command) { + "pause" -> showPauseMenu() + "run", "stop" -> { + hidePauseMenu() + closeControllerSettings(showPreviousMenu = false) + } } - NativeBridge.command(activeSessionId, command) if (command == "pause" || command == "stop") { audioManager.abandonAudioFocusRequest(audioFocusRequest) } + return true } - private fun pauseForExternalReason(reason: String) { - NativeBridge.setJoypadMask(0) - joypadMask = 0 - if (activeSessionId != 0L) { - NativeBridge.command(activeSessionId, "pause") + private fun applyRoutedInput(state: RoutedInputState) { + val gameplayActive = gameplayInputActive() + joypadMask = if (gameplayActive) state.joypadMask else 0 + NativeBridge.setJoypadMask(joypadMask) + NativeBridge.setTurboMask(if (gameplayActive) state.turboMask else 0) + state.fastForwardChanged?.takeIf { gameplayActive }?.let { enabled -> + NativeBridge.command(activeSessionId, if (enabled) "fast:on" else "fast:off") } - if (::audioStatus.isInitialized) audioStatus.text = "已安全暂停:$reason;请手动继续" + if (state.pauseMenuEdge) { + when (lastSessionState) { + "Running" -> sendControlCommand("pause") + "Paused" -> sendControlCommand("run") + } + } + } + + private fun gameplayInputActive(): Boolean = lastSessionState == "Running" && + pauseMenu.visibility != View.VISIBLE && controllerSettingsPanel.visibility != View.VISIBLE + + private fun clearControllerState() { + inputRouter.clearAll() + axisHysteresis.clearAll() + joypadMask = 0 + NativeBridge.setJoypadMask(0) + NativeBridge.setTurboMask(0) + } + + private fun pauseForExternalReason(reason: String): Boolean { + clearControllerState() + if (activeSessionId != 0L) { + val queued = NativeBridge.command(activeSessionId, "pause") + if (::audioStatus.isInitialized) { + audioStatus.text = if (queued) { + "已请求安全暂停:$reason;请手动继续" + } else { + "暂停命令队列已满:$reason;输入已清除" + } + } + return queued + } + return false } private fun rebuildAudioForRoute() { if (activeSessionId == 0L) return - pauseForExternalReason("audio_route_changed") - NativeBridge.command(activeSessionId, "audio_rebuild") + if (!pauseForExternalReason("audio_route_changed")) return + if (!NativeBridge.command(activeSessionId, "audio_rebuild") && ::audioStatus.isInitialized) { + audioStatus.text = "音频路由重建命令队列已满;游戏保持暂停" + } } - private fun joypadBitForKey(keyCode: Int): Int? = when (keyCode) { - KeyEvent.KEYCODE_DPAD_UP -> 4 - KeyEvent.KEYCODE_DPAD_DOWN -> 5 - KeyEvent.KEYCODE_DPAD_LEFT -> 6 - KeyEvent.KEYCODE_DPAD_RIGHT -> 7 - KeyEvent.KEYCODE_BUTTON_A -> 8 - KeyEvent.KEYCODE_BUTTON_B -> 0 - KeyEvent.KEYCODE_BUTTON_START -> 3 - KeyEvent.KEYCODE_BUTTON_SELECT -> 2 - else -> null - } - - private fun Int.withBit(bit: Int, enabled: Boolean): Int = - if (enabled) this or (1 shl bit) else this and (1 shl bit).inv() - private fun buildDiagnosticReport(): JSONObject = JSONObject() .put("formatVersion", 1) .put("exportedAtEpochMs", System.currentTimeMillis()) @@ -577,6 +1034,19 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) .put("device", baseline.toJson()) .put("controllers", JSONArray().apply { controllers.forEach { put(it.toJson()) } }) + .put( + "controllerProfiles", + JSONArray().apply { + controllers.forEach { controller -> + controllerProfiles[controller.deviceId]?.let { profile -> + put( + JSONObject(ControllerProfileJson.encode(profile)) + .put("currentSessionDeviceId", controller.deviceId), + ) + } + } + }, + ) .put( "session", if (activeSessionId == 0L) JSONObject.NULL else diff --git a/app/src/main/java/org/neslite/app/NativeBridge.kt b/app/src/main/java/org/neslite/app/NativeBridge.kt index 77e8f01..7320867 100644 --- a/app/src/main/java/org/neslite/app/NativeBridge.kt +++ b/app/src/main/java/org/neslite/app/NativeBridge.kt @@ -1,6 +1,6 @@ package org.neslite.app -/** JNI boundary. M0 deliberately exposes a build marker, not emulator control. */ +/** JNI boundary. Core state changes remain owned by the native simulation thread. */ object NativeBridge { init { System.loadLibrary("neslite_jni") @@ -18,6 +18,8 @@ object NativeBridge { external fun setJoypadMask(mask: Int) + external fun setTurboMask(mask: Int) + external fun sessionStatus(): String external fun rendererCreated() diff --git a/app/src/main/java/org/neslite/app/input/ControllerProfile.kt b/app/src/main/java/org/neslite/app/input/ControllerProfile.kt new file mode 100644 index 0000000..423b178 --- /dev/null +++ b/app/src/main/java/org/neslite/app/input/ControllerProfile.kt @@ -0,0 +1,124 @@ +package org.neslite.app.input + +import java.security.MessageDigest + +enum class GameAction(val label: String) { + UP("上"), + DOWN("下"), + LEFT("左"), + RIGHT("右"), + NES_A("NES A"), + NES_B("NES B"), + START("Start"), + SELECT("Select"), + TURBO_A("A 连发"), + TURBO_B("B 连发"), + PAUSE_MENU("暂停菜单"), + FAST_FORWARD("按住快进"), +} + +enum class BindingKind { KEY, AXIS_NEGATIVE, AXIS_POSITIVE } + +data class InputBinding(val kind: BindingKind, val code: Int) { + fun displayName(keyName: (Int) -> String, axisName: (Int) -> String): String = when (kind) { + BindingKind.KEY -> keyName(code) + BindingKind.AXIS_NEGATIVE -> "${axisName(code)}−" + BindingKind.AXIS_POSITIVE -> "${axisName(code)}+" + } +} + +data class ControllerIdentity( + val vendorId: Int, + val productId: Int, + val descriptor: String, + val name: String, +) { + fun fingerprint(): String { + val stableDescriptor = descriptor.trim().takeUnless { it.isEmpty() || it == "未知" } + ?: name.trim().lowercase() + val source = "$vendorId|$productId|$stableDescriptor" + return MessageDigest.getInstance("SHA-256") + .digest(source.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + } +} + +enum class ProfileOrigin { GENERIC_ANDROID, X5_LITE_MEASURED, CUSTOM } + +data class ControllerProfile( + val fingerprint: String, + val origin: ProfileOrigin, + val bindings: Map>, + val pressThreshold: Float = 0.55f, + val releaseThreshold: Float = 0.35f, + val swapAB: Boolean = false, +) { + init { + require(pressThreshold in 0.2f..0.95f) + require(releaseThreshold in 0.05f.. = bindings + .filterValues { binding in it } + .keys + + fun replaceBinding(action: GameAction, binding: InputBinding): ControllerProfile = copy( + origin = ProfileOrigin.CUSTOM, + bindings = bindings + (action to setOf(binding)), + ) + + fun removeBinding(binding: InputBinding, except: GameAction): ControllerProfile = copy( + bindings = bindings.mapValues { (action, values) -> + if (action == except) values else values - binding + }, + ) + + fun toggleAB(): ControllerProfile { + val a = bindings[GameAction.NES_A].orEmpty() + val b = bindings[GameAction.NES_B].orEmpty() + return copy( + origin = ProfileOrigin.CUSTOM, + bindings = bindings + mapOf(GameAction.NES_A to b, GameAction.NES_B to a), + swapAB = !swapAB, + ) + } +} + +data class ControllerSignature(val vendorId: Int, val productId: Int, val descriptor: String) + +class ControllerProfileResolver( + private val measuredX5LiteProfiles: Map>> = emptyMap(), +) { + fun resolve(identity: ControllerIdentity): ControllerProfile { + val signature = ControllerSignature(identity.vendorId, identity.productId, identity.descriptor) + val measured = measuredX5LiteProfiles[signature] + return ControllerProfile( + fingerprint = identity.fingerprint(), + origin = if (measured == null) ProfileOrigin.GENERIC_ANDROID else ProfileOrigin.X5_LITE_MEASURED, + bindings = measured ?: GenericAndroidBindings.create(), + ) + } +} + +object GenericAndroidBindings { + // Numeric values are Android's stable KeyEvent/MotionEvent constants. Keeping this + // table platform-free makes the mapping rules directly testable on the JVM. + fun create(): Map> = mapOf( + GameAction.UP to setOf(key(19), negativeAxis(1), negativeAxis(16)), + GameAction.DOWN to setOf(key(20), positiveAxis(1), positiveAxis(16)), + GameAction.LEFT to setOf(key(21), negativeAxis(0), negativeAxis(15)), + GameAction.RIGHT to setOf(key(22), positiveAxis(0), positiveAxis(15)), + GameAction.NES_A to setOf(key(96)), + GameAction.NES_B to setOf(key(97)), + GameAction.TURBO_A to setOf(key(99)), + GameAction.TURBO_B to setOf(key(100)), + GameAction.START to setOf(key(108)), + GameAction.SELECT to setOf(key(109)), + GameAction.PAUSE_MENU to setOf(key(107)), + GameAction.FAST_FORWARD to setOf(key(103)), + ) + + private fun key(code: Int) = InputBinding(BindingKind.KEY, code) + private fun negativeAxis(code: Int) = InputBinding(BindingKind.AXIS_NEGATIVE, code) + private fun positiveAxis(code: Int) = InputBinding(BindingKind.AXIS_POSITIVE, code) +} diff --git a/app/src/main/java/org/neslite/app/input/ControllerProfileJson.kt b/app/src/main/java/org/neslite/app/input/ControllerProfileJson.kt new file mode 100644 index 0000000..85afba7 --- /dev/null +++ b/app/src/main/java/org/neslite/app/input/ControllerProfileJson.kt @@ -0,0 +1,55 @@ +package org.neslite.app.input + +import org.json.JSONArray +import org.json.JSONObject + +object ControllerProfileJson { + private const val FORMAT_VERSION = 1 + + fun encode(profile: ControllerProfile): String = JSONObject() + .put("formatVersion", FORMAT_VERSION) + .put("fingerprint", profile.fingerprint) + .put("origin", profile.origin.name) + .put("pressThreshold", profile.pressThreshold.toDouble()) + .put("releaseThreshold", profile.releaseThreshold.toDouble()) + .put("swapAB", profile.swapAB) + .put( + "bindings", + JSONObject().apply { + profile.bindings.forEach { (action, bindings) -> + put( + action.name, + JSONArray().apply { + bindings.forEach { binding -> + put(JSONObject().put("kind", binding.kind.name).put("code", binding.code)) + } + }, + ) + } + }, + ) + .toString() + + fun decode(encoded: String): ControllerProfile { + val root = JSONObject(encoded) + require(root.getInt("formatVersion") == FORMAT_VERSION) + val bindingRoot = root.getJSONObject("bindings") + val bindings = GameAction.entries.associateWith { action -> + val items = bindingRoot.optJSONArray(action.name) ?: JSONArray() + buildSet { + repeat(items.length()) { index -> + val item = items.getJSONObject(index) + add(InputBinding(BindingKind.valueOf(item.getString("kind")), item.getInt("code"))) + } + } + } + return ControllerProfile( + fingerprint = root.getString("fingerprint"), + origin = ProfileOrigin.valueOf(root.getString("origin")), + bindings = bindings, + pressThreshold = root.getDouble("pressThreshold").toFloat(), + releaseThreshold = root.getDouble("releaseThreshold").toFloat(), + swapAB = root.getBoolean("swapAB"), + ) + } +} diff --git a/app/src/main/java/org/neslite/app/input/ControllerProfileStore.kt b/app/src/main/java/org/neslite/app/input/ControllerProfileStore.kt new file mode 100644 index 0000000..6f1a0a7 --- /dev/null +++ b/app/src/main/java/org/neslite/app/input/ControllerProfileStore.kt @@ -0,0 +1,42 @@ +package org.neslite.app.input + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.first + +private val Context.controllerProfilesDataStore: DataStore by preferencesDataStore( + name = "controller_profiles", +) + +class ControllerProfileStore( + private val context: Context, + private val resolver: ControllerProfileResolver, +) { + suspend fun load(identity: ControllerIdentity): ControllerProfile { + val fallback = resolver.resolve(identity) + val encoded = context.controllerProfilesDataStore.data.first()[key(identity.fingerprint())] + return encoded?.let { runCatching { ControllerProfileJson.decode(it) }.getOrNull() } + ?.takeIf { it.fingerprint == identity.fingerprint() } + ?: fallback + } + + suspend fun save(profile: ControllerProfile) { + context.controllerProfilesDataStore.edit { preferences -> + preferences[key(profile.fingerprint)] = ControllerProfileJson.encode( + profile.copy(origin = ProfileOrigin.CUSTOM), + ) + } + } + + suspend fun reset(identity: ControllerIdentity) { + context.controllerProfilesDataStore.edit { preferences -> + preferences.remove(key(identity.fingerprint())) + } + } + + private fun key(fingerprint: String) = stringPreferencesKey("profile_$fingerprint") +} diff --git a/app/src/main/java/org/neslite/app/input/InputRouter.kt b/app/src/main/java/org/neslite/app/input/InputRouter.kt new file mode 100644 index 0000000..75b70e8 --- /dev/null +++ b/app/src/main/java/org/neslite/app/input/InputRouter.kt @@ -0,0 +1,121 @@ +package org.neslite.app.input + +enum class InputSourceKind { KEY, AXIS, TOUCH } + +data class InputSource( + val deviceId: Int, + val kind: InputSourceKind, + val code: Int, + val direction: Int = 0, +) + +data class RoutedInputState( + val joypadMask: Int, + val turboMask: Int, + val pauseMenuEdge: Boolean = false, + val fastForwardChanged: Boolean? = null, +) + +class InputRouter { + private val sourcesByAction = GameAction.entries.associateWith { linkedSetOf() } + private var fastForward = false + + fun update(source: InputSource, action: GameAction, pressed: Boolean): RoutedInputState { + val sources = sourcesByAction.getValue(action) + val wasPressed = sources.isNotEmpty() + if (pressed) sources += source else sources -= source + val isPressed = sources.isNotEmpty() + return snapshot( + pauseMenuEdge = action == GameAction.PAUSE_MENU && !wasPressed && isPressed, + newFastForward = if (action == GameAction.FAST_FORWARD && wasPressed != isPressed) isPressed else null, + ) + } + + fun clearDevice(deviceId: Int): RoutedInputState { + sourcesByAction.values.forEach { sources -> sources.removeAll { it.deviceId == deviceId } } + return snapshot(newFastForward = currentFastForward()) + } + + fun clearAll(): RoutedInputState { + sourcesByAction.values.forEach(MutableSet::clear) + return snapshot(newFastForward = false) + } + + fun current(): RoutedInputState = snapshot() + + private fun snapshot( + pauseMenuEdge: Boolean = false, + newFastForward: Boolean? = null, + ): RoutedInputState { + val actualFastForward = currentFastForward() + val fastChange = when { + newFastForward != null && actualFastForward != fastForward -> actualFastForward + else -> null + } + fastForward = actualFastForward + val up = pressed(GameAction.UP) && !pressed(GameAction.DOWN) + val down = pressed(GameAction.DOWN) && !pressed(GameAction.UP) + val left = pressed(GameAction.LEFT) && !pressed(GameAction.RIGHT) + val right = pressed(GameAction.RIGHT) && !pressed(GameAction.LEFT) + var mask = 0 + if (pressed(GameAction.NES_B)) mask = mask or (1 shl 0) + if (pressed(GameAction.SELECT)) mask = mask or (1 shl 2) + if (pressed(GameAction.START)) mask = mask or (1 shl 3) + if (up) mask = mask or (1 shl 4) + if (down) mask = mask or (1 shl 5) + if (left) mask = mask or (1 shl 6) + if (right) mask = mask or (1 shl 7) + if (pressed(GameAction.NES_A)) mask = mask or (1 shl 8) + var turbo = 0 + if (pressed(GameAction.TURBO_B)) turbo = turbo or (1 shl 0) + if (pressed(GameAction.TURBO_A)) turbo = turbo or (1 shl 8) + return RoutedInputState(mask, turbo, pauseMenuEdge, fastChange) + } + + private fun pressed(action: GameAction): Boolean = sourcesByAction.getValue(action).isNotEmpty() + private fun currentFastForward(): Boolean = pressed(GameAction.FAST_FORWARD) +} + +data class AxisTransition(val source: InputSource, val pressed: Boolean) + +class AxisHysteresis { + private val pressed = mutableSetOf() + + fun update( + deviceId: Int, + axisCode: Int, + value: Float, + pressThreshold: Float, + releaseThreshold: Float, + ): List { + require(releaseThreshold < pressThreshold) + val negative = InputSource(deviceId, InputSourceKind.AXIS, axisCode, -1) + val positive = InputSource(deviceId, InputSourceKind.AXIS, axisCode, 1) + return buildList { + // Release first so crossing directly from one side to the other never + // leaves both directions asserted, even for the duration of one event. + releaseDirection(negative, value > -releaseThreshold)?.let(::add) + releaseDirection(positive, value < releaseThreshold)?.let(::add) + pressDirection(negative, value <= -pressThreshold)?.let(::add) + pressDirection(positive, value >= pressThreshold)?.let(::add) + } + } + + fun clearDevice(deviceId: Int) { + pressed.removeAll { it.deviceId == deviceId } + } + + fun clearAll() = pressed.clear() + + private fun releaseDirection(source: InputSource, shouldRelease: Boolean): AxisTransition? { + if (source !in pressed || !shouldRelease) return null + pressed -= source + return AxisTransition(source, false) + } + + private fun pressDirection(source: InputSource, shouldPress: Boolean): AxisTransition? { + if (source in pressed || !shouldPress) return null + pressed += source + return AxisTransition(source, true) + } +} diff --git a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt index 1370ca7..932a08c 100644 --- a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt +++ b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt @@ -7,7 +7,7 @@ class BuildIdentityTest { @Test fun debugBuildUsesTheDocumentedIdentity() { assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID) - assertEquals("0.3.4-debug", BuildConfig.VERSION_NAME) - assertEquals(3004, BuildConfig.VERSION_CODE) + assertEquals("0.4.4-debug", BuildConfig.VERSION_NAME) + assertEquals(4004, BuildConfig.VERSION_CODE) } } diff --git a/app/src/test/java/org/neslite/app/input/ControllerProfileTest.kt b/app/src/test/java/org/neslite/app/input/ControllerProfileTest.kt new file mode 100644 index 0000000..80a0262 --- /dev/null +++ b/app/src/test/java/org/neslite/app/input/ControllerProfileTest.kt @@ -0,0 +1,57 @@ +package org.neslite.app.input + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ControllerProfileTest { + private val identity = ControllerIdentity(0x1234, 0x5678, "stable-descriptor", "Gamepad") + + @Test + fun genericMappingKeepsNesAndControlActionsDistinct() { + val profile = ControllerProfileResolver().resolve(identity) + assertEquals(ProfileOrigin.GENERIC_ANDROID, profile.origin) + assertEquals(setOf(GameAction.NES_A), profile.actionsFor(InputBinding(BindingKind.KEY, 96))) + assertEquals(setOf(GameAction.TURBO_A), profile.actionsFor(InputBinding(BindingKind.KEY, 99))) + assertEquals(setOf(GameAction.START), profile.actionsFor(InputBinding(BindingKind.KEY, 108))) + assertEquals(setOf(GameAction.SELECT), profile.actionsFor(InputBinding(BindingKind.KEY, 109))) + assertEquals(setOf(GameAction.PAUSE_MENU), profile.actionsFor(InputBinding(BindingKind.KEY, 107))) + assertEquals(setOf(GameAction.FAST_FORWARD), profile.actionsFor(InputBinding(BindingKind.KEY, 103))) + assertTrue(profile.actionsFor(InputBinding(BindingKind.KEY, 104)).isEmpty()) + } + + @Test + fun measuredProfileRequiresExactStableSignature() { + val signature = ControllerSignature(identity.vendorId, identity.productId, identity.descriptor) + val measured = mapOf(GameAction.NES_A to setOf(InputBinding(BindingKind.KEY, 200))) + val resolver = ControllerProfileResolver(mapOf(signature to measured)) + assertEquals(ProfileOrigin.X5_LITE_MEASURED, resolver.resolve(identity).origin) + assertEquals( + ProfileOrigin.GENERIC_ANDROID, + resolver.resolve(identity.copy(descriptor = "different-device")).origin, + ) + } + + @Test + fun fingerprintIgnoresTemporaryDeviceIdAndSeparatesDescriptors() { + val first = identity.fingerprint() + val reconnected = identity.copy(name = "Gamepad renamed").fingerprint() + assertEquals(first, reconnected) + assertEquals(64, first.length) + assertNotEquals(first, identity.copy(descriptor = "other").fingerprint()) + } + + @Test + fun swapAndJsonRoundTripPreserveConfiguration() { + val original = ControllerProfileResolver().resolve(identity) + val swapped = original.toggleAB().copy(pressThreshold = 0.7f, releaseThreshold = 0.4f) + assertTrue(swapped.swapAB) + assertEquals(original.bindings[GameAction.NES_B], swapped.bindings[GameAction.NES_A]) + val decoded = ControllerProfileJson.decode(ControllerProfileJson.encode(swapped)) + assertEquals(swapped, decoded) + assertFalse(JSONObject(ControllerProfileJson.encode(swapped)).has("deviceId")) + } +} diff --git a/app/src/test/java/org/neslite/app/input/InputRouterTest.kt b/app/src/test/java/org/neslite/app/input/InputRouterTest.kt new file mode 100644 index 0000000..afbe1b9 --- /dev/null +++ b/app/src/test/java/org/neslite/app/input/InputRouterTest.kt @@ -0,0 +1,88 @@ +package org.neslite.app.input + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class InputRouterTest { + @Test + fun independentSourcesDeduplicateEdgesAndReleases() { + val router = InputRouter() + val key = InputSource(1, InputSourceKind.KEY, 19) + val axis = InputSource(1, InputSourceKind.AXIS, 1, -1) + assertTrue(router.update(key, GameAction.UP, true).joypadMask and (1 shl 4) != 0) + assertTrue(router.update(axis, GameAction.UP, true).joypadMask and (1 shl 4) != 0) + assertTrue(router.update(key, GameAction.UP, false).joypadMask and (1 shl 4) != 0) + assertEquals(0, router.update(axis, GameAction.UP, false).joypadMask) + } + + @Test + fun opposingDirectionsCancelUntilOneSourceReleases() { + val router = InputRouter() + val left = InputSource(1, InputSourceKind.KEY, 21) + val right = InputSource(2, InputSourceKind.TOUCH, 22) + router.update(left, GameAction.LEFT, true) + val conflict = router.update(right, GameAction.RIGHT, true) + assertEquals(0, conflict.joypadMask and ((1 shl 6) or (1 shl 7))) + val recovered = router.update(right, GameAction.RIGHT, false) + assertTrue(recovered.joypadMask and (1 shl 6) != 0) + } + + @Test + fun pauseAndFastCommandsOnlyChangeOnAggregateEdges() { + val router = InputRouter() + val pause = InputSource(1, InputSourceKind.KEY, 107) + assertTrue(router.update(pause, GameAction.PAUSE_MENU, true).pauseMenuEdge) + assertFalse(router.update(pause, GameAction.PAUSE_MENU, true).pauseMenuEdge) + val firstFast = InputSource(1, InputSourceKind.KEY, 103) + val secondFast = InputSource(2, InputSourceKind.KEY, 103) + assertEquals(true, router.update(firstFast, GameAction.FAST_FORWARD, true).fastForwardChanged) + assertNull(router.update(secondFast, GameAction.FAST_FORWARD, true).fastForwardChanged) + assertNull(router.update(firstFast, GameAction.FAST_FORWARD, false).fastForwardChanged) + assertEquals(false, router.update(secondFast, GameAction.FAST_FORWARD, false).fastForwardChanged) + } + + @Test + fun clearingOneDeviceKeepsOtherDeviceAndEndsItsFastForward() { + val router = InputRouter() + router.update(InputSource(1, InputSourceKind.KEY, 103), GameAction.FAST_FORWARD, true) + router.update(InputSource(2, InputSourceKind.KEY, 96), GameAction.NES_A, true) + val state = router.clearDevice(1) + assertEquals(false, state.fastForwardChanged) + assertTrue(state.joypadMask and (1 shl 8) != 0) + } + + @Test + fun turboIsSeparateFromHeldNesButtons() { + val router = InputRouter() + val state = router.update( + InputSource(1, InputSourceKind.KEY, 99), + GameAction.TURBO_A, + true, + ) + assertEquals(0, state.joypadMask and (1 shl 8)) + assertTrue(state.turboMask and (1 shl 8) != 0) + } +} + +class AxisHysteresisTest { + @Test + fun axisUsesDifferentPressAndReleaseThresholds() { + val axis = AxisHysteresis() + assertTrue(axis.update(7, 0, 0.54f, 0.55f, 0.35f).isEmpty()) + assertEquals(true, axis.update(7, 0, 0.56f, 0.55f, 0.35f).single().pressed) + assertTrue(axis.update(7, 0, 0.40f, 0.55f, 0.35f).isEmpty()) + assertEquals(false, axis.update(7, 0, 0.34f, 0.55f, 0.35f).single().pressed) + } + + @Test + fun crossingAxisReleasesBeforePressingOppositeDirection() { + val axis = AxisHysteresis() + axis.update(7, 0, 0.8f, 0.55f, 0.35f) + val changes = axis.update(7, 0, -0.8f, 0.55f, 0.35f) + assertEquals(listOf(false, true), changes.map { it.pressed }) + assertEquals(listOf(1, -1), changes.map { it.source.direction }) + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 657ab2e..8bb627f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,4 +1,4 @@ -# NESLite 架构(M3 基线) +# NESLite 架构(M4 基线) ## 边界与线程 @@ -64,9 +64,23 @@ Android 音频焦点丢失会暂停并清输入,重新获得焦点不会自行 GL 线程只在原生侧读取最新缓冲和上传纹理,不经 JNI 逐帧复制图像。默认 4:3、最近邻显示,可切换 原始像素整数缩放;渲染掉帧不减少内核 `retro_run` 次数。 -手柄状态在 Android 事件侧合成为 libretro joypad 位掩码,内核每帧按状态采样。后台、失焦和断柄 -会清零并请求暂停。M1 的 X5 Lite 实测键码仍须在 G1 回填,因此当前只包含 Android 标准按键及 -HAT/主方向轴映射。 +M4 输入层按物理来源维护状态,来源键包含本次设备 ID、按键/轴/触屏类别、代码和轴方向。多个来源 +映射到同一动作时只合成一次;释放一个来源不会清除仍按住的另一个来源。相反方向同时成立时对应轴 +归零。轴使用可配置的按下/释放双阈值,跨向时先释放旧方向再按下新方向,避免边界抖动和瞬时冲突。 + +标准 Android 手柄使用通用映射:方向键/X-Y 轴控制方向,A/B 对应 NES A/B,X/Y 对应 A/B 软件 +连发,Start/Select 保持原义,右摇杆按下切换暂停菜单,RB 按住 2× 快进。暂停和快进只按合成动作 +边沿发命令,系统重复 KeyEvent 不会重复切换;Guide、Mode、肩键组合和快速读档均不占用。软件连发 +在原生核心线程按模拟秒生成 15 Hz 门控,NTSC/PAL 不依赖墙钟频率,离开 Running 即清零。 + +自定义设置可逐动作捕获按键或轴方向,冲突必须确认替换,并支持取消、恢复默认、A/B 交换及死区 +调整。DataStore 以 VID/PID 加 descriptor(不可用时回退规范化名称)的 SHA-256 指纹保存档案,不写入 +临时 deviceId;设备重连后按稳定特征恢复。X5 Lite 专属映射注册只接受 M1 实测的完整签名和事件表, +在该证据缺失时保持空表并使用通用档案,防止按名称误套。 + +运行态输入送入 JNI 的基础掩码和独立连发掩码。暂停菜单、游戏列表及设置均使用可聚焦原生控件; +非运行态不消费方向导航,手柄 B 可从设置返回、从暂停菜单继续。失焦、暂停、断柄和退出同步清除 +来源、轴滞回、基础掩码及连发掩码。 电池存档按 ROM 哈希隔离为 `files/saves//battery/battery.sav`。暂停和正常退出时在内核线程 取得保存内存并以临时文件替换提交,状态通知用 `paused_saved`/`stopped_saved` 报告成功。更完整的 diff --git a/docs/build.md b/docs/build.md index fbad5b6..5a53444 100644 --- a/docs/build.md +++ b/docs/build.md @@ -1,6 +1,6 @@ # NESLite 可复现构建说明 -本说明对应 M0~M3 基线。命令使用系统默认 PowerShell 7.6.6(`pwsh`)从仓库根目录执行;不需要手工复制 `.so`、 +本说明对应 M0~M4 基线。命令使用系统默认 PowerShell 7.6.6(`pwsh`)从仓库根目录执行;不需要手工复制 `.so`、 FCEUmm 或 Oboe 文件。 ## 前置条件 @@ -11,13 +11,13 @@ FCEUmm 或 Oboe 文件。 3. 设置 `ANDROID_HOME`(或在未设置时使用本机记录的 SDK 根目录)。`local.properties` 仅保存 本机 `sdk.dir`,不提交。 4. 首次构建需要访问 Google Maven、Maven Central 与 Gradle 分发服务,以取得已锁定版本。 -5. 若 M2/M3 需要上游源码,运行: +5. M2~M4 构建原生内核、音频和输入层前,运行: ```powershell .\tools\fetch-third-party.ps1 ``` - 该脚本根据 `third_party/manifest.json` 检出固定提交;M3 构建需要 FCEUmm、libretro headers 与 Oboe。 + 该脚本根据 `third_party/manifest.json` 检出固定提交;M4 构建需要 FCEUmm、libretro headers 与 Oboe。 ## 构建调试 APK diff --git a/docs/controller-x5lite.md b/docs/controller-x5lite.md index cd605aa..b342fc1 100644 --- a/docs/controller-x5lite.md +++ b/docs/controller-x5lite.md @@ -1,14 +1,17 @@ # X5 Lite 实测键位与模式 -本文档只登记真实设备结果,不根据按钮字母或网络资料推断 Android 键码。当前尚未连接目标手机和 -X5 Lite,因此表格保持“待实测”;完成下述流程并导出诊断 JSON 后回填。 +本文档只登记真实设备结果,不根据按钮字母、外观或网络资料推断 Android 键码。2026-09-12 已收到 +用户提供的手柄正面和肩部照片;照片确认这是直连 USB-C 的伸缩式布局,并可见十字键、双摇杆、 +ABXY、视图/菜单键及左右肩键。当前尚未连接目标手机,照片不能给出 Android VID/PID、descriptor、 +键码、轴号或上报模式,因此这些字段仍待诊断 JSON 回填。 ## 固定测试条件 - 手柄模式:原生安卓模式,实际切换方法待随设备说明和实测确认。 - 硬件连发:测试前关闭;实际指示状态待实测记录。 - 厂商保留组合:待实测;不得占用“视图+菜单长按”。 -- 应用版本:`0.1.3-debug`。 +- 照片观察:USB-C 直连、伸缩夹持;可见十字键、双摇杆、ABXY、视图/菜单及肩键。 +- 应用版本:M1 采集页基线 `0.1.3-debug`;M4 映射页 `0.4.4-debug`。 - 事件上限:最近 512 条;页面显示最近 30 条。 ## 连贯验收步骤 @@ -35,6 +38,9 @@ X5 Lite,因此表格保持“待实测”;完成下述流程并导出诊断 | 厂商保留组合 | 待实测 | | 诊断 JSON/SHA-256 | 待实测 | +外观照片只作为“物理控件存在”的证据,不作为设备身份或 Android 事件映射证据。M4 在未取得上述 +身份字段时使用标准 Android 通用映射,并允许在应用内逐项捕获;X5 Lite 专属签名不会按名称猜测。 + ## 键位与轴 | 物理控件 | Android KeyEvent/MotionEvent | sources/范围 | 重复上报 | 备注 | diff --git a/docs/dependencies.md b/docs/dependencies.md index 87ffa33..87f7447 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -13,7 +13,7 @@ Gradle 版本锁见 [gradle/libs.versions.toml](../gradle/libs.versions.toml)。 | JSON-java | 20240303 | Maven Central | Public Domain;仅用于 JVM 测试,不打入生产 APK | M1 使用 | | AndroidX test/Espresso | 1.3.0/3.7.0 | Google Maven | Apache-2.0;测试依赖,不打入生产 APK | M0 使用 | | Room | 2.7.2 | Google Maven | Apache-2.0;保留 notices | M2 使用 | -| DataStore | 1.1.7 | Google Maven | Apache-2.0;后续 APK notices | M4/M6 预锁定 | +| DataStore Preferences | 1.1.7 | Google Maven | Apache-2.0;保留 notices | M4 使用 | | FCEUmm | `236ccdfc911e84c60fea6b9d0699c2d440a8de14` | `tools/fetch-third-party.ps1` | GPL-2.0-only;交付完整对应源码、COPYING、修改说明 | M2 使用 | | libretro.h | `0c9622896333ee62dc4326bbe8784a210ddeb03c` | `tools/fetch-third-party.ps1` | MIT;保留版权及许可 | M2 使用 | | Oboe | 1.10.0 / `a81bb9f87d4105b84b682685d3bfbb5beca371d1` | `tools/fetch-third-party.ps1` | Apache-2.0;保留 notices | M3 使用 | diff --git a/docs/identity.md b/docs/identity.md index 6cbc1c7..2cf0a52 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -6,7 +6,7 @@ | --- | --- | | 显示名称 | `NESLite` | | 正式 application ID/namespace | `org.neslite.app` | -| 当前开发版本 | `0.3.4`,`versionCode = 3004` | +| 当前开发版本 | `0.4.4`,`versionCode = 4004` | | 调试 application ID | `org.neslite.app.debug` | | 发布 ABI | `arm64-v8a` | | min/target SDK | 28/36 | diff --git a/docs/reports/m4-controller.md b/docs/reports/m4-controller.md new file mode 100644 index 0000000..f8b6dc1 --- /dev/null +++ b/docs/reports/m4-controller.md @@ -0,0 +1,42 @@ +# M4 完整手柄操作记录 + +日期:2026-09-12 +构建:`org.neslite.app.debug`,`0.4.4-debug`,versionCode 4004,arm64-v8a + +## 已实现 + +- 标准 Android 通用映射覆盖方向、NES A/B、Start/Select、X/Y 软件连发、右摇杆暂停菜单和 RB + 按住快进;Guide/Mode、厂商组合与快速读档不占用,支持 A/B 交换。 +- 设备、按键、轴方向和测试触屏来源独立合成;重复来源去重,单来源释放不误清其他来源,相反方向 + 同时按下归零。 +- 可配置按下/释放双死区阈值,跨向时先释放旧方向;设置页可捕获按键或轴、提示并确认冲突、保存、 + 取消及恢复默认,所有退出路径清输入状态。 +- 软件连发由核心线程按模拟时间生成 15 Hz 门控,NTSC/PAL 采用同一时间口径;暂停、退出、失焦和 + 断柄清除连发。右摇杆暂停及 RB 快进按合成边沿触发,KeyEvent repeat 不重复命令。 +- 游戏列表、暂停菜单和手柄设置使用 Android 可聚焦控件;运行时方向送游戏,暂停时方向留给焦点 + 导航,手柄 B 提供返回路径。 +- DataStore 1.1.7 按 VID/PID 和 descriptor 的稳定指纹保存映射、A/B 状态和死区;临时 deviceId 只 + 出现在当前诊断,不进入持久化档案。 + +## X5 Lite 证据边界 + +用户提供的两张照片确认了 USB-C 伸缩夹持、十字键、双摇杆、ABXY、视图/菜单和肩键的物理布局, +详见 `docs/controller-x5lite.md`。照片不能证明 Android VID/PID、descriptor、键码、轴号、重复上报或 +硬件连发状态;专属签名表因此保持为空,连接前使用标准 Android 通用映射,可在设置页逐项捕获。 + +## 本地验证 + +- 原生 smoke test 覆盖 NTSC 60 帧与 PAL 50 帧各一模拟秒均产生 15 次连发脉冲。 +- JVM 测试覆盖通用与精确签名选择、A/B 交换、档案 JSON 往返、设备指纹、双来源按住/释放、 + 轴键去重、相反方向、死区边界和跨向顺序、暂停/快进边沿、断柄及触屏来源。 +- `tools/check.ps1 -Scope Stage`:APK、Windows 原生 smoke test 和 JVM 测试全部通过;JVM 共 23 项, + 失败 0、错误 0。Android lint:0 错误、30 个非阻断警告。 +- 调试 APK:`app/build/outputs/apk/debug/app-debug.apk`,21,844,231 字节,SHA-256 + `DC57D4F6818A0F637264DC8F96328CBEEA2B16302899FE6777EE70737E5DAC00`。包内原生库仅有目标 ABI + `arm64-v8a` 的 `libneslite_jni.so` 与 DataStore 的 `libdatastore_shared_counter.so`。 + +## 尚未形成门槛证据 + +当前没有已授权目标手机,也没有 M1 导出的 X5 Lite Android 身份/事件表及合法 ROM。真实专属默认 +映射、绑定交互、全手柄启动与菜单路径、NTSC/PAL 实际连发、断柄取消快进和 H-HOT 20 轮插拔尚未 +执行。G1~G3 未通过也阻止进入 G4;`todo.md` 中 M4 项与 G4 保持未勾选。 diff --git a/docs/toolchain.md b/docs/toolchain.md index cd4103e..66f8a92 100644 --- a/docs/toolchain.md +++ b/docs/toolchain.md @@ -30,7 +30,7 @@ NDK 与 CMake。该提示不改变产物使用的具体版本,后续升级 SDK | AndroidX Core KTX | 1.17.0 | Google Maven | Apache-2.0 | M0 已引入 | | AndroidX Activity KTX | 1.12.0 | Google Maven | Apache-2.0 | M0 已引入 | | Room | 2.7.2 | Google Maven | Apache-2.0 | M2 已引入 | -| DataStore Preferences | 1.1.7 | Google Maven | Apache-2.0 | 为 M4/M6 锁定,尚未引入 | +| DataStore Preferences | 1.1.7 | Google Maven | Apache-2.0 | M4 已引入 | | FCEUmm | `236ccdfc911e84c60fea6b9d0699c2d440a8de14` | `libretro/libretro-fceumm` | GPL-2.0-only | M2 已编译并静态链接 | | libretro.h | `0c9622896333ee62dc4326bbe8784a210ddeb03c` | `libretro/RetroArch` | MIT | M2 已引入 | | Oboe | tag `1.10.0`, commit `a81bb9f87d4105b84b682685d3bfbb5beca371d1` | `google/oboe` | Apache-2.0 | M3 已编译并静态链接 | diff --git a/todo.md b/todo.md index 454dc15..7f6ddf7 100644 --- a/todo.md +++ b/todo.md @@ -159,6 +159,11 @@ JVM 测试和 lint 通过,详见 `docs/reports/m3-audio.md`。依照阶段门 ### M4/0.4.x:完整手柄操作 +状态(2026-09-12):以下项目的隔离实现已进入 `0.4.4-debug`,通用映射、自定义绑定、来源合成、 +死区、模拟时间连发、暂停/快进边沿、焦点导航和 DataStore 档案已实现,详见 +`docs/reports/m4-controller.md`。用户照片已确认 X5 Lite 物理布局,但不能替代 Android VID/PID、 +descriptor 和事件实测;G1~G3 尚未通过且无目标手机/ROM,因此 M4/G4 继续保持未勾选。 + - [ ] **M4-01a 建立默认与通用映射**。前置:无。完成:把 M1 档案转为 X5 Lite 默认配置,标准 Android 手柄使用通用映射;支持 A/B 交换并保留厂商组合。验收:L1,档案匹配和默认动作正确;未知设备不套用错误专属配置。 - [ ] **M4-01b 实现自定义绑定页面**。前置:M4-01a。完成:捕获待绑定输入、提示冲突、保存或取消、恢复默认;菜单始终保留可达入口。验收:L2,一个绑定、冲突、取消和恢复流程可完成,退出绑定模式不残留按键。 - [ ] **M4-02a 合成独立来源并去重**。前置:M4-01a。完成:分别维护设备/轴/按键/触屏来源状态;相同动作重复上报不会重复触发菜单,释放一个来源不清除其他来源。验收:L1,用覆盖双来源按住/释放和轴键重复的最小事件序列;此阶段触屏来源可用测试输入。