Compare commits

40 Commits
Author SHA1 Message Date
shenandshen 3166b61321 Fix tree rendering and authored collision, add FPS display and packaging safeguards 2026-10-14 19:16:39 -07:00
shenandshen b3808d8d0c Align AVA2 Windows behavior and improve mobile touch interactions 2026-10-13 23:46:26 -07:00
shenleiandClaude Haiku 5.5 31c5b3dd9b Net: show damage numbers through the actor damage queue
Port CInstanceBase::AddDamageEffect/ProcessDamage: damage packets queue
per actor and show one digit-effect burst per update, dodge/block show
the miss effect. Add CEffectManager::SetEffectTextures and
CFlyingManager::CreateIndexedFly for the indexed fly types, and reset
the damage target on GC_PHASE loading.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-13 21:50:50 +09:00
shenleiandClaude Opus 5.5 f6dfcfc337 Port .msa motion events, .mss sounds and skill motions
ParseRaceMotionData now reads LoopData, MotionEventData and the per-motion
.mss sound script. ActorInstance runs the events each 1/60 s frame:
effects, sounds, splash attacks, fly shots, show/hide and warp. Player
skill and guild-skill motions are registered. ClickSkillSlot and remote
FUNC_SKILL states play the skill motions, and fly targets are synced with
the server (audit P1 #4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:11:00 +09:00
shenleiandClaude Opus 5.5 31c74cec28 Net: port the select-phase packets
Character create/delete/rename and empire selection now reach the
server, and LOGIN_SUCCESS3, PLAYER_CREATE_SUCCESS/FAILURE,
PLAYER_DELETE_SUCCESS/WRONG_SOCIAL_ID, POINT_CHANGE and CHANGE_NAME are
parsed and forwarded to the select/create windows like Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:27:52 +09:00
shenleiandClaude Opus 5.5 40cac5cf52 Net: handle in-game GC_PHASE like the Windows client
PHASE_SELECT returns the connection to LoginSession (cached roster,
SelectReady, later LOGIN_SUCCESS refreshes), PHASE_CLOSE goes to the
login phase, LOADING clears the player, GAME refreshes the status and
DEAD no longer leaves the game phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:24:12 +09:00
shenleiandClaude Opus 5.5 189da4c269 Net: reconnect to the new core on GC_WARP
RecvWarpPacket now matches Windows: DirectEnter for the selected slot
(warp flavour, SetNewLoadingPhase) and Connect(lAddr, wPort) through
LoginClient::warp, discarding what is left on the old socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:20:47 +09:00
shenleiandClaude Opus 5.5 ce6d457808 PORT-PLAN: record the module-by-module Windows parity audit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:13:40 +09:00
shenleiandClaude Opus 5.5 47e867252f Terrain: stream the 3x3 blocks around the player
CMapOutdoor keeps the 3x3 terrain blocks around the player loaded and
reloads them on a block change; we loaded only the warp block, so the
map ended at its edge. Stitch the set into one TerrainHeightmap, fix the
attr.atr cell mapping, and reload terrain, areadata and water per block
from CPythonBackground::Update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:38:11 +09:00
shenleiandClaude Opus 5.5 29f33b289a Render: intro pose, preview hair, tree LOD and terrain seams
- chrRender collects intro draws with hardware skinning off (CPU scene path
  ignores GPU palettes, so the select-screen character stayed in T-pose).
- Preview player hair: warrior/hair/hair_1_1.gr2 (old path did not exist).
- SpeedTree: always draw full geometry like CSpeedTreeWrapper::Advance
  (SetLodLevel(1.0f)); resolve SPT texture names as GetPath+NoExtension+.dds.
- Terrain patches get edge skirts to hide step-1/step-2 T-junction cracks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:19:44 +09:00
shenleiandClaude Opus 5.5 e0b97c2099 Mobile: tapping the focused edit line re-shows the keyboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:53:10 +09:00
shenleiandClaude Opus 5.5 445dd06048 Android: left inset ignores the back-gesture zone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:45:47 +09:00
shenleiandClaude Opus 5.5 ae713a0772 Mobile touch: system edges, per-finger cancel, long-press sort
Interaction ideas from jhaizhou-ops/d2r-mobile (MIT), no code taken:
- world fingers in the bottom safe inset (gesture bar) are ignored
- SDL_EVENT_FINGER_CANCELED cancels one finger; a cancelled joystick
  keeps its vector for 300 ms and a finger near the old base re-acquires it
- attack taps shorter than a frame release on the next Update
- cancelled UI touches and world taps park the pointer (no hover residue)
- long press on an empty inventory cell offers the original sort

Desktop ctest 59/59; sort sheet verified on the device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:42:44 +09:00
shenleiandClaude Opus 5.5 c132891aef Mobile HUD: minimap radar in its frame, top row at the screen edge
Preview radar drew at the fixed PC spot; it now follows the uiminimap
window (CPythonMiniMap::GetScreenPosition) and its open state. On
Android the top safe inset came from the hidden status bar's gesture
zone; Ava2Surface takes the top only from the cutout and visible bars.
The preview keyboard-hint header is skipped in touch mode, and
--game-script also runs with --preview-data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:15:37 +09:00
shenleiandClaude Opus 5.5 15b2397b54 Build against the real SpeedTree SDK; keep assert-based tests in release
SDK 62a5f5a carries the SpeedTree runtime, so the local mirror/shim is no
longer needed. attack_combo and ava2_render_3d tests called the code under
test inside assert() and segfaulted under NDEBUG; undefine it like
hardware_scene_test. android/build.sh prefers the SDK adb. Desktop ctest
59/59 incl. speedtree_forest; device 60 fps with real trees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:03:57 +09:00
shenleiandClaude Opus 5.5 8f96e7a143 Android device verification: forced landscape, fullscreen, data layering
- Ava2Activity passes the "args" intent extra as the command line
  (build.sh forwards AVA2_ARGS); it also always requests sensor landscape.
- app_loop sets SDL_HINT_ORIENTATIONS to landscape and creates the window
  fullscreen on Android/iOS (SDL requested FULL_USER for the resizable
  window, overriding the manifest; the status bar drew over the HUD).
- push_assets.py: pack-manifest test-rundir now wins over assets/loose
  (~1000 differing files; half-size tree atlases broke SpeedTree UVs),
  pushes in batches of <=20k files, and chmods shell-owned files so the
  app can read them on Android 17.
- PORT-PLAN: device verification results and outstanding gaps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:53:56 +09:00
shenleiandClaude Opus 5.5 6244b1d860 Mobile gestures: item tap/drag/double-tap/long-press on original windows
Port the EterPythonLib CSlotWindow/CGridSlotWindow mouse handlers
(select, drop, use, right click, tooltips, grid picking/CheckMoving) and
CWindowManager IsDragging/right button, which were missing so item
interaction did not work on desktop either. app.SetMouseHandler now
renders the attached icon, app.IsPressed reads real key state, desktop
double clicks reach the window manager.

The touch router maps UI touches to the original mouse: tap = click at
the touch-down point, drag = press-and-drag, double tap = double click,
long press on an item slot = touch.SetLongPressEvent, which opens the
ui_mobile_actions item sheet (use / split / quick slot via virtual
Shift/Ctrl). New ava2.inventory_touch test drives uiinventory.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:16:12 +09:00
shenleiandClaude Opus 5.5 908838c8f9 Mobile step 7b: iOS packaging (simulator verified to the game scene)
- ios/build.sh builds static SDL3 + FreeType, then the .app (code only,
  embedded Python); signs ad hoc and runs on a simulator, or signs with a
  development profile and installs with devicectl (device path untested).
  Simulator-only SDL patch: accept the simulator Metal device for SDL_GPU.
- ios/Info.plist.in: landscape, full screen, launch screen, file sharing.
- Data dir is Documents on iOS; ios/push_assets.py stages the client root
  lower-cased (iOS is case-sensitive, the client opens lower-cased paths)
  and copies it into the app container.
- EffectData path normalisation folds A-Z like the effect cache key.
- android/push_assets.py: test-rundir base layer + svside/, which the game
  phase needs (also fixes Android); --lowercase (ASCII only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 01:21:07 +09:00
shenleiandClaude Opus 5.5 f973b24abc Split the frame loop out of main.cpp (app_loop) for SDL main callbacks
main.cpp moves to app_loop.cpp; its body becomes RunClient, a C++20
coroutine suspended at the top of each frame, driven by ava2::app::AppLoop
(Start/Iterate/QueueEvent/Finish/Run). The new main.cpp uses SDL main
callbacks (AVA2_MAIN_CALLBACKS, default on except Android) or the classic
loop. Screenshots are byte-identical through both drivers; 54/54 tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:28:50 +09:00
shenleiandClaude Opus 5.5 64d25e3571 Mobile step 6: client-side auto hunt with AUTO button
Engine-free AutoHunt state machine (search/engage/loot/return/paused) driven
from the game loop through the existing manual paths: move target, target
packet, normal attack, quickslot skills, item pick-up and belt potions.
player.SetAutoHunt/GetAutoHuntState/SetAutoHuntOption with autohunt.cfg;
AUTO button on the combat wheel (tap toggles, long press opens settings).
Tests: ava2.auto_hunt, extended ava2.touch_game; 54/54.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:05:15 +09:00
shenleiandClaude Opus 5.5 ed2c185135 Mobile UI scaling and live safe-area relayout (mobile step 5)
Phones and tablets pick the logical UI size from the screen (height
600..768 from the dp height, width from the aspect ratio) instead of
letterboxing 1024x768; metin2.cfg is left untouched via a display-size
override. --phone/--safe-insets/--ui-height simulate on desktop. The
mobile HUD rebuilds and re-adopts the original windows when the safe
area changes. Keeps HUD gauge backgrounds alive and fixes the step-4
disc pixel check threshold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:39:58 +09:00
shenleiandClaude Opus 5.5 11bd94d1ce Mobile HUD layout: disc widgets, quickslot wheel and belt (mobile step 4)
Native CDisc window for procedural round frames; ui_mobile_widgets
(RoundButton, QuickSlotDisc); HUD laid out as the phone plan: player
panel, top-right entry row with minimap, left button column, attack disc
with two quickslot rings, potion belt on quickslot page 4, exp bar. The
PC taskbar and its tooltips are hidden in mobile mode. Adds global
quickslot use/add/move for the belt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:14:29 +09:00
shenleiandClaude Opus 5.5 b79fbce0b0 Add platform layer: lifecycle, data dirs, safe area (mobile step 2)
Move the macOS/Android data and config directory code out of main.cpp
into src/app/platform. Handle background/foreground: save config and
interface status, pause audio, cancel touch input and skip rendering
while keeping the network pumped. Map the window safe area through the
letterboxed presentation into TouchLayout and expose touch.GetSafeArea()
so the mobile HUD stays clear of notches and gesture bars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:45:07 +09:00
shenleiandClaude Opus 5.5 260d421bde Wire attack and combo execution (mobile step 3b)
Port the ActorInstanceBattle combo state machine, CRaceMotionData attack
data, player motion/combo tables, NEW_Attack + OnAttack/OnHit packets and
remote FUNC_ATTACK/FUNC_COMBO playback so keyboard and touch attacks swing
and hit on the real-server path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:30:57 +09:00
shenleiandClaude Opus 5.5 5597842d90 Add touch input router for mobile (step 3)
Route each finger to UI, the attack button, a floating lower-left joystick or
the camera (drag rotate, pinch zoom, tap = world click). Touch mode is default
on Android/iOS and available on desktop via --touch / AVA2_TOUCH=1; it disables
SDL touch-to-mouse and drives app.ENABLE_MOBILE_HUD. The joystick feeds the
original camera-relative movement path and the attack button sets the same
attack-key state as player.SetAttackKeyState. New `touch` Python module; the
mobile HUD joystick and combat wheel become display-only.

Tests: ava2.touch_router, ava2.touch_game (GameWindow + mobile HUD).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 19:46:24 +09:00
shenleiandClaude Opus 5.5 1dfdcba739 android: name push_assets.py in the missing-data message
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:59:50 +09:00
shenleiandClaude Opus 5.5 81bf7ae629 PORT-PLAN: record Android step 1 (APK packaging and game data)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:58:22 +09:00
shenleiandClaude Opus 5.5 60fa7f7d82 android: add push_assets.py for development game data
Stages assets/loose + upstream/python-root (scripts win, case-insensitive)
+ python27.zip as a hard-link tree in build/android-data/root and sends it
to the app's external files directory with adb push --sync, so later runs
only transfer changed files. The committed assets/loose symlinks into the
old machine's pack_maker tree (bgm, sound/ui, icon/icon) are remapped to
the local pack_maker. The desktop client reaches the login screen inside
the staged tree with no missing-effect errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:58:00 +09:00
shenleiandClaude Opus 5.5 4b8425c64b Show the on-screen keyboard only while an edit line has focus
SDL_StartTextInput was called once for the whole session, which keeps the
Android soft keyboard over the game. Where SDL reports on-screen keyboard
support, the frame loop now starts/stops text input with the original
EditLine focus (ime.EnableCaptureInput/DisableCaptureInput in ui.py), the
in-game chat and the dev login view. Desktop keeps text input always on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:55:51 +09:00
shenleiandClaude Opus 5.5 b0044c9097 android: run from the app's external files directory
The APK holds code only: on Android the client enters
SDL_GetAndroidExternalStoragePath() at startup, where the flattened client
root (assets/loose + python-root + python27.zip) is pushed. Script-root
discovery now also accepts a flattened root (game.py beside uiscript/) in
the working directory. Missing data shows a message box, and fatal errors
go to logcat because stderr is not captured on Android.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:55:50 +09:00
shenleiandClaude Opus 5.5 3ce5fc1a6c android: complete the Gradle project and add build.sh
Move support/android to a top-level android/ and make it build:
Gradle 8.12 wrapper + AGP 8.7.3, compileSdk/targetSdk 35, SDL3 3.4.16
and FreeType 2.13.3 built once into build/android-deps (SDL Java sources
copied from the same release), libSDL3.so staged as a jniLib, 16 KB page
alignment, RelWithDebInfo native code for debug APKs, placeholder adaptive
icon. build.sh installs and launches the APK when a phone is attached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:47:18 +09:00
shenleiandClaude Opus 5.5 043881f032 docs: add mobile architecture plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:30:23 +09:00
shenleiandClaude Opus 5.5 35f768b6ae PORT-PLAN: record helper attachments kept across rebinds
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:18:14 +09:00
shenleiandClaude Opus 5.5 c556795ecf Keep SetWeapon/AttachPart helper attachments across rebinds
Helper attachments made outside the part slots were attached to
PART_MAIN only and dropped whenever the parts were rebound (LOD level
change, shape change, slot update). They are now recorded on the actor,
attached to the drawn instance and re-attached after the slots. A slot
taking the same bone drops the helper (last writer wins, as before);
SetRace/SetModel clear them. LODs missing a helper's bone stay on
PART_MAIN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:18:14 +09:00
shenleiandClaude Opus 5.5 552f6c7df4 PORT-PLAN: record blended centre sort and sibling SDK default
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:09:32 +09:00
shenleiandClaude Opus 5.5 5de09d07e9 Sort blended draws by bounds centre instead of first vertex
Back-to-front order for blended, non-depth-writing, water and additive
draws now uses the bounds centre of the vertices the draw indexes. The
centre of shared (immutable) geometry is cached per index range and
validated against the owning pointer; per-frame geometry is recomputed.
Depth-writing opaque draws keep the first-vertex tie-break.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:09:31 +09:00
shenleiandClaude Opus 5.5 efb7c120c0 Build against sibling ../sdk by default
Point the sdk submodule at https://git.slcydia.fun/4v5u09Z5a4Yuc/metin2-SDK.git
and default AVA2_SDK_ROOT to an SDK checkout beside the repository
(../sdk), falling back to the pinned submodule when it is absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:04:42 +09:00
shenleiandClaude Opus 5.5 7236edf747 PORT-PLAN: record real-time clocks and LOD mesh swap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:56:56 +09:00
shenleiandClaude Opus 5.5 bfd42bd776 Swap actor body to _lod_ meshes by camera distance
Port CGrannyLODController level selection: _lod_01.._03 are queued
{lod_03, lod_02, lod_01, main}, loaded lazily, and chosen from the
camera-target/camera distance bands (actors) or the building factor.
Parts, skins and the current motion follow the drawn instance.

Shipped LODs that drop an attaching bone in use (lion2_lod_02/03 lose
"saddle", shaman_miyeom_lod_* lose equip_left/right) stay on PART_MAIN,
and bone queries fall back to PART_MAIN for bones a LOD lacks.
Weapon item LODs are not ported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:56:41 +09:00
shenleiandClaude Opus 5.5 6282199179 Drive animation clocks from real frame time
Water, network-actor, flying-effect and weapon-trace clocks used
frames*0.033 or frames/60, and the sky box, effect.Update, fly.Update and
render-target previews advanced a fixed 1/30 or 1/60 s per call, so their
speed followed the frame rate. They now use the measured frame delta
(game_clock = sum of dt in main; GetGameFrameDelta for the Python-driven
paths; elapsed SDL ticks for render targets). --frames runs keep their
fixed 0.033 s step. The SpeedTree wind update is left unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:44:04 +09:00
185 changed files with 49392 additions and 4011 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "sdk"]
path = sdk
url = http://192.168.21.200:8418/4v5u09Z5a4Yuc/metin2-SDK.git
url = https://git.slcydia.fun/4v5u09Z5a4Yuc/metin2-SDK.git
+92 -11
View File
@@ -4,11 +4,19 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
include(CTest)
set(AVA2_SDK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/sdk" CACHE PATH "Metin2 SDK source directory")
# Default: the SDK checkout beside this repository (../sdk); fall back to the pinned submodule.
get_filename_component(_ava2_sibling_sdk "${CMAKE_CURRENT_SOURCE_DIR}/../sdk" ABSOLUTE)
if(EXISTS "${_ava2_sibling_sdk}/gr2/CMakeLists.txt" AND EXISTS "${_ava2_sibling_sdk}/speedtree/CMakeLists.txt")
set(_ava2_default_sdk "${_ava2_sibling_sdk}")
else()
set(_ava2_default_sdk "${CMAKE_CURRENT_SOURCE_DIR}/sdk")
endif()
set(AVA2_SDK_ROOT "${_ava2_default_sdk}" CACHE PATH "Metin2 SDK source directory")
if(NOT EXISTS "${AVA2_SDK_ROOT}/gr2/CMakeLists.txt" OR
NOT EXISTS "${AVA2_SDK_ROOT}/speedtree/CMakeLists.txt")
message(FATAL_ERROR "SDK missing. Run git submodule update --init --recursive or set AVA2_SDK_ROOT.")
message(FATAL_ERROR "SDK missing. Clone it beside this repository as ../sdk, run git submodule update --init --recursive, or set AVA2_SDK_ROOT.")
endif()
message(STATUS "AVA2 SDK: ${AVA2_SDK_ROOT}")
add_subdirectory("${AVA2_SDK_ROOT}/speedtree" ${CMAKE_CURRENT_BINARY_DIR}/sdk_speedtree)
add_subdirectory("${AVA2_SDK_ROOT}/gr2" ${CMAKE_CURRENT_BINARY_DIR}/sdk_gr2)
add_subdirectory(shared/codepage)
@@ -20,6 +28,13 @@ if(BUILD_TESTING)
target_link_libraries(skill_poly_test PRIVATE ava2_poly)
add_test(NAME ava2.skill_poly COMMAND skill_poly_test)
endif()
add_library(ava2_input src/app/input/touch_router.cpp)
target_include_directories(ava2_input PUBLIC src)
if(BUILD_TESTING)
add_executable(touch_router_test tests/touch_router_test.cpp)
target_link_libraries(touch_router_test PRIVATE ava2_input)
add_test(NAME ava2.touch_router COMMAND touch_router_test)
endif()
add_library(ava2_protocol src/network/protocol.cpp src/network/legacy_cipher.cpp src/network/login_session.cpp)
target_include_directories(ava2_protocol PUBLIC src src/network src/game)
find_package(Threads REQUIRED)
@@ -27,7 +42,7 @@ find_package(SDL3 CONFIG REQUIRED)
add_library(ava2_transport src/network/login_client.cpp)
target_include_directories(ava2_transport PUBLIC src src/network)
target_link_libraries(ava2_transport PUBLIC ava2_protocol Threads::Threads)
add_library(ava2_render src/eter_render/HardwareScene.cpp src/eter_render/Gr2ModelRenderer.cpp src/eter_render/TerrainHeightmap.cpp src/eter_render/MapObjectManager.cpp src/eter_render/WaterManager.cpp src/eter_render/OrbitCamera.cpp src/eter_render/MinimapManager.cpp src/eter_render/ActorInstance.cpp src/eter_render/RaceData.cpp src/eter_render/FloatingTextManager.cpp src/eter_render/TargetManager.cpp src/eter_render/TextTailManager.cpp src/eter_sound/SoundManager.cpp src/eter_resource/dxt.cpp src/eter_effect/EffectData.cpp src/eter_effect/EffectInstance.cpp src/eter_effect/FlyTrace.cpp src/eter_effect/FlyingManager.cpp src/eter_effect/EffectManager.cpp src/eter_net/NetworkActorManager.cpp src/eter_render/EnvironmentData.cpp src/eter_render/SkyBox.cpp src/eter_render/SpeedTreeRT.cpp src/eter_render/SpeedTreeForest.cpp src/eter_image/MarkManager.cpp src/eter_render/CRenderTarget.cpp shared/common/CRC32.cpp src/eter_image/GrpImageInstance.cpp src/eter_image/GrpDevice.cpp src/eter_resource/texture_decode.cpp)
add_library(ava2_render src/eter_base/Timer.cpp src/eter_base/Random.cpp src/eter_render/HardwareScene.cpp src/eter_render/Gr2ModelRenderer.cpp src/eter_render/TerrainHeightmap.cpp src/eter_render/MapObjectManager.cpp src/eter_render/WaterManager.cpp src/eter_render/OrbitCamera.cpp src/eter_render/MinimapManager.cpp src/eter_render/ActorInstance.cpp src/eter_render/ActorInstanceMotionEvent.cpp src/eter_render/RaceData.cpp src/eter_render/FloatingTextManager.cpp src/eter_render/TargetManager.cpp src/eter_render/TextTailManager.cpp src/eter_sound/SoundManager.cpp src/eter_resource/dxt.cpp src/eter_effect/EffectData.cpp src/eter_effect/EffectInstance.cpp src/eter_effect/FlyTrace.cpp src/eter_effect/FlyingManager.cpp src/eter_effect/EffectManager.cpp src/eter_net/NetworkActorManager.cpp src/eter_render/EnvironmentData.cpp src/eter_render/SkyBox.cpp src/eter_render/SpeedTreeRT.cpp src/eter_render/SpeedTreeForest.cpp src/eter_image/MarkManager.cpp src/eter_render/CRenderTarget.cpp shared/common/CRC32.cpp src/eter_image/GrpImageInstance.cpp src/eter_image/GrpDevice.cpp src/eter_resource/texture_decode.cpp)
target_include_directories(ava2_render PUBLIC src src/network src/game ${CMAKE_CURRENT_SOURCE_DIR} third_party/extern_include)
target_link_libraries(ava2_render PUBLIC libgr2 libgr2_render speedtree SDL3::SDL3)
option(AVA2_EMBED_PYTHON "Build embedded Python 2.7 runtime" ON)
@@ -55,11 +70,13 @@ if(AVA2_EMBED_PYTHON)
src/scripting/python_runtime.cpp
src/scripting/python_net.cpp
src/scripting/python_dbg.cpp
src/scripting/python_touch.cpp
src/scripting/python_system.cpp
src/scripting/python_minimap.cpp
src/scripting/python_chr.cpp
src/scripting/python_app.cpp
src/game/player_settings.cpp
src/game/auto_hunt.cpp
src/scripting/python_wndmgr.cpp
src/scripting/python_gameplay_modules.cpp
src/scripting/python_ime.cpp
@@ -68,8 +85,6 @@ if(AVA2_EMBED_PYTHON)
src/scripting/python_event_manager.cpp
src/scripting/python_chat.cpp
src/eter_lib/parser.cpp
src/eter_base/Random.cpp
src/eter_base/Timer.cpp
src/game/game_type.cpp
src/eter_ui/PythonWindow.cpp
src/eter_ui/PythonWindowManager.cpp
@@ -79,7 +94,7 @@ if(AVA2_EMBED_PYTHON)
src/eter_net/PythonExchange.cpp
src/eter_net/PythonSafeBox.cpp)
target_include_directories(ava2_python PUBLIC src src/network src/game src/scripting ${CMAKE_CURRENT_SOURCE_DIR} third_party/extern_include)
target_link_libraries(ava2_python PUBLIC SDL3::SDL3 mtpython ava2_render PRIVATE mt_codepage ava2_transport ava2_lzo ava2_poly)
target_link_libraries(ava2_python PUBLIC SDL3::SDL3 mtpython ava2_render ava2_input PRIVATE mt_codepage ava2_transport ava2_lzo ava2_poly)
target_sources(ava2_python PRIVATE src/eter_ui/Font.cpp)
find_package(Freetype QUIET)
if(Freetype_FOUND)
@@ -110,6 +125,17 @@ if(BUILD_TESTING AND NOT ANDROID)
add_test(NAME ava2.player_panel COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py"
"AVA2 skill slot, received level and derived status parity passed" "$<TARGET_FILE:player_panel_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
add_executable(python_test tests/python_test.cpp)
add_executable(windows_behavior_test tests/windows_behavior_test.cpp)
target_link_libraries(windows_behavior_test PRIVATE ava2_python ava2_protocol)
add_dependencies(windows_behavior_test mtpython_stdlib)
add_test(NAME ava2.windows_behavior COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py"
"AVA2 Windows network, player and terrain behavior parity passed" "$<TARGET_FILE:windows_behavior_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
add_executable(player_motion_test tests/player_motion_test.cpp)
target_link_libraries(player_motion_test PRIVATE ava2_python ava2_protocol)
add_dependencies(player_motion_test mtpython_stdlib)
add_test(NAME ava2.player_motion COMMAND player_motion_test "${MT_PYTHON_STDLIB_ZIP}")
set_tests_properties(ava2.player_motion PROPERTIES SKIP_RETURN_CODE 77
ENVIRONMENT "AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}")
target_link_libraries(python_test PRIVATE ava2_python ava2_lzo ava2_protocol)
add_dependencies(python_test mtpython_stdlib)
add_executable(item_data_test tests/item_data_test.cpp)
@@ -204,9 +230,24 @@ if(BUILD_TESTING AND NOT ANDROID)
add_test(NAME ava2.game_entry COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py"
"Original GameWindow, inventory, taskbar and minimap created successfully" "$<TARGET_FILE:game_entry_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
set_tests_properties(ava2.game_entry PROPERTIES ENVIRONMENT "AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}" SKIP_RETURN_CODE 77)
add_executable(touch_game_test tests/touch_game_test.cpp)
target_link_libraries(touch_game_test PRIVATE ava2_python mtpython)
add_dependencies(touch_game_test mtpython_stdlib)
add_test(NAME ava2.touch_game COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py"
"Touch router drives joystick, attack and world taps around the mobile HUD" "$<TARGET_FILE:touch_game_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
set_tests_properties(ava2.touch_game PROPERTIES ENVIRONMENT "AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}" SKIP_RETURN_CODE 77)
add_executable(inventory_touch_test tests/inventory_touch_test.cpp)
target_link_libraries(inventory_touch_test PRIVATE ava2_python mtpython)
add_dependencies(inventory_touch_test mtpython_stdlib)
add_test(NAME ava2.inventory_touch COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py"
"Touch gestures drive the original inventory" "$<TARGET_FILE:inventory_touch_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
set_tests_properties(ava2.inventory_touch PROPERTIES ENVIRONMENT "AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}" SKIP_RETURN_CODE 77)
add_test(NAME ava2.pack_assets COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/pack_assets_test.py")
endif()
add_executable(auto_hunt_test tests/auto_hunt_test.cpp src/game/auto_hunt.cpp)
target_include_directories(auto_hunt_test PRIVATE src/game)
add_test(NAME ava2.auto_hunt COMMAND auto_hunt_test)
add_executable(server_clock_test tests/server_clock_test.cpp)
target_include_directories(server_clock_test PRIVATE src src/network)
add_test(NAME ava2.server_clock COMMAND server_clock_test)
@@ -216,6 +257,12 @@ if(BUILD_TESTING AND NOT ANDROID)
add_executable(ava2_render_3d_test tests/ava2_render_3d_test.cpp)
target_link_libraries(ava2_render_3d_test PRIVATE ava2_render)
add_test(NAME ava2.render_3d COMMAND ava2_render_3d_test "ymir work/pc/warrior/warrior_assasin1.gr2")
add_executable(flying_target_test tests/flying_target_test.cpp)
target_link_libraries(flying_target_test PRIVATE ava2_render)
add_test(NAME ava2.flying_target COMMAND flying_target_test)
add_executable(attack_combo_test tests/attack_combo_test.cpp)
target_link_libraries(attack_combo_test PRIVATE ava2_render)
add_test(NAME ava2.attack_combo COMMAND attack_combo_test "ymir work/pc/warrior/warrior_assasin1.gr2")
if(AVA2_EMBED_PYTHON)
add_executable(hardware_scene_test tests/hardware_scene_test.cpp)
target_link_libraries(hardware_scene_test PRIVATE ava2_python)
@@ -306,7 +353,7 @@ if(BUILD_TESTING AND NOT ANDROID)
target_include_directories(login_oracle_test PRIVATE "${CMAKE_BINARY_DIR}/generated")
target_link_libraries(login_oracle_test PRIVATE ava2_protocol)
add_test(NAME ava2.login_oracle COMMAND login_oracle_test)
foreach(asset_test ava2.python ava2.window_tree ava2.render_3d ava2.mark_manager)
foreach(asset_test ava2.python ava2.window_tree ava2.render_3d ava2.attack_combo ava2.mark_manager)
if(TEST ${asset_test})
set_tests_properties(${asset_test} PROPERTIES SKIP_RETURN_CODE 77
ENVIRONMENT "AVA2_PACK_MAKER=${AVA2_PACK_MAKER_DIR};AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}")
@@ -320,15 +367,49 @@ if(BUILD_TESTING AND NOT ANDROID)
endif()
if(AVA2_BUILD_HOST)
find_package(SDL3 CONFIG REQUIRED)
add_library(ava2_platform src/app/platform/platform.cpp)
target_include_directories(ava2_platform PUBLIC src)
target_link_libraries(ava2_platform PUBLIC SDL3::SDL3)
if(BUILD_TESTING)
add_executable(platform_test tests/platform_test.cpp)
target_link_libraries(platform_test PRIVATE ava2_platform ava2_input)
add_test(NAME ava2.platform COMMAND platform_test)
endif()
# SDL main callbacks drive src/app/app_loop.cpp (required on iOS); Android keeps the classic loop.
if(ANDROID)
add_library(main SHARED src/app/main.cpp)
set(AVA2_HOST main)
set(AVA2_MAIN_CALLBACKS_DEFAULT OFF)
else()
add_executable(ava2_client src/app/main.cpp)
set(AVA2_MAIN_CALLBACKS_DEFAULT ON)
endif()
option(AVA2_MAIN_CALLBACKS "Drive the client through SDL_AppInit/SDL_AppIterate" ${AVA2_MAIN_CALLBACKS_DEFAULT})
set(AVA2_HOST_SOURCES src/app/main.cpp src/app/app_loop.cpp)
if(ANDROID)
add_library(main SHARED ${AVA2_HOST_SOURCES})
set(AVA2_HOST main)
elseif(CMAKE_SYSTEM_NAME STREQUAL "iOS")
# ios/build.sh: an .app with code only; the client root goes to Documents (ios/push_assets.py).
add_executable(ava2_client MACOSX_BUNDLE ${AVA2_HOST_SOURCES})
set(AVA2_HOST ava2_client)
if(CMAKE_OSX_SYSROOT MATCHES "[Ss]imulator")
set(AVA2_IOS_PLATFORM iPhoneSimulator)
else()
set(AVA2_IOS_PLATFORM iPhoneOS)
endif()
set(AVA2_IOS_BUNDLE_ID "com.metin2.ava2" CACHE STRING "iOS bundle identifier")
set_target_properties(ava2_client PROPERTIES
MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/ios/Info.plist.in"
MACOSX_BUNDLE_GUI_IDENTIFIER "${AVA2_IOS_BUNDLE_ID}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "1.0.0"
MACOSX_BUNDLE_BUNDLE_VERSION "1")
else()
add_executable(ava2_client ${AVA2_HOST_SOURCES})
set(AVA2_HOST ava2_client)
endif()
if(AVA2_MAIN_CALLBACKS)
target_compile_definitions(${AVA2_HOST} PRIVATE AVA2_MAIN_CALLBACKS)
endif()
target_include_directories(${AVA2_HOST} PRIVATE src src/app src/game src/network src/scripting)
target_link_libraries(${AVA2_HOST} PRIVATE SDL3::SDL3 ava2_protocol ava2_render)
target_link_libraries(${AVA2_HOST} PRIVATE SDL3::SDL3 ava2_protocol ava2_render ava2_platform)
if(AVA2_EMBED_PYTHON)
target_link_libraries(${AVA2_HOST} PRIVATE ava2_python)
target_compile_definitions(${AVA2_HOST} PRIVATE AVA2_HAS_PYTHON)
+8 -6
View File
@@ -3,7 +3,7 @@
Independent AVA2 port, Android arm64 first with macOS arm64 for development. The host, login/selection transport, supported loading/game socket bridge and Python 2 bootstrap are implemented. It is not yet a playable client.
```sh
git submodule update --init --recursive
git submodule update --init --recursive # only when ../sdk is not checked out
cmake -S . -B build/dev -DCMAKE_BUILD_TYPE=Debug
cmake --build build/dev -j 8
ctest --test-dir build/dev --output-on-failure
@@ -17,14 +17,16 @@ SDL3 development package is required for the window host. Use `-DAVA2_BUILD_HOST
Android CMake builds require the NDK toolchain and an Android SDL3 SDK prefix. The `main` shared library compiles and links for arm64; APK packaging and device verification are pending. Original decoded assets remain in the sibling AVA2 directory; only immutable source/script references are copied into this repository.
See [port status](docs/PORT-PLAN.md), [login implementation and verification](docs/LOGIN-TRANSPORT.md), and [active login profile](docs/LOGIN-PROFILE.json).
See [port status](docs/PORT-PLAN.md), [mobile architecture](docs/MOBILE-ARCHITECTURE.md), [login implementation and verification](docs/LOGIN-TRANSPORT.md), and [active login profile](docs/LOGIN-PROFILE.json).
Windows equivalence is tracked in [the parity audit](docs/WINDOWS-PARITY.md). Preview characters require `--preview-data`; game previews do not prove server gameplay. The static [placeholder inventory](docs/WINDOWS-PARITY-INVENTORY.json) is regenerated with `python3 tools/audit_windows_parity.py`.
The SDK is maintained in its own Git repository and pinned by the `sdk` submodule.
Clone with `git clone --recurse-submodules`, or run the initialization command above
before configuring. To develop against an existing SDK checkout, configure with
`-DAVA2_SDK_ROOT=/absolute/path/to/sdk`; normal builds use the pinned submodule.
The SDK is maintained in its own Git repository
(https://git.slcydia.fun/4v5u09Z5a4Yuc/metin2-SDK.git). By default CMake uses an SDK
checkout beside this repository (`../sdk`, i.e. `chakan` and `sdk` in the same parent
directory). Without it, the build falls back to the pinned `sdk` submodule: clone with
`git clone --recurse-submodules` or run the initialization command above. Any other
checkout can be selected with `-DAVA2_SDK_ROOT=/absolute/path/to/sdk`.
Keep build outputs in `build/dev`, `build/release`, or another named directory
under `build/`, rather than configuring directly into `build/`. Put diagnostic
+5
View File
@@ -0,0 +1,5 @@
.gradle/
build/
app/build/
app/.cxx/
local.properties
+56
View File
@@ -0,0 +1,56 @@
# AVA2 Android client
Gradle project for the arm64-v8a APK: SDL3 `SDLActivity` + `libmain.so` (the client, with the
embedded CPython 2.7). The APK holds code only. Game data (`ymir work`, maps, sound, python-root,
`python27.zip`) lives in the app's external files directory, see below.
Architecture and roadmap: `docs/MOBILE-ARCHITECTURE.md`.
## Requirements
- Android SDK with platform 35, NDK 27.2.12479018 and CMake 3.22.1 (`sdkmanager "ndk;27.2.12479018" "cmake;3.22.1"`)
- JDK 17+ (`brew install openjdk@21`; `build.sh` finds it automatically)
- The SDK checkout beside this repository (`../sdk`), as for the desktop build
## Build
```bash
android/build.sh # debug APK; installs and launches it when a phone is attached
android/build.sh release # release APK
android/build.sh deps # only build SDL3 + FreeType into build/android-deps
```
The first run downloads and builds SDL3 and FreeType once into `build/android-deps`. The SDL
Java sources are copied from the same SDL release so they always match `libSDL3.so`. The debug
APK compiles C++ as RelWithDebInfo; a Debug build is too slow to judge frame rate.
Overrides: `ANDROID_HOME`, `ANDROID_NDK_HOME`, `JAVA_HOME`, `AVA2_SDK_ROOT`, `AVA2_SOURCE_DIR`
(CMake source tree to build instead of this checkout), `ADB_SERIAL`.
`AVA2_ARGS` passes client arguments to the launch (`Ava2Activity` reads the `args` intent
extra), e.g. `AVA2_ARGS="--phase game --preview-data" android/build.sh`, or by hand:
`adb shell "am start -n com.metin2.ava2/.Ava2Activity --es args '--phase game --preview-data'"`.
Android Studio can open this directory after `android/build.sh deps` has run once.
## Game data on the phone
```bash
android/push_assets.py # after android/build.sh, with the phone attached
```
Stages `assets/loose`, then `build/dev/test-rundir` (the pack-manifest root from
`tools/make_test_rundir.py`; its pack files win), then `upstream/python-root` (scripts win) and
`python27.zip` as hard links in
`build/android-data/root` and sends them with `adb push --sync` to
`/sdcard/Android/data/com.metin2.ava2/files`, where the client starts. The first push moves
about 4 GB; later pushes only send changed files. The three `assets/loose` symlinks into the
decoded pack_maker tree are remapped to `--pack-maker` (default `../AVA2/TEST/1. Client DEV/pack_maker`).
Uninstalling the app deletes this directory.
On Android 17 (OnePlus PJZ110) the directories `adb push` creates are `shell`-owned with mode
2770, so the app cannot enter them and the first model load dies with `posix_stat ... Permission
denied`. push_assets.py therefore runs `chmod` over the pushed tree afterwards (directories 2777,
files 666).
Running the desktop client inside `build/android-data/root` exercises the same flattened layout.
Logs: `adb logcat -s SDL SDL/APP AndroidRuntime DEBUG`.
+84
View File
@@ -0,0 +1,84 @@
plugins {
id 'com.android.application'
}
// android/build.sh passes these; the defaults let Android Studio reuse what `build.sh deps` built.
def repoRoot = file('../..').canonicalPath
// AVA2_SOURCE_DIR builds another checkout/mirror of this repository (e.g. one with local SDK shims).
def sourceDir = project.findProperty('AVA2_SOURCE_DIR') ?: repoRoot
def depsPrefix = project.findProperty('AVA2_DEPS_PREFIX') ?: "${repoRoot}/build/android-deps/prefix-arm64-v8a"
def sdlJava = project.findProperty('AVA2_SDL_JAVA') ?: "${repoRoot}/build/android-deps/sdl-java"
def cmakeArgs = [
"-DAVA2_BUILD_HOST=ON", "-DAVA2_EMBED_PYTHON=ON", "-DBUILD_TESTING=OFF",
"-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DSDL3_DIR=${depsPrefix}/lib/cmake/SDL3", "-DCMAKE_FIND_ROOT_PATH=${depsPrefix}",
]
if (project.hasProperty('AVA2_SDK_ROOT')) cmakeArgs << "-DAVA2_SDK_ROOT=${project.property('AVA2_SDK_ROOT')}"
android {
namespace 'com.metin2.ava2'
compileSdk 35
ndkVersion project.findProperty('AVA2_NDK_VERSION') ?: '27.2.12479018'
defaultConfig {
applicationId "com.metin2.ava2"
minSdk 26
targetSdk 35
versionCode 1
versionName "0.1.0"
ndk {
abiFilters 'arm64-v8a'
}
externalNativeBuild {
cmake {
arguments(*cmakeArgs)
targets 'main'
}
}
}
buildTypes {
release {
minifyEnabled false
}
debug {
debuggable true
jniDebuggable true
// Debug-built C++ is too slow to judge frame rate on a phone.
externalNativeBuild { cmake { arguments "-DCMAKE_BUILD_TYPE=RelWithDebInfo" } }
}
}
externalNativeBuild {
cmake {
path file("${sourceDir}/CMakeLists.txt")
version project.findProperty('AVA2_CMAKE_VERSION') ?: '3.22.1'
}
}
sourceSets {
main {
java.srcDirs += [sdlJava]
jniLibs.srcDirs += ["${depsPrefix}/lib-jni"]
}
}
packagingOptions {
jniLibs {
useLegacyPackaging = false
}
}
lint {
abortOnError false
}
}
// libSDL3.so is a prebuilt dependency: stage it in the jniLibs layout AGP expects.
tasks.register('stageSdlLibrary', Copy) {
from "${depsPrefix}/lib/libSDL3.so"
into "${depsPrefix}/lib-jni/arm64-v8a"
}
preBuild.dependsOn stageSdlLibrary
@@ -1,37 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.metin2.ava2"
android:versionCode="1"
android:versionName="1.0.0">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
<uses-feature android:name="android.hardware.vulkan.level" android:required="false" android:version="1" />
<uses-feature android:name="android.hardware.vulkan.level" android:required="true" android:version="0" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:label="AVA2"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="true"
android:allowBackup="false"
android:appCategory="game"
android:isGame="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:enableOnBackInvokedCallback="false"
android:hardwareAccelerated="true">
<activity
android:name="org.libsdl.app.SDLActivity"
android:label="AVA2"
android:name="com.metin2.ava2.Ava2Activity"
android:label="@string/app_name"
android:alwaysRetainTaskState="true"
android:launchMode="singleInstance"
android:screenOrientation="sensorLandscape"
android:configChanges="layoutDirection|locale|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:configChanges="layoutDirection|locale|grammaticalGender|fontScale|fontWeightAdjustment|orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:preferMinimalPostProcessing="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Native library to load -->
<meta-data android:name="android.app.lib_name" android:value="main" />
</activity>
</application>
</manifest>
@@ -0,0 +1,70 @@
package com.metin2.ava2;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Insets;
import android.os.Build;
import android.view.View;
import android.view.WindowInsets;
import org.libsdl.app.SDLActivity;
import org.libsdl.app.SDLSurface;
/**
* SDLActivity with command-line arguments for development runs:
* {@code adb shell "am start -n com.metin2.ava2/.Ava2Activity --es args '--phase game --preview-data'"}.
* A normal launch (no extra) passes none, as before.
*/
public class Ava2Activity extends SDLActivity {
@Override
protected String[] getArguments() {
String args = getIntent() != null ? getIntent().getStringExtra("args") : null;
if (args == null || args.trim().isEmpty()) return new String[0];
return args.trim().split("\\s+");
}
/**
* The game is landscape-only. SDL re-requests an orientation whenever a window is created or
* resized (FULL_USER for a resizable window without SDL_HINT_ORIENTATIONS), which would override
* the manifest's sensorLandscape; keep both landscape directions regardless of the hint.
*/
@Override
public void setOrientationBis(int w, int h, boolean resizable, String hint) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
@Override
protected SDLSurface createSDLSurface(Context context) {
return new Ava2Surface(context);
}
/**
* SDL folds the system-gesture insets into the safe area. In landscape fullscreen the status bar
* is hidden, but its swipe-down gesture zone still reported a 120 px top inset, which pushed the
* top HUD row down. The left inset is the same story: Android measures the back-gesture zone
* (90 px) from the cutout edge, so it reported 120 + 90 px and the left HUD column sat far from
* the edge. Taps in the gesture zone still reach the app, so take top and left only from what
* really covers the screen (display cutout and visible system bars); keep SDL's right/bottom.
*/
static class Ava2Surface extends SDLSurface {
Ava2Surface(Context context) {
super(context);
}
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
WindowInsets result = super.onApplyWindowInsets(v, insets);
if (Build.VERSION.SDK_INT >= 30 /* Android 11 (R) */) {
Insets combined = insets.getInsets(WindowInsets.Type.systemBars() |
WindowInsets.Type.systemGestures() |
WindowInsets.Type.mandatorySystemGestures() |
WindowInsets.Type.tappableElement() |
WindowInsets.Type.displayCutout());
Insets covering = insets.getInsets(WindowInsets.Type.systemBars() |
WindowInsets.Type.displayCutout());
SDLActivity.onNativeInsetsChanged(covering.left, combined.right, covering.top, combined.bottom);
}
return result;
}
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#5A1A12" />
</shape>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- "A" monogram inside the 72dp adaptive-icon safe zone. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp"
android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#E8C46A"
android:pathData="M54,30 L74,78 L65,78 L60.5,66 L47.5,66 L43,78 L34,78 Z M50.3,58 L57.7,58 L54,47.5 Z" />
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Placeholder launcher icon until AVA2 artwork is chosen. -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AVA2</string>
</resources>
+3
View File
@@ -0,0 +1,3 @@
plugins {
id 'com.android.application' version '8.7.3' apply false
}
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env bash
# Builds the Android APK (arm64-v8a) and, when a device is attached, installs and launches it.
#
# android/build.sh debug APK (+ install/launch if `adb devices` lists a phone)
# android/build.sh release release APK (unsigned unless signing is configured)
# android/build.sh deps only (re)build the native dependencies
#
# Native dependencies (SDL3 + FreeType) are downloaded and built once into build/android-deps.
# Environment overrides: ANDROID_HOME, ANDROID_NDK_HOME, JAVA_HOME, AVA2_SDK_ROOT, AVA2_SOURCE_DIR
# (CMake source tree, default this checkout), ADB_SERIAL.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/.." && pwd)"
MODE="${1:-debug}"
SDL_VERSION=3.4.16
FREETYPE_VERSION=2.13.3
NDK_VERSION=27.2.12479018
CMAKE_VERSION=3.22.1
API_LEVEL=26
ABI=arm64-v8a
export ANDROID_HOME="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}"
export ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-$ANDROID_HOME/ndk/$NDK_VERSION}"
if [[ -z "${JAVA_HOME:-}" ]] || ! "$JAVA_HOME/bin/java" -version 2>&1 | grep -qE 'version "(1[7-9]|2[0-9])'; then
for candidate in /opt/homebrew/opt/openjdk@21 /opt/homebrew/opt/openjdk@17 /usr/local/opt/openjdk@21 \
"/Applications/Android Studio.app/Contents/jbr/Contents/Home"; do
[[ -x "$candidate/bin/java" ]] && { export JAVA_HOME="$candidate"; break; }
done
fi
[[ -d "$ANDROID_HOME" ]] || { echo "Android SDK not found (set ANDROID_HOME)"; exit 1; }
[[ -d "$ANDROID_NDK_HOME" ]] || { echo "NDK $NDK_VERSION not found (sdkmanager 'ndk;$NDK_VERSION')"; exit 1; }
[[ -x "${JAVA_HOME:-}/bin/java" ]] || { echo "JDK 17+ not found (brew install openjdk@21 or set JAVA_HOME)"; exit 1; }
CMAKE="$ANDROID_HOME/cmake/$CMAKE_VERSION/bin/cmake"
NINJA="$ANDROID_HOME/cmake/$CMAKE_VERSION/bin/ninja"
[[ -x "$CMAKE" ]] || { echo "CMake $CMAKE_VERSION not found (sdkmanager 'cmake;$CMAKE_VERSION')"; exit 1; }
DEPS="$ROOT/build/android-deps"
PREFIX="$DEPS/prefix-$ABI"
mkdir -p "$DEPS/src"
fetch() { # url file
[[ -f "$DEPS/src/$2" ]] && return
curl -fL --retry 3 -o "$DEPS/src/$2.part" "$1" || { echo "download failed: $1"; exit 1; }
mv -f "$DEPS/src/$2.part" "$DEPS/src/$2"
}
cmake_dep() { # source-dir build-dir extra-args...
local src="$1" bld="$2"; shift 2
"$CMAKE" -S "$src" -B "$bld" -G Ninja -DCMAKE_MAKE_PROGRAM="$NINJA" \
-DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=$ABI -DANDROID_PLATFORM=android-$API_LEVEL -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_POSITION_INDEPENDENT_CODE=ON "$@"
"$CMAKE" --build "$bld"
"$CMAKE" --install "$bld"
}
build_deps() {
if [[ ! -f "$PREFIX/lib/libSDL3.so" ]]; then
fetch "https://github.com/libsdl-org/SDL/releases/download/release-$SDL_VERSION/SDL3-$SDL_VERSION.tar.gz" "SDL3-$SDL_VERSION.tar.gz"
rm -rf "$DEPS/src/SDL3-$SDL_VERSION" && tar -xzf "$DEPS/src/SDL3-$SDL_VERSION.tar.gz" -C "$DEPS/src"
cmake_dep "$DEPS/src/SDL3-$SDL_VERSION" "$DEPS/build-sdl3-$ABI" \
-DSDL_SHARED=ON -DSDL_STATIC=OFF -DSDL_TEST_LIBRARY=OFF -DSDL_TESTS=OFF -DSDL_EXAMPLES=OFF
fi
if [[ ! -f "$PREFIX/lib/libfreetype.a" ]]; then
fetch "https://download.savannah.gnu.org/releases/freetype/freetype-$FREETYPE_VERSION.tar.xz" "freetype-$FREETYPE_VERSION.tar.xz"
rm -rf "$DEPS/src/freetype-$FREETYPE_VERSION" && tar -xJf "$DEPS/src/freetype-$FREETYPE_VERSION.tar.xz" -C "$DEPS/src"
cmake_dep "$DEPS/src/freetype-$FREETYPE_VERSION" "$DEPS/build-freetype-$ABI" -DBUILD_SHARED_LIBS=OFF \
-DFT_DISABLE_ZLIB=ON -DFT_DISABLE_BZIP2=ON -DFT_DISABLE_PNG=ON -DFT_DISABLE_HARFBUZZ=ON -DFT_DISABLE_BROTLI=ON
fi
# SDLActivity and friends must match the native libSDL3.so exactly.
rm -rf "$DEPS/sdl-java" && mkdir -p "$DEPS/sdl-java"
cp -R "$DEPS/src/SDL3-$SDL_VERSION/android-project/app/src/main/java/org" "$DEPS/sdl-java/"
}
build_deps
[[ "$MODE" == deps ]] && exit 0
cd "$HERE"
GRADLE_ARGS=(-PAVA2_DEPS_PREFIX="$PREFIX" -PAVA2_SDL_JAVA="$DEPS/sdl-java" -PAVA2_CMAKE_VERSION=$CMAKE_VERSION
-PAVA2_NDK_VERSION=$NDK_VERSION)
[[ -n "${AVA2_SDK_ROOT:-}" ]] && GRADLE_ARGS+=(-PAVA2_SDK_ROOT="$AVA2_SDK_ROOT")
[[ -n "${AVA2_SOURCE_DIR:-}" ]] && GRADLE_ARGS+=(-PAVA2_SOURCE_DIR="$AVA2_SOURCE_DIR")
if [[ "$MODE" == release ]]; then
./gradlew "${GRADLE_ARGS[@]}" assembleRelease
ls -l app/build/outputs/apk/release/*.apk
exit 0
fi
./gradlew "${GRADLE_ARGS[@]}" assembleDebug
APK="$HERE/app/build/outputs/apk/debug/app-debug.apk"
ls -l "$APK"
# Prefer the SDK's adb: a different adb version on PATH (e.g. Homebrew's) restarts a running adb
# server it does not match, which drops an install or push in progress.
ADB="$ANDROID_HOME/platform-tools/adb"; [[ -x "$ADB" ]] || ADB="$(command -v adb)"
[[ -n "${ADB_SERIAL:-}" ]] && ADB="$ADB -s $ADB_SERIAL"
if $ADB get-state >/dev/null 2>&1; then
$ADB install -r -d "$APK"
# AVA2_ARGS: client arguments for this launch (Ava2Activity), e.g. "--phase game --preview-data".
$ADB shell "am start -n com.metin2.ava2/.Ava2Activity${AVA2_ARGS:+ --es args '$AVA2_ARGS'}"
echo "Launched. Logs: $ADB logcat -s SDL SDL/APP AVA2 DEBUG AndroidRuntime"
else
echo "No device attached; APK not installed."
fi
+2
View File
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
android.nonTransitiveRClass=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python3
"""Push the client root to the phone's app data directory (development builds).
The APK holds code only; on Android the client runs in its external files directory
(/sdcard/Android/data/com.metin2.ava2/files) and reads the flattened client root from there:
0. assets/loose the client-root asset tree
1. build/dev/test-rundir the pack-manifest client root (tools/make_test_rundir.py): what
the original client serves from its packs, so it wins over the
~1000 older models/textures assets/loose holds (zone/b tree
atlases at half size broke the SpeedTree UVs on the phone)
2. upstream/python-root scripts; win over same-named asset files (case-insensitive)
3. <pack_maker>/../svside loose client-root folder that is in no pack
4. python27.zip the embedded interpreter's stdlib
Later layers replace earlier files with the same (case-insensitive) path.
The merged tree is staged as hard links (no copy) in build/android-data/root, then sent with
`adb push --sync`, which skips files the device already has with the same timestamp, so later
runs only transfer what changed. The first run moves about 4 GB.
assets/loose keeps a few symlinks into the decoded pack_maker tree of the machine it was
committed on; they are remapped to --pack-maker (default ../AVA2/TEST/1. Client DEV/pack_maker).
usage: android/push_assets.py [--serial SERIAL] [--pack-maker DIR] [--stdlib ZIP] [--stage-only]
"""
import argparse
import glob
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
PACKAGE = "com.metin2.ava2"
DEVICE_DIR = f"/sdcard/Android/data/{PACKAGE}/files"
PACK_MAKER_MARK = "/pack_maker/"
LOOSE_DIRS = ["svside"]
RUNDIR_MARKER = ".ava2_test_rundir"
def find_stdlib():
candidates = glob.glob(str(ROOT / "android/app/.cxx/*/*/arm64-v8a/python27.zip"))
candidates += [str(p) for p in (ROOT / "build").glob("*/python27.zip")]
candidates = [c for c in candidates if os.path.isfile(c)]
return max(candidates, key=os.path.getmtime) if candidates else None
def ascii_lower(name):
"""Lower-cases A-Z only, like the client's ResourceManager::NormalizePath; legacy CP949 names
(stored as Latin-1 code points) must keep their bytes."""
return name.translate(ASCII_LOWER)
ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
class Stage:
"""Hard-link tree; a later source replaces an earlier file with the same lower-case path."""
def __init__(self, out, lowercase=False):
self.out = out
self.lowercase = lowercase # stage every name lower-case (case-sensitive targets, iOS)
self.files = {} # lower-case relative path -> staged path
self.dirs = {"": out}
def _dir(self, rel_parent):
key = ""
for part in rel_parent.parts:
parent = self.dirs[key]
key = f"{key}/{part.lower()}" if key else part.lower()
if key not in self.dirs:
self.dirs[key] = parent / (ascii_lower(part) if self.lowercase else part)
self.dirs[key].mkdir()
return self.dirs[key]
def add(self, rel, source):
key = str(rel).lower()
# Saved accounts are user data, never part of a development asset install.
if key == "lib/wa_ac.py":
return
old = self.files.pop(key, None)
if old is not None:
old.unlink()
target = self._dir(rel.parent) / (ascii_lower(rel.name) if self.lowercase else rel.name)
try:
os.link(source, target)
except OSError: # another volume
shutil.copy2(source, target)
self.files[key] = target
def walk(top, pack_maker, missing):
"""Yields (relative path, real file) under top, following and remapping symlinks."""
stack = [(Path(top), Path(), frozenset())]
while stack:
directory, rel, ancestors = stack.pop()
identity = directory.resolve()
if identity in ancestors:
continue
ancestors = ancestors | {identity}
for entry in sorted(os.scandir(directory), key=lambda e: e.name):
path, child = Path(entry.path), rel / entry.name
if entry.name == ".DS_Store":
continue
# This local convenience link points to the entire decoded pack tree;
# its runtime files are already supplied by the flattened rundir.
if Path(top) == ROOT / "upstream/python-root" and child == Path("pack_maker"):
continue
if entry.is_symlink() and not path.exists():
link = os.readlink(path)
mark = link.find(PACK_MAKER_MARK)
remapped = pack_maker / link[mark + len(PACK_MAKER_MARK):] if mark >= 0 else None
if remapped is None or not remapped.exists():
if os.path.isabs(link): # relative dead links (pack_maker's bgm/bgm -> bgm) are noise
missing.append(f"{child} -> {link}")
continue
path = remapped
if path.is_dir():
stack.append((path, child, ancestors))
elif path.is_file():
yield child, path
PUSH_BATCH = 20000
def count_files(path):
return sum(len(files) for _, _, files in os.walk(path))
def push_batches(stage, rel):
"""Yields stage-relative paths (directories or files) of at most PUSH_BATCH files each."""
path = stage / rel
if not path.is_dir() or count_files(path) <= PUSH_BATCH:
yield rel
return
for entry in sorted(path.iterdir()):
yield from push_batches(stage, rel / entry.name)
def adb(serial, *args, **kwargs):
command = ["adb"] + (["-s", serial] if serial else []) + list(args)
return subprocess.run(command, check=True, **kwargs)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--serial", default=os.environ.get("ADB_SERIAL"))
parser.add_argument("--pack-maker", type=Path, default=ROOT.parent / "AVA2/TEST/1. Client DEV/pack_maker")
parser.add_argument("--stdlib", help="python27.zip (default: newest Android/desktop build output)")
parser.add_argument("--stage", type=Path, default=ROOT / "build/android-data/root")
parser.add_argument("--rundir", type=Path, default=ROOT / "build/dev/test-rundir",
help="pack-manifest client root (tools/make_test_rundir.py), staged underneath")
parser.add_argument("--stage-only", action="store_true", help="build the staging tree, do not push")
parser.add_argument("--lowercase", action="store_true",
help="lower-case every staged name, for case-sensitive file systems (iOS)")
args = parser.parse_args()
stdlib = args.stdlib or find_stdlib()
if not stdlib:
sys.exit("python27.zip not found; run android/build.sh first or pass --stdlib")
if args.stage.exists():
shutil.rmtree(args.stage)
args.stage.mkdir(parents=True)
stage, missing = Stage(args.stage, args.lowercase), []
for rel, path in walk(ROOT / "assets/loose", args.pack_maker, missing):
stage.add(rel, path)
# The pack-manifest client root the desktop tests run against, over assets/loose: assets/loose
# alone lacks the pack files (Dopador_manual/*, the switcher art...) game.py needs, and where
# both have a file the pack version is the one the original client loads.
if args.rundir.is_dir():
for rel, path in walk(args.rundir, args.pack_maker, missing):
if rel.name != RUNDIR_MARKER:
stage.add(rel, path)
else:
print(f"warning: {args.rundir} not found (tools/make_test_rundir.py); the game phase will miss "
"pack files", file=sys.stderr)
for rel, path in walk(ROOT / "upstream/python-root", args.pack_maker, missing):
stage.add(rel, path)
# Loose client-root folders that are in neither assets/loose nor any pack (same as
# tools/make_test_rundir.py); svsideoi.py, built by game.py, needs svside/*.jpg.
for name in LOOSE_DIRS:
top = args.pack_maker.parent / name
if not top.is_dir():
missing.append(f"{name} -> {top}")
continue
for rel, path in walk(top, args.pack_maker, missing):
stage.add(Path(name) / rel, path)
stage.add(Path("python27.zip"), stdlib)
for line in missing:
print(f"warning: unresolved symlink {line}", file=sys.stderr)
size = sum(p.stat().st_size for p in stage.files.values())
print(f"staged {len(stage.files)} files, {size / 2**30:.2f} GiB in {args.stage}")
if args.stage_only:
return
adb(args.serial, "shell", "mkdir", "-p", DEVICE_DIR)
# One `adb push --sync` over all ~98k files aborts in file_sync_client ("protocol fault: failed
# to read stat response"), so push in batches of at most PUSH_BATCH files.
for rel in push_batches(args.stage, Path()):
source, target = args.stage / rel, f"{DEVICE_DIR}/{rel.as_posix()}" if rel.parts else DEVICE_DIR
if source.is_dir():
adb(args.serial, "shell", "mkdir", "-p", f"'{target}'")
# Trailing "/." pushes the directory's contents rather than the directory itself.
adb(args.serial, "push", "--sync", f"{source}/.", target)
else:
adb(args.serial, "push", "--sync", str(source), target)
# Recent Android versions (seen on Android 17) leave what adb creates under Android/data owned
# by `shell` with 2770 directories, which the app's uid cannot enter ("Permission denied" on
# the first model load). Open up what adb created; files the app wrote itself (channel.inf,
# the cfg files) and the files directory belong to the app and cannot be chmodded by shell.
adb(args.serial, "shell",
f"find '{DEVICE_DIR}' -mindepth 1 -user shell -type d ! -perm -005 -exec chmod 2777 {{}} + ; "
f"find '{DEVICE_DIR}' -user shell -type f ! -perm -004 -exec chmod 666 {{}} +")
print(f"pushed to {DEVICE_DIR}")
if __name__ == "__main__":
main()
+59 -48
View File
@@ -4,7 +4,7 @@
{
"module": "ServerStateChecker",
"windows_file": "upstream/ava2-client/UserInterface/ServerStateCheckerModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 5,
"missing": [],
"extra": [],
@@ -13,7 +13,7 @@
{
"module": "app",
"windows_file": "upstream/ava2-client/UserInterface/PythonApplicationModule.cpp",
"port_file": "src/python_app.cpp",
"port_file": "src/scripting/python_app.cpp",
"windows_methods": 116,
"missing": [],
"extra": [],
@@ -22,7 +22,7 @@
{
"module": "background",
"windows_file": "upstream/ava2-client/UserInterface/PythonBackgroundModule.cpp",
"port_file": "src/python_background.cpp",
"port_file": "src/scripting/python_background.cpp",
"windows_methods": 52,
"missing": [],
"extra": [
@@ -34,7 +34,7 @@
{
"module": "battlepass",
"windows_file": "upstream/ava2-client/UserInterface/PythonBattlePass.cpp",
"port_file": "src/python_battlepass.cpp",
"port_file": "src/scripting/python_battlepass.cpp",
"windows_methods": 8,
"missing": [],
"extra": [],
@@ -43,7 +43,7 @@
{
"module": "chat",
"windows_file": "upstream/ava2-client/UserInterface/PythonChatModule.cpp",
"port_file": "src/python_chat.cpp",
"port_file": "src/scripting/python_chat.cpp",
"windows_methods": 33,
"missing": [],
"extra": [],
@@ -52,7 +52,7 @@
{
"module": "chr",
"windows_file": "upstream/ava2-client/UserInterface/PythonCharacterModule.cpp",
"port_file": "src/python_chr.cpp",
"port_file": "src/scripting/python_chr.cpp",
"windows_methods": 80,
"missing": [],
"extra": [],
@@ -61,7 +61,7 @@
{
"module": "chrmgr",
"windows_file": "upstream/ava2-client/UserInterface/PythonCharacterManagerModule.cpp",
"port_file": "src/python_chr.cpp",
"port_file": "src/scripting/python_chr.cpp",
"windows_methods": 37,
"missing": [],
"extra": [],
@@ -70,7 +70,7 @@
{
"module": "cube_renewal",
"windows_file": "upstream/ava2-client/UserInterface/PythonCubeRenewal.cpp",
"port_file": "src/python_cube_renewal.cpp",
"port_file": "src/scripting/python_cube_renewal.cpp",
"windows_methods": 5,
"missing": [],
"extra": [],
@@ -79,7 +79,7 @@
{
"module": "dbg",
"windows_file": "upstream/ava2-client/ScriptLib/PythonDebugModule.cpp",
"port_file": "src/python_dbg.cpp",
"port_file": "src/scripting/python_dbg.cpp",
"windows_methods": 5,
"missing": [],
"extra": [],
@@ -88,7 +88,7 @@
{
"module": "drop_item",
"windows_file": "upstream/ava2-client/UserInterface/PythonDropItem.cpp",
"port_file": "src/python_drop_item.cpp",
"port_file": "src/scripting/python_drop_item.cpp",
"windows_methods": 8,
"missing": [],
"extra": [],
@@ -97,7 +97,7 @@
{
"module": "dungeon_info",
"windows_file": "upstream/ava2-client/UserInterface/PythonDungeonInfo.cpp",
"port_file": "src/python_dungeon_info.cpp",
"port_file": "src/scripting/python_dungeon_info.cpp",
"windows_methods": 12,
"missing": [],
"extra": [],
@@ -106,7 +106,7 @@
{
"module": "effect",
"windows_file": "upstream/ava2-client/UserInterface/PythonEffectModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 7,
"missing": [],
"extra": [],
@@ -115,7 +115,7 @@
{
"module": "event",
"windows_file": "upstream/ava2-client/UserInterface/PythonEventManagerMoudle.cpp",
"port_file": "src/python_event_manager.cpp",
"port_file": "src/scripting/python_event_manager.cpp",
"windows_methods": 29,
"missing": [],
"extra": [],
@@ -124,7 +124,7 @@
{
"module": "eventMgr",
"windows_file": "upstream/ava2-client/UserInterface/PythonGameEventManagerModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 1,
"missing": [],
"extra": [],
@@ -133,7 +133,7 @@
{
"module": "exchange",
"windows_file": "upstream/ava2-client/UserInterface/PythonExchangeModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 23,
"missing": [],
"extra": [
@@ -151,7 +151,7 @@
{
"module": "fly",
"windows_file": "upstream/ava2-client/UserInterface/PythonFlyModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 2,
"missing": [],
"extra": [],
@@ -160,7 +160,7 @@
{
"module": "grp",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonGraphicModule.cpp",
"port_file": "src/python_grp.cpp",
"port_file": "src/scripting/python_grp.cpp",
"windows_methods": 54,
"missing": [],
"extra": [],
@@ -169,7 +169,7 @@
{
"module": "grpImage",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonGraphicImageModule.cpp",
"port_file": "src/python_grp.cpp",
"port_file": "src/scripting/python_grp.cpp",
"windows_methods": 15,
"missing": [],
"extra": [],
@@ -178,7 +178,7 @@
{
"module": "grpText",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonGraphicTextModule.cpp",
"port_file": "src/python_grp.cpp",
"port_file": "src/scripting/python_grp.cpp",
"windows_methods": 21,
"missing": [],
"extra": [],
@@ -187,7 +187,7 @@
{
"module": "grpThing",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonGraphicThingModule.cpp",
"port_file": "src/python_grp.cpp",
"port_file": "src/scripting/python_grp.cpp",
"windows_methods": 8,
"missing": [],
"extra": [],
@@ -196,7 +196,7 @@
{
"module": "guild",
"windows_file": "upstream/ava2-client/UserInterface/PythonGuild.cpp",
"port_file": "src/python_guild.cpp",
"port_file": "src/scripting/python_guild.cpp",
"windows_methods": 34,
"missing": [],
"extra": [],
@@ -205,7 +205,7 @@
{
"module": "ime",
"windows_file": "upstream/ava2-client/UserInterface/PythonIMEModule.cpp",
"port_file": "src/python_ime.cpp",
"port_file": "src/scripting/python_ime.cpp",
"windows_methods": 33,
"missing": [],
"extra": [],
@@ -214,7 +214,7 @@
{
"module": "item",
"windows_file": "upstream/ava2-client/UserInterface/PythonItemModule.cpp",
"port_file": "src/python_gameplay_modules.cpp",
"port_file": "src/scripting/python_gameplay_modules.cpp",
"windows_methods": 48,
"missing": [],
"extra": [
@@ -228,7 +228,7 @@
{
"module": "managerBankLogs",
"windows_file": "upstream/ava2-client/UserInterface/PythonManagerBank.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 1,
"missing": [],
"extra": [],
@@ -237,7 +237,7 @@
{
"module": "messenger",
"windows_file": "upstream/ava2-client/UserInterface/PythonMessenger.cpp",
"port_file": "src/python_messenger.cpp",
"port_file": "src/scripting/python_messenger.cpp",
"windows_methods": 5,
"missing": [],
"extra": [],
@@ -246,7 +246,7 @@
{
"module": "miniMap",
"windows_file": "upstream/ava2-client/UserInterface/PythonMiniMapModule.cpp",
"port_file": "src/python_minimap.cpp",
"port_file": "src/scripting/python_minimap.cpp",
"windows_methods": 27,
"missing": [],
"extra": [],
@@ -255,7 +255,7 @@
{
"module": "net",
"windows_file": "upstream/ava2-client/UserInterface/PythonNetworkStreamModule.cpp",
"port_file": "src/python_net.cpp",
"port_file": "src/scripting/python_net.cpp",
"windows_methods": 154,
"missing": [],
"extra": [
@@ -279,7 +279,7 @@
{
"module": "nonplayer",
"windows_file": "upstream/ava2-client/UserInterface/PythonNonPlayerModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 24,
"missing": [],
"extra": [
@@ -290,7 +290,7 @@
{
"module": "pack",
"windows_file": "upstream/ava2-client/UserInterface/PythonPackModule.cpp",
"port_file": "src/python_runtime.cpp",
"port_file": "src/scripting/python_runtime.cpp",
"windows_methods": 2,
"missing": [],
"extra": [],
@@ -299,7 +299,7 @@
{
"module": "petskill",
"windows_file": "upstream/ava2-client/UserInterface/PythonSkillPet.cpp",
"port_file": "src/python_pet_skill.cpp",
"port_file": "src/scripting/python_pet_skill.cpp",
"windows_methods": 4,
"missing": [],
"extra": [],
@@ -308,11 +308,13 @@
{
"module": "player",
"windows_file": "upstream/ava2-client/UserInterface/PythonPlayerModule.cpp",
"port_file": "src/python_gameplay_modules.cpp",
"port_file": "src/scripting/python_gameplay_modules.cpp",
"windows_methods": 149,
"missing": [],
"extra": [
"CanSealItem",
"GetAutoHuntOption",
"GetAutoHuntState",
"GetCombatZonePoints",
"GetElements",
"GetItemBind",
@@ -323,15 +325,21 @@
"GetItemSealDate",
"GetItemUnSealLeftTime",
"GetItemUnbindTime",
"IsAutoHunt",
"IsCombatZoneMap",
"IsTournamentMap"
"IsTournamentMap",
"RequestAddGlobalQuickSlot",
"RequestMoveGlobalQuickSlotToGlobalQuickSlot",
"RequestUseGlobalQuickSlot",
"SetAutoHunt",
"SetAutoHuntOption"
],
"placeholder": []
},
{
"module": "playerLoad",
"windows_file": "upstream/ava2-client/UserInterface/PythonPlayerSettingsModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 1,
"missing": [],
"extra": [],
@@ -340,7 +348,7 @@
{
"module": "privateShopSearch",
"windows_file": "upstream/ava2-client/UserInterface/PythonPrivateShopSearch.cpp",
"port_file": "src/python_shop_search.cpp",
"port_file": "src/scripting/python_shop_search.cpp",
"windows_methods": 12,
"missing": [],
"extra": [],
@@ -349,7 +357,7 @@
{
"module": "profiler",
"windows_file": "upstream/ava2-client/UserInterface/PythonProfilerModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 2,
"missing": [],
"extra": [],
@@ -358,7 +366,7 @@
{
"module": "quest",
"windows_file": "upstream/ava2-client/UserInterface/PythonQuest.cpp",
"port_file": "src/python_quest.cpp",
"port_file": "src/scripting/python_quest.cpp",
"windows_methods": 6,
"missing": [],
"extra": [],
@@ -367,7 +375,7 @@
{
"module": "renderTarget",
"windows_file": "upstream/ava2-client/UserInterface/CPythonRenderTargetModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 24,
"missing": [],
"extra": [],
@@ -376,7 +384,7 @@
{
"module": "safebox",
"windows_file": "upstream/ava2-client/UserInterface/PythonSafeBox.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 15,
"missing": [],
"extra": [
@@ -389,7 +397,7 @@
{
"module": "sash",
"windows_file": "upstream/ava2-client/UserInterface/PythonSash.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 7,
"missing": [],
"extra": [],
@@ -398,7 +406,7 @@
{
"module": "shop",
"windows_file": "upstream/ava2-client/UserInterface/PythonShop.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 42,
"missing": [],
"extra": [
@@ -410,7 +418,7 @@
{
"module": "skill",
"windows_file": "upstream/ava2-client/UserInterface/PythonSkill.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 41,
"missing": [],
"extra": [],
@@ -419,7 +427,7 @@
{
"module": "snd",
"windows_file": "upstream/ava2-client/UserInterface/PythonSoundManagerModule.cpp",
"port_file": "src/python_gameplay_modules.cpp",
"port_file": "src/scripting/python_gameplay_modules.cpp",
"windows_methods": 14,
"missing": [],
"extra": [],
@@ -428,7 +436,7 @@
{
"module": "switchbot",
"windows_file": "upstream/ava2-client/UserInterface/PythonSwitchbot.cpp",
"port_file": "src/python_switchbot.cpp",
"port_file": "src/scripting/python_switchbot.cpp",
"windows_methods": 9,
"missing": [],
"extra": [],
@@ -437,7 +445,7 @@
{
"module": "systemSetting",
"windows_file": "upstream/ava2-client/UserInterface/PythonSystemModule.cpp",
"port_file": "src/python_system.cpp",
"port_file": "src/scripting/python_system.cpp",
"windows_methods": 73,
"missing": [],
"extra": [],
@@ -446,7 +454,7 @@
{
"module": "textTail",
"windows_file": "upstream/ava2-client/UserInterface/PythonTextTailModule.cpp",
"port_file": "src/python_native_modules.cpp",
"port_file": "src/scripting/python_native_modules.cpp",
"windows_methods": 18,
"missing": [],
"extra": [
@@ -460,7 +468,7 @@
{
"module": "wiki",
"windows_file": "upstream/ava2-client/UserInterface/PythonWiki.cpp",
"port_file": "src/python_wiki.cpp",
"port_file": "src/scripting/python_wiki.cpp",
"windows_methods": 22,
"missing": [],
"extra": [],
@@ -469,11 +477,14 @@
{
"module": "wndMgr",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp",
"port_file": "src/python_wndmgr.cpp",
"port_file": "src/scripting/python_wndmgr.cpp",
"windows_methods": 188,
"missing": [],
"extra": [
"SetClipRect"
"RegisterDisc",
"SetClipRect",
"SetDiscArc",
"SetDiscColors"
],
"placeholder": []
}
+179
View File
@@ -0,0 +1,179 @@
# 移动端架构(2026-10-12)
2026-10-13 交互更新:摇杆闲置隐藏、真实落点与显示中心分离;技能独立多指、拖动瞄准与冷却重试,物品图标抬高、快捷按钮完整热区,以及 NPC/物品接近交互。实现文件、测试和限制见 [移动交互调整](MOBILE-INTERACTION-2026-10-13.md)。
本文是引入移动端(Android 优先,iOS 其后)后的目标结构和实施顺序。游戏逻辑、网络、渲染、资源各层保持现状;变化集中在平台打包、主程序的平台适配与触屏输入、以及 Python 界面的手机 HUD 叠加层。标为"新增"或"拆分"的部分尚未实现。
## 现状
- `android/build.sh` 可以编出 arm64 调试 APK(SDL3 + FreeType 自动编译,16 KB 页对齐),连接手机时自动安装启动;真机运行尚未验证。
- `android/push_assets.py` 把资源(`assets/loose`,其上叠加按打包清单生成的 `build/dev/test-rundir`,同名文件以 pack 版本为准;再叠加 python-root 和 `python27.zip`)推送到应用外部存储目录,客户端启动时切换到该目录。
- 游戏资源为 2.8 GB、约 5 万个散文件(`assets/loose`),17 个源文件中 120 多处通过 `std::filesystem` / `ifstream` 直接读文件,无法读取 APK 内置资源。
- 平台层已实现(`src/app/platform/`):资源根目录与配置目录;前后台切换(进后台时保存配置、暂停声音、取消输入、停止渲染,网络照常收发;Android 设 `SDL_ANDROID_BLOCK_ON_PAUSE=0`);安全区域按逻辑分辨率换算后放进触摸布局,HUD 用 `touch.GetSafeArea()` 内缩。低内存事件目前只记日志;均未真机验证。
- 触摸分流已实现(`src/app/input/touch_router.*`,见下文 `input/`):移动端或 `--touch` / `AVA2_TOUCH=1` 时关闭 SDL 触摸转鼠标,每个手指分到界面、攻击键、左下浮动摇杆或镜头(单指拖动转向、双指缩放、轻点=点地移动)。Python 模块 `touch` 供 HUD 设置攻击键位置并读取摇杆状态;`ui_mobile_joystick` / `ui_mobile_combat` 改为只做显示(`not_pick`)。多指同时操作尚未在真机验证。
- 出招已接通(PORT-PLAN「Mobile step 3b」):触摸攻击键和键盘共用 `ProcessPlayerAttack`,按原版连招时序出招,发送 FUNC_COMBO 移动包,命中检测后发 `CG_ATTACK`;尚未在真服验证,弓箭飞行、技能、PvP 规则等仍缺。
- 手机 HUD 布局已实现(PORT-PLAN「Mobile step 4」):左上头像圆框 + 等级名字 + HP/SP/体力条,buff 图标在其下;顶部居中沿用原版目标栏;右上一排圆形入口(好友、角色、背包、菜单)+ 原版小地图 + 活动图标;左侧竖排按钮(任务、技能、表情、聊天)和原版提示按钮;右下攻击键 + 两圈 8 个快捷格(当前快捷页,可切第 1-3 页)+ 换页、上下马、拾取;底部药水栏(第 4 快捷页,全局格 24-31)和经验细条。移动模式下 PC 任务栏隐藏。圆框由原生 `CDisc`(`wndMgr.RegisterDisc`)几何绘制,图标只用 AVA2 自己的贴图,不用其他服的美术。小地图仍是原版圆形、按钮文字为英文、未真机验证。
- 软键盘已改为仅在输入框获得焦点(`ime.EnableCaptureInput`)或聊天打开时弹出。
- `src/app/main.cpp` 共 2418 行,启动、主循环、登录和调试参数都在其中。
- Android 默认渲染缩放 0.75。
- 界面缩放已实现(PORT-PLAN「Mobile step 5」):手机/平板按屏幕宽高比和像素密度自动选逻辑分辨率(高 600–768,宽随比例,至少 1024),不再给 1024×768 加黑边,也不改写 metin2.cfg;`--ui-height` / `AVA2_UI_HEIGHT` 可改高度;桌面可用 `--phone 2400x1080@2.75 --safe-insets 50,0,0,24` 模拟。安全区变化(如旋转 180 度刘海换边)时 HUD 实时重建并重新摆放原版窗口。运行中窗口尺寸变化(分屏、折叠屏)仍沿用启动时的逻辑分辨率;尚无游戏内界面大小选项;未真机验证。
## 分层结构
```
┌──────────────────────────────────────────────────────────────┐
│ 平台打包 android/ (Gradle + SDLActivity + build.sh) │ 新增
│ ios/ (build.sh) macOS .app (已有脚本) │
├──────────────────────────────────────────────────────────────┤
│ 主程序 src/app/ │
│ main.cpp 入口、命令行参数 │ 拆分
│ app_loop 每帧:事件 → Python → 网络 → 渲染 │ 从 main.cpp 抽出
│ platform/ 数据目录、前后台切换、安全区域、软键盘 │ 新增
│ input/ 触摸分流、虚拟摇杆、攻击键、镜头手势 │ 新增
├──────────────────────────────────────────────────────────────┤
│ Python 2 界面层(原版行为) │
│ upstream/python-root AVA2 原版脚本(不修改) │
│ mobile/ 手机 HUD 叠加层(仅移动端加载) │ 新增
├──────────────────────────────────────────────────────────────┤
│ 原生模块 src/scripting/python_*.cpp │ 不变
│ player / net / chr / app / wndmgr / grp ... │
├──────────────────────────────────────────────────────────────┤
│ 游戏逻辑与网络 src/eter_net, src/network, src/game │ 不变
├──────────────────────────────────────────────────────────────┤
│ 渲染 src/eter_render, eter_effect, eter_image │ 不变
│ HardwareScene: SDL_GPU → Metal (macOS/iOS) │
│ → Vulkan (Android) │
├──────────────────────────────────────────────────────────────┤
│ 资源 CResourceManager + std::filesystem │ 基本不变
│ 根目录由 platform/ 决定 │
├──────────────────────────────────────────────────────────────┤
│ SDK ../sdk (libgr2, speedtree) 第三方: SDL3, CPython │ 不变
└──────────────────────────────────────────────────────────────┘
```
### 平台打包层
- Android APK 只包含 `libmain.so`、`python27.zip` 和 python-root 脚本。
- 游戏资源不进 APK,放在应用外部存储目录(`SDL_GetAndroidExternalStoragePath()`):开发期用 `adb push`,正式版首次启动下载。启动时把工作目录切到该目录,现有文件读取代码无需修改。
- 以后可把散文件合成大包,减少移动端打开大量小文件的开销。
- `support/android` 挪到顶层 `android/` 并补全 Gradle wrapper、SDL3 Java 部分、图标和一键编译安装脚本。
- `AVA2_SDK_ROOT` 沿用默认的 `../sdk`。
### 主程序层
- `platform/` 集中平台差异,替代散落在 `main.cpp` 中的 `#ifdef`:
- 资源根目录与配置目录(Android 配置已写入 `SDL_GetAndroidInternalStoragePath()`);
- 前后台切换:暂停渲染和声音、保存配置、保持网络连接,回到前台后恢复;
- 屏幕安全区域(`SDL_GetWindowSafeArea`),避开刘海和圆角;
- 软键盘:仅在输入框获得焦点时 `SDL_StartTextInput`,失焦时关闭。
- `input/` 是统一输入入口。桌面键盘鼠标路径不变;移动端关闭 SDL 触摸转鼠标,每个手指按顺序判断归属:
```
手指按下 → 落在 HUD 按钮? → 转成点击,交给 Python 界面
→ 落在原版弹出窗口上? → 转成鼠标事件,交给 wndmgr
→ 落在左下摇杆区? → 摇杆 → player.SetSingleDIKKeyState
→ 落在攻击键? → player.SetAttackKeyState
→ 其他区域 → 单指转镜头 (app.RotateCamera) / 双指缩放
```
最终都调用原版已有的移动和攻击接口,游戏逻辑不感知输入设备差异。多指同时操作(摇杆 + 攻击 + 镜头)由此支持。
- `app_loop` 从 `main.cpp` 抽出,便于 iOS 改用 SDL 回调式主循环;可在做 iOS 时再拆。(已完成:`src/app/app_loop.{h,cpp}`,主体为每帧挂起一次的协程;`main.cpp` 只选择 SDL 回调或经典循环。)
### Python 界面层
- `upstream/python-root` 原版脚本不修改(AGENTS.md)。
- 移动端启动时额外加载 `mobile/`:隐藏 PC 任务栏(`uitaskbar`),挂上手机 HUD。背包、商店、任务等窗口仍用原版,整体放大显示。
- 桌面版默认不加载 `mobile/`,现有测试和原版对照检查不受影响;可用开关在 macOS 上打开 HUD 以鼠标调试。
### 不变的层
原生模块、游戏逻辑与网络、渲染、SDK 桌面与移动端共用,已有性能优化同样生效。渲染只有图形后端不同(macOS/iOS Metal,Android Vulkan,均经 SDL_GPU)。
## 每帧数据流
```
SDL 事件 ─→ platform/(前后台、窗口尺寸)
└→ input/(键鼠或触摸分流)─→ Python 界面 / player.* 接口
Python 更新(原版脚本 + mobile HUD)
网络收发(PythonNetworkStream)
游戏对象更新(角色、特效、低模、动画时钟)
渲染(3D 场景 → UI → 合成到屏幕)
```
## 构建矩阵
| 平台 | 产物 | 图形后端 | 界面 | 输入 |
|---|---|---|---|---|
| macOS(开发和测试) | `ava2_client`、.app | Metal | 原版 PC 界面(可开关手机 HUD) | 键盘鼠标 |
| Android(主目标) | APK(`libmain.so`) | Vulkan | 原版界面 + 手机 HUD | 触屏 |
| iOS | .app(`ios/build.sh`,资源用 `ios/push_assets.py` 小写拷入 Documents) | Metal | 同 Android | 触屏 |
## 手机 HUD 布局
参考常见的 Metin2 手游布局。每个元素都对应现有数据或接口,不需要改游戏逻辑:
| 位置 | 元素 | 现有基础 | 工作 |
|---|---|---|---|
| 左上 | 头像、HP/SP/经验、buff 图标 | `player.GetStatus`、affect 数据 | 新做紧凑状态面板 |
| 顶部中间 | 目标名称、等级、血条 | `uitarget.py` | 改位置、放大字号 |
| 右上 | 通知、邮件、角色、背包、菜单 | 原版窗口 | 入口按钮,点开弹出原版窗口 |
| 右侧 | 小地图、+/- 缩放、地图名 | `uiminimap.py` | 重新摆放 |
| 左侧竖排 | 任务、组队、表情、聊天等 | 原版功能 | 图标按钮 |
| 左下 | 浮动摇杆 | `player.SetSingleDIKKeyState` | C++ 虚拟摇杆,方向换算为移动方向 |
| 右下 | 大攻击键 | `player.SetAttackKeyState` | 按住持续攻击 |
| 攻击键外圈 / 底部 | 技能圈、药水栏、翻页 | 原版快捷栏(4 页) | 技能圈对应技能格,底部栏对应道具格 |
| 攻击键附近 | 骑乘、拾取、锁定目标 | `player.PickCloseItem`;骑乘/锁定接口待核对 | 小按钮 |
| 屏幕空白处 | 转镜头、双指缩放 | `app.RotateCamera`;镜头距离接口待核对 | C++ 手势识别 |
| 技能圈旁 | 自动狩猎(AUTO 键) | 原版没有 | 客户端新功能:轻点开关、长按设置;已完成(第 6 步) |
注意事项:
- 原版窗口按 800×600 设计;移动端逻辑分辨率取高 600~720 再整体放大,按钮点击范围不小于手指大小。
- 20:9 等宽屏需按安全区域布局。
- 不使用其他服务器的界面美术;图标用 AVA2 自带技能/道具图标,按钮底框和摇杆另制。
## 物品与窗口手势
原版窗口不改,触摸由 `src/app/input/touch_router` 翻译成原版鼠标事件,经窗口管理器和移植的 `CSlotWindow` 鼠标处理进入 `uiinventory.py` 等原版脚本:
| 手势 | 翻译成 | 原版效果 |
|---|---|---|
| 手指按住不动 | 鼠标移到该处 | 物品格显示原版物品提示 |
| 点按 | 在按下点依次发移动、左键按下、左键抬起 | 拿起物品(图标跟随);再点空格/装备格/其他窗口即放下、穿戴、交易放入 |
| 拖动(超过 tap_slop) | 在起点按下左键,随后跟随移动,抬起即松开 | 原版拖拽:换格、拖到装备栏、拖出窗口丢弃、拖到商店出售 |
| 双击(300 ms、40 px 内) | 原版左键双击 | `OnUseSlot`:使用药水、穿戴/卸下装备 |
| 长按物品格(450 ms) | `touch.SetLongPressEvent` 回调 | 提示保持显示,弹出 `ui_mobile_actions.ItemActionSheet`:使用、拆分、加入快捷栏、关闭 |
| 长按背包空格子(450 ms) | 同一回调,`isEmpty=1` | 面板只有“整理”和“关闭”;整理调用原版整理按钮 `separateButton` 的事件(确认框 → `/click_sort_items`) |
- 长按面板的按钮调用原版槽位事件。“使用”调用 `OnUseSlot`;“拆分”和“加入快捷栏”通过 `touch.SetVirtualKey` 临时按住 Shift / Ctrl,再调用 `OnSelectItemSlot`,走原版的修饰键分支。
- 点面板外任意处关闭面板。长按其他窗口的空格子、或被大件物品占住的格子,仍按普通按下处理。
- 手指抬起后指针移到屏幕外(拿着物品时除外),以免提示一直停留。被取消的触摸、点地面(世界点击)结束后也一样。
- 快捷栏和药水栏:每次点按的左键按下都会触发一次使用;第二下被识别成双击时只多发一个双击,快捷格没有双击事件,所以连点 N 次就是用 N 次。
## 系统边缘与取消
以下交互思路参考 [jhaizhou-ops/d2r-mobile](https://github.com/jhaizhou-ops/d2r-mobile)(MIT),只借鉴想法,没有拷贝代码:
- 底部安全区(手势导航条)里落下的世界手指不拖镜头,也不算点地面。
- 系统取消某一根手指(`SDL_EVENT_FINGER_CANCELED`,例如边缘手势从它下面开始)时只释放这一根,其他手指不受影响。摇杆手指被取消后,摇杆保持原方向 `joy_reacquire_ms`(300 ms);这段时间内在原基点 1.5 倍半径内落下的手指接管摇杆,基点不变。
- 攻击键点得比一帧还快时,松开推迟到下一帧,保证原版 player 模块至少看到一次按下。
- 没有采用的:技能拖动瞄准(Metin2 技能按目标/朝向释放)、点面板外关闭所有窗口(点世界要移动角色)、手柄自动切换(以后再说)。
- 技能:技能圈和底部栏是原版快捷栏格,点按即使用(第 4 步)。从技能窗口把技能拖到快捷栏用的是同一套槽位拖拽,但还没有单独测试。
## 目录变化
- `support/android` → 顶层 `android/`(补全)。
- `src/app/` 拆出 `platform/` 和 `input/`(以及以后的 `app_loop`)。
- 新增 `mobile/`(Python HUD)。
- 其他目录不变;资源不进 APK。
## 实施顺序
1. APK 打包补全,资源 `adb push` 到设备,真机进入登录界面;同时用 `--perf-log` 实测之前的性能优化。
2. `platform/`:资源根目录、前后台切换、软键盘按需打开。
3. `input/`:触摸分流、虚拟摇杆、攻击键、镜头手势——可在手机上移动和战斗。
4. `mobile/`:手机 HUD(状态面板、技能圈和快捷栏、右上角入口、小地图、左侧按钮)。
5. 界面缩放和安全区域收尾。
6. 自动战斗等新增功能(自动狩猎已完成,见 PORT-PLAN);iOS 打包与 `app_loop` 拆分(均已完成,模拟器验证到游戏场景;真机签名安装未测)。
第 3、4 步大部分可在 macOS 上开发(鼠标模拟单指,触控板测双指);多指同时操作和性能需要真机验证。
+31
View File
@@ -0,0 +1,31 @@
# 移动端交互调整:浮动摇杆、技能与物品手势
参考项目:https://github.com/jhaizhou-ops/d2r-mobile 。对照其 `dm/ios/Sources/dm_touch_controls.c` 的交互思路;没有复制其代码或美术,实际移动、技能、物品及 NPC 报文继续调用 AVA2 现有接口。保留 Python 2。
## 修改文件与行为
- `src/app/input/touch_router.h/.cpp`:真实落点与绘制底盘中心分离。边缘夹回仅影响显示,落指不立即移动;系统取消后的接管保留真实输入原点。新增独立 Skill 手指归属,技能按钮能与摇杆、攻击、镜头同时操作;同一技能槽拒绝重复手指。100ms 区分按住、200ms 尝试重复施放,拖动超过死区后提供方向;短点击在抬起时施放一次,抬起不重复,取消/阶段切换不补发。提供 GetSkillAim 给显示层。
- `upstream/python-root/ui_mobile_joystick.py`:去掉闲置固定位置图案,只在激活时显示;隐藏子图案而不是父窗口,保证继续收到更新。
- `src/scripting/python_touch.h/.cpp`:只从窗口管理器当前实际命中的、可见的快捷格查询技能槽,前景面板优先;拖着图标时保留原始槽位操作,不抢作施法。新增 touch.GetSkillAim。
- `upstream/python-root/ui_mobile_widgets.py`:保留 32px 原版图标,快捷按钮整个 46/50px 热区可操作;绑定与点击物品仍走原始快捷格。技能槽提供动态查询,按下时捕获技能槽,不受随后翻页影响。
- `upstream/python-root/ui_mobile_combat.py`:拖动技能时显示指尖方向标记,松开/取消后隐藏;小功能按钮扩大至 44px。视觉沿用 AVA2 自己的图标及圆框。
- `src/scripting/python_gameplay_modules.h/.cpp`:新增移动端施法适配。方向按当前镜头转换;攻击技能可在方向 ±35° 内选择最近有效敌人,没有有效目标的轻点选择范围内最近敌人,距离相同按 VID 排序。辅助/友方/尸体技能不被敌人瞄准覆盖。重复施放排除开关、被动、公会和辅助技能,冷却/动作锁/保留技能期间不重复请求;最终仍进入 ClickSkillSlot 的完整检查和原报文流程。技能/手动攻击/方向键/摇杆取消本适配器的 NPC/拾取接近任务。
- 同文件新增场景触控适配:掉落物名字额外 16px 容差,投影物品和角色 28px 半径;物品精确名字命中优先于外围扩展。选中角色沿用目标报文,NPC/入口超过 500 单位则接近,进入范围发送原 OnClick(1 秒节流);物品进入 150 单位后发送原拾取报文。技能/情绪/不能行动期间暂停接近;删除、主角切换及同 VID 实例替换取消任务。普通地面点击继续使用原有点地输入。
- `src/scripting/python_item.h`:地面物品创建/更新附带本地 generation,接近任务不会拾取删除后复用 VID 的另一件物品;不改变协议。
- `src/eter_render/TextTailManager.h/.cpp`:提供可选名字热区扩展,精确命中优先,然后选择最近扩展框;默认 0 保持桌面行为。
- `src/app/app_loop.cpp`、`src/scripting/python_app.cpp`:接入技能及场景触控适配,处理接近任务;失焦、暂停和阶段退出释放任务。
- `upstream/python-root/mousemodule.py`(文件系统也可用 mouseModule.py 大小写路径访问):移动模式的拖拽图标/数量抬高到手指上方,顶端限制在安全区内;鼠标坐标不变,仍按真实指尖位置落格。保留原文件编码;仅修改相关 ASCII 行。
- `tests/touch_router_test.cpp`:边缘零输入、取消接管、技能单击/拖动/连续/释放/取消/重复指头及四类同时操作。
- `tests/touch_game_test.cpp`:真实 HUD 的闲置摇杆隐藏、快捷按钮外围命中、拖动标记、NPC 接近与报文字节、物品删除后 VID 复用取消。
- `tests/windows_behavior_test.cpp`:实际目标/技能报文字节、镜头方向、冷却阻止重复、冷却结束继续施放、辅助技能不重复、点击附近自动目标。
- `tests/inventory_touch_test.cpp`:保留真实背包双击使用、长按详情/拆分/快捷栏/整理、拖动落格,并加入图标实际抬高坐标验证。
## 验证与边界
日志位于 `build/verification/mobile-interaction-2026-10-13/`。桌面软件渲染、Python 2 实际 HUD、触控路由和报文合成测试不能替代 iOS/Android 真机多指体验。
最终验证:完整构建通过,移动专项 4/4(12.74 秒),完整 CTest 62/62(63.67 秒),严格 ASan/UBSan 4/4(19.86 秒),无跳过和执行路径诊断。Python C 代码未全部同等插桩。46 模块方法无缺失/占位,395 映射协议常量无不匹配/未匹配;git diff --check 通过。SDK 与 Windows 参考无修改。
单击背包仍沿用 AVA2 的选取并拿起图标语义,双击使用/装备、长按详情与操作面板已存在并继续验证;没有改成新的服务器物品操作规则。NPC/入口是否可交互仍由服务器决定。角色热区使用当前投影模型高度近似,没有恢复精确模型点击体;障碍绕行仍依赖现有移动/碰撞,不新增完整寻路。资源矿石的骑乘矿镐特殊交互及完整 Windows 预留点击战斗流程不在本适配器中。
按钮大小、安全区和镜头手势在现有移动 HUD 基础上增强,没有替换全部背包/商城布局。方向提示为指尖标记,未增加技能范围模型、弹道预览或取消施放区域。辅助技能不自动循环,无新增自动药水或服务器玩法。本轮未修改 SDK、Windows 参考或服务器,也未提交/推送。
+885 -1
View File
@@ -1069,7 +1069,7 @@ item:
(`CGrannyLODController::UpdateLODLevel` + `CGrannyModelInstance::Update`):
only models with a `_lod_01.gr2` sibling, more than 500 units from the camera
target, 30-120 FPS by camera distance over 5000 (25000 for models of 500+
units). The `_lod_` meshes are still not swapped in.
units). The `_lod_` meshes are now swapped in too; see the follow-up below.
GPU skinning limit reviewed, not changed: 36 of 3755 skinned models in pc*,
monster*, npc*, npc_mount and npc_pet exceed 128 bones (bosses, metin stones,
@@ -1081,3 +1081,887 @@ Verified: Debug macOS/Metal build, 50/50 CTests (new regressions for
`FlattenDraws`, scaled-scene compositing and LOD animation rate). Not verified:
in-game frame-time capture and 3D screenshots (no server in this session), and
any Vulkan/Android device run.
### 2026-10-12 FPS pass 2 follow-up: real-time clocks and LOD meshes
- Animation clocks follow real frame time: `main.cpp` sums the frame delta into
a game clock (still fixed at 0.033 s per frame under `--frames`) for water,
network actors, `FlyingManager` and weapon traces; the skybox,
`effect.Update`/`fly.Update` (`app.GetGameFrameDelta`) and `CRenderTarget`
previews (elapsed `SDL_GetTicksNS`, clamped to 0.25 s) use real deltas.
The SpeedTree `UpdateSystem(0.033f)` wind clock is unchanged (SDK work pending).
- Actor bodies swap to `_lod_01.._03` meshes (`CGrannyLODController`): queue
`{lod_03, lod_02, lod_01, main}`, lazy loading, the original distance bands
(including the BYTE wrap for a single LOD) and the building factor. Parts,
`.msm` skins and the current motion follow the drawn instance.
- 9 of 1739 shipped LODs drop an attaching bone (`lion2_lod_02/03` lose
`saddle`; `shaman_miyeom_lod_*`, `mutant_1/2`, `gold_monkey` and
`assassin_easter_day_2016` `_lod_01` lose `equip_*`). Such a level stays on
PART_MAIN while that bone is in use, and bone queries fall back to PART_MAIN.
- Not ported: weapon/item LOD models.
- `SetWeapon`/`AttachPart` helper attachments (outside the part slots) are kept
on the actor and re-attached to the drawn instance after the slots, so LOD and
shape changes no longer drop them; a slot taking the same bone replaces the
helper, and `SetRace`/`SetModel` clear them.
- Blended, non-depth-writing, water and additive draws sort back to front by
the bounds centre of their indexed vertices instead of the mesh's first vertex
(cached per shared geometry index range). Depth-writing opaque draws keep the
first-vertex tie-break.
- Build: `AVA2_SDK_ROOT` defaults to a sibling `../sdk` checkout and falls back
to the pinned submodule (now https://git.slcydia.fun/4v5u09Z5a4Yuc/metin2-SDK.git).
Verified: Debug macOS/Metal build, 50/50 CTests (`render_3d` covers the LOD
bands, the 30 FPS far pose rate on `_lod_03` and the `lion2` saddle fallback;
`hardware_scene` covers the blended centre sort).
Not verified: in-game or device visuals (no server in this session).
### 2026-10-12 Android step 1: APK packaging and game data
- `support/android` moved to a top-level `android/` and completed: Gradle 8.12
wrapper, AGP 8.7.3, compileSdk/targetSdk 35, minSdk 26, arm64-v8a, placeholder
adaptive icon. `android/build.sh` builds SDL3 3.4.16 and FreeType 2.13.3 once
into `build/android-deps` (SDL Java sources copied from the same release),
then the APK (C++ as RelWithDebInfo in debug), and installs/launches it when a
phone is attached. `libmain.so`, `libSDL3.so` and `libc++_shared.so` are
16 KB page aligned; FreeType is linked statically (`AVA2_HAS_FREETYPE`).
- On Android the client enters `SDL_GetAndroidExternalStoragePath()`
(`/sdcard/Android/data/com.metin2.ava2/files`) at startup. Script-root
discovery also accepts a flattened root (`game.py` beside `uiscript/`).
- `android/push_assets.py` stages `assets/loose` + `upstream/python-root`
(scripts win) + `python27.zip` as hard links in `build/android-data/root`
(55,761 files, 2.86 GiB) and sends them with `adb push --sync`. It remaps the
three `assets/loose` symlinks that point into the old machine's pack_maker
(`bgm`, `sound/ui`, `icon/icon`).
- The on-screen keyboard follows edit focus (`ime.EnableCaptureInput` /
`DisableCaptureInput` from `ui.py`), the in-game chat and the dev login view
where SDL reports screen-keyboard support; desktop keeps text input on.
- Build workaround: this checkout calls SpeedTree SDK APIs that are not yet in
the SDK repository (`LegacyWindController`, `CreateFromSpt` variance, LOD
fields). Until that SDK work is pushed, the APK builds from a local mirror
with shims: `AVA2_SOURCE_DIR=<mirror> AVA2_SDK_ROOT=<shim> android/build.sh`.
(Obsolete since SDK 62a5f5a, 2026-10-13: plain `AVA2_SDK_ROOT=../sdk` builds.)
Verified: debug APK builds; the desktop client reaches the login screen inside
`build/android-data/root` (the phone layout) with no missing-effect errors.
Not verified: any run on a device (no phone attached), Vulkan rendering, touch,
lifecycle, frame rate.
### 2026-10-12 Mobile step 3: touch input router
- `src/app/input/touch_router.{h,cpp}` (`ava2_input`): per-finger routing in
this order: UI under the finger (or any finger outside the game phase) -> one
UI pointer; attack circle; lower-left joystick area (floating base, dead zone
0.18); otherwise camera (one-finger drag rotates after a slop, two-finger
pinch zooms, a short tap is a world click). `CancelAll` on
`SDL_EVENT_FINGER_CANCELED` / focus loss.
- Touch mode is on by default on Android/iOS, or with `--touch` /
`AVA2_TOUCH=1` on desktop; it sets `SDL_HINT_TOUCH_MOUSE_EVENTS=0` and makes
`app.ENABLE_MOBILE_HUD` follow it. `main.cpp` hosts the sink: UI = a
picked window that is not the player GameWindow; world tap = mouse move +
left down for one frame (GameWindow keeps the move target after release);
joystick -> `SetPlayerJoystick` (replaces the WASD axes while active, so
movement uses the original camera-relative yaw path); attack ->
`SetPlayerAttackKey` (same state and fishing check as
`player.SetAttackKeyState`).
- Python module `touch`: `IsEnabled`, `GetJoystick`, `IsAttackPressed`,
`SetAttackButton`, `SetJoystickArea`, `GetLayout`. The mobile HUD prototype's
joystick and combat wheel are now display-only (`not_pick`); the old joystick
sent raw move packets and the attack button was a one-pointer `ui.Button`.
Verified: `ava2.touch_router` (routing unit test) and `ava2.touch_game` (the
original GameWindow with the mobile HUD in touch mode: open world, joystick
zone and attack button are not UI, the taskbar is; joystick right gives
movement yaw 90 at camera yaw 0; attack held while walking; taskbar tap reaches
the window manager, open-world tap becomes a world click); 51/51 desktop tests;
`ava2_client --touch` reaches the login screen.
Outstanding: no device run (real multi-touch, finger/pixel scale); the attack
key state is still not consumed on the real-server path (`player_ComboAttack`
stub), so touch attack does not swing yet; the prototype's attack/quickslot
`.sub` art is missing from the packs (attack drawn as a coloured block, skill
slots invisible).
### 2026-10-12 Mobile step 3b — attack and combo wiring
The attack key (keyboard or touch) now swings on the real-server path, ported
from GameLib ActorInstanceBattle / ActorInstanceCollisionDetection,
CPythonPlayerInput `NEW_Attack`, CPythonPlayerEventHandler `OnAttack` /
`OnHit` and CInstanceBase `RefreshState` / `RunNormalAttack` / `RunComboAttack`.
- `RaceData`: `RaceMotionData` (`ParseRaceMotionData`, cached
`GetRaceMotionData`) reads ComboInputData and AttackingData in both the old
single-hit layout (`AttackingType`) and the `MotionType` + `HitDataCount`
layout; `.msm` DEFENDING radius. `LoadPlayerRaces` registers every player
motion and combo table (`LoadPlayerMotions`, a port of
PythonPlayerSettingsModule intro/general/weapon/combo/horse/fishing).
- `chr.MOTION_MODE_BOW_SPECIAL` is 17 and there is no `MOTION_MODE_CLAW`
(AVA2 builds without `ENABLE_WOLFMAN_CHARACTER`, Locale_inc.h:131).
- `ActorInstance`: combo state machine (`InputComboAttackCommand`, pre-input
and direct input windows, `ComboProcess`, `__RunNextCombo`, mounted wrap),
normal attack, attack speed (`m_dwAtkSpd / 100`) applied to attack motions,
per-hit-data victim maps with invisible time and the 16 / HitLimitCount
limits, `TestAttackHit` (hit-position segments against the victim).
- `ProcessPlayerAttack` (called from the main loop): `NEW_Attack` checks
(bow needs a target and an arrow), stop packet when the attack interrupts a
walk, `CG_MOVE` FUNC_COMBO per started motion, hit test against live
monsters/stones, `SetTarget` + `CG_ATTACK` on a hit. Walking and click-move
are suspended while attacking. `player.ComboAttack` uses the same path.
- Remote actors: `RefreshState` picks the motion mode from weapon / mount /
polymorph / wedding dress / pickaxe / rod; `CG_MOVE` FUNC_ATTACK / FUNC_COMBO
from the server play the attack motion facing the packet rotation.
Verified: `ava2.attack_combo` (both .msa layouts, warrior combo tables, real
combo timings: pre-input fires at DirectInputTime, direct input chains, input
after InputLimitTime is dropped, attack speed, remote motions not reported,
hit detection at yaw 0 / 90 incl. once-per-combo, range and far side);
`ava2.touch_game`; 52/52 desktop tests.
Outstanding gaps: not verified against the real server; attack speed is a
motion-clock ratio (no blend / speed-ratio curves); accumulation root motion is
not applied during attacks; victims are an upright cylinder of the race
DEFENDING radius (50 default) instead of the bone spheres; bow attacks have no
arrow flight / clickable-distance reserve; horse attack details, emotions and
skills are not wired; PvP `IsAttackableInstance` rules and the `__CanAttack`
checks (emotion, private shop, observer, new mount) are missing; remote
FUNC_ATTACK / FUNC_COMBO snap to the packet position instead of walking there
when 50+ away.
### 2026-10-12 Mobile step 2 — platform layer
`src/app/platform/` (`ava2_platform`) takes the per-platform code out of
`main.cpp`:
- `EnterClientDataDirectory` (macOS per-user data dir linking the bundle
Resources; Android external files dir) and `ConfigDirectory` (Android
internal storage for metin2.cfg / interface.cfg) — moved unchanged.
- `Lifecycle`: an SDL event watch records background / foreground / low
memory / terminating; the main loop applies them. Entering the background
cancels movement and touch fingers, saves the config and interface status,
and pauses the audio device (`SoundManager::SetPaused`); while in the
background the loop skips game update and rendering but keeps receiving and
dispatching network packets. Foreground resets the frame clock. Android
runs with `SDL_ANDROID_BLOCK_ON_PAUSE=0` (SDL then waits up to 100 ms per
poll while paused); SDL's Vulkan backend recreates the surface on resume.
- Safe area: `SDL_GetWindowSafeArea` mapped through the letterboxed logical
presentation (`MapSafeInsets`) into `TouchLayout` (`safe_*`;
`ForScreen` keeps the joystick area and attack button inside) and
re-queried on `SDL_EVENT_WINDOW_SAFE_AREA_CHANGED` / resize. Python
`touch.GetSafeArea()`; the mobile HUD prototype insets the player panel,
target bar, drawer, quick belt and combat wheel.
Verified: `ava2.platform` (lifecycle transitions incl. pause+resume between
frames, inset mapping with letterbox bars and scaling, safe touch layout),
`ava2.touch_game` (desktop insets 0; a HUD built with insets puts the attack
button inside them), 53/53 desktop tests, `ava2_client --touch` starts,
Android APK builds.
Outstanding: no device run (background/resume, surface recreation, audio
resume, server keepalive while paused); low memory only logs (no cache purge);
the HUD reads the insets only when it is built; iOS lifecycle needs the event
watch to do the save work synchronously.
### 2026-10-12 Mobile step 4 — mobile HUD layout
The touch HUD (`upstream/python-root/ui_mobile_*.py`, mobile mode only) now
follows the planned phone layout instead of the step-3 prototype:
- Native `UI::CDisc` (`wndMgr.RegisterDisc` / `SetDiscColors` /
`SetDiscArc`, `WT_DISC`): radial-gradient disc with a bevelled rim and an
optional clockwise pie arc, drawn with `SDL_RenderGeometry`. All round
frames are procedural; icons come only from AVA2's own taskbar / skill /
item / face textures.
- `ui_mobile_widgets.py`: `Disc`, `RoundButton` (icon or label, fires on
release inside), `QuickSlotDisc` (one `ui.SlotWindow` slot inside a disc;
tap uses it, tap while dragging adds or moves into it — the
`uitaskbar.AddQuickSlot` logic; refresh is a one-slot
`TaskBar.RefreshQuickSlot`).
- Layout (inset by `touch.GetSafeArea()`): top-left face disc
(`uiCharacter.FACE_IMAGE_DICT`) + "Lv. name" + HP/SP/stamina gauges with
the original `AffectShower` below; original `uiTarget.TargetBoard` stays top
centre; top-right row Messenger / Status / Inventory / Menu (menu panel:
Skill, Quest, Guild, System) with the original minimap and event icon under
it; left column Quest / Skill / Emote / Chat plus the original
`GameButtonWindow` hint buttons in a second column; bottom-right attack disc
(r 60, `touch.SetAttackButton`) with 8 quickslots on two rings (current
quickslot page, cycles pages 1-3) and page / ride (`/ride`, the Ctrl+G
command) / pick-up buttons; bottom centre potion belt = quickslot page 4
(global 24-31); 3 px experience bar at the bottom edge.
- `interfaceModule.ShowDefaultWindows` / `ShowAllWindows` call
`MobileHUD.AdoptDefaultWindows`: hides the PC taskbar (and its TOP_MOST
HP/SP/EXP tooltips, which only the taskbar's OnUpdate hides), expanded
taskbars and energy bar, moves the minimap, chat and game hint buttons.
`game.GameWindow` calls `AdoptGameWindows` after the event icon opens.
- New `player.RequestUseGlobalQuickSlot` / `RequestAddGlobalQuickSlot` /
`RequestMoveGlobalQuickSlotToGlobalQuickSlot` (global < 32, same
CG_QUICKSLOT packets as the local variants) for the belt; switching
`SetQuickPage` was not usable because it refreshes the inventory.
Verified: `ava2.touch_game` (taskbar hidden, belt = globals 24-31, minimap
under the top row, HUD buttons are UI while open world / joystick / attack are
not, attack disc pixels drawn, insets move the player panel),
`ava2.python` (global quickslot packets and range limits), 53/53 desktop
tests, desktop screenshot reviewed, Android APK builds.
Outstanding: no device run; minimap is still the original round one; labels
are English; chat input line can overlap the wheel's page button while typing;
no auto-hunt / target-lock buttons; Android keeps the 1024x768 letterboxed
logical size (step 5 scaling); the HUD reads the safe area only when built.
### 2026-10-12 Mobile step 5 — UI scaling and live safe area
- Logical UI size on phones / tablets (`platform::ChooseMobileLogicalSize`):
instead of letterboxing metin2.cfg's 1024x768, height =
clamp(round(height in dp x 1.5), 600, 768) and width = height x screen
aspect (landscape, even, at least 1024). A 2400x1080 phone at density 2.75
gets 1332x600, a 2400x1080 at 2.25 gets 1600x720, a 4:3 tablet 1024x768.
`--ui-height N` / `AVA2_UI_HEIGHT` override the height (600..1080).
`CPythonSystem::SetDisplaySizeOverride` makes `systemSetting.GetWidth/Height`
and the window manager report it without rewriting metin2.cfg.
Android / iOS read the primary display (`QueryDisplay`); desktop simulates
with `--phone WxH[@density]` (implies `--touch`) and `--safe-insets L,T,R,B`.
- Live safe area: on `SDL_EVENT_WINDOW_SAFE_AREA_CHANGED` / resize the host
resets the touch layout for the new insets; `MobileHUD.OnUpdate` sees
`touch.GetSafeArea()` change and rebuilds itself under a fresh root window
(old root hidden), re-registers the attack button and re-runs
`AdoptDefaultWindows` / `AdoptGameWindows` (minimap, chat, hint buttons,
buffs, event icon). Covers rotating 180 degrees with a side notch.
- HUD gauge backgrounds and frames are now kept referenced (they were
destroyed right after creation).
- Fixed the step-4 `touch_game` disc pixel check (threshold too high; the
earlier run used a stale test binary because the build stopped at the known
speedtree_forest_test errors without `-k`).
Verified: `ava2.platform` (size choice for phones, portrait-reported
displays, tablets, override clamp, near-square foldable, `--phone` parsing),
`ava2.touch_game` (running HUD relayouts on new insets and back, minimap and
buffs follow, attack button re-registered), 53/53 desktop tests,
`ava2_client --phone 2400x1080@2.75 --safe-insets 50,0,0,24 --phase game
--preview-data` renders 1332x600 full-bleed with the HUD inset.
Outstanding: not run on a device (display mode vs. immersive window size,
real cutout insets); a window size change at runtime (split screen,
foldable) keeps the logical size chosen at start; no in-game UI size option
yet (only `--ui-height` / env); original PC windows (inventory etc.) are
not rearranged for 600 px height.
### 2026-10-12 Mobile step 6 — auto hunt
Client-only feature (the original client has none; not taken from 40250).
It only drives paths that manual play already uses: walk-to (move target),
target packet, the normal attack, quickslot skills, item pick-up and
quickslot potions. Nothing new goes on the wire.
- `src/game/auto_hunt.{h,cpp}`: engine-free state machine
(off / search / engage / loot / return / paused). Hunts the nearest living
mob within `radius` of an anchor point (metin stones optional), loots own
or unowned drops before the next mob, walks back to the anchor when the
area is empty, and gives up on a target whose distance stops shrinking for
8 s (ignored for 30 s). Joystick / attack key / mouse movement pause it;
it resumes 3 s after the last input and re-anchors where the player
stopped. HP / SP potions (belt slots 1 / 2, quickslot 24 / 25) are checked
in every state with a 1 s gap. Death turns it off.
- `ProcessAutoHunt()` (python_gameplay_modules.cpp, called from the game loop
before `ProcessPlayerAttack`) builds the input from NetworkActorManager
(mobs bType 0/2), `CPythonItem::GetGroundItems()` (new read accessor) and
the combat wheel's current skill page, skipping skills on cooldown, active
toggles, 121-123 and guild skills.
- Python: `player.SetAutoHunt / IsAutoHunt / GetAutoHuntState /
SetAutoHuntOption / GetAutoHuntOption`; options (radius, skills, pickup,
stones, hp_percent, sp_percent, hp_slot, sp_slot) persist in
`autohunt.cfg` next to metin2.cfg.
- `ui_mobile_autohunt.py`: AUTO button on the combat wheel (tap toggles,
green while on with the state under it; 0.6 s long press opens the settings
board with range / skills / pick-up / stones / potion thresholds).
Verified: `ava2.auto_hunt` (targeting, range stop, skill gap, busy, loot
before next mob, area and stone filter, return, chase watchdog, pause /
resume / re-anchor, potions, death), `ava2.touch_game` (AUTO is UI under the
finger, tap on/off, engage + target VID + move target, stop in reach,
joystick pauses, long press opens settings, option persistence), 54/54
desktop tests, HUD screenshot shows AUTO above Ride.
Outstanding: not run on a device or against the server (ownership timing,
pick-up refusals, attack speed); straight-line walking only, the stuck
watchdog is the only obstacle handling; party loot rules ignored (only own /
unowned drops); no desktop hotkey (F9 is taken by the preview mode);
English labels, no locale strings; does not run in `--preview-data`.
### 2026-10-12 Mobile step 7a — app_loop split
- `src/app/main.cpp` moved to `src/app/app_loop.cpp` (history kept). The
former `main()` body is now `RunClient`, a C++20 coroutine that suspends
at the top of every frame (`co_yield`), so start-up, frame body and
teardown stay one function with all their locals in the coroutine frame.
`ava2::app::AppLoop` (`app_loop.h`) drives it: `Start` (start-up up to the
first frame), `Iterate` (one frame), `QueueEvent`, `Finish` (lets a running
client leave the loop and tear down), `Run` (classic loop).
- The new `src/app/main.cpp` only picks the driver: SDL main callbacks
(`AVA2_MAIN_CALLBACKS`, default ON except Android; iOS requires it because
UIKit owns the main thread) or a classic `main` loop (Android for now).
With callbacks, SDL_AppEvent queues events and the frame's event pass reads
the queue instead of `SDL_PollEvent`.
- iOS: no software FPS cap by default (SDL_AppIterate follows the display).
Verified: 54/54 desktop tests; `ava2_client --phone 2400x1080@2.75
--safe-insets 50,0,0,24 --phase game --preview-data --frames 150
--screenshot` gives a byte-identical BMP with the callbacks and with the
classic loop (`-DAVA2_MAIN_CALLBACKS=OFF`) compared to before the split;
bad arguments still exit 1.
Outstanding: Android stays on the classic loop until callbacks are tried on
a device; the frame body is still one function (state not yet split into
classes).
### 2026-10-13 Mobile step 7b — iOS packaging
- `ios/build.sh [sim|device] [deps] [--no-run]`: builds static SDL3 3.4.16
and FreeType 2.13.3 once into `build/ios-deps/prefix-<sdk>` (tarballs
shared with `build/android-deps`), then the client as
`build/ios-<sdk>/ava2_client.app` (8.8 MB, code only, Python embedded,
deployment target 15.0, arm64). The simulator build is signed ad hoc,
booted, installed and launched. A device build is signed with
`AVA2_IOS_SIGN_IDENTITY` and the entitlements of `AVA2_IOS_PROFILE`, and
is installed with `xcrun devicectl`.
`ios/Info.plist.in` sets landscape only, full screen, a hidden status bar,
an empty launch screen (native resolution), `UIFileSharingEnabled`
and a local-network usage string.
- Simulator only: SDL_GPU rejects the simulator's Metal device because it
does not report MTLGPUFamilyApple3. `build.sh` patches its private
extracted copy of `SDL_gpu_metal.m` (`|| TARGET_OS_SIMULATOR`). Device
builds use stock SDL.
- Data directory: `platform.cpp` uses the app's Documents folder
(`SDL_FOLDER_DOCUMENTS`). The "game data not found" box names
`ios/push_assets.py`. That script stages the tree with
`android/push_assets.py --stage-only --lowercase` and copies it into the
simulator container as APFS clones (`cp -Rc`), or to a device with
`xcrun devicectl device copy to`.
- iOS file systems are case-sensitive as the app sees them, including the
simulator container. The client opens lower-cased paths
(ResourceManager::NormalizePath), but the data is mixed case
(`Dopador_manual/…`). So the iOS tree is staged with every name
ASCII-lowercased. Only A–Z is folded: legacy CP949 names stored as
Latin-1 code points (`oxà캥æ®.dds`) must keep their bytes.
`EffectData`'s path normalisation now also folds A–Z (scripts spell
`empire_A.mse`), like the effect cache key already did.
- Staging fixes that also apply to Android: `android/push_assets.py` now
uses `build/dev/test-rundir` (tools/make_test_rundir.py) as the base layer
and adds the loose `svside/` folder. Before, `assets/loose` alone lacked
pack files that game.py needs (Dopador_manual/*, the switcher art,
svside/*.jpg), and the game phase ended. The staged tree is now
98,349 files / 3.95 GiB.
Verified: iPhone 17 Pro simulator, `--phase game --preview-data`. The game
scene and the mobile HUD render; the safe area (118/0/118/38) keeps the HUD
clear of the notch on either landscape side. The console has 0 TraceError
or Traceback lines. Without data, the app shows the "game data not found"
box. Desktop 54/54.
Outstanding: the device build, signing and devicectl install/copy are
untested (no device or profile). The network keepalive does not run while
the app is in the background (iOS suspends SDL_AppIterate). Android still
uses the classic loop. Paths the client opens without lower-casing them
would fail on iOS; none showed up in the login screen or the game phase,
but character select and a real-server login have not been run on iOS yet.
### 2026-10-13 Mobile gestures — item and window interaction
- Before this step the port's `CSlotWindow` had no mouse handlers, so item
pick-up, drop, equip, double-click use, right-click and hover tooltips did
not work on desktop either. Ported from EterPythonLib, 1:1:
- `PythonSlotWindow.cpp` handlers: left down → OnSelectItemSlot/OnSelectEmptySlot,
the drop on left up, right down, double click → OnUseSlot, over/over-out
tooltips, RefreshSlot.
- `PythonGridSlotWindow.cpp`: the slot vector, GetPickedSlotList,
OnRefreshSlot, CheckMoving, the grid GetPickedSlotPointer.
- `CWindowManager`: IsDragging (the 10 px rule), mouse over on every move,
right button down/up with DeattachIcon.
- `app.SetMouseHandler` now stores the handler. app_loop calls its
Update/Render after the phase window, so the attached icon follows the
pointer. `app.IsPressed` reads the real keyboard state, so desktop
Shift-split and Ctrl-quickslot work. Desktop double clicks
(`clicks >= 2`) reach RunMouseLeftButtonDoubleClick. Keys are released on
focus loss and when the app goes to the background.
- Touch router UI gestures:
- A tap sends move, down and up at the touch-down point.
- A drag past tap_slop presses at the start point.
- A double tap (within 300 ms and 40 px) becomes a double click.
- A long press (450 ms) on an item slot calls `touch.SetLongPressEvent`.
- The callback opens `ui_mobile_actions.ItemActionSheet` with Use, Split and
Quick slot. Split and Quick slot run the original Shift/Ctrl branches via
`touch.SetVirtualKey`.
- Mapping table: docs/MOBILE-ARCHITECTURE.md, "物品与窗口手势".
Verified: the new `ava2.inventory_touch` test drives the original
uiinventory.py through the router and the window manager. It covers the
hover tooltip, tap pick-up and tap drop (move packet 0→5), drag 0→6,
double-tap use, the long-press sheet (Use, Split opens dlgPickMoney,
Quick slot), tap-outside close, long press on an empty cell, and
app.IsPressed. `touch_router_test` covers the gesture timing. The phone
simulation (`--phone --touch`) draws no software cursor. Desktop 55/55.
Outstanding:
- Gestures have not been tried on an Android or iOS device yet.
- Drop and sell are drag-only; the sheet has no buttons for them.
- A button's zero-size TextLine sits at the button's exact centre pixel,
and IsIn is inclusive, as in the original. Only that one pixel misses
the button.
### 2026-10-13 Android device verification
Device: OnePlus PJZ110 (Android 17), 2376x1080 at density 3.00, giving a 1320x600 logical UI.
Safe area insets: 117/67/50/53.
Changes:
- `Ava2Activity` (extends SDLActivity) passes the `args` intent extra as the command line,
so a dev run can start in `--phase game --preview-data`. `android/build.sh` forwards
`AVA2_ARGS`.
- Startup crash: directories created by `adb push` were owned by `shell` with mode 2770,
so the app uid could not stat `ymir work/pc/...gr2`. The uncaught std::filesystem
exception ended main. `push_assets.py` now chmods what shell owns after the push. It
skips files the app wrote itself (channel.inf, the cfg files), which shell cannot chmod.
- Forced landscape: the window is resizable and had no `SDL_HINT_ORIENTATIONS`, so SDL
requested FULL_USER. That overrode the manifest's `sensorLandscape`, and the game
rendered letterboxed in portrait. Fixes:
- app_loop sets the hint to `LandscapeLeft LandscapeRight` on Android and iOS.
- `Ava2Activity.setOrientationBis` always requests SENSOR_LANDSCAPE.
- Verified with the system rotation locked to portrait.
- The mobile window is `SDL_WINDOW_FULLSCREEN` (immersive). Before this, the status bar
drew over the HUD. Verified.
- Wrong trees on the phone: about 1000 files exist in both `assets/loose` and the
pack-manifest test-rundir with different content. Examples are the zone/b tree atlases
(at half size), monster2/npc_pet models and pc effects. `assets/loose` was layered on
top, which broke the SpeedTree UVs into flat green cards. The desktop client showed the
same result in `build/android-data/root`. Fix: `push_assets.py` now stages
`assets/loose` first and lets test-rundir (what the original client serves from its
packs) win.
- One `adb push --sync` over all ~98k files aborts in file_sync_client ("failed to read
stat response"). push_assets.py now pushes batches of at most 20,000 files.
Verified on the device:
- Game phase renders correctly on Vulkan.
- Joystick moves the player.
- The inventory opens from the HUD and closes with its X.
- Login phase shows the server list.
- 60 fps steady on the 60 Hz panel (SurfaceFlinger latency: 0 frames over 25 ms), with
SoC sensors around 41 °C.
Environment notes:
- A root-owned adb server on :5037 claims the phone, and launchd respawns it. Use the SDK
adb (34.0.4) against it: a different client version restarts that server mid-push.
Outstanding:
- Item gestures on the device: the preview inventory is empty, so pick/drag/double-tap/
long-press were checked only in `ava2.inventory_touch`.
- Real-server login: no isolated AVA2 server or account is available. The listed
servers are not to be used.
- A missing or unreadable model should fail that load, not throw out of main.
- The `--preview-data` camera starts inside the tree canopy, so the player is hidden.
- Thermals over a long session not yet measured.
### 2026-10-13 Real SpeedTree SDK
The SDK repository now carries the SpeedTree runtime this checkout calls (SDK 62a5f5a:
"Implement cross-platform SpeedTree runtime and recovery tests" and "Fix terminal foliage
dispatch on frond branches"). The local mirror and SDK shim are no longer needed; desktop
and Android build against the plain SDK checkout.
Changes:
- `tests/attack_combo_test.cpp` and `tests/ava2_render_3d_test.cpp` call the code under
test inside `assert()`. In RelWithDebInfo (NDEBUG) those calls compiled out and the tests
segfaulted; they had been skipped only because the test rundir was not found. Both now
undefine NDEBUG, like `hardware_scene_test.cpp`.
- `android/build.sh` prefers the SDK's adb over the one on PATH (see the adb note above).
Verified:
- Desktop ctest 59/59 with `-DAVA2_TEST_RUNDIR=<checkout>/build/dev/test-rundir`, including
`ava2.speedtree_forest` (without that option the 9 asset tests are skipped).
- Desktop phone layout and the device both render trees with real branches and fronds.
- Device game phase: 60.3 fps, max frame gap 16.6 ms, 0 frames over 25 ms.
### 2026-10-13 Mobile HUD: minimap frame and top inset
- Minimap outside its frame (preview): with `--preview-data` no map loads, so
`miniMap.Render` returns early and the green circle was app_loop's dev radar, drawn at
the fixed PC spot `(screen_width - 132, 5)`. `CPythonMiniMap::Render` now records the
window position before the map check (`GetScreenPosition`), and the radar draws there.
It opens the minimap once via `ShowMiniMap()` (normally `AtlasInfo` does that on map
load), so `CanShow()` follows its close/open buttons. A real map was not affected.
- Top HUD row too low: SDL folds system-gesture insets into the safe area. In landscape
fullscreen the status bar is hidden but its swipe zone still gave a 120 px (67 logical)
top inset. `Ava2Activity.Ava2Surface` re-sends the insets with the top taken only from
the display cutout and visible system bars (device cutout is left-only).
- The preview keyboard-hint header is not drawn in touch mode; it overlapped the HUD.
- `--game-script` now also runs with `--preview-data` (desktop probing of the mobile HUD).
Verified on the device: minimap inside its frame, portrait/status bars and the entry row
at the top edge. Desktop ctest 59/59.
Outstanding: after a tap the cursor stays where the finger lifted, so hover tooltips
(e.g. "[F6] Battle pass") remain until the next touch. (Addressed below: world taps and
cancelled touches now park the pointer too.)
### 2026-10-13 Mobile touch: system edges, cancel, long-press sort
Interaction ideas from jhaizhou-ops/d2r-mobile (MIT); only the ideas were taken, no code.
docs/MOBILE-ARCHITECTURE.md has the details ("系统边缘与取消").
- `TouchRouter`:
- world fingers that land in the bottom safe inset (the gesture bar) are `Owner::Ignored`;
- new `FingerCancel(id, ms)`: `SDL_EVENT_FINGER_CANCELED` now cancels only that finger
instead of `CancelAll`;
- a cancelled joystick finger keeps the stick vector for `joy_reacquire_ms` (300). A finger
landing within 1.5 radii of the old base takes it over, keeping the same base;
- an attack tap shorter than a frame releases on the next `Update`;
- new sink hook `UiPointerIdle`: a cancelled pending UI touch parks the pointer.
- Host: a world tap's deferred button-up also parks the pointer (`TouchUiPointerIdle`), so no
hover tooltip or target stays under the tap point.
- Long press on an empty inventory cell: `touch.SetLongPressEvent` callbacks get a sixth
argument, `isEmpty`. `ItemActionSheet` offers Sort / Close. Sort fires the original
`separateButton` event, which opens the question and then sends `/click_sort_items`.
Cells covered by a larger item and empty cells in other windows still press normally.
- Checked, no change needed: every quick-slot tap uses the slot once (select on button
down; the double click goes to `OnUseSlot`, and quick-slot discs have no use event).
Dropping an item on any shop slot, empty or occupied, already sells it (uishop).
- Tests:
- `touch_router_test` `system_edges`;
- `inventory_touch_test`: long-press empty cell → Sort → question → `/click_sort_items`;
- `touch_game_test` now keeps its assert()s in release builds.
- Desktop ctest 59/59.
- Verified on the device: long press on an empty bag cell → Sort / Close → the original
sort question.
Outstanding:
- the system-edge strip and joystick re-acquire are covered by unit tests only, not yet
exercised by hand on the phone;
- hold-to-repeat on quick slots (d2r's held potion) is not done.
### 2026-10-13 Mobile HUD: left column closer to the edge
- The left safe inset was 117 logical px on the OnePlus PJZ110 (landscape). Android adds the
back-gesture zone (90 physical px) on top of the punch-hole cutout (120 physical px), so the
portrait and the left button column sat about 130 logical px in from the edge.
- `Ava2Surface.onApplyWindowInsets` now passes `covering.left` (cutout and visible system
bars only) as the left inset, the same way it already handled the top. Taps in the gesture
zone still reach the app. Right and bottom still use the combined insets.
- Verified on the device: the portrait, the Quest/Emote column and the joystick moved about
50 logical px to the left and stay clear of the cutout.
### 2026-10-13 Mobile: tapping an edit line shows the keyboard again
- The frame loop only called `SDL_StartTextInput` when `ime.EnableCaptureInput` state changed.
Once the user hid the on-screen keyboard (Back or the keyboard's hide key), the login edit
kept focus, so tapping the ID or password box changed nothing and the keyboard stayed hidden.
- `HostTouchSink::UiMouseDown` now notes a finger landing on the focused window (or a child of
it) while text is captured. The next frame calls `SDL_StartTextInput` again if the keyboard is
hidden; SDL shows it again without restarting text input.
- Verified on the device (login board): Back hides the keyboard; tapping ID or Password
brings it back; tapping the background does not. Desktop ctest 59/59.
### 2026-10-13 Render: intro pose, preview hair, tree LOD, terrain seams
All four issues reproduced on desktop too (`--phone ... --phase select|game --preview-data`).
- Select screen T-pose: `chrRender` draws intro characters through the CPU scene renderer,
which ignores GPU skinning palettes, so with hardware skinning on they stayed in bind pose.
It now turns hardware skinning off while it collects those draws. The intro character plays
`intro/wait` again.
- Missing head on the preview player: its hair path
(`plechito/summer2020_costume/hair/warrior_m.gr2`) does not exist, and the body models carry no
head. It now uses `ymir work/pc/warrior/hair/hair_1_1.gr2` (warrior_m.msm HairData00).
Network actors already went through the original `SetHair` logic.
- Trees: `CSpeedTreeWrapper::Advance` calls `ComputeLodLevel()` and then always
`SetLodLevel(1.0f)`, so the original draws full geometry at alpha ref 84 and never shows the
billboards. Our integration compared the camera distance with the raw .spt lod_near/far
(100/1100), so nearby trees dropped to their billboards (dark composite silhouettes, pine
needle quads). `SpeedTreeRT.cpp` now always builds trunk, leaf and frond geometry. Texture
names resolve like `LoadTree`: GetPath(spt) + NoExtension(name) + ".dds"
(`CompositeMap`, `plant_grass` had no extension and stayed untextured).
Leaf density and branch shape come from the SDK generator, which is still being worked on.
- Terrain white seams/blocks: far patches (step 2) next to near ones (step 1) left T-junction
cracks that showed the cleared background. Each patch now hangs a vertical skirt
(2 cells deep) below its edges. Forcing step 1 everywhere removed the seam the same way.
- Desktop ctest 59/59. Device (OnePlus PJZ110): select screen shows the warrior and ninja in
their intro idle with heads; the game preview shows full-geometry trees and no terrain seam.
The preview player stands inside a pine, so its head was not visible in the game shot.
### 2026-10-13 Terrain: load the 3x3 blocks around the player
On the real server (Android, "AVA2 General" at 412,760) the terrain stopped at a block edge,
with empty sky beyond it. `CPythonBackground::LoadMap` loaded only the block under the warp
point and never loaded another one. The original `CMapOutdoor::Update`/`LoadTerrain`
(`LOAD_SIZE_WIDTH` 1) keeps the 3x3 terrains and areas around the player's terrain coordinate,
clamped to `MapSize`, and reloads them when that coordinate changes.
- `TerrainHeightmap::LoadBlockDirs` stitches up to 3x3 blocks into one heightmap:
- heights are (128n+3)², tiles (256n+2)², attr 256n²; neighbours share their border samples;
- the patch grid is 8 patches per block, and the quadtree is built over the patch ranges;
- patches of blocks with no `height.raw` are skipped.
The active-terrain pointer stays the same, so height, attribute and actor queries work as before.
- `GetAttrAtWorld` now maps attr.atr the way the files are laid out: 256 cells of 100 per block,
starting at the block origin (raw index 1). Before, the 256 cells were stretched over the
130-cell bordered height grid.
- `CPythonBackground::Update(x, y, z)` takes map x, map y and height (as `app_update_game` passes
them; the app_loop call had y and z swapped). When the terrain coordinate changes it reloads
the set: terrain, every block's `areadata.txt`, and one water surface per block. The object
loading centre now uses map y instead of height.
- Desktop ctest 59/59 (background_test checks a 2x2 stitch: heights, attributes, and Update with no block change).
### 2026-10-13 Audit: remaining differences from the Windows client
Compared module by module against `upstream/ava2-client` in three passes:
1. Python module surfaces (functions and constants, nearest method table, `#ifdef` checked against `Locale_inc.h`/`ServiceDefs.h`);
2. every packet handler per phase and every `net.Send*`;
3. engine subsystems.
The Python surface has no real gaps. What remains:
- names commented out in the reference (CHAT_TYPE_UNK_10, ITEM_FLAG_RARE, RARITY_MAX_VALUE, MOB_RESIST_BLEEDING, chrmgr.RegisterMotion);
- names behind macros that are off (WJ_COMBAT_ZONE, ENABLE_WOLFMAN_CHARACTER, ENABLE_SOULBIND_SYSTEM, ELEMENT_SPELL_WORLDARD, WJ_CHANGELOOK_SYSTEM, ENABLE_PERMA_ITEM, ENABLE_OPTION_COLLECT_EQUIPMENT, NEW_PET_SYSTEM);
- modules python-root never imports (udp, guild_ranking, wndSlot, wndText).
Every GamePhase case exists. The 9 upstream-only cases are all macro-off: CSHIELD, ELEMENTS_SPELL, KEY_AGREEMENT*, COMBAT_ZONE*, SUPPORT_SKILL, TOURNAMENT_ADD, and TARGET_CREATE (commented out).
Outstanding, most severe first:
P0, the real-server flow stops:
1. `RecvWarpPacket` reads and drops GC_WARP. Windows sets DirectEnter for the selected slot and reconnects to `lAddr:wPort`. Map teleports and channel moves hang.
- **Fixed:** `RecvWarpPacket` stops processing the old socket and `pump_python_net` calls `LoginClient::warp`. It reconnects like DirectEnter: same login key, the remembered selected slot, a new generation so the server clock is re-synced, and `SetNewLoadingPhase` (ENABLE_NEW_LOADING). A connect failure under DirectEnter is ClosePhase (`SetLoginPhase`). Covered in `login_oracle_test`.
2. In-game `RecvPhasePacket` only stores the phase. Windows calls `SetSelectPhase` (plus `__DownloadMark`), `SetLoginPhase`, `SetLoadingPhase`, `SetGamePhase` or `ClosePhase`. Going back to character select and reloading after a warp do not work.
- **Fixed:** `RecvPhasePacket` follows the Windows switch: CLOSE → SetLoginPhase; SELECT → leave the game phase and hand the unread bytes back to `LoginSession::return_to_select`, which shows the cached roster at once (SelectReady); a later LOGIN_SUCCESS raises SelectRefresh → select window `Refresh`; LOADING → player clear; GAME → status refresh; DEAD → no-op (it used to make `IsGamePhase()` false). `__DownloadMark` waits on item 8.
3. `LoginSession` (select phase) only accepts headers 0/7/32/44/90/150-153/253-255 and drops the connection on anything else. The following are missing:
- GC 6 LOGIN_SUCCESS3;
- GC 8/9 PLAYER_CREATE_SUCCESS/FAILURE;
- GC 10/11 PLAYER_DELETE_SUCCESS/WRONG_SOCIAL_ID;
- GC 17 POINT_CHANGE;
- GC 107 CHANGE_NAME.
On the real server, `net.SendCreateCharacterPacket`/`SendDestroyCharacterPacket` raise NotImplementedError, and `SendSelectEmpirePacket`/`SendChangeNamePacket` send nothing.
- **Fixed:** `LoginSession` parses GC 6/8/9/10/11/17/107 in LoggingIn/Selecting/Entering (17 is dropped like Windows) and queues `SelectResult`s; `pump_python_net` turns them into OnCreateSuccess (create window), OnCreateFailure (create + select), OnDeleteSuccess/OnDeleteFailure/OnChangeName (select). The four senders build the original struct images (`wire::create_character`/`destroy_character`/`select_empire`/`change_name`, checked against Packet.h in `login_oracle_test`); a failed Send only logs, and the empire is stored after a successful Send.
P1, visible gameplay:
4. `ParseRaceMotionData` ignores `motioneventdata` in .msa files (effect, effect-to-target, fly, screen waving/flashing, special attack, character show/hide). Per-motion .mss sound scripts are not loaded either. On the real server, skills and attacks show no effects and play no swing, footstep, hit or death sounds.
- **Fixed:** `ParseRaceMotionData` reads LoopData and MotionEventData (effect / effect-to-target registered with EffectManager, fly with FlyingManager, special attacking with its collision spheres, sound, show/hide, warp; AttackType defaults to SPLASH = 0) and the `sound/<path>.mss` script. `ActorInstanceMotionEvent.cpp` runs the events per 1/60 s frame (loop motions finish their frames before wrapping): effects attach to bones or follow them, .mss sounds go through `PlayCharacterSound3D` (5000 range and 0.3 s repeat check for non-PCs), motion loops follow `CurrentMotionLoopProcess`, splash hits feed `ProcessPlayerAttack` → SendAttackPacket(skill), fly shots → FlyingManager + SendShootPacket, warp → FUNC_WAIT state. Player skill and guild-skill motions are registered (`__LoadSkill` / `__LoadNinethSkill` / `__LoadGuildSkill`); `ClickSkillSlot` plays NAME_SKILL + grade motion with the formula loop count, sets the fly target and sends the FUNC_SKILL state; remote FUNC_SKILL states play the skill motion; GC FLY_TARGETING (71) / ADD_FLY_TARGETING (69) set the shooter fly target by VID or position, CG fly-targeting sends global coordinates. Limitations: screen waving is a no-op, the fishing effect-to-target is skipped, flying instances aim at the target position at launch, fan/circle multi-target AddFlyTarget and moving skills are not ported, the fly-target centre approximates the bounding sphere, splash spheres are tested as cylinders. Covered in `attack_combo_test` (TestMotionEvents).
5. `RecvDamageInfoPacket` and fly-target hits always spawn `warrior/effect/gihyeol_spark.mse` and play `sound/ui/punch.wav`. These are invented. Windows uses the race-registered hit effects (chrmgr EFFECT_HIT…) and the damage-number effects.
6. Terrain (MapOutdoorLoad/RenderHTP, TextureSet):
- textureset UScale/VScale/UOffset/VOffset/Begin/End are ignored (fixed world/500 UVs);
- splat alpha is per-vertex 3x3 instead of per-tile, and only for textures with tiles;
- the static `shadowmap.dds` and the dynamic character shadow texture are not applied;
- fog bands are missing (no fog near, untextured fog-colour patches past fogFar+1600, splat limit, 3 LOD index sets);
- setting.txt HeightScale, ViewRadius and TerrainVisible are ignored; the environment path rule is unverified;
- `areaambiencedata.txt` ambient sounds and `AreaProperty.txt` are not used.
7. Actor visuals:
- armour/weapon refine glow and shining are missing;
- weapon trace is missing;
- the horse actor is missing (rider only);
- emotions (`player.ActEmotion`, `IsActingEmotion`) are missing;
- dig and fishing motion queues are missing;
- movement dust is missing;
- the percent-weighted random motion pick and motion blend times are missing;
- race smoke and attached effects are missing.
8. Guild marks: `net.UploadMark`/`UploadSymbol`/`SendGuildSymbol`/`RecvGuildSymbol` and `wndMgr.MarkBox_Load` are stubs; there is no `__DownloadMark` and no guild-area terrain overlay.
9. Stubbed queries used by python-root:
- `player.IsPVPInstance` (uitarget PvP menu) and `player.IsOpenPrivateShop` (uiprivateshopbuilder) always return 0, as do `player.IsInSafeArea` and `chr.PickAll`;
- `background.TextureChange` (game options) does nothing, nor do `chr.LookAt` and `chr.DismountHorse`;
- `player.SetMouseState` is unused on touch.
10. Features that are on in the reference but stubbed here:
- 67-attr (`__BL_67_ATTR__`: Send67AttrPacket/Close);
- calendar (`ENABLE_CALENDAR_SYSTEM`: CalendarOpen/Close/Send);
- Catch-the-King (`ENABLE_MINI_GAME_CATCH_KING`);
- `net.SendMobileMessagePacket`;
- SafeBoxWrongPassword does not call `OnSafeBoxError`;
- background Create/DeleteTargetEffect (shop and location markers);
- server commands StoneDetect and Start/StopStaminaConsume.
### 2026-10-13 Module behavior parity: first repair batch
This is a targeted behavior repair after updating to client HEAD 31c5b3dd, not a claim of full Windows equivalence. See [the per-module audit](WINDOWS-MODULE-AUDIT-2026-10-13.md) for all 46 modules, source paths, reviewed scope and remaining work. The audit scripts now inspect src/scripting and fail instead of reporting an empty source set. Method coverage is complete, but 71 constant-return candidates and unreviewed behavior remain.
Fixed SMS and enabled 67-attribute/calendar/CatchKing senders; warehouse row capacities and original open/error/money/batched refresh callbacks; stamina start/stop/frame accumulation and mobile callbacks; PvP/safe-area queries and shared attack eligibility; casting cooldown using point 21 instead of movement point 19; TextureChange and original per-texture scale/offset coordinates. Added windows_behavior_test with literal wire fixtures, state/callback and terrain checks. Corrected obsolete forest tests to the source's forced full LOD and full-bound frustum culling.
Desktop build and all 60 CTests pass. ASan/UBSan windows_behavior passes. Packet audit compares 395 constants with zero mismatch. No live-server or Android-device test, no Windows process output oracle. Five Python baseline hash differences predate this batch in the pulled HEAD; original reference C++ and the shared SDK were not changed. Pending: guild mark connection/cache; target/StoneDetect effects; motion queues and advanced skills; terrain splat/shadows/fog/environment; Windows NO_WIND/static-lighting vs current tree rendering (leaf rocking needs separate handling); adapt necessary collision/GPU changes from the preserved pre-pull stash to the new layout. Older backlog descriptions about damage-number queues, missing network horse actors, LookAt and MarkBox_Load are superseded by the linked audit.
### 2026-10-13 Windows behavior parity: target effects, StoneDetect, tree lighting
Restored the missing background calls in target-create/update/delete receive handlers. Background now owns target effect instances, follows actual actor positions, converts global coordinates using MapOutdoor BasePosition, defers zero-height locations, and cleans its instances/bindings on deletion and map changes. Preserves first-insert actor bindings and the original shared reservation resource rule. Removes stale special-effect ID associations so deleted/recreated targets can follow instead of leaking. StoneDetect now selects the four original assets and converts its compass angle; invalid input does not spawn. SpeedTree tree/frond/leaf commands now disable dynamic lighting as WRAPPER_USE_STATIC_LIGHTING requires, preserving vertex diffuse colors.
See [second-batch details](WINDOWS-TARGET-EFFECTS-2026-10-13.md) and verification logs in build/verification/windows-target-effects-2026-10-13. Expanded windows_behavior tests cover received packet fragments, nonzero map bases, draw positions, following and ownership lifecycle; forest tests cover static lighting. Full Windows/Android visual parity remains unverified. Still pending: guild mark transfer/cache, advanced motion and skills, terrain shading/fog/splat/environment, tree wind-method separation and prior collision/GPU integration adaptation. Target effects still depend on the replacement effect renderer and current terrain-only height query.
Validation: desktop full build and CTest 60/60 passed (52.67 s); final expanded behavior/forest tests 2/2 passed (1.75 s), ASan/UBSan 2/2 passed (3.17 s). git diff --check passed; no new upstream reference changes and the shared SDK is clean.
### 2026-10-13 Windows terrain parity: map settings, culling and water grid
Restored HeightScale through initial and streamed terrain loads and water vertices; TerrainVisible now independently gates terrain drawing. Reset per-map settings and texture/UV caches at map load. The compatibility fallback block entry now uses the same streaming loader instead of a stale-origin raw path. Valid camera culling no longer falls back to an uncullable whole-map draw. Water starts at its block origin, uses the map height scale without the invented -200 bias, draws every valid cell (including odd rows/columns) and skips -1 layers.
[Third-batch source comparisons and regression cases](WINDOWS-TERRAIN-SETTINGS-2026-10-13.md) document retained developer-map defaults and malformed-input boundaries. background_test covers 4×1 streaming, heights, pointers, per-map vs runtime visibility, reset, culling, sparse water and bad scale. ViewRadius patch allocation, true LOD, shadow/fog/splat, water depth alpha/material/animation and ambient sound remain outstanding; this is not visual equivalence. Other backlog: guild mark transfer/cache, advanced actors/skills, tree wind separation and collision/GPU adaptation. No reference/server/SDK changes or live-server/device proof.
Validation: full desktop build and 60/60 CTests passed (52.49 s). ASan/UBSan background + windows_behavior 2/2 passed (1.51 s); SDK/client C++ instrumented, Python C dependency not equally instrumented. git diff --check passed.
### 2026-10-13 Windows SpeedTree parity: WIND_NONE vs leaf rocking
Client forest/model now default to no branch/frond/leaf-center deformation using identity wind matrices, matching WRAPPER_USE_NO_WIND. Empty matrices cannot mean no wind because the SDK synthesizes it. Leaf pivot rocking and camera-facing placement remain active. Explicit SetCpuWindEnabled(true) / the final BuildDrawCommands cpuWind argument preserves optional CPU wind. The background forest now uses accepted game-frame dt instead of fixed 0.033; invalid/overflowing forest time steps retain prior state.
[Fourth-batch source comparison and limits](WINDOWS-SPEEDTREE-WIND-MODE-2026-10-13.md) distinguish completed mode separation from still-approximate leaf amplitudes, normalized strength and original per-tree creation/environment propagation. Added actual draw/pivot checks under yaw/scale and adversarial custom matrices, mode toggling, stable fronds/trunks and background frame-clock comparisons. No SDK/reference/server modifications. Random generation, exact leaf/DLL values, collision/GPU adapter migration, guild marks, advanced actors/skills and remaining terrain shading continue in the backlog.
Validation: full desktop build and CTest 60/60 passed (49.73 s); ASan/UBSan forest/background/windows_behavior 3/3 passed (2.38 s). Method audit: 46 modules, no missing methods; packet audit: 395 constants, zero differences. No Windows or Android dynamic parity proof.
### 2026-10-13 Windows player motion parity: emotion request, fishing and digging
Restored player.ActEmotion's alive-target /kiss request and original NEED_TARGET callback, and IsActingEmotion's narrow KISS/FRENCH_KISS motion-index query (not all emotes). RecvFishing now drives the existing once/loop motion queue and fish emoticon, gates STOP/REACT on actual fishing WAIT/REACT, and preserves main-only failure callbacks. Removed the packet-flag stand-in: cancellation and fish messages query current motion data. RecvDigMotion faces an existing target and queues exactly the received count, while missing targets do not suppress digging.
[Source comparisons and precise limits](WINDOWS-PLAYER-MOTION-2026-10-13.md) retain pending dual-emotion approach/TCP locking and fishing water target/blend timing. New asset-backed player_motion uses temporary MSA/race data with original read-only model/wait GR2 to verify transitions, eight kiss queries and fragmented/repeated DIG; it explicitly skips if resources are absent, but ran and passed here. Full build and CTest 61/61 passed (31.98 s); ASan/UBSan windows_behavior + player_motion 2/2 passed (1.53 s). Static method and packet audits remain zero-mismatch; git diff --check passed. No SDK/reference/server changes or Windows/Android visual equivalence proof. Guild marks, advanced skills/dual motions, terrain shading and exact tree generation/leaf values remain outstanding.
### 2026-10-13 Windows dual-emotion parity: scheduling, approach and roles
Replaced server-command local pair pushes with a VID-based dual scheduler: 500ms clock deadline, requested 100-unit endpoint, far approach then mutual facing and job-specific once motions. Preserved MAKELONG high/low assignment (slap sender HIT, receiver HURT). Pending main as either participant blocks manual movement/attack; native move target/direction entry points cannot bypass the lock. Kiss/slap local movement stays locked by current motion. TCP movement packets are deferred instead of discarded and resume after permission; deletion/clear releases state. Server clock callback and existing deterministic test clock cover uint32 rollover.
[Sixth-batch details and remaining differences](WINDOWS-DUAL-EMOTION-2026-10-13.md) explicitly retain root motion/blend/collision and unified TCP scheduling gaps, plus conservative rejection of self/overlapping pairs and safe coincident coordinates. Extended player_motion exercises delay, approach, job/role mapping, input recovery, queued movement, both main roles and removal. No reference/SDK/server modifications or visual equivalence proof.
Validation: full desktop build and CTest 61/61 passed (50.91 s); ASan/UBSan windows_behavior/player_motion 2/2 passed (1.47 s). Active method audit 46 modules and mapped packet audit 395 constants remain zero-mismatch. git diff --check passed; no new reference changes or shared SDK edits.
### 2026-10-13 Windows motion parity: weighted variants and playback speed
Restored BYTE percentage selection for all motion modes, including the original first-entry fallback for underfilled weights. Selected GR2 and MSA metadata now stay together; queued motions select only at activation and LOD uses the selected file. Added explicit C++ speed overloads retained in queued nodes while preserving existing native attack-speed behavior. Network body and mount creation/updates now propagate movspd/100 to WALK/RUN; running speed changes restart the loop. Zero speed stays zero and >1100 clamps to zero, including main input movement.
See [seventh-batch comparison and limits](WINDOWS-MOTION-VARIANTS-SPEED-2026-10-13.md). Asset-backed player_motion tests enumerate all 100 selection values, malformed totals, metadata/clip identity, immediate/queued speeds and live network speed changes. Mount propagation is source-reviewed without a dedicated mount fixture. Platform RNG sequence, skeletal blending, blend-overlap timing, root motion, special NPC/polymorph speed rules and full TCP scheduling remain pending. No SDK/reference/server changes.
Validation: full desktop build succeeded; CTest 61/61 passed (49.58 s); ASan/UBSan player_motion/windows_behavior/attack_combo 3/3 passed (3.62 s). No Windows/Android dynamic or visual equivalence proof.
### 2026-10-13 Windows attack speed: zero, overflow and binding time
Network creation/RefreshState/updates and mount creation/updates now clamp raw attack speed >1100 to zero and normalize by 100, preserving zero instead of replacing it with normal speed. Actor speed storage accepts finite nonnegative values; bound attacks retain their current ratio until a new attack binds, matching the original setter and elapsed-time calculation. Regressions cover raw boundaries including UINT32_MAX, mount storage, zero-speed attack freeze, next-attack recovery and unchanged current-attack speed.
See [eighth-batch comparison](WINDOWS-ATTACK-SPEED-2026-10-13.md). The AVA2 reference disables ENABLE_FAST_MOB_MOVE_SPEED; its guarded NPC caps are not missing active features. Outstanding: overflow detection queue, polymorph type/mode and 1.1-second scaling, bone blending, root motion and full TCP scheduling. No reference/SDK/server changes or runtime visual parity claim.
The full suite exposed intermittent inventory_touch shutdown failure after its completion marker. macOS crash frames identify preview-manager static destruction releasing an image after the resource cache died. Added CRenderTargetManager::Destroy and call it during PythonRuntime teardown before image pools/resources, following Windows PythonApplication::Destroy. Added weak ownership/index lifecycle regression; retained initial failure logs.
Final full build succeeded; CTest 61/61 passed (42.78 s). Instrumented four-test regression passed (10.88 s), inventory_touch repeated three times passed (21.60 s), and the preview-image use-after-free disappeared. Recoverable UBSan diagnostics remain in unmodified Singleton offset calculation, unaligned reads and font color conversion; process success does not establish sanitizer-clean code. Detailed logs retain these findings for follow-up. Method/packet audits: 46 modules with no missing methods, 395 mapped constants with no mismatch. git diff --check passed; SDK/reference unchanged.
### 2026-10-13 Strict UBSan and polymorph motion parity
Removed invented-address singleton offset arithmetic; actual base-subobject registration plus compiler casts preserves multiple inheritance. Font RGB now retains valid Win32 truncation and uses explicit ARGB packing, with documented finite/clamped input boundaries. Packed sockets use memcpy in inventory/warehouse/switchbot paths; packed attribute values are materialized before pair reference forwarding. Regression tests cover nonzero singleton base offsets and exact font colors.
Restored TYPE_POLY or PC race>=8 classification, GENERAL mode, base-variant interception without RNG and duration/1.1 speed scaling; ordinary loops retain random selection and unscaled explicit speed. Network poly shape zero and PC-poly sash rejection follow Windows. Synthetic ordinary-PC motion fixtures now use playable race indices 1/2. See [ninth-batch scope and remaining work](WINDOWS-UBSAN-POLYMORPH-2026-10-13.md).
Strict ASan/UBSan four-test regression with halt_on_error=1 passed (11.89 s), including inventory teardown; detailed output contains no sanitizer diagnostics on those paths. Python C dependency is not equally instrumented. Remaining modules and unreviewed paths are not declared complete; no SDK/reference/server edits or Windows/Android/live-server dynamic parity proof.
Full desktop build and CTest 61/61 passed (50.12 s). Subsequent test-only strengthening checks literal odd-aligned socket bytes and a negative attribute value: native targeted test passed (1.23 s), strict sanitizer targeted test passed (2.05 s). Active method inventory 46 modules/zero missing, packet audit 395 constants/zero mismatches; git diff --check passed.
### 2026-10-13 Windows skill permission and toggle requests
Restored pre-send actor/observer/poly/dress/pickaxe permissions, passive rejection, MSA LoopCancelEnable cancellation, active AVA2 riding slot 107 threshold and source mount-level cases. Added horse-skill mismatch and attack-skill safe-zone callbacks; blocked paths emit no packets or cooldown events. Ordinary active toggles send the skill-slot argument; active standing toggles retain the separate original zero-argument branch before generic permissions. Animal/dress weapon constraints and repeated-armor checks now use requested PART_MAIN instead of poly render shape zero.
See [tenth-batch source comparisons and limitations](WINDOWS-SKILL-PERMISSION-2026-10-13.md). Literal AVA2 CG233 fixtures cover acceptance/refusal and both toggle paths; asset-backed actor tests cover cancel flags and stun priority. Static mount-case audit compares all 100 active cases with zero differences. Strict ASan/UBSan four-test regression with halt_on_error=1 passed (10.23 s). No SDK/reference/server modifications; remaining skill conditions, targets/movement, guild marks, terrain and tree work are not declared complete.
Final full desktop build succeeded and CTest 61/61 passed (49.71 s). Strict sanitizer detailed output has no diagnostics on executed paths. Method audit 46 modules/zero missing, packet audit 395 mapped constants/zero mismatch; git diff --check passed. Python C dependency not equally instrumented; no live-server or device proof.
### 2026-10-13 Windows skill costs, learned level and equipment conditions
Restored bottle scans, fishing-mode restriction, active/default learned-level gate, weapon masks and bow-arrow condition. HP/SP use source point indices 5/7 and Win32 formula truncation; equal resources pass, client does not deduct ahead of server. Preserve source zero-cost refusal/chat, -1 SP sentinel, partial-SP flag, summon exemption and DASH/CHARGE cooldown/resource exceptions. Skill failure/cooldown/arrow callbacks now go to the network game-phase window, verified with distinct player and phase windows.
See [eleventh-batch evidence and limitations](WINDOWS-SKILL-COST-2026-10-13.md). Real SkillDesc/SkillTable inputs cover normal/exception boundaries and literal CG233 requests. Targets, multi-target/moving skills, right-button mode, bone blending/root motion, guild marks, terrain and tree work remain pending; no reference/SDK/server changes or live-server/device parity claim.
Final full build and CTest 61/61 passed (47.53 s); strict ASan/UBSan four-test regression passed (11.84 s) without diagnostics on executed paths. Method inventory 46 modules/zero missing; packet audit 395 mapped constants/zero mismatch; git diff --check passed. Earlier intermediate runs retained in the verification directory; final logs include the window-routing correction.
### 2026-10-13 Windows skill target resolution
Separated UI selection from local skill target: no-target skills send zero; alive/corpse lookup, picked fallback, alliance/self and enemy safe/attack checks now follow the reviewed source branches. Added front auto-search's distance-varying cone and capped-distance/VID ordering, actual fly target binding and horizontal facing. Failed animation binding cannot send packets/cooldown. Restored __UseSkill's second IsUsingSkill lock even when the lower actor predicate allows LoopCancelEnable; asset-backed regression proves that distinction.
See [twelfth-batch scope and limitations](WINDOWS-SKILL-TARGET-2026-10-13.md). Static/fixture tests cover literal target/use packets, native picked state, target deletion/death and roles. Source range reservation/approach, 1000/2000ms selection throttling/UI targeting effects, fan/circle/random fly targets, moving skills and blending remain pending. No SDK/reference/server changes or Windows/Android/live-server visual proof.
Final full build and CTest 61/61 passed (48.43 s); strict four-test ASan/UBSan passed (11.96 s) with no diagnostics on executed paths. Subsequent test-only deletion, capped-sort ties and 2000/2001 distance boundaries passed native (1.29 s) and strict sanitizer (2.26 s). Method inventory 46 modules/zero missing; packet audit 395 mapped constants/zero mismatch; git diff --check passed.
### 2026-10-13 Windows skill range and reserved approach
Added targetRange + point34*100, source >= range reservation and strict arrival with the 10-unit margin, moving-target following and permission/resource rechecks. Restore source huge race2493 correction, enemy ATTR_BLOCK check, zero-range exemption and charge's first target-zero send/cooldown followed by DASH completion. Frame pipeline processes the reservation; locks pause owned movement, manual input/deletion/main changes cancel. Weak actor identity prevents VID reuse inheriting a cast. Auto hunt does not overwrite the reserved approach. Formal skill callback (-1) no longer invokes the app's preview cooldown/effects.
See [thirteenth-batch source comparisons and limits](WINDOWS-SKILL-RANGE-2026-10-13.md). Tests cover 190/189 boundaries, follow/reselect/one-shot, stun/revive, input/lifecycle cancellation, friendly approach, range bonus, blockers and charge bytes. Root motion, exact movement/stop packet timing, full right-button/standing-toggle reservation interactions, target hold/UI lifecycle and multi-target remain pending. No SDK/reference/server changes or Windows/Android/live-server visual proof.
Final full build and CTest 61/61 passed (46.68 s); strict four-test ASan/UBSan passed (8.48 s) without diagnostics on executed paths. Method inventory 46 modules/zero missing; packet audit 395 mapped constants/zero mismatch; git diff --check passed. Python C dependency not equally instrumented. Preview callback guard is compiled/static-checked without app visual proof.
### 2026-10-13 第十四批:技能追加飞行目标
已接通 FAN/CIRCLE 候选选择、距离/VID 排序、MSM 防御球位置与严格 3D 范围、原版随机算法的 8000 锥形补足、CG53→动作绑定→CG233 顺序和现有 Actor 队列。新增报文回归与真实 GR2/MSA 队列消费/主目标恢复测试。异常数量上限保护为明确偏差;精确模型中心、骨骼矩阵/附件生命周期、持续追踪和移动技能仍未完成。详见 [第十四批记录](WINDOWS-SKILL-FLIGHT-2026-10-13.md)。
本批验证:桌面完整构建成功,61/61 CTest(33.73 秒);四项严格 ASan/UBSan(10.85 秒)通过,无执行路径诊断。方法与协议静态审计通过。未提交/推送本轮修改。
### 2026-10-13 第十五批:飞行物目标与生命周期
接通 FLY/服务器索引飞行物的对象追踪、对象消失转最后位置与安全实例身份、严格线段命中、实际飞行距离退出,删除五秒误报命中。恢复 MSF 初始旋转及速度/加速度积分、重力、homing 延迟/半角规则、主目标一次性穿透及受击动作。新增独立飞行回归和真实 GR2/MSA 回调链测试;背景/其他怪物碰撞、视觉附件、shake 和精确包围中心仍未完成。详见 [第十五批记录](WINDOWS-FLYING-LIFECYCLE-2026-10-13.md)。
同批继续恢复 SpreadingFlag 的三次原版随机调用和初始旋转顺序;固定种子验证独立计算轨迹、速度/加速度一致旋转及关闭时随机序列不变。
本批最终验证:完整构建成功,62/62 CTest(57.66 秒);五项严格 ASan/UBSan(14.25 秒)通过,无执行路径诊断。静态方法与协议审计通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 第十六批:飞行物场景碰撞
已接通 BODY/DEFENDING 分类、演员双轨迹检测、发射者身份排除、额外角色穿透去重、回调/碰撞优先级、严格地形高度和当前物体三维 OBB 代理;游戏入口借用当前场景,地图高度使用多区块查询。新增合成 MSM/移动演员回归及真实 GR2 物体代理测试。原版 culling 首候选顺序、静态完整碰撞图元、树木碰撞、骨骼/部件历史仍未完全对齐。详见 [第十六批记录](WINDOWS-FLYING-COLLISION-2026-10-13.md)。
本批最终验证:完整构建成功,62/62 CTest(54.71 秒);五项严格 ASan/UBSan(12.49 秒)通过,无执行路径诊断。方法与协议审计通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 第十七批:飞行附件与受击震动
已接通多 AttachData、独立效果与尾迹、angular rotation、LINE/MULTI/SINE/EXP 偏移、全局矩阵与完整清理,以及 OnShootDamage 的 100ms 图形震动。主体/骨骼/飞行中心使用图形偏移,逻辑坐标和碰撞球不受影响。修正 CG51 图形 Y 符号并验证实际默认处理器报文字节。真实 GR2/MSA 与 MSE/尾迹绘制回归已加入;CRT 精确随机序列、第一帧/粒子时序、近战全部受击流程和 GPU 逐帧画面仍未对齐。详见 [第十七批记录](WINDOWS-FLYING-VISUAL-2026-10-13.md)。
本批最终验证:完整构建成功,62/62 CTest(53.47 秒);五项严格 ASan/UBSan(13.20 秒)通过,无执行路径诊断。方法与协议审计通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 第十八批:飞行尾迹几何与衰减
恢复六顶点四三角形尖角尾迹、相机位置参与的方向基底、逐段深度排序、原色恒定 alpha、宽度衰减、原版 UV、alpha test、小尺寸参数及严格过期边界。扩展固定源公式绘制几何和前批多附件回归。逐段 frustum、继承 GPU 深度状态、首帧绝对时间和相机/浮点动态输出仍未完全对齐。详见 [第十八批记录](WINDOWS-FLYTRACE-2026-10-13.md)。
本批最终验证:完整构建成功,62/62 CTest(51.52 秒);五项严格 ASan/UBSan(12.55 秒)通过,无执行路径诊断。方法与协议审计通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 第十九批:尾迹逐段视锥裁剪
接通 view×projection 六平面、每段中点/最长轴半长球、外侧相切剔除及部分可见保留;标准透视粗球保留原版 FOV 度值直接传 tan 的历史行为。新增边界/相机/透视及历史单位回归,基础几何测试使用明确宽投影。原版全局 frustum 更新时序、非标准投影粗球、浮点逐位和 GPU 深度继承仍待对照。详见 [第十九批记录](WINDOWS-TAIL-FRUSTUM-2026-10-13.md)。
本批最终验证:完整构建成功,62/62 CTest(50.78 秒);五项严格 ASan/UBSan(12.06 秒)通过,无执行路径诊断。Python C 代码未全部同等插桩。46 模块方法和 395 个映射协议常量审计通过,git diff --check 通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 第二十批:视锥更新缓存、非标准投影与 GPU 深度继承
UpdateGame 更新阶段建立缓存,渲染阶段尾迹读取该快照。相机/投影设置不自动刷新缓存,正交及自定义矩阵继续使用最近透视元数据计算原版粗球。接通 Python 正交投影;尾迹继承深度开关/写入并使用 LESS,硬件管线键及软件光栅器同步支持;加法混合不再强制关闭软件深度写入。新增快照/投影/软件回归和真实 GPU 像素回读。Windows 浮点逐位、全局相机切换、SDL 几何备用后端无深度缓冲等边界详见 [第二十批记录](WINDOWS-TAIL-STATE-2026-10-13.md)。
本批最终验证:完整构建成功,62/62 CTest(62.48 秒);六项严格 ASan/UBSan(17.43 秒)通过,包含实际执行的 GPU 回读,无执行路径诊断。Python C 代码未全部同等插桩。方法/协议审计与 git diff --check 通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
### 2026-10-13 移动交互:浮动摇杆、技能手势及场景点击
参考 d2r-mobile 的交互思路,移除闲置固定摇杆,真实落点与绘制中心分离,补齐技能独立多指归属、拖动方向提示、按住遵守冷却重试、最近敌人选择、完整快捷按钮热区及物品拖拽抬高。增加 NPC/入口和掉落物热区、接近交互、失焦取消与实例/物品 generation 防复用。保留原版双击/长按物品面板及报文,新增真实 HUD、库存和目标/技能/NPC 字节测试。详见 [移动交互调整](MOBILE-INTERACTION-2026-10-13.md)。真机多指、精确模型点击体、完整寻路和技能范围预览仍待验证/实现。
本批最终验证:完整构建成功,62/62 CTest(63.67 秒),移动专项 4/4,严格 ASan/UBSan 4/4(19.86 秒),无执行路径诊断。Python C 代码未全部同等插桩。方法/协议审计及 git diff --check 通过。SDK/参考/服务器未修改,尚未提交或推送。
### 2026-10-14 树木:包围裁剪、透明测试、静态网格与资源碰撞
改为实际 min/max 包围及整树冠距离裁剪;默认树干/frond 使用共享静态流和实例 world 矩阵,材质路径模板缓存,叶片仍按相机/摇摆更新。接通原版森林/实例/环境风强生命周期并移除 ×0.05;修复树干 alpha=84 GREATER、软件 alpha reference 0/调制时序/浮点边界。接通 authored 球/圆柱到角色 BODY 与飞行物查询,保留忽略 box 和平移规则,防高速完整跨越;生命周期删除和真实 SPT 加载失败不产生假树。485 个当前真实 SPT 两次全 LOD 快照一致且无截断。详见 [树木修复记录](TREE-RENDERING-2026-10-14.md)。原 DLL 数值、GPU 叶片/风 shader、真机性能和完整球体响应仍待对齐。
验证:62/62 完整 CTest(48.61 秒)、专项 6/6、严格 ASan/UBSan 5/5(4.07 秒)通过,包含实际 GPU 回读;方法/协议与 diff 检查通过。资源审计额外确认 280 个文件在 token 22000 处停止扩展解析,不能将无截断视为元数据完整;客户端已记录诊断,未知扩展继续保留为明确待办。SDK/参考/服务器未修改,尚未提交/推送。
### 2026-10-14 — Game FPS display and movement altitude check
Added an always-visible, non-interactive FPS badge at the safe top centre of the game screen. It counts completed SDL presentations over half-second windows (including pacing/render cost), resets on phase transitions and foreground resume, and remains hidden outside the game. It does not use the existing app.GetRenderFPS stub, which currently returns the requested rate.
Corrected MapObjectManager movement collision to test actor BODY sphere altitude against the 3D mesh OBB instead of an infinitely tall 2D footprint. Added real-model regression checks for solid obstruction, passage above/below geometry and ActorInstance walking above an object. Added rate-limited device logs for attempted movement that produces no displacement, including map, position, next position and terrain block flag.
Verified: desktop and Android builds; 4/4 focused CTests (player_motion, touch_game, flying_target, speedtree_forest); capped desktop 10 FPS measured 10.0 and displayed 10; desktop 30 FPS cap under scene load measured 16.4 and displayed 17; physical PJZ110 Android preview displayed 10 at a 10 FPS cap. Updated APK installed with existing data retained, then restored normal login launch. Evidence: build/verification/fps-movement-2026-10-14/.
Remaining: the user's specific blocked region still needs a live retest after login; this change alone does not prove its cause. Static objects still use mesh OBB proxies rather than original authored .mdatr primitives, which can incorrectly cover openings. The original Python FPS getters and app.SetFPS host integration remain separate parity gaps.
### 2026-10-14 — Reported town gate falsely sealed by mesh OBB
Live device logs pinpointed the continuing movement obstruction to metin2_map_a1 near (66041.5, 71337.5), with terrainBlock=0. The corresponding a1-middledam-01.gr2 instance at (66907.429688, 19664.039063, 72199.484375), yaw 30 degrees, has six authored planes in its companion .mdatr. The former whole-mesh OBB incorrectly seals its doorway.
MapObjectManager now reads validated little-endian AttributeData plane sets, transforms quaternion axes and centres with the same (x,z,-y) basis and object transform as the rendered model, and uses source plane crossing/radius/rectangle tests for movement and flying collision. Movement permits escape from a plane overlap. Broad-phase candidates include authored plane extents. Valid empty attributes suppress dummy collision; missing, truncated or mixed/non-plane files retain the existing OBB fallback.
Verified with the reported real gate and coordinates: the old 2D footprint intersects the doorway; the authored-plane movement test clears it; ActorInstance moves 2000 units through the entire opening; all six wall planes still block approaching spheres and allow escape. Empty/truncated attribute and above/below-OBB regressions pass. Desktop/Android builds and 4/4 focused CTests passed. APK: build/verification/fps-movement-2026-10-14/ava2-gate-fix.apk.
Deployment pending: USB disconnected before this gate-fix APK could install. The phone currently has the earlier FPS/3D-altitude fix. Reconnect and install gate-fix APK, then verify the reported passage on the live device. Remaining parity gaps: authored non-plane .mdatr primitives and height meshes, mesh-proxy camera/2D collision queries, original Python FPS getter values.
### 2026-10-14 — Mac test package and gate-fix device installation
After USB reconnection, installed the gate-fix Android APK successfully with adb install --user 0 -r (application data retained). Live passage/movement retest remains separate; the user reports additional running issues and requested a Mac package first.
Built the current workspace as macOS arm64 RelWithDebInfo and packaged full game resources into dist/AVA2.app, with dist/AVA2-macOS-arm64.tar.gz for transfer. Bundled/relocated all non-system dylibs and applied ad-hoc signatures for local testing. Verified strict deep codesign, all 88,052 asset-manifest hashes, internal bundle links, and inclusion of the reported gate .mdatr. Isolated-data packaged executable checks exited successfully in normal login (45 frames) and game preview (35 frames); opened the normal application for manual login and gameplay testing. Evidence: build/verification/macos-package-2026-10-14/.
Packager now excludes saved-account lib/wa_ac.py and optional no.py auto-login overrides from both manifest and adapted-script layers, preventing host user state from entering the test package; packaging regression passed. This is a local Apple Silicon test build, not a notarized release. Live running/animation correctness is still under investigation.
+92
View File
@@ -0,0 +1,92 @@
# SpeedTreeRT 静态反编译记录
## 本次结果
分析对象为 `../AVA2/1. Client DEV/SpeedTreeRT.dll`,PE32 / x86 Windows DLL,
映像基址 `0x10000000`。PE 时间戳为 2004-01-09;时间戳仅为文件元数据。
SHA-256:`ddba9b9b427d541ebc0bf1221fffc5d56a85d7b8ee0dfe6370a83a133da6967b`。
使用 Ghidra 12.1.4、OpenJDK 21 和在本机编译的 arm64 decompiler:
- 识别并成功导出 1,219 个函数,失败 0 个;包含运行库、模板和异常处理辅助函数,不能视为 1,219 个树木算法。
- 139 个命名导出项:137 个函数、2 个静态数据项;137 个函数均有反编译文件。
- 合并伪代码 41,100 行,静态调用图 2,162 条边。
- 355 个函数包含 Ghidra 警告。导出成功仅表示工具产生了结果,不证明类型、数组大小、控制流或算法已完全恢复。
- 未运行原 DLL,未进行原版输出对照,未修改原 DLL、SDK 实现或客户端运行行为。
生成结果集中在 `build/verification/speedtree-decompile/`:
| 文件 | 内容 |
|---|---|
| `decompiled.c` | 全部函数的合并反编译伪代码 |
| `functions/*.c` | 按原始虚拟地址拆分的函数伪代码 |
| `functions.tsv` | 地址、名称、推断签名、状态及文件路径 |
| `exports.tsv` | 原 DLL 导出项与反编译文件的对应关系 |
| `calls.tsv` | Ghidra 识别的静态调用边;间接调用可能不完整 |
| `disassembly.txt` | LLVM objdump 输出的反汇编 |
| `pe-headers.txt`、`strings.txt` | PE 头、导入/导出表与字符串 |
| `summary.txt`、`validation.json`、`analysis.log` | 导出统计、完整性检查和分析日志 |
| `input-sha256.txt` | DLL、导入库和接口头文件的输入哈希 |
| `ghidra-project/` | 可继续交互分析的 Ghidra 项目 |
## 核心入口
下列地址是虚拟地址;对应文件为 `functions/<地址>.c`。
| 地址 | 函数 | 分析用途 |
|---|---|---|
| `1001ae70` | `CSpeedTreeRT::LoadTree(char const*)` | 文件读取,调用内存版加载器 |
| `1001b110` | `CSpeedTreeRT::LoadTree(unsigned char const*, unsigned int)` | 主加载流程和扩展段分派 |
| `10022950` | 未命名内部函数 | 主文件段解析;检查起始 token 和标识字符串 |
| `10007ae0` | 未命名内部函数 | 从当前游标读取 4 字节并推进游标;在此上下文中用作 token 读取 |
| `10007ad0` | 未命名内部函数 | 从当前游标读取 float 并推进 4 字节 |
| `1001a2b0` | `CSpeedTreeRT::Compute` | 树木计算、几何准备、变换、包围与投影等流程 |
| `100232c0` | 未命名内部函数 | Compute 调用的种子处理逻辑;0、1 和其他值有不同分支 |
| `1001fb10` | `CSpeedTreeRT::GetGeometry` | 按位掩码分派树枝、frond、叶片和 billboard 几何 |
| `1001fc90` | `CSpeedTreeRT::GetBranchGeometry` | 树枝几何输出 |
| `1001fea0` | `CSpeedTreeRT::GetFrondGeometry` | Frond 几何输出 |
| `100200b0` | `CSpeedTreeRT::GetLeafGeometry` | 叶片几何输出 |
| `10020390`、`10020560` | `Get360BillboardGeometry`、`GetSimpleBillboardGeometry` | 远景面片输出 |
| `10020cd0` | `CSpeedTreeRT::GetTextures` | 纹理信息输出 |
| `1001b4a0` | `CSpeedTreeRT::SaveTree` | 序列化流程,可与解析器交叉核对 |
| `1001c230` | `CSpeedTreeRT::ComputeWindEffects` | 风力求值入口 |
| `1001d1c0` | `CSpeedTreeRT::ComputeLodLevel` | LOD 计算入口,内部调用 `10022fc0` |
## 已从静态结果观察到的结构
内存版 LoadTree 先调用 `10022950` 解析主文件段,再分派扩展段。
主段解析器检查 token `1000`,并读取和比较标识字符串;主段以 `1001` 结束。
当前观察到的扩展段入口如下;语义来自已识别函数名称或所在调用上下文,
未命名部分仍需进一步研究和运行对照。
| token | 处理入口 |
|---|---|
| `8000` | `10018380`,未命名内部处理器 |
| `9000` | `ParseLodInfo` (`1001e840`) |
| `10000` | `ParseTextureCoordInfo` (`1001ebb0`) |
| `11000` | `ParseWindInfo` (`1001ea20`) |
| `12000` | `ParseCollisionObjects` (`1001f2d0`) |
| `13000` | `100085b0`,未命名内部处理器 |
| `15000` | `100243c0`,未命名内部处理器 |
| `16000` | `10024760`,未命名内部处理器 |
| `16013` | `10024e30`,未命名内部处理器 |
| `16014` | 读取 float,写入 CSpeedTreeRT 对象偏移 `0x28` |
| `18000` | `ParseShadowProjectionInfo` (`10020ad0`) |
| `19000` | `ParseUserData` (`100211f0`) |
| `20000` | `ParseSupplementalTexCoordInfo` (`10021840`) |
GetGeometry 的分派位为:`1` 树枝、`2` frond、`4` 叶片、`8` billboard;
billboard 分支还检查 `0x10` 和对象状态,选择 simple 或 360 输出。
现有 `sdk/speedtree/src/spt_parser.cpp` 只处理部分标记,并有纹理字符串扫描回退。
本次结果提供了补齐解析和生成流程的入口,但尚未把反编译算法移植到该 SDK。
## 后续跨平台实现的验证边界
伪代码仍使用 Win32 ABI、32 位地址、异常处理和旧 C++ 运行库结构,
包含 `undefined*`、自动生成变量名及可能错误的局部数组尺寸,不能直接作为可编译源码。
应逐段恢复结构和算法,使用明确宽度的数据读取与边界检查,
再通过原 DLL 对同一 SPT、种子、LOD 和时间输入产生的输出做差分验证。
优先顺序:恢复文件格式和字段 → 静态几何对照 → LOD → 叶片/billboard → 风力。
精确的树木生成、对象字段命名、内部函数命名和动态等价验证仍未完成。
+37
View File
@@ -0,0 +1,37 @@
# 树木渲染与碰撞修复 — 2026-10-14
本批在 `b3808d8d` 之后修改客户端,参考本地 AVA2 `SpeedTreeForestDirectX8.cpp`、`SpeedTreeWrapper.cpp`、`SpeedTreeForest.cpp`、`GameLib/MapUtil.cpp / MapOutdoor.cpp` 和 `EterLib/CollisionData.cpp`。SDK、Windows 参考和服务器未修改。
## 修改位置
- `src/eter_render/SpeedTreeRT.h/.cpp`:使用 SDK 实际 min/max(包含 authored 叶卡旋转余量)计算实例包围球中心、半径,支持当前场景 yaw/scale。默认无风模式允许共享静态树干/frond 顶点、法线、索引、UV 与 diffuse;通过实例 world 矩阵定位,叶片仍按相机及摇摆更新。模板只解析一次材质路径,减少每实例每帧的文件检查。树干与叶片/frond 均使用原版 GREATER / alpha=84,不再把树干当作没有透明测试的完全不透明网格。
- `src/eter_render/SpeedTreeForest.h/.cpp`:视锥使用实际包围中心,距离裁剪只剔除整棵树冠都在距离之外的实例;CPU 风力选项用以原点为中心的保守球涵盖加权旋转。森林与实例分别维护风状态,取消未经原版定义的 ×0.05 换算。森林初始强度 0,实例 LoadTree 初始强度 1;不同环境强度更新现有实例,并保持叶片相位连续;相同强度 setter 不重复更新之后新建的实例,保留原版生命周期规则。
- 同文件:新增 SPT 球体及有限圆柱的连续碰撞。使用 source XYZ→当前 engine XZY 和实例平移,按 Wrapper 的规则不额外旋转/缩放碰撞图元;CO_BOX 忽略。球相切使用严格 `<`,圆柱使用 `<=`,保留圆柱高度筛选。移动允许退出重叠,并补充两端在外的完整跨越检测,防止帧间跨过树干;飞行物使用无退出豁免的检测。无 authored 碰撞数据时不虚构树干障碍。
- 同文件:真实资源加载失败不再伪装成程序化树;直接给定 `.spt` 名称时实际加载文件并使用 authored size,而不是按文件名生成无关树。仅没有真实资源声明的预览调用继续支持程序化树;拒绝非有限实例位置/yaw。
- `SpeedTreeRT.cpp` 在模板加载时明确报告未完整解析的 token,保留 SDK 已恢复的元数据和 `metadata_complete=false` 状态,不通过跳过未知字节伪装为完整解析。
- `src/eter_render/MapObjectManager.h/.cpp`:关联森林并用 weak lifetime 防止析构后访问;将树碰撞接到三维移动与飞行物查询。AreaData 的树加载失败不计为成功实例。
- `src/eter_render/ActorInstance.cpp`:实际移动使用 BODY 球扫掠检测树木,缺少 BODY 的模型保留当前半径 30 的备用探针;点地移动最后一步也检测树木。原有建筑/地形及滑动路径继续使用。
- `src/eter_render/EnvironmentData.h`、`src/scripting/python_background.cpp`:接通原版环境默认强度 0.2、森林初始化和环境切换;地图没有环境文件也能取得默认环境强度。
- `src/eter_render/Gr2ModelRenderer.cpp`:软件 alpha test 改为纹理/顶点/材质 alpha 调制之后的 GREATER;reference 0 不再替换为 70;使用差值式插值,避免恒定 alpha=84 因浮点权重和误差变成略大于 84,和现有 GPU 管线统一。
- `tests/speedtree_forest_test.cpp`:网格包围、yaw/scale 世界变换、部分树冠可见、130 实例共享一份树干流、CPU 模式切换、风强及相位连续、新实例与同值 setter、真实名称加载/失败、球/圆柱/忽略 box、高度/相切/高速跨越/退出重叠、角色阻挡、删除/析构后的查询。
- `tests/background_test.cpp`:默认环境风强接通及原有帧步长回归。
- `tests/flying_target_test.cpp`:软件透明阈值等于/大于 84、reference 0、透明片元不写深度、材质 alpha 调制之后再判断。
- `tests/hardware_scene_test.cpp`:实际 GPU 像素回读核对纹理 alpha 84/85/0/1 的颜色与深度遮挡边界。
## 资源与验证
日志位于 `build/verification/tree-rendering-2026-10-14/`。使用 `generation_baseline` 对当前真实资源目录的 485 个 SPT 跑两次快照,包含所有 LOD 的顶点、索引、几何/pivot hash、包围范围、节点数和限制状态;两次几何与包围结果无变化,均无截断。这证明当前恢复实现的可重复性与本资源集的完整生成,不能证明与 Windows DLL 随机序列或树形等价。
额外元数据审计:205 个完全解析,280 个报告未知扩展 token 22000(已有 REVERSE-ENGINEERING 中的待办)。这些文件的已知主数据可生成几何,但 22000 及后续扩展没有恢复;生成无截断不能掩盖这一缺口。详见 `metadata-summary.log` 与 `incomplete-metadata.jsonl`。
共享树干流测试直接核对世界变换后顶点与原展开路径一致,以及 130 个实例复用相同几何指针;不把此结果当作手机 FPS 或耗电测量。
最终验证:完整构建通过;专项 6/6(6.82 秒);完整 CTest 62/62(48.61 秒);严格 ASan/UBSan 5/5(4.07 秒),含实际执行的 GPU alpha 像素回读,无跳过或执行路径诊断。Python C 代码未全部同等插桩。46 模块方法无缺失/占位,395 映射协议常量无不匹配/未匹配,git diff --check 通过。
## 剩余边界
完整树形/随机调用分布、叶片摆幅/绝对首帧时间、原 DLL 输出尚未动态对齐。本批维持原版全几何 LOD 行为,没有启用会改变画面的自动降级。当前共享静态几何能交给原有 SDL_GPU resident/实例管线;专用叶片 GPU placement/风力 shader 尚未接入,叶片仍由 CPU 更新。密集森林真机 FPS、CPU/GPU 时间和耗电仍待测量。
碰撞数据来自资源元数据,requested tree size 对原 DLL 返回图元的内部缩放仍缺少动态证据;本批按 Wrapper 可见的平移规则实现。自定义 yaw/scale 的画面与 source 不旋转/缩放图元规则可能不同,不能宣称这些扩展变换的碰撞完全贴合。完整动态球推开/滑动响应、矿石交互、空间 culling 候选顺序及不在本资源集内的资产仍待对照;缺少 BODY 时的探针是当前移植的备用方案。
以上改动未提交或推送;设备与原版实机画面对照尚未完成。
+34
View File
@@ -0,0 +1,34 @@
# AVA2 Windows 第八批修复:攻击速度边界和生效时机
> 后续:[第九批](WINDOWS-UBSAN-POLYMORPH-2026-10-13.md) 修复了下方记录的已复现 UBSan 告警,并接通变形基础动作倍率。其余未覆盖路径仍需审查。
修复网络攻击速度 0 被替换成 100、超过 1100 未归零,以及坐骑没有接收攻击速度的问题。仅使用 AVA2 Windows 源码作为行为依据。
## 依据和实现
- `UserInterface/InstanceBaseMovement.cpp::SetAttackSpeed` 将原始值大于 1100 的速度设为 0,然后除以 100 传给演员及坐骑。NetworkActorManager 的创建、RefreshState、属性更新和坐骑路径现在采用该规则。
- `GameLib/ActorInstance.cpp::SetAttackSpeed` 保存倍率,包括 0;没有重启动画。当前实现保留有效的非负有限值,拒绝负值和非有限值,避免非法本地调用污染状态。
- `GameLib/ActorInstanceBattle.cpp::GetAttackingElapsedTime` 使用当前动作节点已经绑定的速度;新攻击通过 `InterceptOnceMotion` 获取新的攻速。回归验证当前动作不因攻速更新立即改变,下次攻击采用新值。零速攻击不推进动作时间,不会自动变成正常速度。
- 坐骑初始化和属性更新也保存同一归一化倍率;更新坐骑不需要重新创建实例。
## 有效开关核查
第七批记录中的“NPC 非移动动作限速”需要以编译开关为前提:`Locale_inc.h` 注释了 `ENABLE_FAST_MOB_MOVE_SPEED`,整个参考目录没有其他定义。因此 `ActorInstanceMotion.cpp` 中循环 1.5 倍、插入 1.0 倍的 NPC 限速分支在 AVA2 未启用。本批没有添加这些限制;不再将其列为当前配置缺失功能。
## 验证和边界
player_motion 验证创建及更新的原始速度 0、1、100、175、1100、1101、UINT32_MAX,并验证独立坐骑实例创建/更新的存储倍率。坐骑使用临时 race,没有证明其真实攻击动画视觉效果。attack_combo 使用原版模型和动作验证当前/下次攻击计时、零速冻结及恢复。
## 退出生命周期修复
首次完整测试的 inventory_touch 在完成所有断言后退出崩溃;单独重跑一次通过、再次重跑失败。macOS 崩溃栈定位到进程结束时 CRenderTargetManager 的静态析构,随后 CGraphicImageInstance::Destroy / CRef<CGraphicImage>::Clear / CReferenceObject::Release 访问已释放的图像资源。未修复前的另一轮完整测试虽通过,也不能排除这个生命周期缺陷。
原版 `UserInterface/PythonApplication.cpp::Destroy` 显式调用预览窗口管理器 Destroy。跨平台版本新增同等清理入口,在 PythonRuntime 的窗口和 minimap 清理后、图像池及资源缓存销毁前释放预览窗口,避免静态单例继续持有背景图。player_motion 通过 weak_ptr 和索引回收检查确认退出时释放;inventory_touch 继续使用真实预览 UI 检查退出流程。
验证日志保存在 `build/verification/windows-attack-speed-2026-10-13/`,保留首次失败与修复前复跑记录。没有 Windows 原版进程、Android 设备或真实服务器动态验证。
修复后的 ASan/UBSan 四项回归(player_motion、attack_combo、windows_behavior、inventory_touch)进程均通过,10.88 秒,原先预览图像 heap-use-after-free 不再出现。但 UBSan 为可恢复模式:详细日志仍包含已有 Singleton 虚构地址偏移计算、未对齐读取和 UI 字体颜色越界转换告警,不能将“测试通过”解释成 sanitizer 全无告警。这些未修改路径仍需后续修复;Python C 依赖未全面插桩。
最终完整桌面构建成功,CTest 61/61 通过(42.78 秒);插桩的 inventory_touch 连续三次通过(21.60 秒)。46 个 Python 模块方法清点无缺失,395 个映射协议常量无差异;git diff --check 通过,平级 SDK 和原版参考源码无修改。
仍待恢复:原版攻速异常检测队列(大于 3 倍时记录检测,并不因此限速)、变形演员的类型/模式及 1.1 秒动作归一化、局部骨骼混合、root motion、精确队列时序与完整 TCP 调度。显式 C++ 速度接口仍拒绝非正值,网络零攻速通过普通攻击路径接入。没有修改参考源码、SDK 或服务器。
+40
View File
@@ -0,0 +1,40 @@
# AVA2 Windows 第六批修复:双人情绪调度与移动锁
本批接通 kiss / french_kiss / slap 的双人协调,替换原先双方原地各排一个动作的实现。依据仅为 AVA2 Windows 源码;不修改参考源码、SDK 或服务器。
## 对照与实现
`SpeedTree`、地形与单人动作前序结果见 [逐模块记录](WINDOWS-MODULE-AUDIT-2026-10-13.md)。双人流程依据 `UserInterface/InstanceBaseMotion.cpp::ActDualEmotion`、`InstanceBase.cpp::__ProcessFunctionEmotion / __IsEnableTCPProcess`、`GameLib/ActorInstanceMotion.cpp::isLock` 和 `PythonPlayerInput.cpp::__CanMove / __CanAttack`。
- 收到服务端双人命令后,通过 NetworkActorManager 建立 VID 配对调度。双方已有移动目的地/行走状态清理,必要时回 WAIT,500 毫秒后处理。
- 目的地在请求时计算:目标当前位置沿“目标→发起者”方向偏移 100。若离目的地超过 100,则先走到那里;较近时直接执行原版位置设置。
- 使用当前图形演员坐标和已有移动速度靠近,过程中更新网络坐标、主角位置及地形高度。目标保持不动,发送者逐帧移动;普通输入不能覆盖这段靠近过程。
- 到达后双方立即相向,清理行走,按对方职业选择一次动作。Windows 的 MAKELONG(first,second) 在处理时 src 使用 HIWORD、dst 使用 LOWORD;因此 slap 发起者为 HIT+目标职业,接收者为 HURT+发起者职业,而不是照原参数顺序播放。
- 正常客户端使用 GetServerMSec 回调作为调度时钟;原有测试时钟可注入,比较按 Win32 32 位回绕处理。纯渲染环境没有 Python 时使用本地单调时钟备用。
- 主角为任一方时,靠近期间阻止键盘/摇杆、鼠标移动和普通攻击,暂停自动狩猎产生新动作;原有移动目标取消。动作开始即结束“处理情绪”的 pending 状态;接吻/slap 动画自身仍按原版运动锁阻止本地移动。
- 原版 TCP 锁是处理限制:锁定期间和接吻期间的移动报文暂存,允许后逐帧恢复处理,不直接丢弃。slap 的 IsActingEmotion 为 false(原版如此),其网络状态可按原规则恢复。
- 删除任一方取消配对并释放存活方,Clear 清理配对与暂存报文。自配对、缺失演员和已有重叠配对拒绝,避免一方被两个调度同时控制。坐标重合时采用发起者朝向的后方作为方向,避免复制原版除零导致的坏坐标。
## 本地回归
扩展 `ava2.player_motion` 的真实 ActorInstance/GR2 时序回归:
- 499ms 不开始,500ms 开始靠近;100 速度从 x=0 分步到 x=400,目标停在 x=500。
- 两个不同职业的 kiss 和 slap 动作编号,以及 90/270 度相互朝向。
- 主角为发起者或接收者时都锁定;直接移动、点地目的地和摇杆不能绕过 pending 锁,动作结束后输入恢复。
- 锁期间收到的 Stop/MOVE 状态会恢复消费;接吻播放期间不会提前抢占。
- uint32 时钟回绕、双方重合、自配对/重叠请求、删除目标或删除发起者的解除锁。
使用临时 MSA、只读原版战士 body/wait GR2;动画资源用于状态机验证,不是实际接吻/拍打图像对照。
## 仍待对齐的边界
本批是专门的双人调度器,不是完整原版 TCP 状态队列:其他动作报文的统一时间排序、网络延迟补偿、与多个重复情绪请求的队列关系仍待恢复。已有配对的重复/重叠请求当前拒绝,原版可能继续排队;这是明确的保护策略差异。
靠近使用现有线性 Actor speed 和高度采样,原版 root motion、渐变旋转/动作混合、碰撞与 skip-collision 恢复时序仍不完全等价。动画开始后的输入锁只补充双人动作范围,没有假称全部 isLock / 可取消技能规则已经恢复。自动狩猎暂停但保留自身控制器状态,未把它冒充原版 CPythonPlayer 的全部保留动作/自动攻击状态。
钓鱼水面目标、移动技能/多目标、完整动画混合/随机动作、公会标记传输、地形阴影/雾/splat、水材质动画、树形生成/叶片数值仍是其他待办。没有 Windows 动态输出或 Android 画面对照。
完整日志在 `build/verification/windows-dual-emotion-2026-10-13/`。
验证结果:完整桌面构建通过,CTest 61/61 通过(50.91 秒),新增/扩展动作回归实际执行而未跳过;ASan/UBSan windows_behavior 与 player_motion 2/2 通过(1.47 秒)。客户端/SDK C++ 插桩,Python C 依赖未同等插桩。46 模块方法名审计零缺失,395 个映射协议常量零差异;git diff --check 通过。未做真实服务器或 Windows/Android 动态对照。
@@ -0,0 +1,35 @@
# AVA2 Windows 第十六批修复:飞行物场景碰撞
对照本地 `FlyingInstance.cpp::FCheckAnotherMonsterDuringFlying / FCheckBackgroundDuringFlying / Update`、`ActorInstanceCollisionDetection.cpp::TestCollisionWithDynamicSphere`、`GameUtil.cpp::DetectCollisionDynamicSphereVSDynamicSphere`、`GameType.h` 和 `CollisionData.cpp::COBBCollisionInstance::OnCollisionDynamicSphere`。只修改跨平台客户端。
## 本批接通
- 解析 MSF HitOnBackground 和 HitOnAnotherMonster;关闭标志时不执行对应碰撞。
- RaceData 分别保留 BODY(1) 与 DEFENDING(3) 球,BODY 不污染技能距离/普通攻击使用的 DEFENDING 半径。Actor 提供变换后的 BODY 球及当前帧移动前的球心,支持演员和飞行物的两段轨迹检测;半径保留原版不随 actor scale 缩放的行为。
- 额外角色检测使用 radius=10 的飞行球与 BODY 球轨迹的最近距离,边界包含等号。与主目标严格 bomb_range 距离分支不同。
- 只排除发射者实例,不按敌我、是否可攻击或是否死亡过滤。主目标穿透后仍可能进入普通角色碰撞分支,保留原版不同集合的语义。
- 碰撞集合按弱实例身份记录,穿透时每个实例只触发一次额外目标回调。相同 VID 的新实例可以重新碰撞。保留原版先选首个碰撞对象、再检查集合的顺序:已经击中过的首个对象可能遮住其他候选。
- 检查顺序为射程耗尽→主目标→额外角色→地形→物体。命中且继续穿透时立即返回本帧,不继续处理其他碰撞。
- 地形只检查移动终点是否严格低于地面,不把高度相等判为撞地。Python/app 入口逐帧借用当前场景,原生地图使用 CPythonBackground 的多区块高度查询;地图销毁后不保留旧指针。
- 地图物体接入现有三维 OBB 代理,使用 radius=1、旧/新端点距离判断;保留原版 OBB 端点检查,不擅自改成整条线段扫掠。高度、yaw 和接触边界生效,避免沿用角色走路的二维圆柱检查。
- FLY 动作事件捕获发射者身份、技能 ID 与额外角色/背景回调。沿用原版 PythonPlayerEventHandler:额外目标回调默认不发送攻击报文,也不触发额外角色 OnShootDamage。
## 验证
flying_target 新增真实 MSM BODY 数据、BODY/DEFENDING 分类、发射者排除、死亡友方角色仍碰撞、双轨迹交叉、BODY 半径等号边界、对象穿透去重与同 VID 新实例、已命中首候选遮蔽规则、主目标/额外角色/地形/射程优先级、地形等高与低于地面、关闭标志及多区块高度回调覆盖。
player_motion 使用真实 GR2 生成 MapObjectManager OBB,验证旧/新端点碰撞、飞越物体顶部、两端在外的原版 OBB 漏扫分支,以及实际背景回调。测试资源仅复制到临时目录,没有新增或改写项目资源。
验证日志位于 `build/verification/windows-flying-collision-2026-10-13/`。
最终桌面完整构建成功,CTest 62/62 通过(54.71 秒);五项严格 ASan/UBSan 通过(12.49 秒,halt_on_error=1),详细执行日志无 sanitizer 诊断。Python C 依赖未同等全面插桩。46 模块方法清点无缺失/占位,395 个映射协议常量无差异,git diff --check 通过。SDK、Windows 参考和服务器未修改,本轮尚未提交或推送。
## 仍未完全对齐
原版 CCullingManager 的空间候选集合和遍历顺序尚未恢复。额外角色目前遍历网络演员、按 VID 稳定排序,可能与原版树的首候选不同;未注册的预览演员不参与。碰撞几何相符不等于原版空间筛选与性能相符。
静态物体使用现有 mesh OBB,不是原版 .mdatr/.atr 的所有 Sphere/Plane/Cylinder/AABB/OBB 碰撞图元。原版 AABB 等图元还有历史代码差异;SpeedTree 独立碰撞球也未接入本路径。本批证明代理路径已工作,不宣称建筑和树木碰撞形状完全相同。
骨骼 BODY 球复用现有 Granny 姿态转换,缺失根骨骼回退、不同部件的 attaching model index 和 shape/装备碰撞实例生命周期仍有差异。移动前球心记录覆盖 Actor.Update 内部运动,网络坐标瞬移与模型/骨骼历史缓存的精确时序尚需继续恢复。平行/极短轨迹的浮点逐位等价未验证。
100ms 受击震动、angular velocity 和多视觉附件、精确包围球中心、移动技能/root motion、选择节流、完整 TCP 时序,以及公会标记、地形/水材质、SpeedTree 数值和旧 GPU/碰撞接入仍待推进。没有 Windows、Android 或真实服务器动态验证。
@@ -0,0 +1,38 @@
# AVA2 Windows 第十五批修复:飞行物目标与生命周期
依据本地 `GameLib/FlyTarget.cpp`、`FlyingInstance.cpp`、`FlyingData.cpp`、`FlyingObjectManager.cpp`、`ActorInstanceMotionEvent.cpp`、`ActorInstanceBattle.cpp::OnShootDamage`、`ActorInstanceMotion.cpp::isLock` 与 `PythonPlayerEventHandler.cpp`。只修改跨平台客户端。
## 本批修复
- FLY 动作事件及服务器 CreateFly 的 normal/auto-fire 路径捕获对象目标,每帧读取其当前位置。对无追踪需求的位置目标保留固定位置。烟花继续使用随机位置。
- 对象删除后转为最后采样的位置,停止 homing 和对象命中回调。弱生命周期标识加实例身份检查,避免删除、同 VID 替换或旧对象仍被其他代码持有时继承飞行物。与原版 NotifyTargetClear 的生命周期行为对应,使用安全身份而不是裸指针注册链。
- 命中改为本帧飞行线段到目标点的平方距离,严格小于 bomb_range²;不再使用默认最小 25 半径,高速穿过目标也可命中。
- 每帧累计实际移动距离并扣减 range,剩余 range<0 时退出,优先于目标命中。超射程不播放爆炸、不触发命中;删除五秒即当作命中的旧分支。
- MSF initial velocity 保留低速/零速;积分顺序为加速度和 gravity 先更新速度,再移动。gravity 使用原版直接加速度和 Z-up→engine height 转换,不再乘 -9.8 或施加到地面 Z。
- 初始 roll/cone 旋转及目标方向旋转同时作用于速度和加速度,修复原版前向加速资源被当作侧向加速的问题。
- homing 仅针对对象目标,保留 homing_start_time 严格边界、原版 SafeRotationNormalizedArc、0.001 方向近似阈值和每次更新的 quaternion 半角限制;不按 dt 插值。超过 180 时直接转向,并同时旋转加速度。
- 解析 pierce_count,主目标命中只回调一次;剩余穿透次数时播放爆炸并继续飞行,否则终止。
- FLY 对象命中接入 OnShootDamage:眩晕角色死亡,否则在原版动作锁、击飞/起身限制之外播放 DAMAGE 并排队 WAIT,保留可取消技能例外。不自行扣除 HP。
- 技能身份由发射时的 motion node 捕获,避免主角切换技能或目标后改变飞行物回调参数。原版主目标命中回调不发送攻击报文,本批也不增加该报文。
- SpreadingFlag 已恢复三次原版随机调用和发射旋转:两次散布角求平均,再绕负 Y 旋转,随后应用初始 roll/cone 与目标方向。速度和加速度共用旋转。组合顺序依据 [Microsoft D3DXQuaternionMultiply 定义](https://learn.microsoft.com/en-us/windows/win32/direct3d9/d3dxquaternionmultiply)核对。
- Indexed 烟花改用已有 eter::frandom;Random.cpp 下移到渲染公共库,所有调用共享原来的同一发生器。
## 测试
新增 flying_target 测试:实际 MSF 新字段、移动目标采样、严格半径、跨帧高速线段命中、超射程优先级与不误报命中、range=0 边界、低速超过五秒仍存活、原版重力轴/单位/积分顺序、初始旋转后的加速度、延迟 homing 与半角/速度保持、无限制 homing、固定位置不 homing、一次性穿透目标回调、对象删除转位置及同 VID 替换安全性。
player_motion 扩展真实 GR2/MSA:DAMAGE→WAIT、锁定与可取消技能、眩晕受击死亡;FLY 事件发射后移动目标,验证实际 FlyingManager 更新命中、受击动作及携带原技能身份的一次性回调。原 render_3d 真实 geompung.msf 命中回归保留。
Spreading 使用固定种子及独立计算的原版轨迹坐标,验证速度与加速度共用旋转、恰好消耗三次随机数,以及关闭时不消耗随机数。
验证日志位于 `build/verification/windows-flying-lifecycle-2026-10-13/`。
最终桌面完整构建成功,CTest 62/62 通过(57.66 秒)。五项严格 ASan/UBSan 通过(14.25 秒,halt_on_error=1),详细日志无 sanitizer 诊断。Python C 依赖未同等全面插桩。46 模块方法清点无缺失/占位,395 个映射协议常量无差异,git diff --check 通过。SDK、Windows 参考和服务器未修改,尚未提交或推送。
## 剩余差异
angular velocity 视觉转动、多附件/网格及烟花视觉尚未完整恢复。背景和其他怪物的飞行碰撞、穿透其他怪物/碰撞集合、owner 排除和对应回调尚未接入。本批穿透测试只覆盖原主目标一次性处理。零长度目标方向采用安全零速度分支,不复现原版异常输入路径。
OnShootDamage 的 100ms shake 尚未接入;现有 InterceptMotion 的混合、精确包围球中心和骨骼附件碰撞矩阵仍有差异。GetFlyTargetCenter 仍取现有近似中心,不能据本批证明命中视觉完全一致。对象身份安全检查比原版更保守;native 位置 hitCb 为现有调用兼容接口,区别于原版只对对象调用 IFlyEventHandler。
技能移动/root motion、选择节流/UI 生命周期、完整 TCP 时序,以及公会标记、地形/水材质、SpeedTree 数值及旧 GPU/碰撞接入继续保留在差异清单。无 Windows、Android 或真实服务器动态验证,不宣称整个客户端完全对齐。
+32
View File
@@ -0,0 +1,32 @@
# AVA2 Windows 第十七批修复:飞行附件与受击震动
依据本地 `FlyingData.cpp::LoadScriptFile`、`FlyingInstance.cpp::UpdateAttachInstance / BuildAttachInstance / AdjustDirectionForHoming`、`ActorInstanceBattle.cpp::OnShootDamage / __Shake / ShakeProcess`、`ActorInstance.cpp::INSTANCEBASE_Transform` 和 `PythonPlayerEventHandler.cpp::OnSetFlyTarget`。只修改跨平台客户端。
## 本批修复
- MSF 保留全部 AttachData,而不是只保留最后一个。每个 EFFECT 附件独立创建效果与尾迹,解析 Roll/Distance/Period/Amplitude 和 AngularVelocity;现有 attach 字段保留首附件兼容访问。
- 保留初始 roll/cone、spreading、目标方向和 homing 后的飞行四元数。AngularVelocity 按每帧增量累积附件旋转,不改变飞行速度或加速度。
- LINE 沿飞行姿态,按原版忽略附件旋转;MULTI_LINE 使用 Roll/Distance 的侧向偏移;SINE 使用 amplitude×sin(age×2π/period);EXP 使用 amplitude×exp(-age/period)×age/period。后三类偏移受组合后的附件/飞行旋转影响。
- 效果收到完整全局矩阵,尾迹按各自附件的实际位置更新;飞行物终止或销毁时清理所有拥有的效果及尾迹,不删除无关效果。保留原版 homing 两个分支的四元数组合顺序差异。
- OnShootDamage 未眩晕时开始 100ms 图形震动,即使当前技能锁定也震动;眩晕时走死亡分支,不新增震动。每次 Actor.Update/Transform 采样一次,三个原版轴各使用 sign=rand()%2 与 amount=rand()%10,再转换到 engine X/height/Z。
- 图形偏移进入主体绘制、骨骼世界矩阵和现有飞行目标中心,逻辑坐标保持不变。BODY/DEFENDING 球使用不含震动的矩阵,避免把图形震动变成物理移动。下一帧先清除旧图形偏移,再计算当前偏移;零 dt 也处理震动过期。
- 保留原版严格 `shakeEnd < now`:正好 100ms 时仍采样,101ms 清理。Timer.cpp 下移到公共渲染库,Python 和非 Python 路径共享同一原有计时状态。
- 修正主飞行目标 CG51 的 Y 符号,按原版 OnGetFlyTargetPosition 图形坐标发送负 game Y,与前批 CG53 一致,再加地图基址。
## 回归
player_motion 使用真实 GR2/MSA 验证 100/101ms 边界、固定六次震动随机调用、坐标轴转换、逻辑坐标不变、重复绘制不再采样、锁定技能仍震动和眩晕死亡不新增震动。实际主角 FLY 动作绑定触发默认处理器,断言 CG51 的完整 13 字节及负 Y。
flying_target 使用实际四个 AttachData 和 MSE:解析顺序、四条独立尾迹的绘制顶点、LINE/MULTI/SINE/EXP 偏移及 angular rotation、实际粒子绘制中心、全部拥有的效果释放、无关效果保留、终止尾迹清空。另验证震动不改变 BODY 几何,而图形飞行中心具有偏移。原 render_3d 真实飞行资源回归保留。
日志位于 `build/verification/windows-flying-visual-2026-10-13/`。
最终桌面完整构建成功,CTest 62/62 通过(53.47 秒)。五项严格 ASan/UBSan 通过(13.20 秒,halt_on_error=1),详细执行日志无 sanitizer 诊断;Python C 依赖未同等全面插桩。46 模块方法清点无缺失/占位,395 个映射协议常量无差异,git diff --check 通过。SDK、Windows 参考和服务器未修改,本轮尚未提交或推送。
## 剩余差异
Windows CRT rand 的精确全局序列与各模块调用顺序尚未恢复;本批验证采样数量和范围,不声称随机震动逐位相同。DWORD 极端回绕沿用原版比较规则,没有新加回绕修正。普通近战/特殊攻击的完整 HitGood/HitGreat/HitStone 及其震动触发未在本批重写。
零/非有限 Period 使用零振幅的安全偏移,不复现原版除零。FLY_ATTACH_OBJECT 在原版自身就是未实现项,当前跳过;未知 FlyType 和缺失字段的非法资源行为未逐位恢复。附件第一帧时间戳、粒子发射顺序、尾迹衰减/形状和浮点组合的 Windows 动态输出尚未验证,本批为绘制命令/顶点验证,没有 GPU 截图或视觉逐帧对照。
模型包围球中心仍使用近似值,骨骼附件时序、完整 shape/装备碰撞生命周期、原版 culling 遍历、.mdatr 完整图元及 SpeedTree 独立碰撞仍有差异。移动技能/root motion、选择节流、完整 TCP 时序、公会标记、地形/水材质、SpeedTree 数值与旧 GPU 接入仍待推进。没有 Windows、Android 或真实服务器动态验证。
+32
View File
@@ -0,0 +1,32 @@
# AVA2 Windows 第十八批修复:飞行尾迹几何与衰减
依据本地 `GameLib/FlyTrace.cpp::Create / Destroy / UpdateNewPosition / Render` 和 `EterLib/Camera.cpp::GetView / SetViewMatrix`,结合当前跨平台相机矩阵约定。只修改跨平台客户端。
## 修复
- 尾迹每段恢复六顶点三角带,转换成四个三角形索引,包括头/尾尖角及中间带面;不再用旧四顶点矩形段代替。
- 方向基底按原版:B=旧点−新点,E=相机位置−新点,P=B×E,U=normalize(F×P),R=F×U。相机位置从当前刚性 view 矩阵反解,F 使用当前客户端保存的视线方向。顶点使用原版对应的两组三个端点偏移。
- 同一尾迹的各段按 −dot(E,F) 升序提交。相同深度使用稳定顺序;原版 std::sort 的等键次序未验证。
- diffuse 保持原始 TailColor,包括 alpha;原版当前启用代码并未做 alpha 衰减。非矩形尾迹只按 `1-age/tailLength` 缩小宽度,矩形维持固定宽度,不擅自 clamp 原版有限 rate。
- 恢复六顶点 UV,保留加法混合,并启用 alpha>0 的 alpha test 绘制标记。
- 直接保留有效的小 TailLength/TailSize,不再把小于 0.01/0.1 的参数替换成默认值。过期判断按原版 `sampleTime + tailLength < currentTime`,等号处保留节点。
- 构造/清理状态回到零色、零长度、零尺寸;Clear 清空采样。Create 作为当前 API 的重新初始化仍清空旧记录。重复位置不再被旧“短线段跳过”分支删除,保留原版退化顶点语义。
- 对零/非有限 tailLength、非有限尺寸和缺失相机矩阵不生成无效几何。这属于明确安全保护,不复现原版无效资源产生 NaN 的路径。
## 验证
flying_target 增加基于源公式的固定相机六顶点数值、四三角形数量、恒定 alpha、混合/alpha test 标记、矩形与收缩宽度、严格过期边界、极小有效参数、零长度保护、真正改变段提交顺序的深度测试及清理断言。
前批多附件用新尖角几何中的对称顶点恢复中心,继续验证四种附件偏移、实际 MSE 粒子中心和各自尾迹。本批也运行原 render_3d 的实际资源与尾迹回归。
日志位于 `build/verification/windows-flytrace-2026-10-13/`。
最终桌面完整构建成功,CTest 62/62 通过(51.52 秒);五项严格 ASan/UBSan 通过(12.55 秒,halt_on_error=1),详细执行日志无 sanitizer 诊断。Python C 依赖未同等全面插桩。46 模块方法清点无缺失/占位,395 个映射协议常量无差异,git diff --check 通过。SDK、Windows 参考和服务器未修改,本轮尚未提交或推送。
## 剩余差异
原版逐段 ViewVolumeTest/frustum sphere 裁剪尚未恢复;当前由后续渲染流程裁剪,可能多提交段,宽尾迹边缘的可见性也可能不同。原版尾迹继承当时 ZWRITE 状态并临时用 LESS,当前绘制命令仍沿用不写深度的近似状态;完整 GPU 深度/混合状态和截图对照未验证。
本批相机反解针对当前客户端的刚性 view,非正交/缩放相机矩阵不承诺等价。原版相同深度的非稳定排序、首帧采样绝对时间、粒子发射顺序和浮点逐位输出仍待对照。尾迹重新 Create 时的当前清历史 API 行为区别于原版单纯设置字段,正常实例创建/销毁路径仍使用新实例或已清理实例。
其他尚未完成项包括 CRT 精确随机序列、近战完整受击流程、模型精确包围中心、骨骼/部件碰撞生命周期、原版 culling 遍历、完整 .mdatr 图元及 SpeedTree 独立碰撞、移动技能/root motion、选择节流、TCP 时序、公会标记、地形/水材质及 SpeedTree 数值和旧 GPU 接入。没有 Windows、Android 或真实服务器动态验证。
+157
View File
@@ -0,0 +1,157 @@
# AVA2 Windows 逐模块对照与修复 — 2026-10-13
> 2026-10-14 树木后续:[树木渲染与碰撞](TREE-RENDERING-2026-10-14.md)。实际包围/整树冠距离、共享静态几何、树干/软件透明边界、环境风强和球/圆柱碰撞已接通;旧记录中的 ×0.05 和未接树碰撞状态为历史状态。原 DLL 随机/摆幅、GPU 叶片和真机性能仍待验证。
> 最新状态进展:[第二十批视锥缓存与尾迹深度](WINDOWS-TAIL-STATE-2026-10-13.md)。更新阶段缓存、正交/偏轴粗球元数据及 LESS/继承深度写入已接通,并加入 GPU 像素回读;Windows 浮点逐位与全局相机切换仍待动态对照。以下旧记录保留各批当时状态。
> 最新裁剪进展:[第十九批尾迹逐段视锥裁剪](WINDOWS-TAIL-FRUSTUM-2026-10-13.md)。六平面、线段球和标准透视粗球已接通,并保留原版 FOV 单位混用;全局缓存时序、非标准投影粗球及 GPU 深度继承仍待对照。
> 最新尾迹进展:[第十八批尾迹几何与衰减](WINDOWS-FLYTRACE-2026-10-13.md)。尖角三角带、相机基底、深度排序及原色/宽度规则已恢复;逐段 frustum、GPU 深度继承与首帧绝对时序仍待验证。
> 最新视觉进展:[第十七批飞行附件与受击震动](WINDOWS-FLYING-VISUAL-2026-10-13.md)。多附件、独立尾迹、旋转/偏移和 100ms 震动已接通,CG51 图形 Y 已修正;精确随机序列、粒子时序和 GPU 逐帧对照仍待验证。
> 最新场景碰撞进展:[第十六批飞行物场景碰撞](WINDOWS-FLYING-COLLISION-2026-10-13.md)。BODY 球、额外角色穿透、地形及三维物体代理已接通;原版空间候选顺序、完整静态图元和树木碰撞仍待恢复。下方记录保留各批当时状态。
> 最新飞行生命周期进展:[第十五批目标追踪与生命周期](WINDOWS-FLYING-LIFECYCLE-2026-10-13.md)。对象持续追踪、线段命中、射程退出、homing、主目标穿透与受击动作已接通;背景/其他怪物碰撞、精确中心及视觉附件仍待恢复。
> 最新飞行目标进展:[第十四批追加飞行目标](WINDOWS-SKILL-FLIGHT-2026-10-13.md)。扇形/圆形排序、随机补足和 CG53 顺序已接入;精确包围球中心、骨骼碰撞和移动对象持续追踪仍待对齐。后面的批次记录保留当时状态。
> 最新距离进展:[第十三批技能距离与保留动作](WINDOWS-SKILL-RANGE-2026-10-13.md)。范围外靠近/重检、距离加成、2493 修正、阻挡与蓄力开场已接通;精确 root motion、选择节流和多目标等仍待对齐。
> 最新目标进展:[第十二批技能实际目标](WINDOWS-SKILL-TARGET-2026-10-13.md)。已补存活/尸体/友方/自用、拾取回退、前方自动选择及请求目标绑定;距离保留动作、选择节流和多目标仍待对齐。
> 最新资源进展:[第十一批技能资源与使用条件](WINDOWS-SKILL-COST-2026-10-13.md)。已补等级、武器、瓶子、HP/SP、冲刺例外和游戏阶段窗口回调;多目标/移动技能与其余模块仍待完成。
> 最新技能进展:[第十批技能许可与请求参数](WINDOWS-SKILL-PERMISSION-2026-10-13.md)。已接通变形/状态/骑乘/安全区限制、MSA 可取消技能规则和开关技能请求差异;其余技能条件与多目标/移动技能仍待完成。
> 最新进展:[第九批未定义行为与变形动作](WINDOWS-UBSAN-POLYMORPH-2026-10-13.md)。已复现的单例/颜色/道具未对齐访问已修复;变形识别、基础动作与 1.1 秒规则接通。完整变形状态流程、骨骼混合和其余模块仍需推进。
> 最新速度进展:[第八批攻击速度边界与生效时机](WINDOWS-ATTACK-SPEED-2026-10-13.md)。角色与坐骑接通零速/异常值规则;确认 AVA2 未启用 NPC 动作限速开关。变形倍率、混合与 root motion 仍待对齐。
> 最新动画进展:[第七批动画变体与播放速度](WINDOWS-MOTION-VARIANTS-SPEED-2026-10-13.md)。百分比选择、对应 MSA 数据和网络移动动画速度已修复;Windows 随机序列、骨骼混合、root motion 及特殊角色倍率仍待对齐。
> 最新双人进展:[第六批双人情绪调度、靠近与移动锁](WINDOWS-DUAL-EMOTION-2026-10-13.md)。500ms 调度、100 距离、职业/角色选择与锁已接通;完整 TCP 排序、root motion、混合/碰撞仍待对齐。
> 最新动作进展:[第五批情绪请求、钓鱼与挖矿队列修复](WINDOWS-PLAYER-MOTION-2026-10-13.md)。玩家情绪请求/查询和基本钓鱼、挖矿队列已接通;双人靠近/TCP 锁、钓鱼水面目标与动画混合仍待完成。
> 最新树木进展:[第四批默认 WIND_NONE 与叶片摆动分离](WINDOWS-SPEEDTREE-WIND-MODE-2026-10-13.md)。默认网格变形开关和固定风力帧步长已修复,叶片摆幅/风强传播与 DLL 数值仍待对照。
> 最新地形进展:[第三批地图配置、剔除与水面修复](WINDOWS-TERRAIN-SETTINGS-2026-10-13.md)。HeightScale、TerrainVisible 和本批列出的水格/剔除差异已修复;ViewRadius、阴影/雾/splat 仍待完成。
> 后续进展:[第二批目标特效、StoneDetect 与树木静态光照修复](WINDOWS-TARGET-EFFECTS-2026-10-13.md)。下方首次审计中的目标效果生命周期/StoneDetect 和树木动态光照问题已在第二批修复;其余待办仍保留。
这是首轮行为修复记录,不是“整个客户端已完全等价”的证明。所有 46 个实际编译的 Windows Python 模块完成了方法名清点;本轮深入对照网络、仓库、玩家规则、体力、技能冷却和地形纹理。其余模块只有接口清点或局部核查,下面明确保留后续工作。
## 对照依据与边界
- 行为依据仅为 `upstream/ava2-client` 的 AVA2 Windows 源码、Windows 工程实际编译文件及 `Locale_inc.h` / `ServiceDefs.h` 的有效开关,不使用其他客户端版本代替原版。
- 开始时客户端 HEAD 为 `31c5b3dd`;桌面构建使用平级 `../sdk`(HEAD `62a5f5a`),不把嵌套 SDK 的固定版本混作同一份源码。
- 修正审计脚本的目录:模块已经搬到 `src/scripting`。旧路径扫描会错误地产生“零问题”;现在找不到源码直接报错。
- 28 个脚本桥接文件覆盖 46 个模块,方法名缺失 0,dummy 方法绑定 0;另有 71 个常量返回候选,必须阅读原版后才可判定。这个工具不识别全部带参数解析的空实现,也不证明常量、签名、调用顺序或渲染行为等价。
- 395 个已映射协议常量对照无差异,不代表所有报文的语义都已验证。
- 本轮没有 Windows DLL/原版进程动态输出对照,也没有 Android 设备或真实服务器验证。未修改原版参考源码、平级 SDK 或服务器。
## 已确认并修复的行为差异
| 模块/流程 | Windows 原版与此前差异 | 本轮修复与验证 |
| --- | --- | --- |
| `net` SMS | `SendMobileMessagePacket` 空操作;原版 CG107 有 WORD 长度、25 字节收件人和 NUL 文本 | 固定宽度编码,24 字符截断后终止;一个完整报文占一个发送序列边界;黄金字节与最大长度测试 |
| `net` 67 属性 | 已启用的 CG208/209 接口不发送 | 恢复材料/辅助物及两个有符号短整型位置、关闭单字节包;黄金字节测试 |
| `net` 日历 | 已启用 CG220 开启/关闭/事件接口不发送 | 恢复子头、32 位日期/索引、两个 6 字节时间;保留原版主角可行动条件,零填充未使用字段 |
| `net` CatchKing | 开启窗口和游戏操作为空 | `OpenCatchKing` 只调用 `StartCatchKing`;CG163 操作按子头构造 4/5 字节报文,保持其原版行动条件差异 |
| `safebox` 容量 | 把服务器传来的行数当成页数,乘 45 | 按原版每行 5 格:9 行=45 格,18 行=90 格;普通仓库/商城均修复,覆盖容量末端 |
| `net` 仓库回调 | 丢失错误、开启、金钱及物品刷新回调 | 恢复 `OnSafeBoxError`、`OpenSafeboxWindow`、`OpenMallWindow`、`RefreshSafeboxMoney`;物品变化在一次接收后合并为 `RefreshSafebox` / `RefreshMall`,顺序依原版;覆盖分片和合并报文 |
| `player` 体力 | Start/StopStaminaConsume 仅日志,状态和界面不变 | 保留浮点累计体力、帧更新、DWORD 状态转换与 `RefreshStamina`;停止/重置清理;两次半单位消耗不会分别丢弃小数 |
| `player` 手机 | sms/nosms 修改网络标记但未通知玩家窗口 | 同步 `RefreshMobile`,通过真实命令接收分派验证 |
| `player` PvP/安全区 | 查询恒为 0;实际攻击仅允许怪物/石头 | 恢复决斗、PVP/GVG、PK 模式、队伍、保护模式、阵营、善恶、杀手、观察者、可攻击种类及门模型条件;实际近战/范围攻击复用同一规则;安全区按实际角色位置查询 BANPK |
| `skill` 冷却 | 普通/公会技能用点 19(移动速度)算施法冷却 | 改为原版点 21(施法速度);测试移动速度 1000、施法速度 200 时,20 秒公会技能为 10 秒 |
| `background` 纹理 | TextureChange 无操作,所有纹理固定 world/500 UV | 读取纹理文件的比例/偏移等字段,按原版 1/(16×cellScale) 与地图坐标计算 UV;每个 splat 层使用自己的变换;换纹理清理缓存;验证坐标、偏移符号和错误输入回滚 |
| 审计/树木测试 | 旧测试假定远距离自动广告牌,与 Windows Advance 强制 LOD=1 相反;仅凭原点在相机后断言剔除 | 校正为原版全几何、alpha=84;剔除测试保证完整包围球在相机后;SDK 广告牌能力单独验证 |
源码依据:`UserInterface/PythonNetworkStreamPhaseGame.cpp`、`PythonNetworkStreamPhaseGameItem.cpp`、`PythonNetworkStreamCommand.cpp`、`PythonSafeBox.cpp`、`PythonPlayer.cpp`、`PythonPlayerModule.cpp`、`InstanceBase.cpp`、`InstanceBaseEffect.cpp`、`Packet.h`、`PythonBackgroundModule.cpp`、`PRTerrainLib/TextureSet.cpp`、`GameLib/MapOutdoor.cpp`、`SpeedTreeLib/SpeedTreeWrapper.cpp`。本轮实现位置和测试可由 Git diff 及 `tests/windows_behavior_test.cpp` 复查。
SMS 超过 WORD 可表示长度时拒绝发送,避免复制原版长度溢出。日历开启/关闭中原版未初始化字段统一填零。损坏纹理的非有限数字/越界值拒绝并保留原集合。这些是明确的边界处理差异,正常报文字段保持原格式。
`bSplat`、Begin/End 虽已读取保存,本轮没有恢复按高度生成纹理 alpha;不能因此宣称完整 splat 等价。
## 逐模块清单
每行的方法数来自 Windows 有效方法表,全部方法名在移植侧存在。默认“待逐函数对照”意味着本轮没有完成该模块内部行为审计。名字存在不代表功能完成。
| 模块 | Windows 方法数 | 本轮行为审查/后续工作 | Windows 入口 → 移植入口 |
| --- | ---: | --- | --- |
| `ServerStateChecker` | 5 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/ServerStateCheckerModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `app` | 116 | 修复 UpdateGame 体力更新;帧时序、相机/诊断接口待逐函数对照 | `upstream/ava2-client/UserInterface/PythonApplicationModule.cpp` → `src/scripting/python_app.cpp` |
| `background` | 52 | 修复 TextureChange 与纹理 UV;阴影、雾、splat、目标特效待完成 | `upstream/ava2-client/UserInterface/PythonBackgroundModule.cpp` → `src/scripting/python_background.cpp` |
| `battlepass` | 8 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonBattlePass.cpp` → `src/scripting/python_battlepass.cpp` |
| `chat` | 33 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonChatModule.cpp` → `src/scripting/python_chat.cpp` |
| `chr` | 80 | 核查 PickAll/LookAt 已有实现或原版空操作;脚本骑乘和动作队列待完成 | `upstream/ava2-client/UserInterface/PythonCharacterModule.cpp` → `src/scripting/python_chr.cpp` |
| `chrmgr` | 37 | 动作/效果注册需继续逐项对照;不能按接口存在认定等价 | `upstream/ava2-client/UserInterface/PythonCharacterManagerModule.cpp` → `src/scripting/python_chr.cpp` |
| `cube_renewal` | 5 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonCubeRenewal.cpp` → `src/scripting/python_cube_renewal.cpp` |
| `dbg` | 5 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/ScriptLib/PythonDebugModule.cpp` → `src/scripting/python_dbg.cpp` |
| `drop_item` | 8 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonDropItem.cpp` → `src/scripting/python_drop_item.cpp` |
| `dungeon_info` | 12 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonDungeonInfo.cpp` → `src/scripting/python_dungeon_info.cpp` |
| `effect` | 7 | 注册/播放接口覆盖;目标跟随、特殊事件效果待完成 | `upstream/ava2-client/UserInterface/PythonEffectModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `event` | 29 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonEventManagerMoudle.cpp` → `src/scripting/python_event_manager.cpp` |
| `eventMgr` | 1 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonGameEventManagerModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `exchange` | 23 | 本轮运行现有交易/仓库回归;完整交易状态机待对照 | `upstream/ava2-client/UserInterface/PythonExchangeModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `fly` | 2 | 接口覆盖;飞行目标实时跟踪、多目标/扇形技能待完成 | `upstream/ava2-client/UserInterface/PythonFlyModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `grp` | 54 | 接口覆盖;静态/动态光照、阴影、屏幕震动需专项对照 | `upstream/ava2-client/EterPythonLib/PythonGraphicModule.cpp` → `src/scripting/python_grp.cpp` |
| `grpImage` | 15 | 接口覆盖;采样/混合/裁剪需图像对照 | `upstream/ava2-client/EterPythonLib/PythonGraphicImageModule.cpp` → `src/scripting/python_grp.cpp` |
| `grpText` | 21 | 接口覆盖;字体度量/字形布局需专项对照 | `upstream/ava2-client/EterPythonLib/PythonGraphicTextModule.cpp` → `src/scripting/python_grp.cpp` |
| `grpThing` | 8 | 接口覆盖;模型/骨骼/动画混合需专项对照 | `upstream/ava2-client/EterPythonLib/PythonGraphicThingModule.cpp` → `src/scripting/python_grp.cpp` |
| `guild` | 34 | 数据接口覆盖;标记下载/上传、区域显示待完成 | `upstream/ava2-client/UserInterface/PythonGuild.cpp` → `src/scripting/python_guild.cpp` |
| `ime` | 33 | 接口覆盖;系统输入法与 Python2 字节/光标行为需专项对照 | `upstream/ava2-client/UserInterface/PythonIMEModule.cpp` → `src/scripting/python_ime.cpp` |
| `item` | 48 | 接口覆盖;资源/属性/选择状态仍需逐函数对照 | `upstream/ava2-client/UserInterface/PythonItemModule.cpp` → `src/scripting/python_gameplay_modules.cpp` |
| `managerBankLogs` | 1 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonManagerBank.cpp` → `src/scripting/python_native_modules.cpp` |
| `messenger` | 5 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonMessenger.cpp` → `src/scripting/python_messenger.cpp` |
| `miniMap` | 27 | 接口覆盖;坐标、目标、公会区域显示需专项对照 | `upstream/ava2-client/UserInterface/PythonMiniMapModule.cpp` → `src/scripting/python_minimap.cpp` |
| `net` | 154 | 修复 SMS、67 属性、日历、CatchKing 发送及仓库回调;公会标记链路待完成 | `upstream/ava2-client/UserInterface/PythonNetworkStreamModule.cpp` → `src/scripting/python_net.cpp` |
| `nonplayer` | 24 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonNonPlayerModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `pack` | 2 | 接口覆盖;实际 FoxFS/加密包读写需专项对照 | `upstream/ava2-client/UserInterface/PythonPackModule.cpp` → `src/scripting/python_runtime.cpp` |
| `petskill` | 4 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonSkillPet.cpp` → `src/scripting/python_pet_skill.cpp` |
| `player` | 149 | 修复 PvP/安全区/攻击过滤/体力;情绪与完整技能动作流程待完成 | `upstream/ava2-client/UserInterface/PythonPlayerModule.cpp` → `src/scripting/python_gameplay_modules.cpp` |
| `playerLoad` | 1 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonPlayerSettingsModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `privateShopSearch` | 12 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonPrivateShopSearch.cpp` → `src/scripting/python_shop_search.cpp` |
| `profiler` | 2 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonProfilerModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `quest` | 6 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonQuest.cpp` → `src/scripting/python_quest.cpp` |
| `renderTarget` | 24 | 接口覆盖;离屏生命周期、相机、裁剪需专项对照 | `upstream/ava2-client/UserInterface/CPythonRenderTargetModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `safebox` | 15 | 修复行数解释、容量、商城和 UI 刷新;本轮有行为回归 | `upstream/ava2-client/UserInterface/PythonSafeBox.cpp` → `src/scripting/python_native_modules.cpp` |
| `sash` | 7 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonSash.cpp` → `src/scripting/python_native_modules.cpp` |
| `shop` | 42 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonShop.cpp` → `src/scripting/python_native_modules.cpp` |
| `skill` | 41 | 修复普通/公会技能施法速度索引;完整技能时序待对照 | `upstream/ava2-client/UserInterface/PythonSkill.cpp` → `src/scripting/python_native_modules.cpp` |
| `snd` | 14 | 接口覆盖;声源衰减、重复抑制、地图环境音需专项对照 | `upstream/ava2-client/UserInterface/PythonSoundManagerModule.cpp` → `src/scripting/python_gameplay_modules.cpp` |
| `switchbot` | 9 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonSwitchbot.cpp` → `src/scripting/python_switchbot.cpp` |
| `systemSetting` | 73 | 接口覆盖;配置持久化与画质选项实际生效需专项对照 | `upstream/ava2-client/UserInterface/PythonSystemModule.cpp` → `src/scripting/python_system.cpp` |
| `textTail` | 18 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonTextTailModule.cpp` → `src/scripting/python_native_modules.cpp` |
| `wiki` | 22 | 接口名覆盖;内部状态、参数、回调及资源行为待逐函数对照 | `upstream/ava2-client/UserInterface/PythonWiki.cpp` → `src/scripting/python_wiki.cpp` |
| `wndMgr` | 188 | 接口覆盖;MarkBox_Load 在原版也是空操作;窗口生命周期需专项对照 | `upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp` → `src/scripting/python_wndmgr.cpp` |
## 仍需推进的差异
| 优先级 | 子系统 | 已确认未完成/下一步 | 验收依据 |
| --- | --- | --- | --- |
| P1 | 公会标记 | SetMarkServer/UploadMark/UploadSymbol 仍不执行原版连接与传输;选择阶段缺少 __DownloadMark。先恢复独立标记连接与块缓存,再接 UI | 原版 GuildMarkDownloader/Uploader、MarkManager;使用隔离模拟端验证报文、CRC、缓存更新及失败结果,禁止把返回 0 当成功 |
| P1 | 玩家动作/技能 | 情绪状态、挖掘/钓鱼队列、移动技能、扇形/多目标、精确扫掠碰撞仍需对照 | PythonPlayer、ActorInstanceMotionEvent、InstanceBase;逐事件时序和命中集合回归 |
| P1 | 背景/特效 | 目标效果接口目前只保存 VID/位置,缺少完整绘制/跟随;StoneDetect 命令仍仅日志,SpecialEffect 空操作 | PythonBackground、GameEventManager、网络命令;验证创建/移动/销毁与作用距离 |
| P1 | 地形 | 阴影图/角色阴影、逐 tile splat、按高度 alpha、雾带及 LOD、HeightScale/ViewRadius/TerrainVisible、环境音仍需实现或核查 | MapOutdoorLoad/RenderHTP、TextureSet、TerrainPatch、Area;字段解析加图像/数值对照 |
| P1 | SpeedTree 客户端接入 | 当前端固定全几何与原版一致,但生成几何/随机分布等库差异仍需单独验证;旧 stash 的多碰撞体/GPU 修改尚未适配远端新代码 | 以共享 SDK 的恢复记录为库层依据;先检查新的坐标/顶点布局,再迁移必要接入逻辑,避免覆盖远端修复 |
| P1 | SpeedTree 默认配置 | 原版定义 WRAPPER_USE_NO_WIND + STATIC_LIGHTING + CPU_LEAF_PLACEMENT,却还启用 LeafRockingState;当前移植对网格统一施加风矩阵并启用 draw.lighting | 分离枝干/叶片中心风变形与叶片卡片摆动;静态色/光照单独对照。不能简单清零风强或重新开启远景广告牌,也不能用 SDK 有风能力代替客户端默认配置等价 |
| P2 | Actor 视觉 | 精炼光效、武器轨迹、烟尘、加权随机动作、混合时长、脚本骑乘需逐条核对;飞行弹道当前偏发射时目标位置 | Character/ActorInstance/RaceData/FlyingInstance;模拟目标移动与动作时间线;实体创建存在不等于视觉完整 |
| P2 | 屏幕震动 | 移植事件路径存在空处理;原版 GameEventManager/GrpBase 保存震动结束时间/强度,需检查并恢复其实际渲染消费链 | 不能仅因 Actor 层某段注释就判为原版无效果;先对照调用链,再测试范围与时间 |
| P2 | 其他脚本桥接/UI/资源 | 上表中仍待逐函数对照的模块;重点 IME 字节/光标、字体布局、窗口生命周期、音频衰减、FoxFS、配置选项生效 | 同输入的状态/回调序列、资源结果与截图比较;阶段测试通过不能替代这些专项审计 |
历史清单需要纠正的内容:伤害数字队列已经在开始时 HEAD 中实现;网络演员的 ConfigureMount 已创建骑乘实体,不应继续写“马实体完全没有”;chr.PickAll 有拾取实现;chr.LookAt 的执行代码在 Windows 本身被注释;wndMgr.MarkBox_Load 在 Windows 本身也是空操作。IsOpenPrivateShop 的原版状态写入路径未找到实际调用,不应只凭移植返回 0 就擅自添加新的状态语义。上述核查不证明相关整个模块完全等价。
## 验证结果与复现
- `cmake --build build/dev -j8`:桌面客户端及测试构建通过。
- `ctest --test-dir build/dev --output-on-failure`:60/60 通过(47.77 秒)。
- 新增 `ava2.windows_behavior`:报文字节、接收分片、批处理回调、体力、PvP/攻击、安全区、技能冷却、纹理坐标与换纹理回滚。
- 单独 ASan/UBSan 构建的 `ava2.windows_behavior`:1/1 通过(1.63 秒);SDK/客户端 C++ 插桩,Python C 依赖未做同等插桩。
- `python3 tools/audit_ava2_python_interfaces.py`、`python3 tools/audit_windows_parity.py`、`python3 tools/audit_ava2_packet_constants.py`:分别记录方法覆盖、71 个复核候选、395 个协议常量零差异。
- `git diff --check`:通过。
- `verify_baseline.py` 仍报告 5 个 Python 脚本历史哈希差异:game.py、interfacemodule.py、intrologin.py、serverinfo.py、ui.py。它们已存在于本轮开始的远端 HEAD,本轮未修改这些文件,未篡改基线以使检查变绿。
- 完整日志:`build/verification/windows-module-parity-2026-10-13/full-tests.log` 与 `sanitizer-tests.log`。隔离测试使用临时资源和模拟网络字节,不访问或改动运行服务器。
以上结论仅覆盖静态原版对照及本地回归。下一批先完成公会标记连接/缓存和目标特效生命周期,再推进动作、地形和 SpeedTree 接入;其余模块按上表保持待审状态。
@@ -0,0 +1,33 @@
# AVA2 Windows 第七批修复:动画变体与播放速度
> 后续:[第八批攻速修复](WINDOWS-ATTACK-SPEED-2026-10-13.md) 已接通网络零攻速与异常值规则,并确认 NPC 限速开关在 AVA2 关闭;下方待办是第七批结束时的记录。
本批修复始终播放首个注册动作、变体动画与 MSA 事件数据不一致,以及服务端移动速度没有影响行走动画的问题。依据为本地 AVA2 Windows 源码,没有原版进程动态输出对照。
## 对照与实现
依据 `GameLib/ActorInstanceMotion.cpp::GetRandomMotionKey / __SetMotion / ReservingMotionProcess`、`GameLib/ActorInstance.cpp::SetMoveSpeed / Move / Walk` 和 `UserInterface/InstanceBaseMovement.cpp::SetMoveSpeed`。
- GENERAL 及其他动作模式按注册百分比选择变体,沿用原版 BYTE 权重逐项扣减规则,不重新归一化。权重不足 100 时剩余区间回退首项;超过 100 时尾部区间可能无法被选择。
- 播放所选 GR2,同时绑定该变体的 MSA 数据,事件、循环次数和动作属性不再固定来自首项。LOD 使用同一个已选动画文件。队列在动作实际激活时抽取一次变体。
- C++ 循环、插入和排队接口增加显式速度倍率;排队倍率保留到激活。既有调用保留普通攻击/连击的自动攻速选择。非有限值和非正显式倍率拒绝,不改变当前状态。
- 网络创建/更新角色时,将移动速度除以 100 接入 WALK/RUN 动画倍率。运行中修改速度会重启动作循环;坐骑创建及更新也接入该倍率。
- 移动速度 0 保持为 0,大于 1100 按原版归零;删除原先 0 速度自动替换为 100/250 的行为。主角输入位移使用归一化后的倍率,避免绕过该上限规则。
## 回归与证据
扩展 `tests/player_motion_test.cpp`,使用临时 MSA/race 与只读原版 body/wait/walk/run GR2:
- 注入全部 100 个随机取值,验证 15/25/60 区间、所选文件、MSA 时长及实际 GR2 时长;验证零权重、不足和超额权重。
- 验证立即和排队的 2 倍/0.5 倍播放速度、激活时单次抽样及非法倍率保持状态。
- 验证网络角色 150/200/0/1101 移动速度对应动画计时、运行中重启和零速度停止位移。坐骑接入经过源码核查,本批没有独立坐骑资源回归。
完整桌面构建成功;CTest 61/61 通过(49.58 秒);ASan/UBSan 的 player_motion、windows_behavior、attack_combo 3/3 通过(3.62 秒)。日志在 `build/verification/windows-motion-variants-speed-2026-10-13/`。资源回归本机实际执行通过,没有因资源缺失跳过。
## 仍待对齐
百分比选择区间与原版一致,但当前使用平台 std::rand,不保证 Windows 随机数序列和全局调用顺序一致。显式倍率是 C++ 接口补充,没有新增 Python 参数或完成 chr.BlendLoopMotion 的混合语义。
SDK 当前只提供单个外部动画片段的采样接口;原版多动画控制器权重、局部骨骼 TRS 混合和共享 CPU/GPU 骨骼结果仍需实现。队列混合提前开始时间、root motion、碰撞、精确事件时间及完整 TCP 调度尚未对齐。NPC 非移动动作的速度上限、变形角色倍率与攻击速度归零规则也不在本批范围。
未修改参考源码、服务器或平级 SDK;未提供 Windows/Android 视觉等价证明。其他模块待办见 [逐模块对照记录](WINDOWS-MODULE-AUDIT-2026-10-13.md)。
+496 -2
View File
@@ -1,5 +1,499 @@
{
"scope": "Static Python method-table inventory; excludes hidden no-ops, renderer and packet behavior. Full parity is NOT established.",
"scope": "Static Python method-table inventory in src/scripting. Constant returns are review candidates, not proven defects. Packet/renderer behavior still requires source comparison. Full parity is NOT established.",
"source_count": 28,
"placeholder_count": 0,
"placeholders": []
"placeholders": [],
"constant_return_candidate_count": 70,
"constant_return_candidates": [
{
"file": "src/scripting/python_app.cpp",
"line": 588,
"api": "IsDevStage",
"handler": "app_is_dev_stage",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 591,
"api": "IsTestStage",
"handler": "app_is_test_stage",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 594,
"api": "IsLiveStage",
"handler": "app_is_live_stage",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 642,
"api": "Process",
"handler": "app_process",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 188,
"api": "MovieResetCamera",
"handler": "app_movie_reset_camera",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 685,
"api": "GetLoad",
"handler": "app_get_load",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 691,
"api": "GetFaceCount",
"handler": "app_get_face_count",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 722,
"api": "IsWebPageMode",
"handler": "app_is_web_page_mode",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 730,
"api": "MoveWebPage",
"handler": "app_move_web_page",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 733,
"api": "HideWebPage",
"handler": "app_hide_web_page",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 756,
"api": "IsLiarCursorOn",
"handler": "app_is_liar_cursor_on",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 852,
"api": "SetControlFP",
"handler": "app_set_control_fp",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 883,
"api": "OnLogoUpdate",
"handler": "app_on_logo_update",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 886,
"api": "OnLogoRender",
"handler": "app_on_logo_render",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 894,
"api": "OnLogoClose",
"handler": "app_on_logo_close",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 897,
"api": "FlashApplication",
"handler": "app_flash_application",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 911,
"api": "IsVisible",
"handler": "app_is_visible",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_app.cpp",
"line": 929,
"api": "IsCanOpenRender",
"handler": "app_is_can_open_render",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_background.cpp",
"line": 1024,
"api": "RenderDungeon",
"handler": "background_RenderDungeon",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 338,
"api": "SetMovingSpeed",
"handler": "chrmgrSetMovingSpeed",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 788,
"api": "DismountHorse",
"handler": "chrDismountHorse",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 525,
"api": "RenderCollision",
"handler": "chrRenderCollision",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 777,
"api": "Refresh",
"handler": "chrRefresh",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 1066,
"api": "SetMoveSpeed",
"handler": "chrSetMoveSpeed",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 1067,
"api": "SetAttackSpeed",
"handler": "chrSetAttackSpeed",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 1076,
"api": "WeaponTraceUseAlpha",
"handler": "chrWeaponTraceUseAlpha",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_chr.cpp",
"line": 1075,
"api": "WeaponTraceUseTexture",
"handler": "chrWeaponTraceUseTexture",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4068,
"api": "GetItemBind",
"handler": "player_GetItemBind",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4025,
"api": "StartMouseWalking",
"handler": "player_StartMouseWalking",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 3231,
"api": "EndMouseWalking",
"handler": "player_EndMouseWalking",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 3859,
"api": "ResetCameraRotation",
"handler": "player_ResetCameraRotation",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4077,
"api": "GetItemUnbindTime",
"handler": "player_GetItemUnbindTime",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 3541,
"api": "IsOpenPrivateShop",
"handler": "player_IsOpenPrivateShop",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4081,
"api": "GetItemElementGrade",
"handler": "player_GetItemElementGrade",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4085,
"api": "GetItemElementAttack",
"handler": "player_GetItemElementAttack",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4089,
"api": "GetItemElementType",
"handler": "player_GetItemElementType",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4093,
"api": "GetItemElementValue",
"handler": "player_GetItemElementValue",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 3849,
"api": "Render",
"handler": "player_Render",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4106,
"api": "GetCombatZonePoints",
"handler": "player_GetCombatZonePoints",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4110,
"api": "CanSealItem",
"handler": "player_CanSealItem",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4114,
"api": "GetItemSealDate",
"handler": "player_GetItemSealDate",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_gameplay_modules.cpp",
"line": 4118,
"api": "GetItemUnSealLeftTime",
"handler": "player_GetItemUnSealLeftTime",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 339,
"api": "InitScreenEffect",
"handler": "grpInitScreenEffect",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 338,
"api": "Culling",
"handler": "grpCulling",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 340,
"api": "ClearDepthBuffer",
"handler": "grpClearDepthBuffer",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 345,
"api": "Identity",
"handler": "grpIdentity",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 342,
"api": "PopState",
"handler": "grpPopState",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 341,
"api": "PushState",
"handler": "grpPushState",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 343,
"api": "PushMatrix",
"handler": "grpPushMatrix",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 344,
"api": "PopMatrix",
"handler": "grpPopMatrix",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 361,
"api": "SetColorRenderState",
"handler": "grpSetColorRenderState",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 578,
"api": "SetInterfaceRenderState",
"handler": "grpSetInterfaceRenderState",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 579,
"api": "SetGameRenderState",
"handler": "grpSetGameRenderState",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_grp.cpp",
"line": 608,
"api": "SetOmniLight",
"handler": "grpSetOmniLight",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_ime.cpp",
"line": 70,
"api": "GetCandidateCount",
"handler": "ime_get_candidate_count",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_ime.cpp",
"line": 78,
"api": "GetCandidateSelection",
"handler": "ime_get_candidate_selection",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_ime.cpp",
"line": 86,
"api": "GetReadingError",
"handler": "ime_get_reading_error",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_native_modules.cpp",
"line": 899,
"api": "GetOfflineShopItemTransmutation",
"handler": "shop_GetOfflineShopItemTransmutation",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_native_modules.cpp",
"line": 1301,
"api": "LoadSkillData",
"handler": "skill_LoadSkillData",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 877,
"api": "IsTest",
"handler": "net_IsTest",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 903,
"api": "ToggleGameDebugInfo",
"handler": "net_ToggleGameDebugInfo",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 1008,
"api": "SetOfflinePhase",
"handler": "net_SetOfflinePhase",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 1041,
"api": "DisconnectUploader",
"handler": "net_DisconnectUploader",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 124,
"api": "ElementsSpellClose",
"handler": "net_ElementsSpellClose",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 125,
"api": "ElementsSpellAdd",
"handler": "net_ElementsSpellAdd",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 126,
"api": "ElementsSpellChange",
"handler": "net_ElementsSpellChange",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 127,
"api": "SendCombatZoneRequestActionPacket",
"handler": "net_SendCombatZoneRequestActionPacket",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 128,
"api": "IsRunning",
"handler": "net_CombatZone_IsRunning",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_net.cpp",
"line": 131,
"api": "GetDayActivate",
"handler": "net_CombatZone_GetDayActivate",
"status": "constant-return candidate; compare original behavior before treating as a defect"
},
{
"file": "src/scripting/python_system.cpp",
"line": 867,
"api": "ReserveResource",
"handler": "systemReserveResource",
"status": "constant-return candidate; compare original behavior before treating as a defect"
}
]
}
+2
View File
@@ -1,3 +1,5 @@
> Current status (2026-10-13): [module audit and first behavior repair batch](WINDOWS-MODULE-AUDIT-2026-10-13.md). Earlier sections below are historical snapshots, including placeholder counts and gaps since fixed. They are not the current backlog.
# AVA2 Windows parity audit — 2026-10-05
Full 1:1 behavior is NOT implemented. The original AVA2 C++/Python snapshot is the reference; successful compilation and visible original Python screens do not establish gameplay parity.
+42
View File
@@ -0,0 +1,42 @@
# AVA2 Windows 第五批修复:玩家情绪请求、钓鱼与挖矿动作队列
延续 [逐模块审计](WINDOWS-MODULE-AUDIT-2026-10-13.md),修复移植客户端的真实报文/动作桥接。没有修改 Windows 源码、共享 SDK 或服务器;并非完整高级动作或技能等价的结论。
## 原版依据与修复
| 流程 | Windows 依据 | 本批实现 |
| --- | --- | --- |
| player.ActEmotion | UserInterface/PythonPlayer.cpp::ActEmotion、PythonPlayerInput.cpp::__GetAliveTargetInstancePtr | 参数是 emotion ID,但原版忽略它;当前目标存在且存活时发送 `/kiss <目标名字>`,否则 OnCannotShotError(mainVID,"NEED_TARGET")。不把参数当 VID,不自行播放动作 |
| player.IsActingEmotion | PythonPlayerModule.cpp、InstanceBaseMovement.cpp、GameLib/ActorInstanceBattle.cpp::IsActEmotion | 查询主角当前实际动作;有效开关关闭 Wolfman,只有 KISS/FRENCH_KISS 的四职业变体返回真。拍手、舞蹈、挖矿和 slap 不是此查询的 true 条件 |
| Fishing START | PythonNetworkStreamPhaseGame.cpp::RecvFishing、InstanceBaseMotion.cpp::StartFishing | 朝向为 BYTE dir×5;推入 THROW 一次动作,再推入 WAIT 循环 |
| Fishing STOP/REACT | 同上 | 仅实际处于 FISHING_WAIT/REACT 才生效;STOP 插入 STOP 一次动作后排 WAIT;REACT 使用已有 Emoticon 系统编号 11,再排 REACT 与 FISHING_WAIT |
| Fishing SUCCESS/FAIL | 同上 | 插入 CATCH/FAIL 一次动作并清旧队列,再排普通 WAIT;仅主角失败回调 OnFishingFailure,远端演员不触发本地界面 |
| Fishing 状态及鱼消息 | GameLib/ActorInstanceMotion.cpp::IsFishing、RecvFishing 的 FISH 分支 | 从实际 WAIT/REACT 动作及已绑定 motion data 查询,不把刚收到 START、排队 THROW 或 STOP/CATCH 认作正在等待鱼;移除矛盾的包驱动 m_isFishing 标记,玩家取消和鱼通知均使用真实动作状态 |
| Mining | PythonNetworkStreamPhaseGame.cpp::RecvDigMotionPacket | actor 存在时朝向已有目标,按 BYTE count 排入准确次数的 NAME_DIG;不存在目标仍排动作,不存在 actor 则只消费报文 |
原有服务端单人情绪命令已调用 ActorInstance::ActEmotion 排一次动作,本批没有再造另一套情绪布尔状态。也没有把 IsActingEmotion 塞进 CanAct:原版 CanAct 是死亡/晕眩等健康状态检查,不能擅自让所有拍手/跳舞阻塞同样操作。
## 回归验证
扩展 `windows_behavior_test` 验证:无目标/死目标报错、不发送接吻包,存在存活目标时以目标名发出原版 chat 请求,即使 emotion ID 不同也不把它作为目标。选中目标自身会发送 TARGET 包,测试在选中后清理发送队列再验证 ActEmotion,明确分离两次用户操作。
新增 `ava2.player_motion`:在临时合成 race/MSA 中引用只读的原版战士 GR2 模型及 wait GR2 动画,真正运行 SDK 动画和 ActorInstance 队列,不只是检查一个 bool。覆盖:
- 抛竿→等待→反应→等待,以及收竿/成功/失败→普通等待。
- THROW 时 STOP 按原版被忽略,非钓鱼状态的 REACT 被忽略;方向、未知演员、远端失败回调限制。
- 分片 DIG 报文不会提前排动作,完整接收后恰好三次 DIG,再回 WAIT,并朝向目标。
- 八个接吻动作的情绪查询为真,结束后恢复假;拍手/舞蹈/挖矿/slap 查询为假。
测试缺少原版 GR2 资源时显式 SKIP=77;本轮执行有资源、实际通过,未跳过。合成 MSA 统一引用 wait GR2 是为了验证状态机和时序,不证明实际钓鱼/情绪视觉与 Windows 一致。
## 仍待完成
双人情绪的 100 距离靠近、500ms 排程、双方职业动作选择、互相朝向、TCP 锁与 Start/EndEmotionProcess 尚未恢复完整;现有 ActorInstance::ActDualEmotion 仅排动作,不应宣称等价。移动技能、扇形/多目标和精确命中仍未完成。
钓鱼前方 600 的水面/抛竿特效目标尚未恢复;角色转向本批立即设置 yaw,原版 BlendRotation 的渐变时序及动作 blend/speed/随机选取仍待对照。完整模型/服饰资源、真实动画表现、事件音效、原版 Windows 动态和 Android 画面对照未做。
公会标记传输/缓存、地形阴影/雾/splat/水材质动画、树形生成与叶片摆幅/风强传播仍在其他模块待办中。
## 本轮结果
完整桌面构建通过,CTest 61/61 通过(31.98 秒),新增动作测试实际执行;ASan/UBSan windows_behavior 与 player_motion 2/2 通过(1.53 秒)。客户端/SDK C++ 插桩,Python C 依赖没有同等插桩。方法名审计 46 模块零缺失,395 个映射协议常量零差异;不代表全部行为等价。git diff --check 通过。日志位于 `build/verification/windows-player-motion-2026-10-13/`。
+30
View File
@@ -0,0 +1,30 @@
# AVA2 Windows 第十一批修复:技能资源与使用条件
依据本地 AVA2 `PythonPlayerSkill.cpp::__CheckSkillUsable / __CheckShortLife / __CheckShortMana / __HasItem / __HasEnoughArrow`,以及 PythonSkill 的费用和武器规则。继续沿用上一批的许可顺序,没有修改参考源码、SDK 或服务器。
## 已恢复
- 空瓶 27995、毒瓶 27996 检查扫描普通背包(含装备/腰带)、龙魂背包及五类特殊仓库;不把银行、商城或 switchbot 当成携带物品。
- 普通技能在钓鱼模式下回调 REMOVE_FISHING_ROD。学习等级限制默认开启,ToggleLevelLimit 控制真正的 NOT_YET_LEARN 检查,不再只是独立返回值。
- WEAPON_LIMITATION 使用已登记的物品类型/子类型与 needWeapon 位掩码,无武器为当前 AVA2 的 WEAPON_NONE=11;不匹配回调 NOT_MATCHABLE_WEAPON。需要弓的非骑乘技能复用已有箭/箭袋检查及 EMPTY_ARROW 回调。
- 费用公式按技能当前有效百分比求值,再采用已有 skill.GetSkillNeedSP 的明确 Win32 int32 转换。正常小数截断为整数。非有限公式值按已有桥接规则归零,不复制原版浮点转整数的未定义行为。
- USE_HP 先检查 POINT_HP=5;原版仍继续检查 POINT_SP=7,本批保留这一实际行为。费用恰等于资源允许,客户端不抢先扣除资源,等待服务器更新。
- 非开关技能费用 0 时,保留原版信息聊天及 NOT_ENOUGH_SP 拒绝;费用 -1 跳过普通 SP 数量比较。CAN_USE_IF_NOT_ENOUGH 允许 SP 小于费用但必须大于 0。召唤技能 131 只豁免 mana 检查。
- DASH 状态跳过 HP/SP 检查;CHARGE_ATTACK 在 DASH 下还跳过剩余冷却检查,其他技能仍检查冷却。没有把这些例外推广到其他技能。
- 技能失败、冷却以及箭矢错误通知,改为原版网络 PHASE_WINDOW_GAME 接收,含公会技能;不再依赖 player.SetGameWindow 指向同一对象。新增 C++ 借用窗口查询,没有改变 Python 方法表。
## 本地回归
扩展 windows_behavior 的真实 SkillDesc/SkillTable 输入和 CG233 字节断言:未学习与调试开关、SP 19/20、HP 19/20、HP 技能仍检查 SP、零费用、-1、召唤、CAN_USE_IF_NOT_ENOUGH、无武器掩码/弓不匹配、龙魂/特殊仓库瓶子、钓鱼模式、小数费用 1.9、冲刺/蓄力冷却例外,以及不同玩家窗口/游戏阶段窗口的回调路由。
没有使用真实服务器;骑乘/技能无动作资源等前序测试仍保留。成功发送检查九字节请求;失败检查空队列和原版 reason,并确认没有启动新的冷却回调。
日志在 `build/verification/windows-skill-cost-2026-10-13/`。严格插桩使用 halt_on_error=1;Python C 依赖没有同等全面插桩,不能由这些路径推断整个客户端无未定义行为。
最终完整桌面构建成功,CTest 61/61 通过(47.53 秒),四项严格 ASan/UBSan 通过(11.84 秒),详细输出未出现 sanitizer 告警。46 模块方法清点无缺失、395 个映射协议常量无差异;git diff --check 通过,参考源码及平级 SDK 未修改。
## 仍待对齐
技能目标死亡/距离/尸体/阵营、多目标和自动寻找、移动技能及保留动作,右键模式与渐变朝向、精确事件和动作混合仍需恢复。费用公式各变量的全量数值对照、所有弓/箭袋资源组合和原版进程动态结果也未覆盖。
公会标记传输与缓存、完整 TCP 调度、root motion、完整变形模型切换、地形/水材质、SpeedTree 精确数值和旧碰撞/GPU 接入迁移继续保留在 [逐模块清单](WINDOWS-MODULE-AUDIT-2026-10-13.md)。本批没有宣称整体等价。
+29
View File
@@ -0,0 +1,29 @@
# AVA2 Windows 第十四批修复:技能追加飞行目标
对照本地 `PythonPlayerSkill.cpp::__UseSkill`、`InstanceBaseBattle.cpp::NEW_GetInstanceVectorInFanRange / NEW_GetInstanceVectorInCircleRange / NEW_GetRandomPositionInFanRange`、`ActorInstanceBattle.cpp::IsClickableDistanceDestInstance`、`ActorInstanceFly.cpp`、`PythonNetworkStreamPhaseGame.cpp::SendAddFlyTargetingPacket` 和 `EterBase/Random.cpp`。只修改跨平台客户端。
## 本批实现
- 目标数量按 targetCountFormula 和当前技能效率求值并截断;主目标占一个名额。0/1 不追加,无目标不扩展。
- FAN_RANGE 优先于 CIRCLE_RANGE。扇形围绕主目标方向,半角为 40°−0.02×min(距离,1000),保持原版有符号角区间,不增加跨 ±180° 的绕回。
- 扇形排序距离上限 1000,圆形使用实际平面距离;同距离按原版角色 map 的 VID 顺序。排除主角、主目标、不可攻击和死亡目标。
- MSM DEFENDING 碰撞球保留位置、半径和骨骼附件信息。技能范围用 3D 球心距离,严格 `radius + range > distance`;缺失碰撞球不发明默认圆柱。碰撞球半径沿用原版不随 actor scale 缩放,球心按角色矩阵变换。
- 追加目标不足时,包括没有 FAN/CIRCLE 标志的技能,使用已有 eter::frandom(原版 Park–Miller)在主目标方向 ±10° 生成 8000 长度的位置,取施法者脚下地形高度;使用图形 Y 的符号发送 CG53,随后加地图基址。真实目标也按图形坐标发送。
- 追加飞行目标加入现有 Actor 队列,并在动作绑定及 CG233 使用技能前发包。保留原版绑定失败仍可能已经发出 CG53 的顺序。
- 异常公式(非有限、负数或超过 4096)中止使用,避免原版无界 DWORD 循环产生大量分配和报文。该保护不是原版等价行为;正常资源数量不触发此限制。
## 验证范围
windows_behavior 使用实际 SkillDesc/SkillTable、MSM 和演员对象,断言 CG53/CG233 的字节、排序和目标数量。覆盖 FAN/CIRCLE 优先级、距离 1000 截断和 VID 同值排序、死亡目标、主目标排除、严格碰撞球边界/高度、缺失球、非零施法者位置、随机种子及 8000 锥形坐标、公式截断、0/1 数量、异常数量和绑定失败时序。
player_motion 使用真实 GR2 和 MSA LoopData 播放,验证演员目标和位置目标按队列逐次消费、动作完成恢复原主目标、ClearFlyTarget 清理状态。
最终桌面构建成功,完整 CTest 61/61 通过(33.73 秒);严格 ASan/UBSan 四项通过(10.85 秒,halt_on_error=1),详细执行日志无 sanitizer 诊断。Python C 依赖未同等全面插桩。46 个模块无缺失方法,395 个映射协议常量无差异,git diff --check 通过。SDK、Windows 参考和服务器未修改。日志保存于 `build/verification/windows-skill-flight-2026-10-13/`。
## 仍待对齐
现有 GetFlyTargetCenter 使用半高度近似,尚未恢复原版模型包围球精确中心。骨骼附件复用现有 Granny 姿态转换;原版 composite 骨骼矩阵与 bone translation 的组合、缺失骨骼回退到根骨骼、不同部件模型附件以及形状变化后碰撞实例生命周期尚未动态验证。本批测试验证无骨骼球和既有队列,不证明这些骨骼路径完全等价。
飞行实例在发射时取目标位置,持续追踪移动对象、命中/消失/受击回调及网络对端 CG53/GC 同步完整流程仍有差异。原版随机序列算法已复用,但未证明全客户端随机调用顺序和 Windows 浮点逐位一致。
移动技能、root motion、骨骼混合、选择节流/UI 生命周期、完整 TCP 时序,以及公会标记、地形/水材质、SpeedTree 数值与碰撞/GPU 接入等仍待处理。没有 Windows 动态对照、Android 或真实服务器验证。
@@ -0,0 +1,32 @@
# AVA2 Windows 第十批修复:技能许可与请求参数
> 后续:[第十一批资源条件](WINDOWS-SKILL-COST-2026-10-13.md) 补齐等级/武器/瓶子/HP/SP 等检查,并修正技能回调的接收窗口;下方仍保留第十批结束时的范围记录。
> 补充:[第十二批](WINDOWS-SKILL-TARGET-2026-10-13.md) 确认并恢复玩家入口的第二道 IsUsingSkill 锁;底层 LoopCancelEnable 许可不能单独证明点击可以替换技能。
继续修复角色/技能模块。依据仅为 AVA2 Windows 的 PythonPlayerSkill、InstanceBase 和 ActorInstanceBattle,不修改参考源码、SDK 或服务器。
## 已接通的行为
- 普通技能发送前拒绝缺失主角、观察模式、变形、婚服、镐头以及不能行动的演员;无动作技能和钓鱼/连击特殊技能也经过许可检查,避免只有动画分支才检查死亡/眩晕。
- ActorInstance::CanUseSkill 对全部六个钓鱼动作保留原版例外;当前技能只有 MSA LoopData 的 LoopCancelEnable 非零才能被另一个技能替换。CanAct 仍先检查死亡、眩晕、麻痹、昏厥和睡眠。
- 当前 AVA2 启用 ENABLE_CONQUEROR_LEVEL,骑乘使用槽位 107 的骑术检查:grade>=1 或 level>=20;坐骑还必须为军用等级。新增 mount_rules.h,严格恢复 GetMountLevelByVnum(vnum,false) 的 100 个有效 case,未知编号为 0。原版注释可能与分支结果冲突(例如 20228),采用实际代码结果,不根据注释重新分类。
- 按原版顺序拒绝被动技能,检查 HORSE_SKILL 与骑乘状态,分别回调 NOT_HORSE_SKILL/HAVE_TO_RIDE;ATTACK_SKILL 在地图 BANPK 区域回调 IN_SAFE。拒绝不会发送技能/动作报文或触发新的冷却回调。
- 普通已激活的开关技能关闭请求,目标字段改为当前技能槽位,匹配 __UseSkill;站立型开关技能采用 ClickSkillSlot 的单独分支,目标字段为 0,不套普通许可检查,但正在使用技能时仍拒绝。该差异来自原版代码,而非推断。
- 外观判断使用请求的 PART_MAIN 形状,避免变形图形 shape=0 覆盖原版 InstanceBase 保留的形状状态。SetWeapon 的动物装/婚服限制及 ChangeArmor 的重复形状比较不再依赖该图形值。
## 验证
windows_behavior 使用真正 SkillDesc 空动作列和字节固定的 AVA2 CG233 请求,覆盖无主角、被动、变形、观察模式、婚服、镐头、眩晕、未骑乘、骑术 19/20、低级/军用坐骑、普通/骑乘技能、安全区攻击和两种开关技能关闭路径。检查拒绝时空发送队列及 UI 回调;接受时检查请求所有九字节。没有拿其他版本的报文头替代 AVA2。
player_motion 使用只读原版模型/GR2 与临时 MSA,验证 LoopCancelEnable=0/1、眩晕优先于可取消技能、复活恢复。坐骑等级回归使用临界及原版注释冲突 case;全部 100 case 另经静态映射比较,零差异。骑乘许可回归使用演员标志/网络状态,不证明真实坐骑技能画面。
严格 ASan/UBSan 四项测试(windows_behavior/player_motion/inventory_touch/attack_combo)通过,10.23 秒,启用 halt_on_error=1;详细日志保存在 `build/verification/windows-skill-permission-2026-10-13/`。Python C 依赖未同等全面插桩,没有 Windows/Android/真实服务器动态输出对照。
完整桌面构建成功,CTest 61/61 通过(49.71 秒)。严格插桩详细输出未出现 runtime error 或 AddressSanitizer ERROR。方法审计 46 个模块无缺失、395 个映射协议常量无差异;git diff --check 通过,平级 SDK 与参考源码未修改。
## 仍待恢复
本批不宣称完整技能系统等价。技能 SP/HP/武器/等级等其余可用性条件、目标死亡/距离/阵营/多目标和保留动作、移动技能、渐变朝向/骨骼混合/root motion、右键技能模式、完整 TCP 时间排序仍需逐项对照。私店状态的原版有效写入流程仍未确认,不擅自新增语义。
公会标记传输/缓存、地形 LOD/阴影/雾/splat/水材质、SpeedTree 精确数值及 collision/GPU 接入迁移、完整变形模型切换/还原和攻速异常检测也继续保留在 [逐模块清单](WINDOWS-MODULE-AUDIT-2026-10-13.md)。
+35
View File
@@ -0,0 +1,35 @@
# AVA2 Windows 第十三批修复:技能距离与保留动作
依据本地 AVA2 `PythonPlayerSkill.cpp::__GetSkillTargetRange / __ProcessEnemySkillTargetRange`、`PythonPlayerInput.cpp::__ReserveUseSkill`、`PythonPlayerInputMouse.cpp::MODE_USE_SKILL` 和 `ActorInstanceBattle.cpp::IS_HUGE_RACE`。只修改跨平台客户端。
## 实现
- 实际技能范围为 targetRange + POINT_BOW_DISTANCE(34)×100,采用 Win32 uint32 运算。范围 0 沿用原版不做距离和目标阻挡检查的分支。
- 距离大于或等于范围时保留目标 VID、技能槽及范围,首次不直接向远处目标施放;范围大于 100 时保留范围减 10。到达判定严格小于保留范围,避免正好在边缘反复保留。
- 当前帧接入 ProcessPlayerAttack 前的保留动作处理,目标移动时更新行走目的地;进入范围后恢复目标选择并重新走技能许可、资源和目标检查。通过后只施放一次并清理保留状态。
- 敌方首次施放和保留动作检查对原版唯一 huge race 2493 减 200 距离。友方首次距离判断不减,保留动作判断按原版统一处理,不擅自改变两个位置的差异。
- 范围内敌方位置带 ATTR_BLOCK 时回调 CANNOT_APPROACH。按原版顺序,范围外先保留,再在靠近后的技能重检中检查阻挡。
- 蓄力技能首次范围外请求先发送 CG233(target=0) 并启动冷却;同槽保留不重复发送开场请求。服务器 DASH 状态到来后沿用前批蓄力冷却例外,进入范围时发送实际目标。
- 不能行动、攻击/技能/情绪锁期间停止本控制器拥有的移动并保留任务,许可恢复后继续。目标删除、主角变化和实例替换取消任务;键盘/摇杆、攻击、手动地面目的地及相应鼠标状态清理任务。再次拾取相同保留目标不直接取消。
- 使用弱实例引用防止删除后同 VID 的新演员继承旧技能,这比原版纯 VID 保留更保守。取消仅清理本控制器设置的移动目的地。自动狩猎暂停发出新命令,避免覆盖靠近;这属于现有移动端接入。
- 应用入口不再将正式技能的 quickSlot=-1 通知交给旧演示技能回调,避免其固定冷却覆盖源公式和重复播放预览效果。正槽位演示调用保留;本批仅编译/静态核查该应用入口,没有实机画面对照。
## 回归
扩展 windows_behavior 的实际 SkillDesc/SkillTable、网络演员和 CG61/CG233 字节断言:
- 远处不立即发包,现有 Actor.Update 推进坐标,目的地跟随移动目标。
- 200 范围保留为 190,190 不施放、189 施放;途中切换选中 VID 后恢复原目标,后续帧不重复施放。
- 眩晕停止移动、复活继续;键盘、摇杆和攻击取消;目标删除、同 VID 实例替换、主角切换释放原移动。
- 友方技能靠近、34 点距离加成、目标阻挡及范围 0 例外、2493 距离修正。
- 蓄力开场 VID 0、冷却期间不重复,DASH 后保留动作完成时使用真实 VID。
使用临时地图和无动作技能验证状态/报文,不能据此证明原版 root motion 或视觉路径相同。前序真实 GR2/MSA 回归仍保留。日志在 `build/verification/windows-skill-range-2026-10-13/`。
最终完整桌面构建成功,CTest 61/61 通过(46.68 秒);四项严格 ASan/UBSan 使用 halt_on_error=1 通过(8.48 秒),详细日志没有 sanitizer 告警。46 模块方法清点无缺失、395 个映射协议常量无差异;git diff --check 通过。Python C 依赖未同等全面插桩,SDK/参考/服务器未修改。
## 剩余差异
自动靠近仍使用当前线性 Actor 移动与地形/物体碰撞接口,原版 root motion、路径避障、渐变转向、完整移动技能和移动/停止报文精确时序未对齐。保留动作复用当前技能入口;右键技能模式、站立开关等入口的所有交互还需继续审查。
选择的 1000/2000ms 节流、OnTargeted UI 生命周期、多目标 fan/circle/随机补足飞行目标和统一 TCP 调度仍待完成。公会标记、地形/水材质、SpeedTree 数值与旧碰撞/GPU 接入等也未完成。没有 Windows 动态输出、Android 或真实服务器验证,未修改 SDK/参考/服务器。
+35
View File
@@ -0,0 +1,35 @@
# AVA2 Windows 第十二批修复:技能实际目标
> 后续:[第十三批](WINDOWS-SKILL-RANGE-2026-10-13.md) 已接通距离保留/靠近重检、距离加成、2493 修正和目标阻挡。下方保留第十二批结束时的范围记录。
依据本地 AVA2 `PythonPlayerSkill.cpp::__UseSkill`、`PythonPlayerInput.cpp` 的存活/死亡目标查询及拾取回退、`InstanceBaseBattle.cpp::NEW_GetFrontInstance`。不修改原版参考、SDK 或服务器。
## 本批实现
- 将当前选中 VID 与本次技能的局部目标分开。没有 NEED_TARGET/CAN_CHANGE_DIRECTION/SEARCH_TARGET 的技能发送 VID 0,不能仅因 UI 选中了敌人就携带其 VID。
- 根据 NEED_CORPSE 查询死亡目标,其余查询存活目标;不存在、删除或状态不符的 VID 不再直接用于技能请求。失败回调为 NEED_TARGET 或 ONLY_FOR_CORPSE,自用许可按原版分支回退主角。
- 原目标不可用时采用现有本地拾取 VID,再验证状态。目标变更的 CG61 在技能 CG233 前发送;重复拾取同一非主角 VID 不重复发送,重复拾取自己清除选择。拾取帧的精确图形命中仍沿用现有实现。
- ONLY_FOR_ALLIANCE 拒绝自己(未允许自用时)及可攻击/非玩家目标,使用 CANNOT_USE_SELF、ONLY_FOR_ALLIANCE;允许自用时相应回退主角。非友方分支按原版检查目标 BANPK 和攻击许可,回调 CANNOT_ATTACK_ENEMY_IN_SAFE_AREA/CANNOT_ATTACK。
- SEARCH_TARGET 无可用目标时,恢复前方 2000 范围选择:原版有符号角度、随距离变化的半扇角,以及 min(distance,1000) 排序。等键按 VID 遍历次序,不能改为纯最近距离排序。保留原版分支在搜索后再处理自用许可的顺序。
- 实际选定目标同时绑定飞行目标,包括无动作技能;演员朝向目标的水平位置。渐变旋转和精确骨骼/飞行中心视觉仍未对齐。
- 有动作技能绑定失败立即返回,不发送动作/技能报文或启动冷却。
## 对第十批记录的补充
`ActorInstance::CanUseSkill` 确实根据 LoopCancelEnable 给出底层许可,但 `PythonPlayer::__UseSkill` 在资源检查后还有独立的 IsUsingSkill 拒绝。因此不能由底层可取消推断玩家点击可以替换当前技能。本批接通第二道检查,真实 GR2/MSA 回归验证底层许可为 true 时点击仍不发送。站立型开关技能等早返回分支仍保留其原版规则。
## 验证范围
windows_behavior 使用 SkillDesc/SkillTable 和 literal CG61/CG233,验证失效 VID、存活/尸体切换、自用和友方、自己拒绝、安全区、选中但无目标技能、拾取回退及重复 VID、飞行目标、朝向、前方/后方自动查找和动作绑定失败。测试使用网络演员状态和临时地图,不证明实际技能图像相同。
player_motion 使用只读原版模型/GR2 和注册前写好的多行 MSA 验证第二道技能锁。初次追加 fixture 不符合 loader/缓存顺序,已纠正后重建;失败日志保留,不用于最终验证结论。
日志在 `build/verification/windows-skill-target-2026-10-13/`。严格 ASan/UBSan 使用 halt_on_error=1;Python C 依赖未同等全面插桩。没有 Windows 动态进程、Android 或真实服务器对照。
最终桌面构建成功,完整 CTest 61/61 通过(48.43 秒),四项严格插桩通过(11.96 秒),详细日志没有 sanitizer 告警。随后只加强测试,增加删除对象、超过 1000 的排序键相等与 2000/2001 边界:普通定向回归通过(1.29 秒),严格插桩通过(2.26 秒)。方法审计 46 模块无缺失、395 个映射协议常量无差异;git diff --check 通过,平级 SDK 与参考源码未修改。
## 仍待恢复
远距离的技能保留动作/自动靠近、弓距离加成和大体型距离修正、目标阻挡检查、选择的 1000/2000ms 节流和 OnTargeted UI 生命周期尚未恢复。本批拾取变更沿用现有选择桥,不声称全套 SetTarget 等价。自动搜索已恢复源算法核心,但完整攻击许可、坏坐标及图形拾取仍继承现有桥接的边界。
多目标 fan/circle、随机补足飞行目标、移动技能、方向技能的拾取地面回退、右键保留技能、动画混合/root motion 继续待办。公会标记、地形水面、SpeedTree 精确数值和碰撞/GPU 适配等模块也未完成,见 [总对照记录](WINDOWS-MODULE-AUDIT-2026-10-13.md)。
@@ -0,0 +1,34 @@
# AVA2 Windows 第四批修复:SpeedTree 默认风力模式与帧步长
本批修复客户端接入,未修改平级共享 SDK、Windows 参考源码或服务器。延续 [逐模块审计](WINDOWS-MODULE-AUDIT-2026-10-13.md),不宣称完整树形或原版 DLL 输出等价。
## 确认差异与处理
原版 `SpeedTreeLib/SpeedTreeConfig.h` 定义 WRAPPER_USE_NO_WIND 和 WRAPPER_USE_CPU_LEAF_PLACEMENT;`SpeedTreeWrapper.cpp::LoadTree` 将 Branch/Leaf/FrondWindMethod 设为 WIND_NONE,但仍调用 SetLeafRockingState(true)。枝干/frond 顶点更新和风矩阵上传还受 CPU/GPU_WIND 编译开关限制,而 RenderLeaves 仍做 CPU leaf placement。因此不能把“无风”解释为关闭叶片朝向相机和卡片摆动。
移植此前对每个网格统一应用 SDK 风矩阵,造成原版默认配置下不应有的枝干/frond 变形和叶片中心位移。现在:
- `SpeedTreeModel::BuildDrawCommands` 增加末尾 `cpuWind=false` 参数,默认使用单位风矩阵;不能用空矩阵,因为 SDK 对空矩阵会自动合成风力。
- 单位矩阵只取消网格的加权风力变换,保留 SDK 的叶片支点摆动、相机朝向、法线和世界 yaw/scale 变换;不把风强设为 0。
- `SpeedTreeForest` 默认 CPU deformation 关闭,可通过 SetCpuWindEnabled(true) 显式启用已有 CPU 风力功能。风强参数本身不隐式启用 CPU 变形,符合原版编译模式与风强分别控制的关系。
- 自定义 frameWind 的矩阵也不会绕过默认模式;叶片 phase/strength 保留。显式 CPU 模式才使用这些矩阵。
- 背景 UpdateSystem 从固定 0.033 改为 GetGameFrameDelta,与游戏接受的帧步长一致;仍沿用现有 SetGameFrameDelta 的 0.001–0.25 限制,本批未改变整个游戏计时策略。
- Forest 拒绝负数、非有限或造成累计时间溢出的步长,保持上一帧状态。
共享 SDK 的风力 API、GPU 参考着色器、随机/网格生成能力保持原样。原版客户端强制全几何 LOD、alpha=84 及已修复的静态光照也保持原样。
## 验证覆盖
`tests/speedtree_forest_test.cpp`:默认枝干和 frond 位置/法线随时间不变,叶片仍摆动;显式 CPU 模式能变形,关闭后恢复相同结果;负数/NaN 步长不推进状态。Authored leaf 夹具用世界 yaw=90、scale=2,检查摆动顶点到原支点的距离不变;即使传入大平移风矩阵,默认路径仍等价于单位矩阵,显式 CPU 路径才发生位移。相机朝向、索引、UV、远景全几何与原版静态光照仍有测试。
`tests/background_test.cpp`:将背景森林与独立森林在不同已接受帧步长下的实际绘制位置逐项比较,防止背景再次使用固定 0.033。测试曾发现期望值忽略现有应用 dt clamp,已按游戏实际接受的 dt 修正测试;没有为了测试修改应用计时策略。
## 仍未完成
默认网格风变形开关已对齐,但叶片摆幅、环境 wind strength 的单位与传播到既有/新树的时序,以及原版每棵树的 leaf rocking 状态仍需更精确对照。当前保留原先移植的 windStrength×0.05 和 SDK 的叶片角度/阶段算法,本批没有冒称这些已数值等价。原版 Forest 与 Wrapper 的初始强度不同,MapOutdoor 又在环境切换时设置强度,应对完整创建顺序恢复后再修改归一化。
树形生成/随机调用顺序/原版 DLL 数值、旧 stash 中碰撞与 GPU 接入的适配仍是独立待办。公会标记、高级动作/技能、地形阴影/雾/splat/水材质动画也未被本批解决。没有 Windows 动态输出或 Android 画面对照。
验证日志位于 `build/verification/windows-speedtree-wind-mode-2026-10-13/`。
验证结果:完整桌面构建及 60/60 CTests 通过(49.73 秒);ASan/UBSan 森林、背景与 windows_behavior 3/3 通过(2.38 秒)。46 模块的方法名对照零缺失、395 个映射协议常量零差异;这不证明完整行为等价。`git diff --check` 通过,参考文件未新增变更,共享 SDK 保持干净。
+24
View File
@@ -0,0 +1,24 @@
# AVA2 Windows 第十九批修复:尾迹逐段视锥裁剪
对照本地 `GameLib/FlyTrace.cpp::Render`、`SphereLib/frustum.cpp::BuildViewFrustum / BuildViewFrustum2 / ViewVolumeTest`、`EterLib/GrpScreen.cpp::BuildViewFrustum` 和 `GrpBase.cpp::SetPerspective`。只修改跨平台客户端。
## 本批修改位置
- `src/eter_effect/FlyTrace.cpp`:新增 TraceFrustum。按当前 view×projection 提取并归一化六个 D3D 0..w 深度平面;每段中点为球心,最长坐标轴跨度的一半为半径。尾迹宽度不扩大原版这个球。平面距离 `<= -radius` 判定在外,保留原版外侧相切也剔除的规则,裁剪发生在顶点生成及深度排序前。
- 同文件恢复标准当前透视矩阵的粗裁剪球:反推 near/far/FOV/aspect,按原版 camera eye/view 和 P−Q 计算球心、半径。核对发现原版 SetPerspective 将 FOV 以度存储,但 BuildViewFrustum2 将该值直接传给 tan;本批保留该历史单位混用,不擅自纠正原版可见性。
- 同文件保留退化平面的安全处理;正交、偏轴或非标准投影仅用六平面,不能从这些矩阵唯一恢复原版外部相机元数据。保留 SphereLib 来源和版权说明。
- `tests/flying_target_test.cpp`:新增六面内外、外侧相切/部分相交、宽尾迹不扩大裁剪球、同一尾迹逐段过滤、移动相机矩阵乘法、标准透视 near/far/侧面,以及历史 FOV 单位导致“平面内但粗球外”的用例。旧几何/多附件测试改用明确的宽投影,避免新增裁剪掩盖这些测试原本核对的几何公式。
- `tests/ava2_render_3d_test.cpp`:尾迹基础回归使用明确覆盖其世界坐标的投影矩阵;真实场景仍使用真实相机矩阵,不关闭裁剪。
- `docs/PORT-PLAN.md`、`docs/WINDOWS-MODULE-AUDIT-2026-10-13.md`:更新进展及剩余差异,本文件记录实现和验证边界。
## 验证
使用真实渲染资源的 render_3d 和飞行附件/尾迹的 flying_target 专项通过。完整日志在 `build/verification/windows-tail-frustum-2026-10-13/`。
最终完整构建成功,62/62 CTest(50.78 秒);五项严格 ASan/UBSan(12.06 秒)通过,无执行路径诊断。Python C 代码未全部同等插桩。46 个模块的方法审计无缺失/占位,395 个映射协议常量无不匹配/未匹配;git diff --check 通过。SDK/参考/服务器未修改,本轮尚未提交或推送。
## 尚未完全对齐
当前直接使用提交绘制命令时的相机矩阵,没有复制原版全局 CScreen frustum 缓存更新时序。透视粗球的相机元数据由矩阵反推,原始 FOV 标量与浮点逐位差异仍未动态验证;非标准投影的粗球分支尚未恢复。六平面和历史单位规则的合成回归不能代替 Windows 实机输出。
深度状态继承(原版 ZWRITE/LESS)、首帧绝对采样时间、相同深度排序、精确 CRT 序列及 GPU 截图仍待对照。其余包括完整近战受击、模型精确包围中心、骨骼/部件碰撞、原版 culling 遍历、.mdatr 完整图元、SpeedTree 独立碰撞、移动技能/root motion、选择节流/TCP 时序、公会标记和地形/水/SpeedTree 其余差异。本批没有 Windows、Android 或真实服务器动态验证。
+25
View File
@@ -0,0 +1,25 @@
# AVA2 Windows 第二十批:视锥缓存、非标准投影与尾迹深度状态
对照 `UserInterface/PythonApplication.cpp::UpdateGame`、`EterLib/GrpScreen.cpp::BuildViewFrustum`、`GrpBase.cpp::SetPerspective / SetOrtho2D / SetOrtho3D`、`SphereLib/frustum.cpp::BuildViewFrustum2`、`GameLib/FlyTrace.cpp::Render` 和 `EffectLib/EffectInstance.cpp::Render`。只修改跨平台客户端。
## 修改位置
- `src/eter_render/ViewFrustum.h`:从尾迹内部提取视锥实现,使用独立保存的 FOV/aspect/near/far,而不是从矩阵反推。任何投影均可使用原版粗球公式,并保留 FOV 度值直接传 tan 的历史行为;无效浮点和平面仍安全处理。
- `src/eter_render/Gr2ModelRenderer.h/.cpp`:保存透视参数;接通正交与自定义投影;它们不覆盖最近一次透视元数据。显式 BuildViewFrustum 生成更新阶段快照,修改相机/投影不自动刷新快照。缓存属于场景渲染器,离屏 RenderTarget 不污染游戏快照。提供继承深度状态。
- `src/scripting/python_app.cpp`:UpdateGame 开头按系统 FOV、窗口 aspect、near=100 和背景 far clip 设置透视,再建立缓存,早于背景/角色/飞行更新。
- `src/app/app_loop.cpp`:原生帧更新入口建立缓存,游戏阶段使用同样 near=100 的规则;尾迹绘制传入缓存与继承深度状态。Python UpdateGame 仍在实际调用边界显式更新。尾迹几何使用渲染阶段相机,裁剪读取更新阶段缓存,两者有意分离。
- `src/scripting/python_grp.cpp`:SetOrtho2d / SetOrtho3d 从占位变为实际投影设置,继续保留透视元数据及已有快照。
- `src/eter_effect/FlyTrace.h/.cpp`、`FlyingManager.h/.cpp`:传递缓存和 DepthState。生产路径不重建视锥;无更新阶段的独立测试调用保留推导回退。尾迹继承 ZENABLE/ZWRITE,临时使用 LESS,命令明确捕获状态,不影响后续绘制。原版效果会恢复 ZWRITE,所以不能从前一条粒子命令的 false 推导尾迹状态;普通场景默认为 true。
- `src/eter_render/RenderCommands3D.h`:增加明确的 LESS 比较状态,默认仍为 LESSEQUAL。
- `src/eter_render/HardwareScene.h/.cpp`:管线键与实例合批条件区分 LESS/LESSEQUAL,SDL_GPU 管线按状态选择比较函数。
- `src/eter_render/Gr2ModelRenderer.cpp`:传递比较状态到硬件批次;软件路径使用同样比较,深度写入由 ZENABLE/ZWRITE 决定,不能因 alpha/additive 混合而擅自关闭。
- `tests/flying_target_test.cpp`:验证更新快照跨相机/投影修改保持不变、下次更新刷新、正交/偏轴粗球保留透视参数、正交二维映射、尾迹深度继承、软件相等深度与加法深度写入。
- `tests/hardware_scene_test.cpp`:真实 GPU 像素回读验证 LESS 与 LESSEQUAL、加法混合写入开关及禁用深度测试。原有几何/字体/纹理/实例等回归保留。
## 验证与边界
日志位于 `build/verification/windows-tail-state-2026-10-13/`。本机 GPU 回读用例已执行,没有跳过。独立无上下文调用无法恢复原版外部相机元数据,仍使用回退;游戏路径已传入真实更新快照与保存参数。
最终验证:完整开发构建通过,专项 3/3(6.59 秒),完整 CTest 62/62(62.48 秒),严格 ASan/UBSan 6/6(17.43 秒),包含真实 GPU 测试。执行日志无 sanitizer 诊断;Python C 代码未全部同等插桩。46 模块方法无缺失/占位,395 映射协议常量无不匹配/未匹配,git diff --check 通过。
尚无 Windows 实机输出,因此原版与当前后端的浮点逐位、驱动舍入、相同深度排序和全局相机切换仍未动态证明。SDL 几何备用后端没有原生深度缓冲,严格 GPU 深度行为仅适用于 SDL_GPU 管线及软件深度光栅器。首帧绝对采样/精确 CRT 序列、完整碰撞及其他模块差异仍在后续计划。本批不修改 SDK、Windows 参考或服务器,尚未提交或推送。
+35
View File
@@ -0,0 +1,35 @@
# AVA2 Windows 第二批行为修复:目标特效、StoneDetect 与树木光照
本批延续 [逐模块审计](WINDOWS-MODULE-AUDIT-2026-10-13.md),修改移植客户端,保留原版源码和共享 SDK。只覆盖以下明确差异;公会标记传输、完整动作队列/高级技能、地形阴影和雾、SpeedTree 默认风力等尚未完成。
## 目标报文与效果生命周期
原版依据:`UserInterface/PythonNetworkStreamPhaseGame.cpp` 的 RecvTargetCreatePacketNew/RecvTargetUpdatePacket/RecvTargetDeletePacket,`PythonBackground.cpp` 的 target maps/Reserve Target Effect,以及 `GameLib/MapOutdoor.cpp` 的 SpecialEffect_Create/Delete/Destroy。
- 新目标创建的非 LOCATION 类型,同时注册背景角色目标;坐标更新的类型 5 调用商店效果,其余调用普通目标效果;删除同时清理背景目标,不再仅更新小地图。
- 保持原版 `insert` 的首次角色绑定语义;已有角色目标不会被同 ID 的坐标更新替换。每帧使用真实图形演员位置跟随,演员暂时不存在时跳过,保留原绑定和最后效果位置。
- 普通资源为 `effect/etc/direction/direction_land.mse`;商店资源为 `effect/direction/direction_land2.mse`,目录按原版保留。
- 坐标包是全局地图坐标,先减 MapOutdoor 的 BasePosition,再查询地形高度。特殊效果接口仍接收原版渲染坐标 `(localX,-localMapY,height)`,内部转换为移植 Y-up `(localX,height,localMapY)`。直接 LoadMap 和 Warp 都有回归,避免仅用 PythonBackground 的 warp 基准造成直接加载时坐标错误。
- 高度为 0 时加入延迟创建集合;非零后创建并移除预约。原版普通/商店共用预约集合,预约兑现使用普通资源;本批忠实保留该行为,包括真实零高度暂不创建。
- 活跃实例只更新位置,不每帧重新创建,亦不在同 ID 更新时替换已有资源;实例失效后可重新创建。删除清理普通/商店角色绑定、预约和实例关联;地图加载/销毁清理自身实例,保留其他系统创建的效果。
- 原版 SpecialEffect_Delete 留下旧 ID 关联,失效后 Create 使用 insert 也可能留下旧关联。本批删除时移除旧关联、重新创建时更新实例 ID,避免复用目标 ID 后不能跟随及泄漏;这是明确的生命周期修复。
## StoneDetect
原版依据:`UserInterface/PythonNetworkStreamCommand.cpp`。
恢复 `StoneDetect VID distance angle` 的实际效果:距离 0 为 firecracker/find_out,1/2/3 为 compass/appear_small/middle/large;角度为 `fmod(540-angle,360)`,围绕移植 Y-up 的垂直轴旋转;位置来自当前图形演员。保持原版 BYTE 距离转换;参数数量错误、演员不存在和未知距离不创建效果,额外拒绝非有限角度以防传播坏矩阵。
## SpeedTree 静态光照
原版 `SpeedTreeConfig.h` 选择 WRAPPER_USE_STATIC_LIGHTING,`SpeedTreeForestDirectX8.cpp` 对树木关闭 D3DRS_LIGHTING、开启顶点颜色。移植此前设置 `draw.lighting=true`,会再叠加动态环境光。本批对枝干、叶片和 frond 关闭动态光照,保留 SDK 顶点 diffuse 色和原有 alpha/剔除规则。
这项不证明 SDK 静态颜色值与原版完全一致,也没有修改风力:WRAPPER_USE_NO_WIND 与仍启用的 LeafRockingState 需要分开对照枝干/中心变形和叶片卡片摆动。不能简单将风强全部清零。
## 回归与限制
`tests/windows_behavior_test.cpp` 新增真实接收分派覆盖:分片创建、非零地图基点、角色跟随、重复绑定、坐标更新不能替换角色目标、商店资源、共享预约行为、目标删除、ID 复用、失效实例重建、换图/销毁清理和不删除无关效果;通过生成的粒子绘制顶点验证实际中心位置,并检查 StoneDetect 四种资源与旋转。`tests/speedtree_forest_test.cpp` 增加枝干/叶片/frond 静态光照状态回归。
使用临时合成 MSE/地形及本地报文字节。没有真实服务器、Windows 原版运行输出或 Android 图像对照;图像、特效完整粒子/网格/光源和地形物件高度查询仍受已有引擎实现限制。验证日志位于 `build/verification/windows-target-effects-2026-10-13/`。
验证结果:桌面完整构建通过,完整 CTest 60/60 通过(52.67 秒);补强四种 StoneDetect 资源选择、BYTE 距离回绕及非有限角度测试后,相关 2/2 测试通过(1.75 秒),ASan/UBSan 2/2 通过(3.17 秒)。`git diff --check` 通过,Windows 参考源码没有本轮差异,共享 SDK 工作区保持干净。
@@ -0,0 +1,40 @@
# AVA2 Windows 第三批修复:地图配置、地形剔除与水面
延续 [逐模块审计](WINDOWS-MODULE-AUDIT-2026-10-13.md)。本批修改地形接入,不修改 Windows 参考文件、平级 SDK 或服务器。不是完整地形视觉等价的结论。
## 原版依据与修复
| 对照位置 | 确认差异 | 实现 |
| --- | --- | --- |
| GameLib/MapOutdoorLoad.cpp::LoadSetting、AreaTerrain.cpp | HeightScale 未读取,所有块固定乘 0.5 | 保存地图 HeightScale,传给首次加载和每次 3×3 分块加载;高度/法线/包围盒均由同一缩放后的数据生成 |
| GameLib/MapOutdoorRender.cpp::RenderTerrain | 忽略 TerrainVisible | 地形绘制同时要求地图 TerrainVisible 与运行时 PART_TERRAIN;地图隐藏地形不影响水、物件或地形碰撞/高度查询 |
| MapOutdoor::Clear/LoadSetting、纹理集合 | 新地图遗漏字段时沿用上张图的地图大小/基点/纹理;新高度与隐藏配置也需独立初始化 | 每次加载重置地图信息、高度比例、地图可见性和纹理集合及 UV/绘制缓存;默认可见性恢复 true;分块刷新不清空本图纹理 |
| MapOutdoor::RenderTerrain、TerrainQuadtree | 相机剔除得到零 patch 时又通过备用路径绘制整张地图 | 有有效 view/projection 时尊重零绘制结果;只有未提供相机的开发调用使用整图备用绘制 |
| AreaTerrain.cpp::CalculatePatch | 水面高度固定乘 0.5 后再减 200;坐标沿用带边框高度图起点(减一个 cell) | 水面使用地图 HeightScale,取消固定偏移;水格起点是 block×25600,首格不使用 height.raw 的边框偏移 |
| PRTerrainLib/Terrain.cpp、AreaTerrain.cpp::CalculatePatch | 跳过奇数水格,扩大偶数水格覆盖;高度 -1 的层也被绘制 | 每个有效水格绘制自身两个三角形,保持干燥格/无效层边界;-1 层不计数也不绘制 |
| 地图加载备用分支 | 单独 LoadRaw 路径遗留上一张图的原点/属性状态,且与分块路径不同 | 合法六位块名的备用入口复用同一分块加载器,保证比例、原点、属性清理、后续 streaming 使用一致流程 |
CellScale 保持原版固定 200;原版虽要求 setting.txt 中有 cellscale,但实际读取那行被注释。没有把该字段当作可自由改变的像素尺度。
## 保留边界与未完成项
- 原版完整地图要求 scripttype/viewradius/cellscale/heightscale/mapsize/textureset。本客户端仍容许既有最小测试/开发地图省略字段;省略 HeightScale 时为 0.5。这是现有兼容路径,不宣称原版对缺字段输入亦接受。
- 显式 HeightScale 拒绝非数字尾缀和 NaN/Inf,避免坏坐标传播;原版 atof 对部分损坏文本更宽松。正常数值按 float 保存,未人为限制为正值。
- ViewRadius 用于原版 patch 分配和转换区域,不能简单替代 FarClip。其精确区域、三级 LOD、阴影/雾带、按 tile splat、按高度生成 alpha、环境音仍待恢复。
- 水面本批只修正格覆盖、缩放、起点和无效层。原版按水深生成的顶点 alpha、纹理动画、随机高度变化/混合、材质与颜色仍需对照。没有把更完整的网格当成视觉等价证明。
- 备用地图加载是开发兼容路径;正常服务器传入的地图位置应位于地图内。它不代替原版严格地图验证。
## 回归覆盖
扩展 `tests/background_test.cpp`,使用 4×1 合成地图:
- HeightScale=2 时 raw 200→400;从第 0 块移到第 3 块后 raw 500→1000,活动 Terrain 指针保持一致。
- TerrainVisible=0 时不输出地形,但仍能查询高度和绘制水面;运行时关闭 PART_TERRAIN 也生效;换图省略该项时恢复默认显示。
- 换图清空基点/旧纹理和旧 UV 集合,高度比例恢复 0.5。
- 相机距离剔除掉所有 patch 后不会再输出整图备用绘制。
- 水面 odd row/column 的单格恰为两个三角形;相邻 -1 水层不计数/绘制;raw 水高 1000→2000,没有减 200;第 2 块首个 `(1,1)` 水格位于 `(51400,2000,200)`。
- 备用块加载同样使用配置比例 1.25;非有限 HeightScale 返回失败且地图未就绪。
使用临时资源和本地测试,无真实服务器、Windows 输出对照或 Android 画面对照。完整日志在 `build/verification/windows-terrain-settings-2026-10-13/`。
验证结果:完整桌面构建通过,CTest 60/60 通过(52.49 秒);ASan/UBSan 下 background 与 windows_behavior 2/2 通过(1.51 秒)。`git diff --check` 通过;参考源码没有本轮变更,共享 SDK 工作区保持干净。
@@ -0,0 +1,32 @@
# AVA2 Windows 第九批修复:未定义行为与变形动作
本批继续修复逐模块清单。修复范围为上一批已复现的 UBSan 问题及变形角色的基础动作规则;公会标记、骨骼混合和地形渲染等较大模块仍未完成。
## 消除已复现的未定义行为
- `shared/common/Singleton.h` 保留现有单例接口和来源代码的单实例约束,注册真实基类子对象,访问时由编译器转换到派生类。删除通过地址 1 计算继承偏移的写法。回归采用单例基类不在对象起始位置的多重继承,验证 Instance/instance/InstancePtr、销毁后清空。没有修改原版参考头文件。
- `wndMgr.SetFontColor` 对正常 0..1 RGB 保留 Windows 乘 255 后截断的转换,直接拼接 ARGB,删除 BYTE 数组强转 DWORD 的未对齐读取。超出范围的值夹到 0..1,NaN/Inf 变为 0;这是对原版未定义输入的明确边界处理,不声称与原版异常值结果一致。整数颜色路径不变。
- 严格 UBSan 堆栈定位到仓库道具 `item_data` 的 sockets:压紧 Win32 结构中的 int32 数组被传入 std::copy_n,标准库会按对齐整数读取。改为 memcpy,同样修复普通道具更新和 switchbot 更新路径;报文尺寸、偏移和字节不变。
- 道具属性的压紧 int16 字段先复制为对齐的局部值,再传入 std::pair,避免模板转发引用绑定到奇数地址。
## 变形角色规则
依据 `GameLib/ActorInstance.cpp::IsPoly`、`ActorInstanceMotion.cpp::InterceptMotion / __SetMotion`、`UserInterface/InstanceBase.cpp::RefreshState / SetShape / SetSash`。当前 AVA2 未启用 WOLFMAN,因此普通玩家模型范围为 0..7。
- 网络演员接收原始类型。TYPE_POLY=7,或 TYPE_PC=6 且 race>=8,均识别为变形;普通怪物不会仅因 race 较大而被认作变形。现有本地 SetPolymorph 标记仍被支持。
- 变形强制 GENERAL 动作模式,不沿用手持武器、骑乘或婚服模式。
- 插入动作(一次或循环)固定使用基础变体,不调用百分比随机选择;动画速度乘基础片段时长/1.1,再应用指定倍率。普通 SetLoop、排队和直接播放仍保留各自已有选择行为,不把插入规则扩展到所有动作。
- 网络形状选择对变形演员使用图形 shape=0,并保留请求的 PART_MAIN 元数据;变形玩家拒绝 SetSash,与原版允许 IsPC 和 IsPoly 同时为真的规则一致。
- 单人/双人情绪测试的临时 race 改为合法玩家编号 1/2,避免以前的 777/778 人为触发现在已恢复的变形判断。两职业映射和只读 GR2 状态机验证不变;新增独立怪物 race 验证变形路径。
## 验证与剩余范围
windows_behavior 新增多重继承单例及字体颜色精确值回归;player_motion 新增网络类型、模式、基础变体、随机调用次数、1.1 秒倍率、普通循环不归一化及变形 sash 拒绝回归。
完整桌面构建及 CTest 61/61 通过(50.12 秒)。随后仅加强测试,增加 Win32 固定偏移的非零 sockets 和负属性值校验;普通定向回归通过(1.23 秒),严格插桩回归通过(2.05 秒)。方法清点 46 个模块无缺失、395 个映射协议常量无差异,git diff --check 通过。
采用 `UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1`,windows_behavior/player_motion/inventory_touch/attack_combo 四项严格插桩测试通过(11.89 秒);完整输出没有 runtime error 或 AddressSanitizer ERROR。该结论只限于执行路径,不代表整个客户端没有未定义行为,Python C 依赖没有同等全面插桩。
日志位于 `build/verification/windows-ubsan-polymorph-2026-10-13/`。未修改平级 SDK、服务器或 Windows 参考源码;没有 Windows 动态进程输出、Android 或真实服务器验证。
仍需推进:完整变形模型切换/还原、技能可用规则及外观状态流程;骨骼局部 TRS 混合、root motion、精确动作队列/TCP 调度和多目标碰撞;公会标记连接/传输/缓存;地形 LOD/阴影/雾/splat、水深透明度及水面动画;SpeedTree 精确数值对照和旧 collision/GPU 接入迁移;攻速异常检测队列及尚未深审的 Python 模块行为。以上继续保留在 [逐模块对照](WINDOWS-MODULE-AUDIT-2026-10-13.md),没有将局部测试通过视为整体等价。
+71
View File
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>ava2_client</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>AVA2</string>
<key>CFBundleDisplayName</key>
<string>AVA2</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>${AVA2_IOS_PLATFORM}</string>
</array>
<key>MinimumOSVersion</key>
<string>${CMAKE_OSX_DEPLOYMENT_TARGET}</string>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>LSRequiresIPhoneOS</key>
<true/>
<!-- An (empty) launch screen opts into the native resolution instead of legacy letterboxing. -->
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
<string>metal</string>
</array>
<!-- The client root lives in Documents (ios/push_assets.py); Finder / the Files app can copy it in. -->
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<!-- The game server is plain TCP on the local network. -->
<key>NSLocalNetworkUsageDescription</key>
<string>Connects to the AVA2 game server on your network.</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.role-playing-games</string>
</dict>
</plist>
Executable
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env bash
# Builds the iOS app (arm64) and installs + launches it on a simulator or an attached device.
#
# ios/build.sh simulator build; boots $AVA2_IOS_SIMULATOR (default: first available
# iPhone), installs and launches
# ios/build.sh device device build, signed with $AVA2_IOS_SIGN_IDENTITY and
# $AVA2_IOS_PROFILE (.mobileprovision); installs + launches when
# `xcrun devicectl` sees a device
# ios/build.sh deps [device] only (re)build the native dependencies
# --no-run (any mode) build only
#
# Like the APK, the .app holds code only; push the client root with ios/push_assets.py.
# Native dependencies (static SDL3 + FreeType) are built once into build/ios-deps (sources are
# shared with build/android-deps when already downloaded).
# Environment overrides: AVA2_SDK_ROOT, AVA2_SOURCE_DIR (CMake source tree, default this checkout),
# AVA2_IOS_BUNDLE_ID (default com.metin2.ava2), AVA2_IOS_SIMULATOR, AVA2_IOS_DEVICE,
# AVA2_IOS_BUILD_TYPE (default RelWithDebInfo).
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/.." && pwd)"
SOURCE_DIR="${AVA2_SOURCE_DIR:-$ROOT}"
SDL_VERSION=3.4.16
FREETYPE_VERSION=2.13.3
DEPLOYMENT_TARGET=15.0
MODE=simulator RUN=1 DEPS_ONLY=0
for arg in "$@"; do
case "$arg" in
sim|simulator) MODE=simulator ;;
device) MODE=device ;;
deps) DEPS_ONLY=1 ;;
--no-run) RUN=0 ;;
*) echo "unknown argument: $arg"; exit 2 ;;
esac
done
if [[ "$MODE" == simulator ]]; then SDK=iphonesimulator; else SDK=iphoneos; fi
xcrun --sdk "$SDK" --show-sdk-path >/dev/null 2>&1 || { echo "Xcode $SDK SDK not found (xcode-select)"; exit 1; }
DEPS="$ROOT/build/ios-deps"
PREFIX="$DEPS/prefix-$SDK"
mkdir -p "$DEPS/src"
IOS_CMAKE=(-DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT="$SDK" -DCMAKE_OSX_ARCHITECTURES=arm64
-DCMAKE_OSX_DEPLOYMENT_TARGET=$DEPLOYMENT_TARGET)
fetch() { # url file
[[ -f "$DEPS/src/$2" ]] && return
if [[ -f "$ROOT/build/android-deps/src/$2" ]]; then cp "$ROOT/build/android-deps/src/$2" "$DEPS/src/$2"; return; fi
curl -fL --retry 3 -o "$DEPS/src/$2.part" "$1" || { echo "download failed: $1"; exit 1; }
mv -f "$DEPS/src/$2.part" "$DEPS/src/$2"
}
cmake_dep() { # source-dir build-dir extra-args...
local src="$1" bld="$2"; shift 2
cmake -S "$src" -B "$bld" "${IOS_CMAKE[@]}" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" "$@"
cmake --build "$bld" -j"$(sysctl -n hw.ncpu)"
cmake --install "$bld"
}
if [[ ! -f "$PREFIX/lib/libSDL3.a" ]]; then
fetch "https://github.com/libsdl-org/SDL/releases/download/release-$SDL_VERSION/SDL3-$SDL_VERSION.tar.gz" "SDL3-$SDL_VERSION.tar.gz"
rm -rf "$DEPS/src/SDL3-$SDL_VERSION-$SDK" && mkdir "$DEPS/src/SDL3-$SDL_VERSION-$SDK"
tar -xzf "$DEPS/src/SDL3-$SDL_VERSION.tar.gz" -C "$DEPS/src/SDL3-$SDL_VERSION-$SDK" --strip-components 1
if [[ "$SDK" == iphonesimulator ]]; then
# The simulator's Metal device does not report MTLGPUFamilyApple3, so SDL_GPU refuses it
# although the host GPU runs the client fine. Skip the check there; device builds are untouched.
perl -0pi -e 's/(hasHardwareSupport = \[device supportsFamily:MTLGPUFamilyApple3\])/$1 || TARGET_OS_SIMULATOR/' \
"$DEPS/src/SDL3-$SDL_VERSION-$SDK/src/gpu/metal/SDL_gpu_metal.m"
grep -q "MTLGPUFamilyApple3\] || TARGET_OS_SIMULATOR" \
"$DEPS/src/SDL3-$SDL_VERSION-$SDK/src/gpu/metal/SDL_gpu_metal.m" || { echo "SDL simulator patch failed"; exit 1; }
fi
cmake_dep "$DEPS/src/SDL3-$SDL_VERSION-$SDK" "$DEPS/build-sdl3-$SDK" \
-DSDL_SHARED=OFF -DSDL_STATIC=ON -DSDL_TEST_LIBRARY=OFF -DSDL_TESTS=OFF -DSDL_EXAMPLES=OFF
fi
if [[ ! -f "$PREFIX/lib/libfreetype.a" ]]; then
fetch "https://download.savannah.gnu.org/releases/freetype/freetype-$FREETYPE_VERSION.tar.xz" "freetype-$FREETYPE_VERSION.tar.xz"
rm -rf "$DEPS/src/freetype-$FREETYPE_VERSION" && tar -xJf "$DEPS/src/freetype-$FREETYPE_VERSION.tar.xz" -C "$DEPS/src"
cmake_dep "$DEPS/src/freetype-$FREETYPE_VERSION" "$DEPS/build-freetype-$SDK" -DBUILD_SHARED_LIBS=OFF \
-DFT_DISABLE_ZLIB=ON -DFT_DISABLE_BZIP2=ON -DFT_DISABLE_PNG=ON -DFT_DISABLE_HARFBUZZ=ON -DFT_DISABLE_BROTLI=ON
fi
[[ "$DEPS_ONLY" == 1 ]] && exit 0
BUILD="$ROOT/build/ios-$SDK"
CONFIG_ARGS=("${IOS_CMAKE[@]}" -DCMAKE_BUILD_TYPE="${AVA2_IOS_BUILD_TYPE:-RelWithDebInfo}"
-DAVA2_BUILD_HOST=ON -DAVA2_EMBED_PYTHON=ON -DBUILD_TESTING=OFF
-DSDL3_DIR="$PREFIX/lib/cmake/SDL3" -DCMAKE_PREFIX_PATH="$PREFIX"
-DAVA2_IOS_BUNDLE_ID="${AVA2_IOS_BUNDLE_ID:-com.metin2.ava2}")
[[ -n "${AVA2_SDK_ROOT:-}" ]] && CONFIG_ARGS+=(-DAVA2_SDK_ROOT="$AVA2_SDK_ROOT")
cmake -S "$SOURCE_DIR" -B "$BUILD" "${CONFIG_ARGS[@]}"
cmake --build "$BUILD" --target ava2_client mtpython_stdlib -j"$(sysctl -n hw.ncpu)"
APP="$BUILD/ava2_client.app"
BUNDLE_ID="${AVA2_IOS_BUNDLE_ID:-com.metin2.ava2}"
if [[ "$MODE" == simulator ]]; then
codesign --force --sign - --timestamp=none "$APP"
else
[[ -n "${AVA2_IOS_SIGN_IDENTITY:-}" && -f "${AVA2_IOS_PROFILE:-}" ]] || {
echo "Device builds need AVA2_IOS_SIGN_IDENTITY (security find-identity -v -p codesigning) and"
echo "AVA2_IOS_PROFILE (a development .mobileprovision for $BUNDLE_ID)."; exit 1; }
cp "$AVA2_IOS_PROFILE" "$APP/embedded.mobileprovision"
ENTITLEMENTS="$BUILD/entitlements.plist"
security cms -D -i "$AVA2_IOS_PROFILE" > "$BUILD/profile.plist"
/usr/libexec/PlistBuddy -x -c "Print :Entitlements" "$BUILD/profile.plist" > "$ENTITLEMENTS"
codesign --force --sign "$AVA2_IOS_SIGN_IDENTITY" --entitlements "$ENTITLEMENTS" --timestamp=none "$APP"
fi
du -sh "$APP"
[[ "$RUN" == 1 ]] || exit 0
if [[ "$MODE" == simulator ]]; then
SIM="${AVA2_IOS_SIMULATOR:-}"
if [[ -z "$SIM" ]]; then
SIM="$(xcrun simctl list devices booted | sed -nE 's/.*\(([0-9A-F-]{36})\) \(Booted\).*/\1/p' | head -1)"
fi
if [[ -z "$SIM" ]]; then
SIM="$(xcrun simctl list devices available | grep -E '^ +iPhone' | tail -1 | sed -nE 's/.*\(([0-9A-F-]{36})\).*/\1/p')"
fi
[[ -n "$SIM" ]] || { echo "No iOS simulator available (Xcode > Settings > Platforms)"; exit 1; }
xcrun simctl boot "$SIM" 2>/dev/null || true
open -a Simulator --args -CurrentDeviceUDID "$SIM" || true
xcrun simctl bootstatus "$SIM" -b >/dev/null
xcrun simctl install "$SIM" "$APP"
xcrun simctl launch "$SIM" "$BUNDLE_ID"
echo "Launched on simulator $SIM. Logs: xcrun simctl spawn $SIM log stream --predicate 'process == \"ava2_client\"'"
else
DEVICE="${AVA2_IOS_DEVICE:-}"
if [[ -z "$DEVICE" ]]; then
DEVICE="$(xcrun devicectl list devices 2>/dev/null | awk '/available|connected/ && /iPhone|iPad/ {print $3; exit}')"
fi
if [[ -z "$DEVICE" ]]; then echo "No device attached; app not installed."; exit 0; fi
xcrun devicectl device install app --device "$DEVICE" "$APP"
xcrun devicectl device process launch --device "$DEVICE" "$BUNDLE_ID"
fi
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Copy the client root into the iOS app's Documents directory (development builds).
The .app holds code only; on iOS the client runs in its Documents directory and reads the same
flattened client root as Android (assets/loose + test-rundir + upstream/python-root + python27.zip).
The tree is staged by android/push_assets.py --stage-only --lowercase into build/ios-data/root (all
names ASCII lower-case: iOS file systems are case-sensitive and the client opens lower-cased
paths), then:
simulator copied into `xcrun simctl get_app_container <udid> <bundle> data`/Documents as APFS
clones (cp -c: no extra disk space, and the app cannot write through to the checkout)
device sent with `xcrun devicectl device copy to` into the app data container
Install the app first (ios/build.sh), since the container only exists after install.
usage: ios/push_assets.py [device] [--simulator UDID] [--device ID] [--stdlib ZIP] [--pack-maker DIR]
"""
import argparse
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BUNDLE_ID = os.environ.get("AVA2_IOS_BUNDLE_ID", "com.metin2.ava2")
def booted_simulator():
out = subprocess.run(["xcrun", "simctl", "list", "devices", "booted"], check=True,
capture_output=True, text=True).stdout
match = re.search(r"\(([0-9A-F-]{36})\) \(Booted\)", out)
return match.group(1) if match else None
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("target", nargs="?", choices=["sim", "simulator", "device"], default="simulator")
parser.add_argument("--simulator", default=os.environ.get("AVA2_IOS_SIMULATOR"), help="UDID (default: booted)")
parser.add_argument("--device", default=os.environ.get("AVA2_IOS_DEVICE"), help="devicectl device id")
parser.add_argument("--stdlib", help="python27.zip (default: the matching ios/build.sh output)")
parser.add_argument("--pack-maker", help="passed to android/push_assets.py")
parser.add_argument("--stage", type=Path, default=ROOT / "build/ios-data/root")
args = parser.parse_args()
device = args.target == "device"
stdlib = args.stdlib or ROOT / f"build/ios-{'iphoneos' if device else 'iphonesimulator'}/python27.zip"
if not Path(stdlib).is_file():
sys.exit(f"{stdlib} not found; run ios/build.sh first or pass --stdlib")
# iOS file systems are case-sensitive while the client lower-cases the paths it opens
# (ResourceManager::NormalizePath) and the data mixes cases, so stage every name lower-case.
stage_cmd = [sys.executable, str(ROOT / "android/push_assets.py"), "--stage-only", "--lowercase",
"--stage", str(args.stage), "--stdlib", str(stdlib)]
if args.pack_maker:
stage_cmd += ["--pack-maker", args.pack_maker]
subprocess.run(stage_cmd, check=True)
if not device:
udid = args.simulator or booted_simulator()
if not udid:
sys.exit("no booted simulator; run ios/build.sh or pass --simulator")
container = subprocess.run(["xcrun", "simctl", "get_app_container", udid, BUNDLE_ID, "data"],
check=True, capture_output=True, text=True).stdout.strip()
docs = Path(container) / "Documents"
docs.mkdir(parents=True, exist_ok=True)
# Trailing "/." copies the directory's contents; -c clones, plain copy across volumes.
if subprocess.run(["cp", "-Rc", f"{args.stage}/.", str(docs)]).returncode != 0:
subprocess.run(["cp", "-R", f"{args.stage}/.", str(docs)], check=True)
print(f"copied to {docs}")
return
if not args.device:
out = subprocess.run(["xcrun", "devicectl", "list", "devices"], check=True,
capture_output=True, text=True).stdout
ids = [line.split()[2] for line in out.splitlines()
if re.search(r"available|connected", line) and re.search(r"iPhone|iPad", line)]
if not ids:
sys.exit("no device attached")
args.device = ids[0]
subprocess.run(["xcrun", "devicectl", "device", "copy", "to", "--device", args.device,
"--domain-type", "appDataContainer", "--domain-identifier", BUNDLE_ID,
"--source", str(args.stage), "--destination", "Documents"], check=True)
print(f"copied to {args.device}:{BUNDLE_ID}/Documents")
if __name__ == "__main__":
main()
+8 -7
View File
@@ -10,14 +10,15 @@
template <typename T>
class CSingleton
{
static T * ms_singleton;
static CSingleton<T> * ms_singleton;
public:
CSingleton()
{
assert(!ms_singleton);
intptr_t offset = (intptr_t) (T*) 1 - (intptr_t) (CSingleton <T>*) (T*) 1;
ms_singleton = (T*) ((intptr_t) this + offset);
// Register the actual base subobject. Convert to T only after its
// construction starts, using the compiler's multiple-inheritance adjustment.
ms_singleton = this;
}
virtual ~CSingleton()
@@ -29,19 +30,19 @@ public:
__forceinline static T & Instance()
{
assert(ms_singleton);
return (*ms_singleton);
return *static_cast<T*>(ms_singleton);
}
__forceinline static T * InstancePtr()
{
return (ms_singleton);
return static_cast<T*>(ms_singleton);
}
__forceinline static T & instance()
{
assert(ms_singleton);
return (*ms_singleton);
return *static_cast<T*>(ms_singleton);
}
};
template <typename T> T * CSingleton<T>::ms_singleton = nullptr;
template <typename T> CSingleton<T> * CSingleton<T>::ms_singleton = nullptr;
+2868
View File
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
#pragma once
// Client frame loop (docs/MOBILE-ARCHITECTURE.md, app_loop), split out of main.cpp so one source
// serves both ways SDL can drive an app:
// - SDL's main callbacks (main.cpp with AVA2_MAIN_CALLBACKS): SDL_AppInit -> Start,
// SDL_AppIterate -> Iterate, SDL_AppEvent -> QueueEvent, SDL_AppQuit -> Finish. Required on
// iOS, where UIKit owns the main thread and calls SDL_AppIterate once per display refresh.
// - a classic main loop (Run): the frame polls SDL for events itself.
//
// Start-up, the per-frame body and teardown stay one function (RunClient in app_loop.cpp). It is a
// C++20 coroutine that suspends at the top of every frame, so the renderer, scene, actors and the
// lambdas that capture them live in the coroutine frame between callbacks.
#include <SDL3/SDL_events.h>
#include <coroutine>
#include <deque>
namespace ava2::app {
class AppLoop {
public:
struct Frame; // RunClient's coroutine type (app_loop.cpp)
AppLoop() = default;
~AppLoop();
AppLoop(const AppLoop&) = delete;
AppLoop& operator=(const AppLoop&) = delete;
// Runs the start-up (arguments, SDL, Python, scene) up to the first frame. queuedEvents: events
// arrive through QueueEvent (main callbacks) instead of SDL_PollEvent. False when the client
// already finished (bad arguments, failed start-up); ExitCode() tells how.
bool Start(int argc, char** argv, bool queuedEvents);
// One frame; false once the client has finished.
bool Iterate();
// Called from SDL_AppEvent; the next frame's event pass reads it.
void QueueEvent(const SDL_Event& event);
// Lets a still-running client leave its loop and tear down (SDL_AppQuit), then returns the
// exit code. Safe to call more than once.
int Finish();
int ExitCode() const { return m_exitCode; }
// Classic main loop: Start, Iterate until done, Finish.
int Run(int argc, char** argv);
// For the frame body: the next event of this frame, and whether the host asked it to stop.
bool PollEvent(SDL_Event* event);
bool QuitRequested() const { return m_quit; }
private:
bool Resume();
std::coroutine_handle<> m_frame;
std::deque<SDL_Event> m_events;
bool m_queuedEvents = false, m_quit = false, m_inFrame = false;
int m_exitCode = 0;
};
} // namespace ava2::app
+379
View File
@@ -0,0 +1,379 @@
#include "touch_router.h"
#include <algorithm>
#include <cmath>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
namespace ava2::input {
TouchLayout TouchLayout::ForScreen(float w, float h, float safeLeft, float safeTop, float safeRight, float safeBottom) {
TouchLayout layout;
layout.screen_w = w;
layout.screen_h = h;
layout.safe_left = safeLeft;
layout.safe_top = safeTop;
layout.safe_right = safeRight;
layout.safe_bottom = safeBottom;
const float unit = std::min(w, h);
// The joystick area starts at the safe edge; the stick floats, so its bottom can stay wide.
layout.joy_x = safeLeft;
layout.joy_y = h * 0.45f;
layout.joy_w = w * 0.40f;
layout.joy_h = h * 0.55f - safeBottom;
layout.joy_radius = unit * 0.12f;
layout.attack_r = unit * 0.11f;
layout.attack_x = w - safeRight - layout.attack_r - unit * 0.06f;
layout.attack_y = h - safeBottom - layout.attack_r - unit * 0.06f;
layout.tap_slop = unit * 0.02f;
layout.double_tap_slop = unit * 0.06f;
return layout;
}
void TouchRouter::SetWorldEnabled(bool enabled) {
if (enabled == m_world) return;
// Phase change: world fingers would otherwise keep a stale joystick or attack state.
if (!enabled) {
ReleaseDeferred();
for (auto it = m_fingers.begin(); it != m_fingers.end();) {
if (it->second.owner != Owner::Ui) {
Release(it->first, it->second, true);
it = m_fingers.erase(it);
} else {
++it;
}
}
}
m_world = enabled;
}
bool TouchRouter::InAttack(float x, float y) const {
if (m_layout.attack_r <= 0.0f) return false;
const float dx = x - m_layout.attack_x, dy = y - m_layout.attack_y;
return dx * dx + dy * dy <= m_layout.attack_r * m_layout.attack_r;
}
bool TouchRouter::InJoystickArea(float x, float y) const {
return x >= m_layout.joy_x && x < m_layout.joy_x + m_layout.joy_w &&
y >= m_layout.joy_y && y < m_layout.joy_y + m_layout.joy_h;
}
bool TouchRouter::InSystemEdge(float, float y) const {
return m_layout.safe_bottom > 0.0f && y >= m_layout.screen_h - m_layout.safe_bottom;
}
bool TouchRouter::CanReacquireJoystick(float x, float y, std::uint64_t ms) const {
if (!m_joy_orphan || (ms > m_joy_orphan_ms && ms - m_joy_orphan_ms > m_layout.joy_reacquire_ms)) return false;
// The thumb comes back roughly where it was: anywhere within one and a half stick radii.
const float reach = m_layout.joy_radius * 1.5f;
return std::hypot(x - m_joy.base_x, y - m_joy.base_y) <= reach;
}
void TouchRouter::ReleaseJoystick() {
m_joy_finger = 0;
m_joy_orphan = false;
m_joy = JoystickView{};
if (m_sink) m_sink->Joystick(false, 0.0f, 0.0f);
}
void TouchRouter::ReleaseDeferred() {
if (m_joy_orphan) ReleaseJoystick();
if (m_attack_release_pending) {
m_attack_release_pending = false;
if (m_sink) m_sink->Attack(false);
}
m_attack_fresh = false;
}
void TouchRouter::UpdateJoystick(float x, float y) {
const float r = m_layout.joy_radius;
float dx = x - m_joy_touch_x, dy = y - m_joy_touch_y;
const float dist = std::sqrt(dx * dx + dy * dy);
if (dist > r && dist > 0.0f) {
dx *= r / dist;
dy *= r / dist;
}
m_joy.knob_x = m_joy.base_x + dx;
m_joy.knob_y = m_joy.base_y + dy;
if (!m_sink) return;
const float len = std::min(dist, r) / r;
if (len < m_layout.joy_dead_zone)
m_sink->Joystick(true, 0.0f, 0.0f);
else
m_sink->Joystick(true, dx / r, dy / r);
}
TouchRouter::Finger* TouchRouter::OtherCameraFinger(std::uint64_t id) {
for (auto& [other, finger] : m_fingers)
if (other != id && finger.owner == Owner::Camera) return &finger;
return nullptr;
}
void TouchRouter::FingerDown(std::uint64_t raw_id, float x, float y, std::uint64_t ms) {
const std::uint64_t id = raw_id + 1;
if (m_fingers.count(id)) return;
Finger finger;
finger.x = finger.start_x = x;
finger.y = finger.start_y = y;
finger.start_ms = ms;
const int skill=m_world && m_sink ? m_sink->SkillAt(x,y) : -1;
if(skill>=0) {
// A second finger on the same shortcut cannot duplicate its repeat stream.
for(const auto& entry:m_fingers)if(entry.second.owner==Owner::Skill && entry.second.skill_slot==skill)return;
finger.owner=Owner::Skill;finger.skill_slot=skill;m_fingers[id]=finger;return;
}
const bool ui = m_sink && m_sink->IsUiAt(x, y);
if (!m_world || ui) {
// wndMgr tracks a single pointer; further fingers on UI are ignored.
if (m_ui_finger || !m_sink) return;
finger.owner = Owner::Ui;
m_ui_finger = id;
finger.ui = Finger::Ui::Pending;
m_fingers[id] = finger;
m_sink->UiMouseMove(x, y);
return;
}
if (!m_attack_finger && InAttack(x, y)) {
finger.owner = Owner::Attack;
m_attack_finger = id;
m_attack_fresh = true;
m_fingers[id] = finger;
// A release still waiting for its frame: the key simply stays down.
if (m_attack_release_pending)
m_attack_release_pending = false;
else if (m_sink)
m_sink->Attack(true);
return;
}
if (!m_joy_finger && CanReacquireJoystick(x, y, ms)) {
// Same base as before the system cancel, so the direction does not jump.
finger.owner = Owner::Joystick;
m_joy_finger = id;
m_joy_orphan = false;
m_fingers[id] = finger;
UpdateJoystick(x, y);
return;
}
if (!m_joy_finger && InJoystickArea(x, y)) {
m_joy_orphan = false;
finger.owner = Owner::Joystick;
m_joy_finger = id;
m_fingers[id] = finger;
const float r = m_layout.joy_radius;
m_joy_touch_x=x;m_joy_touch_y=y;
m_joy.active = true;
m_joy.base_x = std::clamp(x, r, std::max(r, m_layout.screen_w - r));
m_joy.base_y = std::clamp(y, r, std::max(r, m_layout.screen_h - r));
UpdateJoystick(x, y);
return;
}
if (InSystemEdge(x, y)) {
// Home-gesture strip: a swipe up here belongs to the system, not to the camera.
finger.owner = Owner::Ignored;
m_fingers[id] = finger;
return;
}
finger.owner = Owner::Camera;
if (Finger* other = OtherCameraFinger(id)) {
// Second camera finger: a pinch, neither finger can still be a tap.
other->tap = false;
finger.tap = false;
}
m_fingers[id] = finger;
}
void TouchRouter::FingerMove(std::uint64_t raw_id, float x, float y, std::uint64_t) {
const std::uint64_t id = raw_id + 1;
auto it = m_fingers.find(id);
if (it == m_fingers.end()) return;
Finger& finger = it->second;
const float prev_x = finger.x, prev_y = finger.y;
finger.x = x;
finger.y = y;
switch (finger.owner) {
case Owner::Ui:
if (!m_sink || finger.ui == Finger::Ui::Consumed) break;
if (finger.ui == Finger::Ui::Pending) {
if (std::hypot(x - finger.start_x, y - finger.start_y) <= m_layout.tap_slop) break;
// A drag: the button goes down where the finger landed, as a mouse drag would start.
finger.ui = Finger::Ui::Pressed;
m_sink->UiMouseMove(finger.start_x, finger.start_y);
m_sink->UiMouseDown(finger.start_x, finger.start_y);
}
m_sink->UiMouseMove(x, y);
break;
case Owner::Skill:
case Owner::Attack:
case Owner::Ignored:
break;
case Owner::Joystick:
UpdateJoystick(x, y);
break;
case Owner::Camera: {
if (Finger* other = OtherCameraFinger(id)) {
const float before = std::hypot(prev_x - other->x, prev_y - other->y);
const float after = std::hypot(x - other->x, y - other->y);
if (before > 1.0f && after > 1.0f && m_sink) m_sink->CameraZoom(after / before);
break;
}
if (finger.tap) {
if (std::hypot(x - finger.start_x, y - finger.start_y) <= m_layout.tap_slop) break;
finger.tap = false;
// The slop distance is part of the drag so the camera does not jump.
if (m_sink) m_sink->CameraRotate(x - finger.start_x, y - finger.start_y);
break;
}
if (m_sink) m_sink->CameraRotate(x - prev_x, y - prev_y);
break;
}
}
}
void TouchRouter::Release(std::uint64_t id, Finger& finger, bool cancelled) {
switch (finger.owner) {
case Owner::Ui:
m_ui_finger = 0;
// A cancelled UI finger still releases a pressed button so no window keeps the capture.
if (finger.ui == Finger::Ui::Pressed && m_sink) m_sink->UiMouseUp(finger.x, finger.y);
// A cancelled pending touch never clicked: its hover tooltip would otherwise stay. A long
// press the host took keeps the pointer (the item tooltip stays next to the action sheet).
else if (finger.ui == Finger::Ui::Pending && m_sink) m_sink->UiPointerIdle();
break;
case Owner::Skill:
if(!cancelled && !finger.skill_cast && m_sink) {
const float dx=finger.x-finger.start_x,dy=finger.y-finger.start_y;
const bool aimed=std::hypot(dx,dy)>m_layout.tap_slop;
m_sink->Skill(finger.skill_slot,aimed?dx:0,aimed?dy:0,false);
}
break;
case Owner::Attack:
m_attack_finger = 0;
if (!cancelled && m_attack_fresh)
m_attack_release_pending = true;
else if (m_sink)
m_sink->Attack(false);
break;
case Owner::Joystick:
ReleaseJoystick();
break;
case Owner::Camera:
if (!cancelled && finger.tap && m_sink) m_sink->WorldTap(finger.x, finger.y);
break;
case Owner::Ignored:
break;
}
(void)id;
}
void TouchRouter::FingerUp(std::uint64_t raw_id, float x, float y, std::uint64_t ms) {
const std::uint64_t id = raw_id + 1;
auto it = m_fingers.find(id);
if (it == m_fingers.end()) return;
Finger finger = it->second;
m_fingers.erase(it);
finger.x = x;
finger.y = y;
if (finger.owner == Owner::Ui && finger.ui == Finger::Ui::Pending) {
m_ui_finger = 0;
UiTap(finger, ms);
return;
}
if (finger.owner == Owner::Ui && finger.ui == Finger::Ui::Pressed && m_sink) m_sink->UiMouseMove(x, y);
if (finger.owner == Owner::Camera && finger.tap &&
(ms - finger.start_ms > m_layout.tap_ms ||
std::hypot(x - finger.start_x, y - finger.start_y) > m_layout.tap_slop))
finger.tap = false;
Release(id, finger, false);
}
void TouchRouter::FingerCancel(std::uint64_t raw_id, std::uint64_t ms) {
const std::uint64_t id = raw_id + 1;
auto it = m_fingers.find(id);
if (it == m_fingers.end()) return;
Finger finger = it->second;
m_fingers.erase(it);
if (finger.owner == Owner::Joystick) {
// Keep moving for a moment: the finger is usually still on the glass and comes back.
m_joy_finger = 0;
m_joy_orphan = true;
m_joy_orphan_ms = ms;
return;
}
Release(id, finger, true);
}
void TouchRouter::UiTap(const Finger& finger, std::uint64_t ms) {
if (!m_sink) return;
// The click lands where the finger landed; a tap moves less than tap_slop anyway.
const float x = finger.start_x, y = finger.start_y;
const bool second = m_last_tap_valid && finger.start_ms >= m_last_tap_ms &&
finger.start_ms - m_last_tap_ms <= m_layout.double_tap_ms &&
std::hypot(x - m_last_tap_x, y - m_last_tap_y) <= m_layout.double_tap_slop;
m_sink->UiMouseMove(x, y);
m_sink->UiMouseDown(x, y);
if (second) m_sink->UiDoubleClick(x, y);
m_sink->UiMouseUp(x, y);
// A third tap starts a new pair.
m_last_tap_valid = !second;
m_last_tap_ms = ms;
m_last_tap_x = x;
m_last_tap_y = y;
}
void TouchRouter::Update(std::uint64_t ms) {
m_attack_fresh = false;
if (m_attack_release_pending) {
m_attack_release_pending = false;
if (m_sink) m_sink->Attack(false);
}
if (m_joy_orphan && ms > m_joy_orphan_ms && ms - m_joy_orphan_ms > m_layout.joy_reacquire_ms) ReleaseJoystick();
if(m_sink)for(auto& entry:m_fingers) {
auto& finger=entry.second;if(finger.owner!=Owner::Skill || ms<finger.start_ms)continue;
const float dx=finger.x-finger.start_x,dy=finger.y-finger.start_y;
const bool aimed=std::hypot(dx,dy)>m_layout.tap_slop;
if((!finger.skill_cast && (aimed || ms-finger.start_ms>=m_layout.skill_settle_ms))
|| (finger.skill_cast && ms>=finger.skill_last_ms && ms-finger.skill_last_ms>=m_layout.skill_repeat_ms)) {
m_sink->Skill(finger.skill_slot,aimed?dx:0,aimed?dy:0,finger.skill_cast);
finger.skill_cast=true;finger.skill_last_ms=ms;
}
}
if (!m_ui_finger || !m_sink) return;
auto it = m_fingers.find(m_ui_finger);
if (it == m_fingers.end()) return;
Finger& finger = it->second;
if (finger.ui != Finger::Ui::Pending || ms < finger.start_ms || ms - finger.start_ms < m_layout.long_press_ms) return;
m_last_tap_valid = false;
if (m_sink->UiLongPress(finger.x, finger.y)) {
finger.ui = Finger::Ui::Consumed;
return;
}
finger.ui = Finger::Ui::Pressed;
m_sink->UiMouseMove(finger.x, finger.y);
m_sink->UiMouseDown(finger.x, finger.y);
}
void TouchRouter::CancelAll() {
ReleaseDeferred();
for (auto& [id, finger] : m_fingers) Release(id, finger, true);
m_fingers.clear();
}
TouchRouter& GetTouchRouter() {
static TouchRouter router;
return router;
}
namespace {
#if defined(__ANDROID__) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
bool s_touch_mode = true;
#else
bool s_touch_mode = false;
#endif
} // namespace
bool IsTouchMode() { return s_touch_mode; }
void SetTouchMode(bool enabled) { s_touch_mode = enabled; }
} // namespace ava2::input
+186
View File
@@ -0,0 +1,186 @@
#pragma once
// Touch input router for the mobile client (docs/MOBILE-ARCHITECTURE.md, input/).
//
// Every finger is assigned an owner when it goes down and keeps it until it lifts:
//
// UI window under the finger -> mouse events for the window manager (one finger at a time),
// see "UI gestures" below
// attack button circle -> attack key held while the finger is down
// joystick area (lower left) -> floating virtual joystick, camera-relative movement
// anything else -> one finger drags the camera, two fingers pinch-zoom,
// a short tap clicks the game world (target / ground)
//
// UI gestures. The button press is held back until the finger shows what it is doing:
//
// tap -> down + up where the finger lifts (a click: pick up / drop an item)
// second tap nearby -> down + double click + up, as PythonApplicationEvent.cpp sends a mouse
// double click (use / equip an item)
// move past tap_slop -> down at the start point, then moves (drag an item, scroll, move a window)
// hold long_press_ms -> UiLongPress; when the host takes it (item details / action sheet) the
// rest of the touch is ignored, otherwise the button goes down and the
// touch continues as a press
//
// The pointer follows the finger from the moment it lands, so hover tooltips show while holding;
// when a touch ends without a click (cancelled, or a world tap) the host parks it off screen
// (UiPointerIdle) so no hover tooltip stays behind.
//
// System edges (interaction ideas from jhaizhou-ops/d2r-mobile, MIT; no code taken):
//
// - a world finger that lands in the bottom safe inset (the home-gesture strip) is ignored:
// no camera drag, no world tap;
// - when the system cancels the joystick finger (FingerCancel, e.g. an edge gesture starting
// under it) the stick keeps its vector for joy_reacquire_ms, and a finger landing near the
// old base in that time takes it over with the same base;
// - an attack tap shorter than one frame is held until the next Update so the player module
// sees the key at least once.
//
// Outside the game phase only the UI owner exists. Coordinates are UI pixels (the same space as
// wndMgr). The router has no SDL or game dependencies; the host implements TouchSink.
#include <cstdint>
#include <map>
namespace ava2::input {
struct TouchSink {
virtual ~TouchSink() = default;
// True when a UI window other than the full-screen game window is under the point.
virtual bool IsUiAt(float x, float y) = 0;
virtual void UiMouseMove(float x, float y) = 0;
virtual void UiMouseDown(float x, float y) = 0;
virtual void UiMouseUp(float x, float y) = 0;
// Second tap of a double tap, between its UiMouseDown and UiMouseUp.
virtual void UiDoubleClick(float, float) {}
// Finger held still on UI; true when the host handled it and wants no button press.
virtual bool UiLongPress(float, float) { return false; }
// A UI or world touch ended without the pointer being parked by UiMouseUp: the host moves it
// off screen unless an item hangs on the cursor.
virtual void UiPointerIdle() {}
// Short tap on the game world: the host clicks there as the original left button would.
virtual void WorldTap(float x, float y) = 0;
// Joystick vector in screen axes (x right, y down), length 0..1; active=false releases it.
virtual void Joystick(bool active, float x, float y) = 0;
virtual void Attack(bool pressed) = 0;
// Pick only a visible skill shortcut under the finger; -1 means ordinary UI.
virtual int SkillAt(float, float) { return -1; }
virtual void Skill(int, float, float, bool) {} // slot, aim vector, repeated cast
// Camera drag in UI pixels since the last call.
virtual void CameraRotate(float dx, float dy) = 0;
// Pinch ratio since the last call: > 1 fingers moved apart (zoom in).
virtual void CameraZoom(float ratio) = 0;
};
struct TouchLayout {
float screen_w = 1280.0f, screen_h = 720.0f;
// Joystick area; the stick centres where the finger lands inside it.
float joy_x = 0.0f, joy_y = 0.0f, joy_w = 0.0f, joy_h = 0.0f;
float joy_radius = 80.0f; // full deflection distance
float joy_dead_zone = 0.18f; // fraction of joy_radius treated as centred
// Attack button circle; radius 0 disables it.
float attack_x = 0.0f, attack_y = 0.0f, attack_r = 0.0f;
float tap_slop = 14.0f; // movement that turns a tap into a camera drag
std::uint64_t tap_ms = 300;
std::uint64_t skill_settle_ms = 100, skill_repeat_ms = 200; // longer presses are not taps
std::uint64_t double_tap_ms = 300; // first tap's lift to second tap's landing
float double_tap_slop = 40.0f; // distance between the two taps
std::uint64_t long_press_ms = 450;
std::uint64_t joy_reacquire_ms = 300; // a cancelled joystick waits this long for a new finger
// Unobstructed-area insets (platform::SafeInsets); the HUD reads them through `touch`.
float safe_left = 0.0f, safe_top = 0.0f, safe_right = 0.0f, safe_bottom = 0.0f;
// Default layout for a screen: joystick in the lower-left 40% x 55%, attack bottom right,
// both kept inside the safe insets.
static TouchLayout ForScreen(float w, float h, float safeLeft = 0.0f, float safeTop = 0.0f,
float safeRight = 0.0f, float safeBottom = 0.0f);
};
struct JoystickView {
bool active = false;
float base_x = 0.0f, base_y = 0.0f; // where the finger landed (clamped on screen)
float knob_x = 0.0f, knob_y = 0.0f; // knob centre, at most joy_radius from the base
};
class TouchRouter {
public:
// Ignored: a world finger that landed in the bottom system-gesture strip.
enum class Owner { Ui, Attack, Skill, Joystick, Camera, Ignored };
void SetSink(TouchSink* sink) { m_sink = sink; }
void SetLayout(const TouchLayout& layout) { m_layout = layout; }
const TouchLayout& GetLayout() const { return m_layout; }
// World controls (joystick, attack, camera, world taps) exist only in the game phase.
void SetWorldEnabled(bool enabled);
bool IsWorldEnabled() const { return m_world; }
void FingerDown(std::uint64_t id, float x, float y, std::uint64_t ms);
void FingerMove(std::uint64_t id, float x, float y, std::uint64_t ms);
void FingerUp(std::uint64_t id, float x, float y, std::uint64_t ms);
// The system took this finger (SDL_EVENT_FINGER_CANCELED): released without a tap or click.
void FingerCancel(std::uint64_t id, std::uint64_t ms);
// Per-frame tick in the same milliseconds as the finger events (long press detection).
void Update(std::uint64_t ms);
// Lost focus / app paused: release everything without taps or clicks.
void CancelAll();
JoystickView GetJoystick() const { return m_joy; }
JoystickView GetSkillAim() const {
for(const auto& entry:m_fingers)if(entry.second.owner==Owner::Skill)
return {true,entry.second.start_x,entry.second.start_y,entry.second.x,entry.second.y};
return {};
}
bool IsAttackPressed() const { return m_attack_finger != 0 || m_attack_release_pending; }
std::size_t FingerCount() const { return m_fingers.size(); }
private:
struct Finger {
Owner owner = Owner::Ui;
float x = 0.0f, y = 0.0f; // last position
float start_x = 0.0f, start_y = 0.0f;
std::uint64_t start_ms = 0;
int skill_slot = -1;
bool skill_cast = false;
std::uint64_t skill_last_ms = 0;
bool tap = true; // still a tap candidate (camera fingers)
// UI fingers: Pending holds the button press back, Pressed sent it, Consumed was a long
// press the host took.
enum class Ui { Pending, Pressed, Consumed } ui = Ui::Pending;
};
bool InAttack(float x, float y) const;
bool InJoystickArea(float x, float y) const;
bool InSystemEdge(float x, float y) const;
bool CanReacquireJoystick(float x, float y, std::uint64_t ms) const;
void ReleaseJoystick();
// Drops the orphaned joystick and a deferred attack release (phase change, focus loss).
void ReleaseDeferred();
void UpdateJoystick(float x, float y);
Finger* OtherCameraFinger(std::uint64_t id);
void Release(std::uint64_t id, Finger& finger, bool cancelled);
void UiTap(const Finger& finger, std::uint64_t ms);
TouchSink* m_sink = nullptr;
TouchLayout m_layout;
bool m_world = false;
std::map<std::uint64_t, Finger> m_fingers; // ids are offset by one so 0 means "none"
std::uint64_t m_ui_finger = 0, m_joy_finger = 0, m_attack_finger = 0;
JoystickView m_joy;
float m_joy_touch_x=0, m_joy_touch_y=0;
// Joystick whose finger the system cancelled; still active until m_joy_orphan_ms + reacquire.
bool m_joy_orphan = false;
std::uint64_t m_joy_orphan_ms = 0;
// Attack finger landed since the last Update; a lift before it defers the release to Update.
bool m_attack_fresh = false, m_attack_release_pending = false;
// Last UI tap for double tap detection; m_last_tap_valid is cleared once it pairs.
bool m_last_tap_valid = false;
std::uint64_t m_last_tap_ms = 0;
float m_last_tap_x = 0.0f, m_last_tap_y = 0.0f;
};
// The client's router, shared by the host loop and the Python `touch` module.
TouchRouter& GetTouchRouter();
// Touch mode: on for Android/iOS, or desktop with --touch (mouse emulates one finger).
bool IsTouchMode();
void SetTouchMode(bool enabled);
} // namespace ava2::input
+37 -2409
View File
File diff suppressed because it is too large Load Diff
+199
View File
@@ -0,0 +1,199 @@
#include "platform.h"
#include <SDL3/SDL.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <stdexcept>
namespace ava2::platform {
bool EnterClientDataDirectory(std::string* error) {
#if defined(SDL_PLATFORM_IOS)
// Like the APK, the .app holds code only. The flattened client root (ios/push_assets.py, or
// copied in with Finder / the Files app — Info.plist enables file sharing) lives in Documents.
const char* data = SDL_GetUserFolder(SDL_FOLDER_DOCUMENTS);
std::error_code ec;
if (data) std::filesystem::current_path(data, ec);
if (!data || ec) {
if (error) *error = std::string("Cannot enter client data directory: ") + (data ? ec.message() : SDL_GetError());
return false;
}
SDL_Log("Client data: %s", data);
#elif defined(__APPLE__)
// Keep legacy Python's relative config/chat writes outside the signed application.
try {
std::filesystem::path base = std::filesystem::path(SDL_GetBasePath()).lexically_normal();
if (base.filename().empty()) base = base.parent_path();
// SDL on macOS returns the bundle's Resources directory by default.
if (base.filename() == "Resources" && base.parent_path().filename() == "Contents")
base = base.parent_path() / "MacOS";
const auto resources = base / "../Resources";
if (base.filename() == "MacOS" && std::filesystem::is_directory(resources)) {
std::filesystem::path data;
if (const char* overridePath = std::getenv("AVA2_USER_DATA_DIR")) data = overridePath;
else {
char* preferences = SDL_GetPrefPath("AVA2", "Client");
if (!preferences) throw std::runtime_error(SDL_GetError());
data = preferences; SDL_free(preferences);
}
std::filesystem::create_directories(data);
for (const auto& entry : std::filesystem::directory_iterator(resources)) {
const auto name = entry.path().filename();
const auto extension = name.extension().string();
if (name == "lib" || extension == ".cfg" || extension == ".inf" || extension == ".chat") continue;
const auto link = data / name;
const auto target = std::filesystem::canonical(entry.path());
if (std::filesystem::is_symlink(link) && std::filesystem::read_symlink(link) != target)
std::filesystem::remove(link);
if (!std::filesystem::exists(link)) std::filesystem::create_symlink(target, link);
}
std::filesystem::current_path(data);
SDL_Log("Client user data: %s", data.string().c_str());
}
} catch (const std::exception& e) {
if (error) *error = std::string("Cannot initialize client data directory: ") + e.what();
return false;
}
#elif defined(__ANDROID__)
// The APK holds code only. The flattened client root (assets/loose + python-root + python27.zip,
// android/push_assets.py) lives in the app's external files directory; the legacy code reads
// paths relative to the working directory.
const char* data = SDL_GetAndroidExternalStoragePath();
std::error_code ec;
if (data) std::filesystem::current_path(data, ec);
if (!data || ec) {
if (error) *error = std::string("Cannot enter client data directory: ") + (data ? ec.message() : SDL_GetError());
return false;
}
SDL_Log("Client data: %s", data);
#else
(void)error;
#endif
return true;
}
std::string ConfigDirectory() {
#ifdef __ANDROID__
// metin2.cfg / interface.cfg live in the client's working directory on Windows; the APK's
// working directory is not writable, so they go to the app's internal storage instead.
if (const char* internal = SDL_GetAndroidInternalStoragePath()) return internal;
#endif
return {};
}
namespace {
bool SDLCALL LifecycleWatch(void* userdata, SDL_Event* event) {
static_cast<Lifecycle*>(userdata)->OnEvent(event->type);
return true;
}
} // namespace
void Lifecycle::SetHints() {
// Keep the loop (and the game connection) alive while paused; rendering and sound stop.
SDL_SetHint(SDL_HINT_ANDROID_BLOCK_ON_PAUSE, "0");
}
void Lifecycle::Install() {
if (m_installed) return;
m_installed = SDL_AddEventWatch(LifecycleWatch, this);
}
void Lifecycle::Uninstall() {
if (!m_installed) return;
SDL_RemoveEventWatch(LifecycleWatch, this);
m_installed = false;
}
void Lifecycle::OnEvent(unsigned int type) {
switch (type) {
case SDL_EVENT_WILL_ENTER_BACKGROUND:
case SDL_EVENT_DID_ENTER_BACKGROUND:
if (!m_background.exchange(true)) m_enteredBackground = true;
break;
case SDL_EVENT_WILL_ENTER_FOREGROUND:
case SDL_EVENT_DID_ENTER_FOREGROUND:
if (m_background.exchange(false)) m_enteredForeground = true;
break;
case SDL_EVENT_LOW_MEMORY: m_lowMemory = true; break;
case SDL_EVENT_TERMINATING: m_terminating = true; break;
default: break;
}
}
Lifecycle::Change Lifecycle::Poll() {
if (m_enteredBackground.exchange(false)) {
// A resume that already happened is reported on the next poll.
return Change::EnterBackground;
}
if (m_enteredForeground.exchange(false)) return Change::EnterForeground;
return Change::None;
}
SafeInsets MapSafeInsets(float windowW, float windowH, float safeX, float safeY, float safeW, float safeH,
float logicalW, float logicalH) {
SafeInsets out;
if (windowW <= 0.0f || windowH <= 0.0f || logicalW <= 0.0f || logicalH <= 0.0f) return out;
// Letterbox: uniform scale, centred.
const float scale = std::min(windowW / logicalW, windowH / logicalH);
const float offX = (windowW - logicalW * scale) * 0.5f;
const float offY = (windowH - logicalH * scale) * 0.5f;
auto clampInset = [](float v, float limit) { return std::clamp(v, 0.0f, limit); };
out.left = clampInset((safeX - offX) / scale, logicalW);
out.top = clampInset((safeY - offY) / scale, logicalH);
out.right = clampInset((offX + logicalW * scale - (safeX + safeW)) / scale, logicalW);
out.bottom = clampInset((offY + logicalH * scale - (safeY + safeH)) / scale, logicalH);
return out;
}
LogicalSize ChooseMobileLogicalSize(float pixelW, float pixelH, float density, int uiHeight) {
if (pixelW <= 0.0f || pixelH <= 0.0f) return {1024, 768};
if (pixelW < pixelH) std::swap(pixelW, pixelH); // the activity is landscape
if (density <= 0.0f) density = 1.0f;
const float aspect = pixelW / pixelH;
int height = uiHeight > 0 ? std::clamp(uiHeight, 600, 1080)
: std::clamp(int(std::lround(pixelH / density * 1.5f)), 600, 768);
int width = int(std::lround(height * aspect)) & ~1;
if (width < 1024) {
width = 1024;
height = int(std::lround(1024.0f / aspect)) & ~1;
}
return {width, height};
}
bool QueryDisplay(float* pixelW, float* pixelH, float* density) {
const SDL_DisplayID display = SDL_GetPrimaryDisplay();
const SDL_DisplayMode* mode = display ? SDL_GetCurrentDisplayMode(display) : nullptr;
if (!mode || mode->w <= 0 || mode->h <= 0) return false;
const float pd = mode->pixel_density > 0.0f ? mode->pixel_density : 1.0f;
*pixelW = float(mode->w) * pd;
*pixelH = float(mode->h) * pd;
// Android: content scale = DisplayMetrics.density (dp -> px); desktop: the UI scale.
const float scale = SDL_GetDisplayContentScale(display);
*density = scale > 0.0f ? scale : pd;
return true;
}
bool ParsePhoneSpec(const std::string& spec, float* pixelW, float* pixelH, float* density) {
float w = 0.0f, h = 0.0f, d = 1.0f;
char extra = 0;
const int n = std::sscanf(spec.c_str(), "%fx%f@%f%c", &w, &h, &d, &extra);
if ((n != 2 && n != 3) || w <= 0.0f || h <= 0.0f || d <= 0.0f) return false;
*pixelW = w; *pixelH = h; *density = d;
return true;
}
SafeInsets QuerySafeInsets(SDL_Window* window, SDL_Renderer* renderer) {
int ww = 0, wh = 0, lw = 0, lh = 0;
SDL_Rect safe{};
SDL_RendererLogicalPresentation mode;
if (!window || !renderer || !SDL_GetWindowSize(window, &ww, &wh) || !SDL_GetWindowSafeArea(window, &safe) ||
!SDL_GetRenderLogicalPresentation(renderer, &lw, &lh, &mode) || lw <= 0 || lh <= 0)
return {};
return MapSafeInsets(float(ww), float(wh), float(safe.x), float(safe.y), float(safe.w), float(safe.h),
float(lw), float(lh));
}
} // namespace ava2::platform
+91
View File
@@ -0,0 +1,91 @@
#pragma once
// Platform layer for the client host (docs/MOBILE-ARCHITECTURE.md, platform/): data and config
// directories, application lifecycle (background / foreground / low memory / terminate) and the
// screen safe area. Keeps the per-platform #ifdefs out of the main loop.
#include <atomic>
#include <string>
struct SDL_Window;
struct SDL_Renderer;
namespace ava2::platform {
// Enters the client root the legacy code reads relative paths from: on macOS the per-user data
// directory that links the bundle Resources (config/chat writes stay outside the signed app); on
// Android the app's external files directory (android/push_assets.py); on iOS the app's Documents
// folder (ios/push_assets.py). Elsewhere a no-op.
// False with *error set when the directory cannot be entered.
bool EnterClientDataDirectory(std::string* error);
// Where metin2.cfg / interface.cfg are written when the working directory is not writable
// (Android internal storage); empty keeps the working directory.
std::string ConfigDirectory();
// Background/foreground handling. SDL delivers the app events from the OS thread on mobile
// (SDL_AddEventWatch), so the watch only records them; the main loop applies them with Poll().
// Android runs with SDL_ANDROID_BLOCK_ON_PAUSE=0 so the loop keeps pumping the network while
// paused (SDL then waits up to 100 ms per poll).
class Lifecycle {
public:
enum class Change { None, EnterBackground, EnterForeground };
// Sets the hints (before SDL_Init) and installs the event watch (after SDL_Init).
static void SetHints();
void Install();
void Uninstall();
// Records one app event (called by the watch; public for tests).
void OnEvent(unsigned int sdlEventType);
// The next background/foreground transition since the last call (background wins when both
// happened, so a quick pause-resume still saves the config once).
Change Poll();
bool IsBackground() const { return m_background.load(); }
// True once per SDL_EVENT_LOW_MEMORY.
bool TakeLowMemory() { return m_lowMemory.exchange(false); }
bool IsTerminating() const { return m_terminating.load(); }
private:
std::atomic<bool> m_background{false}, m_enteredBackground{false}, m_enteredForeground{false};
std::atomic<bool> m_lowMemory{false}, m_terminating{false};
bool m_installed = false;
};
// Insets of the unobstructed area (notch, rounded corners, gesture bar) in logical UI pixels.
struct SafeInsets {
float left = 0.0f, top = 0.0f, right = 0.0f, bottom = 0.0f;
bool operator==(const SafeInsets& o) const {
return left == o.left && top == o.top && right == o.right && bottom == o.bottom;
}
};
// Maps a window-space safe rectangle into a letterboxed logical presentation of logicalW x
// logicalH inside a windowW x windowH window (SDL_LOGICAL_PRESENTATION_LETTERBOX). Insets that
// fall into the letterbox bars are 0; results are clamped to the logical screen.
SafeInsets MapSafeInsets(float windowW, float windowH, float safeX, float safeY, float safeW, float safeH,
float logicalW, float logicalH);
// SDL_GetWindowSafeArea mapped through the renderer's logical presentation.
SafeInsets QuerySafeInsets(SDL_Window* window, SDL_Renderer* renderer);
// Logical UI size on a phone or tablet (mobile step 5). The original windows are laid out in
// fixed UI pixels for 800x600 and up, so instead of letterboxing metin2.cfg's 1024x768 the UI
// height follows the screen's physical size and the width follows its aspect ratio:
// height = clamp(round(heightInDp * 1.5), 600, 768) — a 48 px HUD button is ~32 dp or more;
// width = height * aspect (landscape, even), at least 1024 (a 4:3 tablet gets 1024x768).
// uiHeight > 0 overrides the height (still clamped to 600..1080).
struct LogicalSize {
int width = 0, height = 0;
bool operator==(const LogicalSize& o) const { return width == o.width && height == o.height; }
};
LogicalSize ChooseMobileLogicalSize(float pixelW, float pixelH, float density, int uiHeight = 0);
// The primary display's pixel size and density (SDL_GetCurrentDisplayMode / content scale);
// false when SDL video is not up.
bool QueryDisplay(float* pixelW, float* pixelH, float* density);
// Parses "WxH" or "WxH@density" (desktop --phone simulation, e.g. 2400x1080@2.75).
bool ParsePhoneSpec(const std::string& spec, float* pixelW, float* pixelH, float* density);
} // namespace ava2::platform
+12
View File
@@ -34,9 +34,13 @@ float InterpolateTimeEvent(const std::vector<TimeEvent>& events, float time, flo
EffectData::EffectData() = default;
EffectData::~EffectData() = default;
// Slashes forward and A-Z lower-cased, like ResourceManager::NormalizePath: the client root is
// staged lower-case on case-sensitive file systems (iOS), and scripts spell names in mixed case
// (d:/ymir work/effect/etc/empire/empire_A.mse).
static std::string NormalizePath(std::string path) {
for (char& c : path) {
if (c == '\\') c = '/';
else if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':' && path[2] == '/') {
path = path.substr(3);
@@ -47,6 +51,14 @@ static std::string NormalizePath(std::string path) {
return path;
}
bool EffectData::ChangeTexture(size_t particleIndex, const std::string& fileName) {
if (particleIndex >= m_particles.size()) return false;
auto& textures = m_particles[particleIndex].particle.texture_files;
if (textures.size() > 1) return false;
textures.assign(1, NormalizePath(fileName));
return true;
}
static std::vector<std::string> TokenizeScript(const std::string& content) {
std::vector<std::string> tokens;
size_t i = 0;
+3
View File
@@ -87,6 +87,9 @@ public:
const float* GetBoundingSpherePosition() const { return m_bounding_sphere_position; }
const std::vector<ParticleElement>& GetParticles() const { return m_particles; }
const std::string& GetSoundFileName() const { return m_sound_filename; }
// CParticleSystemData::ChangeTexture -> CParticleProperty::SetTexture: replaces a single-texture
// particle's image (false for animated multi-texture particles or a missing particle).
bool ChangeTexture(size_t particleIndex, const std::string& fileName);
private:
std::string m_filename;
+7 -5
View File
@@ -16,6 +16,7 @@ EffectInstance::EffectInstance(std::shared_ptr<EffectData> data)
: m_data(std::move(data)) {
if (m_data) {
m_emitters.resize(m_data->GetParticles().size());
for (const auto& pe : m_data->GetParticles()) m_textures.push_back(pe.particle.texture_files);
}
}
@@ -204,8 +205,8 @@ void EffectInstance::Update(float dt) {
it->scale[1] = InterpolateTimeEvent(pe.particle.time_scale_y, t, 1.0f);
// Texture animation
if (pe.particle.texture_files.size() > 1 && pe.particle.tex_ani_delay > 0.001f) {
it->frame_index = static_cast<uint8_t>(std::fmod(it->life / pe.particle.tex_ani_delay, pe.particle.texture_files.size()));
if (m_textures[i].size() > 1 && pe.particle.tex_ani_delay > 0.001f) {
it->frame_index = static_cast<uint8_t>(std::fmod(it->life / pe.particle.tex_ani_delay, m_textures[i].size()));
}
++it;
@@ -250,9 +251,10 @@ void EffectInstance::BuildDrawCommands(const float* viewMatrix, const float* pro
for (size_t pIdx = 0; pIdx < inst.particles.size(); ++pIdx) {
const auto& p = inst.particles[pIdx];
std::string tex = "";
if (!pe.particle.texture_files.empty()) {
size_t frame = p.frame_index % pe.particle.texture_files.size();
tex = pe.particle.texture_files[frame];
const auto& textures = m_textures[i];
if (!textures.empty()) {
size_t frame = p.frame_index % textures.size();
tex = textures[frame];
}
texGroups[tex].push_back(pIdx);
}
+3
View File
@@ -60,6 +60,9 @@ private:
bool m_hasCustomMatrix = false;
std::vector<EmitterInstance> m_emitters;
// CParticleSystemInstance m_kVct_pkImgInst: the texture list is taken when the instance is created,
// so CEffectManager::SetEffectTextures only affects instances created after it.
std::vector<std::vector<std::string>> m_textures;
};
} // namespace ava2
+6
View File
@@ -64,6 +64,12 @@ uint32_t EffectManager::CreateEffect(uint32_t effectId, float x, float y, float
return instId;
}
void EffectManager::SetEffectTextures(uint32_t effectId, const std::vector<std::string>& textures) {
auto it = m_dataCache.find(effectId);
if (it == m_dataCache.end() || !it->second) return; // Tracef("... - NO DATA")
for (size_t i = 0; i < textures.size(); ++i) it->second->ChangeTexture(i, textures[i]);
}
bool EffectManager::DestroyEffectInstance(uint32_t instanceId) {
auto it = m_instances.find(instanceId);
if (it != m_instances.end()) {
+3
View File
@@ -18,6 +18,9 @@ public:
uint32_t CreateEffect(const std::string& filename, float x = 0.0f, float y = 0.0f, float z = 0.0f, float yaw = 0.0f);
uint32_t CreateEffect(uint32_t effectId, float x = 0.0f, float y = 0.0f, float z = 0.0f, float yaw = 0.0f);
// CEffectManager::SetEffectTextures: texture i replaces particle i's image in the shared data.
void SetEffectTextures(uint32_t effectId, const std::vector<std::string>& textures);
bool DestroyEffectInstance(uint32_t instanceId);
void DeleteAllInstances();
bool IsAliveEffect(uint32_t instanceId) const;
+67 -114
View File
@@ -1,127 +1,80 @@
#include "FlyTrace.h"
#include <cmath>
#include <algorithm>
#include <array>
#include <optional>
namespace ava2 {
// Portions Copyright (C) John W. Ratcliff, 2001 (AVA2 SphereLib/frustum.cpp).
// AVA2 GameLib/FlyTrace.cpp: six-vertex triangle strip, camera-eye basis,
// constant diffuse color and width decay. Engine coordinates are already converted.
FlyTrace::FlyTrace() = default;
FlyTrace::~FlyTrace() = default;
void FlyTrace::Create(uint32_t color, float tailLength, float tailSize, bool rectShape) {
m_color = color;
m_tailLength = tailLength > 0.01f ? tailLength : 0.25f;
m_tailSize = tailSize > 0.1f ? tailSize : 10.0f;
m_rectShape = rectShape;
m_history.clear();
void FlyTrace::Create(uint32_t color,float tailLength,float tailSize,bool rectShape) {
m_color=color;m_tailLength=tailLength;m_tailSize=tailSize;m_rectShape=rectShape;m_history.clear();
}
void FlyTrace::Clear(){m_history.clear();m_color=0;m_tailLength=0;m_tailSize=0;m_rectShape=false;}
void FlyTrace::UpdateNewPosition(float x,float y,float z,float currentTime) {
m_history.push_front({currentTime,{x,y,z}});
while(!m_history.empty() && m_history.back().time+m_tailLength<currentTime)m_history.pop_back();
}
namespace {
std::array<float,3> Cross(const std::array<float,3>& a,const std::array<float,3>& b) {
return {a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]};
}
void Normalize(std::array<float,3>& v) {
const float length=std::sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
if(length>0)for(auto& value:v)value/=length;
}
void FlyTrace::Clear() {
m_history.clear();
}
void FlyTrace::UpdateNewPosition(float x, float y, float z, float currentTime) {
TraceNode node;
node.time = currentTime;
node.pos[0] = x;
node.pos[1] = y;
node.pos[2] = z;
m_history.push_front(node);
while (!m_history.empty() && (currentTime - m_history.back().time) > m_tailLength) {
m_history.pop_back();
void FlyTrace::BuildDrawCommands(const float* view,const float* projection,float now,std::vector<Render3DDraw>& out,const ViewFrustum* cachedFrustum,DepthState depthState) {
if(m_history.size()<2 || !view || !projection || !std::isfinite(m_tailLength) || m_tailLength<=0 || !std::isfinite(m_tailSize))return;
std::array<float,3> forward={view[2],view[6],view[10]};Normalize(forward);
// Rigid camera inverse: eye=-R^T * translation.
const std::array<float,3> eye={-(view[0]*view[12]+view[1]*view[13]+view[2]*view[14]),
-(view[4]*view[12]+view[5]*view[13]+view[6]*view[14]),-(view[8]*view[12]+view[9]*view[13]+view[10]*view[14])};
// Standalone callers have no update phase; production passes the UpdateGame snapshot.
std::optional<ViewFrustum> fallback;
if(!cachedFrustum) {
PerspectiveMetadata inferred;const PerspectiveMetadata* metadata=nullptr;
if(projection[11]==1 && projection[15]==0 && projection[8]==0 && projection[9]==0 && projection[0]>0 && projection[5]>0 && projection[10]>1) {
inferred={2*std::atan(1/projection[5])*180/3.14159265358979323846f,projection[5]/projection[0],-projection[14]/projection[10],projection[14]/(1-projection[10])};metadata=&inferred;
}
fallback.emplace(view,projection,eye,forward,metadata);
}
const ViewFrustum& frustum=cachedFrustum?*cachedFrustum:*fallback;
struct Segment {float depth;std::array<float,18> positions;};
std::vector<Segment> segments;
for(size_t index=0;index+1<m_history.size();++index) {
const auto& first=m_history[index];const auto& second=m_history[index+1];
std::array<float,3> b,e;for(int k=0;k<3;++k){b[k]=second.pos[k]-first.pos[k];e[k]=eye[k]-first.pos[k];}
std::array<float,3> center;for(int k=0;k<3;++k)center[k]=first.pos[k]+b[k]*0.5f;
const float radius=std::max({std::abs(b[0]),std::abs(b[1]),std::abs(b[2])})*0.5f;
if(frustum.Outside(center,radius))continue;
const auto p=Cross(b,e);auto up=Cross(forward,p);Normalize(up);const auto right=Cross(forward,up);
// Source does not clamp valid aged rates or fade diffuse alpha.
const float firstSize=m_rectShape?m_tailSize:m_tailSize*(1-(now-first.time)/m_tailLength);
const float secondSize=m_rectShape?m_tailSize:m_tailSize*(1-(now-second.time)/m_tailLength);
const float local[6][2]={{0,firstSize},{-firstSize,0},{firstSize,0},{-secondSize,0},{secondSize,0},{0,-secondSize}};
Segment segment{};for(int k=0;k<3;++k)segment.depth-=e[k]*forward[k];
for(int vertex=0;vertex<6;++vertex)for(int k=0;k<3;++k)
segment.positions[vertex*3+k]=local[vertex][0]*right[k]+local[vertex][1]*up[k]+(vertex<3?first.pos[k]:second.pos[k]);
segments.push_back(segment);
}
std::stable_sort(segments.begin(),segments.end(),[](const auto& a,const auto& b){return a.depth<b.depth;});
Render3DDraw draw;draw.lighting=false;draw.z_enable=depthState.enabled;draw.z_write=depthState.write;draw.depth_less=true;draw.cull_mode=1;
draw.alpha_blend=true;draw.blend_mode=1;draw.alpha_test=true;draw.alpha_ref=0;
std::copy(view,view+16,draw.view);std::copy(projection,projection+16,draw.proj);
for(int k=0;k<16;++k)draw.world[k]=(k%5==0)?1.0f:0.0f;
for(const auto& segment:segments) {
const uint32_t base=uint32_t(draw.positions.size()/3);
draw.positions.insert(draw.positions.end(),segment.positions.begin(),segment.positions.end());
draw.diffuse.insert(draw.diffuse.end(),6,m_color);
draw.uv0.insert(draw.uv0.end(),{0,0,0,0.5f,0.5f,0,0.5f,1,1,0.5f,1,1});
for(uint32_t index:{0u,1u,2u,2u,1u,3u,2u,3u,4u,4u,3u,5u})draw.indices.push_back(base+index);
}
if(!draw.indices.empty())out.push_back(std::move(draw));
}
void FlyTrace::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
if (m_history.size() < 2) return;
Render3DDraw draw;
draw.lighting = false;
draw.z_enable = true;
draw.z_write = false;
draw.cull_mode = 1; // D3DCULL_NONE
draw.alpha_blend = true;
draw.blend_mode = 1; // Additive (D3DBLEND_ONE)
for (int m = 0; m < 16; ++m) {
draw.view[m] = viewMatrix[m];
draw.proj[m] = projMatrix[m];
draw.world[m] = (m % 5 == 0) ? 1.0f : 0.0f;
}
float camDir[3] = {viewMatrix[2], viewMatrix[6], viewMatrix[10]};
float camLen = std::sqrt(camDir[0]*camDir[0] + camDir[1]*camDir[1] + camDir[2]*camDir[2]);
if (camLen > 1e-5f) { camDir[0] /= camLen; camDir[1] /= camLen; camDir[2] /= camLen; }
uint32_t vertexOffset = 0;
for (size_t i = 0; i + 1 < m_history.size(); ++i) {
const auto& n0 = m_history[i];
const auto& n1 = m_history[i + 1];
float age0 = currentTime - n0.time;
float age1 = currentTime - n1.time;
float rate0 = std::clamp(1.0f - age0 / m_tailLength, 0.0f, 1.0f);
float rate1 = std::clamp(1.0f - age1 / m_tailLength, 0.0f, 1.0f);
float s0 = m_rectShape ? m_tailSize : m_tailSize * rate0;
float s1 = m_rectShape ? m_tailSize : m_tailSize * rate1;
// Ribbon segment direction
float seg[3] = {n1.pos[0] - n0.pos[0], n1.pos[1] - n0.pos[1], n1.pos[2] - n0.pos[2]};
float segLen = std::sqrt(seg[0]*seg[0] + seg[1]*seg[1] + seg[2]*seg[2]);
if (segLen < 1e-4f) continue;
// Normal perpendicular to segment and camera look
float norm[3] = {
seg[1] * camDir[2] - seg[2] * camDir[1],
seg[2] * camDir[0] - seg[0] * camDir[2],
seg[0] * camDir[1] - seg[1] * camDir[0]
};
float normLen = std::sqrt(norm[0]*norm[0] + norm[1]*norm[1] + norm[2]*norm[2]);
if (normLen > 1e-5f) {
norm[0] /= normLen; norm[1] /= normLen; norm[2] /= normLen;
}
// Vertices for this quad segment
float v0[3] = {n0.pos[0] + norm[0] * s0, n0.pos[1] + norm[1] * s0, n0.pos[2] + norm[2] * s0};
float v1[3] = {n0.pos[0] - norm[0] * s0, n0.pos[1] - norm[1] * s0, n0.pos[2] - norm[2] * s0};
float v2[3] = {n1.pos[0] - norm[0] * s1, n1.pos[1] - norm[1] * s1, n1.pos[2] - norm[2] * s1};
float v3[3] = {n1.pos[0] + norm[0] * s1, n1.pos[1] + norm[1] * s1, n1.pos[2] + norm[2] * s1};
uint8_t baseA = (m_color >> 24) & 0xFF;
uint8_t baseR = (m_color >> 16) & 0xFF;
uint8_t baseG = (m_color >> 8) & 0xFF;
uint8_t baseB = m_color & 0xFF;
uint8_t a0 = static_cast<uint8_t>(baseA * rate0);
uint8_t a1 = static_cast<uint8_t>(baseA * rate1);
uint32_t diff0 = (static_cast<uint32_t>(a0) << 24) | (static_cast<uint32_t>(baseR) << 16) | (static_cast<uint32_t>(baseG) << 8) | baseB;
uint32_t diff1 = (static_cast<uint32_t>(a1) << 24) | (static_cast<uint32_t>(baseR) << 16) | (static_cast<uint32_t>(baseG) << 8) | baseB;
draw.positions.insert(draw.positions.end(), {v0[0], v0[1], v0[2]});
draw.positions.insert(draw.positions.end(), {v1[0], v1[1], v1[2]});
draw.positions.insert(draw.positions.end(), {v2[0], v2[1], v2[2]});
draw.positions.insert(draw.positions.end(), {v3[0], v3[1], v3[2]});
draw.diffuse.insert(draw.diffuse.end(), {diff0, diff0, diff1, diff1});
draw.uv0.insert(draw.uv0.end(), {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f});
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 1);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 3);
vertexOffset += 4;
}
if (!draw.indices.empty()) {
outDraws.push_back(std::move(draw));
}
}
} // namespace ava2
+5 -4
View File
@@ -1,6 +1,7 @@
#pragma once
#include "eter_render/RenderCommands3D.h"
#include "eter_render/ViewFrustum.h"
#include <deque>
#include <vector>
#include <cstdint>
@@ -16,7 +17,7 @@ public:
void UpdateNewPosition(float x, float y, float z, float currentTime);
void Clear();
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws, const ViewFrustum* cachedFrustum = nullptr, DepthState depthState = {});
bool IsEmpty() const { return m_history.size() < 2; }
@@ -26,9 +27,9 @@ private:
float pos[3] = {0.0f, 0.0f, 0.0f};
};
uint32_t m_color = 0xFFFFFFFF;
float m_tailLength = 0.25f;
float m_tailSize = 10.0f;
uint32_t m_color = 0;
float m_tailLength = 0;
float m_tailSize = 0;
bool m_rectShape = false;
std::deque<TraceNode> m_history;
+306 -91
View File
@@ -1,9 +1,14 @@
#include "FlyingManager.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <filesystem>
#include "eter_base/Random.h"
#include "eter_net/NetworkActorManager.h"
#include "eter_render/MapObjectManager.h"
namespace ava2 {
@@ -84,6 +89,7 @@ bool FlyingData::LoadScriptFile(const std::string& filepath) {
dir = filepath.substr(0, lastSlash + 1);
}
attachments.clear();attach=FlyingAttachData();
auto tokens = TokenizeScript(content);
size_t idx = 0;
size_t numTokens = tokens.size();
@@ -99,6 +105,8 @@ bool FlyingData::LoadScriptFile(const std::string& filepath) {
acceleration[0] = std::stof(tokens[idx++]);
acceleration[1] = std::stof(tokens[idx++]);
acceleration[2] = std::stof(tokens[idx++]);
} else if (key == "angularvelocity" && idx + 2 < numTokens) {
for(int k=0;k<3;++k)angular_velocity[k]=std::stof(tokens[idx++]);
} else if (key == "bombrange" && idx < numTokens) {
bomb_range = std::stof(tokens[idx++]);
} else if (key == "bombeffect" && idx < numTokens) {
@@ -112,11 +120,28 @@ bool FlyingData::LoadScriptFile(const std::string& filepath) {
homing_flag = (std::stoi(tokens[idx++]) != 0);
} else if (key == "homingmaxangle" && idx < numTokens) {
homing_max_angle = std::stof(tokens[idx++]);
} else if (key == "hitonbackground" && idx < numTokens) {
hit_on_background=std::stoi(tokens[idx++])!=0;
} else if (key == "hitonanothermonster" && idx < numTokens) {
hit_on_another_monster=std::stoi(tokens[idx++])!=0;
} else if (key == "spreadingflag" && idx < numTokens) {
spreading = std::stoi(tokens[idx++]) != 0;
} else if (key == "rollangle" && idx < numTokens) {
roll_angle = std::stof(tokens[idx++]);
} else if (key == "coneangle" && idx < numTokens) {
cone_angle = std::stof(tokens[idx++]);
} else if (key == "homingstarttime" && idx < numTokens) {
homing_start_time = std::stof(tokens[idx++]);
} else if (key == "piercecount" && idx < numTokens) {
pierce_count = std::stoi(tokens[idx++]);
} else if (key == "maintainparallelflag" && idx < numTokens) {
maintain_parallel = std::stoi(tokens[idx++]) != 0;
} else if (key == "range" && idx < numTokens) {
range = std::stof(tokens[idx++]);
} else if (key == "group" && idx < numTokens && ToLower(tokens[idx]) == "attachdata") {
idx++; // skip attachdata
if (idx < numTokens && tokens[idx] == "{") idx++;
FlyingAttachData entry;
int aDepth = 1;
while (idx < numTokens && aDepth > 0) {
@@ -125,39 +150,78 @@ bool FlyingData::LoadScriptFile(const std::string& filepath) {
std::string aKey = ToLower(tokens[idx++]);
if (aKey == "type" && idx < numTokens) {
attach.type = std::stoi(tokens[idx++]);
entry.type = std::stoi(tokens[idx++]);
} else if (aKey == "flytype" && idx < numTokens) {
attach.fly_type = std::stoi(tokens[idx++]);
entry.fly_type = std::stoi(tokens[idx++]);
} else if (aKey == "attachfile" && idx < numTokens) {
std::string att = NormalizePath(tokens[idx++]);
if (!dir.empty() && !std::filesystem::exists(att)) {
std::string candidate = NormalizePath(dir + att);
if (std::filesystem::exists(candidate)) att = candidate;
}
attach.attach_file = att;
entry.attach_file = att;
} else if (aKey == "tailflag" && idx < numTokens) {
attach.has_tail = (std::stoi(tokens[idx++]) != 0);
entry.has_tail = (std::stoi(tokens[idx++]) != 0);
} else if (aKey == "tailcolor" && idx < numTokens) {
std::string cStr = tokens[idx++];
if (!cStr.empty() && (cStr.back() == 'd' || cStr.back() == 'D')) {
cStr.pop_back();
}
attach.tail_color = static_cast<uint32_t>(std::stoul(cStr));
entry.tail_color = static_cast<uint32_t>(std::stoul(cStr));
} else if (aKey == "taillength" && idx < numTokens) {
attach.tail_length = std::stof(tokens[idx++]);
entry.tail_length = std::stof(tokens[idx++]);
} else if (aKey == "tailsize" && idx < numTokens) {
attach.tail_size = std::stof(tokens[idx++]);
entry.tail_size = std::stof(tokens[idx++]);
} else if (aKey == "roll" && idx < numTokens) {
entry.roll=std::stof(tokens[idx++]);
} else if (aKey == "distance" && idx < numTokens) {
entry.distance=std::stof(tokens[idx++]);
} else if (aKey == "period" && idx < numTokens) {
entry.period=std::stof(tokens[idx++]);
} else if (aKey == "amplitude" && idx < numTokens) {
entry.amplitude=std::stof(tokens[idx++]);
} else if (aKey == "tailshaperect" && idx < numTokens) {
attach.rect_shape = (std::stoi(tokens[idx++]) != 0);
entry.rect_shape = (std::stoi(tokens[idx++]) != 0);
}
}
attachments.push_back(entry);if(attachments.size()==1)attach=entry;
}
}
return true;
}
FlyingInstance::FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos)
: m_data(std::move(data)) {
namespace {
void RotateQuaternion(const float* q,float* v) {
float cross[3]={q[1]*v[2]-q[2]*v[1],q[2]*v[0]-q[0]*v[2],q[0]*v[1]-q[1]*v[0]};
float second[3]={q[1]*cross[2]-q[2]*cross[1],q[2]*cross[0]-q[0]*cross[2],q[0]*cross[1]-q[1]*cross[0]};
for(int k=0;k<3;++k)v[k]+=2*(q[3]*cross[k]+second[k]);
}
// D3DXQuaternionMultiply(first,second): apply first, then second (second * first).
void Compose(const float* a,const float* b,float* out) {
float q[4]={b[3]*a[0]+b[0]*a[3]+b[1]*a[2]-b[2]*a[1],
b[3]*a[1]-b[0]*a[2]+b[1]*a[3]+b[2]*a[0],
b[3]*a[2]+b[0]*a[1]-b[1]*a[0]+b[2]*a[3],
b[3]*a[3]-b[0]*a[0]-b[1]*a[1]-b[2]*a[2]};std::copy(q,q+4,out);
}
void NativeYawPitchRoll(float yaw,float pitch,float roll,float* out) {
const float c=3.14159265358979323846f/360;
const float cy=std::cos(yaw*c),sy=std::sin(yaw*c),cp=std::cos(pitch*c),sp=std::sin(pitch*c),cr=std::cos(roll*c),sr=std::sin(roll*c);
out[0]=cy*sp*cr+sy*cp*sr;out[1]=cy*cp*sr-sy*sp*cr;
out[2]=-(sy*cp*cr-cy*sp*sr);out[3]=cy*cp*cr+sy*sp*sr;
}
void QuaternionMatrix(const float* q,const float* position,float* out) {
const float x=q[0],y=q[1],z=q[2],w=q[3];
std::fill(out,out+16,0.0f);out[15]=1;
out[0]=1-2*y*y-2*z*z;out[1]=2*x*y+2*z*w;out[2]=2*x*z-2*y*w;
out[4]=2*x*y-2*z*w;out[5]=1-2*x*x-2*z*z;out[6]=2*y*z+2*x*w;
out[8]=2*x*z+2*y*w;out[9]=2*y*z-2*x*w;out[10]=1-2*x*x-2*y*y;
std::copy(position,position+3,out+12);
}
}
FlyingInstance::FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos, FlyTargetResolver targetResolver)
: m_data(std::move(data)), m_targetResolver(std::move(targetResolver)) {
if (startPos) {
m_position[0] = startPos[0];
m_position[1] = startPos[1];
@@ -169,107 +233,224 @@ FlyingInstance::FlyingInstance(std::shared_ptr<FlyingData> data, const float* st
m_targetPosition[2] = targetPos[2];
}
if(m_targetResolver && !m_targetResolver(m_targetPosition)) m_targetResolver={};
m_remainingRange=m_data?m_data->range:10000;
m_pierceCount=m_data?m_data->pierce_count:0;
if(m_data) { // MSF acceleration is native Z-up, gravity is direct acceleration.
m_acceleration[0]=m_data->acceleration[0];
m_acceleration[1]=m_data->acceleration[2];
m_acceleration[2]=-m_data->acceleration[1];
}
float dir[3] = {
m_targetPosition[0] - m_position[0],
m_targetPosition[1] - m_position[1],
m_targetPosition[1] - m_position[1] + ((m_data && m_data->maintain_parallel)?50:0),
m_targetPosition[2] - m_position[2]
};
float len = std::sqrt(dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]);
float speed = m_data ? m_data->initial_velocity : 1000.0f;
if (speed < 100.0f) speed = 1000.0f;
if (len > 1e-4f) {
m_velocity[0] = (dir[0] / len) * speed;
m_velocity[1] = (dir[1] / len) * speed;
m_velocity[2] = (dir[2] / len) * speed;
for(int k=0;k<3;++k)dir[k]/=len;
// __SetDataPointer uses native RotationYawPitchRoll(roll-90,0,cone),
// followed by __SetTargetDirection's arc from native (0,-1,0).
const float yaw=((m_data?m_data->roll_angle:0)-90)*3.14159265358979323846f/360;
const float cone=(m_data?m_data->cone_angle:0)*3.14159265358979323846f/360;
const float initial[4]={std::sin(yaw)*std::sin(cone),std::cos(yaw)*std::sin(cone),-std::sin(yaw)*std::cos(cone),std::cos(yaw)*std::cos(cone)};
m_velocity[2]=speed;
std::copy(initial,initial+4,m_orientation);
if(m_data && m_data->spreading) {
// FlyingInstance::__SetDataPointer. D3DX Multiply(Q1,Q2) applies Q1
// then Q2: Z spread -> negative-Y spin -> initial roll/cone -> target arc.
const float first=eter::frandom(-3.141592f/3,+3.141592f/3);
const float second=eter::frandom(-3.141592f/3,+3.141592f/3);
const float spread=(first+second)/4;
const float spin=eter::frandom(0,2*3.14159265358979323846f)/2;
const float spreadRotation[4]={0,std::sin(spread),0,std::cos(spread)};
const float spinRotation[4]={0,0,std::sin(spin),std::cos(spin)};
RotateQuaternion(spreadRotation,m_velocity);RotateQuaternion(spreadRotation,m_acceleration);
RotateQuaternion(spinRotation,m_velocity);RotateQuaternion(spinRotation,m_acceleration);
float spreading[4];Compose(spreadRotation,spinRotation,spreading);Compose(spreading,initial,m_orientation);
}
RotateQuaternion(initial,m_velocity);RotateQuaternion(initial,m_acceleration);
float arc[4]={0,1,0,0};
if(dir[2]>-1) {
const float scale=std::sqrt((1+dir[2])*2);
arc[0]=-dir[1]/scale;arc[1]=dir[0]/scale;arc[2]=0;arc[3]=scale*0.5f;
}
RotateQuaternion(arc,m_velocity);RotateQuaternion(arc,m_acceleration);Compose(m_orientation,arc,m_orientation);
} else {
m_velocity[0] = speed;
m_velocity[1] = 0.0f;
m_velocity[2] = 0.0f;
std::fill(m_velocity,m_velocity+3,0.0f);
}
if (m_data) {
if (!m_data->attach.attach_file.empty()) {
m_attachedEffectId = EffectManager::Instance().CreateEffect(m_data->attach.attach_file, m_position[0], m_position[1], m_position[2]);
}
if (m_data->attach.has_tail) {
m_tail.Create(m_data->attach.tail_color, m_data->attach.tail_length, m_data->attach.tail_size, m_data->attach.rect_shape);
if(m_data) {
auto definitions=m_data->attachments;
if(definitions.empty())definitions.push_back(m_data->attach);
m_attachments.reserve(definitions.size());
for(const auto& definition:definitions) {
if(definition.type!=1)continue; // Source FLY_ATTACH_OBJECT is itself unimplemented.
m_attachments.emplace_back();auto& entry=m_attachments.back();entry.data=definition;
if(!definition.attach_file.empty())entry.effect=EffectManager::Instance().CreateEffect(definition.attach_file,m_position[0],m_position[1],m_position[2]);
if(definition.has_tail)entry.tail.Create(definition.tail_color,definition.tail_length,definition.tail_size,definition.rect_shape);
}
}
UpdateAttachments(0,0);
}
FlyingInstance::~FlyingInstance() {
if (m_attachedEffectId != 0) {
EffectManager::Instance().DestroyEffectInstance(m_attachedEffectId);
m_attachedEffectId = 0;
}
FlyingInstance::~FlyingInstance() {ClearAttachments();}
void FlyingInstance::ClearAttachments() {
for(auto& entry:m_attachments){if(entry.effect)EffectManager::Instance().DestroyEffectInstance(entry.effect);entry.effect=0;entry.tail.Clear();}
}
bool FlyingInstance::Update(float dt, float currentTime) {
if (!m_isAlive) return false;
m_age += dt;
// Move
m_position[0] += m_velocity[0] * dt;
m_position[1] += m_velocity[1] * dt;
m_position[2] += m_velocity[2] * dt;
if (m_data) {
m_velocity[0] += m_data->acceleration[0] * dt;
m_velocity[1] += m_data->acceleration[1] * dt;
m_velocity[2] += (m_data->acceleration[2] - m_data->gravity * 9.8f) * dt;
if (m_data->homing_flag) {
float toTarget[3] = {
m_targetPosition[0] - m_position[0],
m_targetPosition[1] - m_position[1],
m_targetPosition[2] - m_position[2]
};
float tLen = std::sqrt(toTarget[0]*toTarget[0] + toTarget[1]*toTarget[1] + toTarget[2]*toTarget[2]);
if (tLen > 1e-4f) {
float curSpeed = std::sqrt(m_velocity[0]*m_velocity[0] + m_velocity[1]*m_velocity[1] + m_velocity[2]*m_velocity[2]);
float steer = std::min(1.0f, m_data->homing_max_angle * dt * 0.5f);
m_velocity[0] = m_velocity[0] * (1.0f - steer) + (toTarget[0] / tLen) * curSpeed * steer;
m_velocity[1] = m_velocity[1] * (1.0f - steer) + (toTarget[1] / tLen) * curSpeed * steer;
m_velocity[2] = m_velocity[2] * (1.0f - steer) + (toTarget[2] / tLen) * curSpeed * steer;
void FlyingInstance::UpdateAttachments(float dt,float currentTime) {
float increment[4]={0,0,0,1};
if(m_data)NativeYawPitchRoll(m_data->angular_velocity[1]*dt,m_data->angular_velocity[0]*dt,m_data->angular_velocity[2]*dt,increment);
Compose(m_attachRotation,increment,m_attachRotation);
float combined[4];Compose(m_attachRotation,m_orientation,combined);
for(auto& entry:m_attachments) {
const auto& definition=entry.data;float position[3];std::copy(m_position,m_position+3,position);
const float* rotation=m_orientation;
float amount=0;
if(definition.fly_type!=1) {
rotation=combined;
if(definition.fly_type==2)amount=definition.distance;
else if(definition.period>0 && std::isfinite(definition.period)) {
const float phase=m_age/definition.period;
if(definition.fly_type==3)amount=definition.amplitude*std::sin(phase*2*3.14159265358979323846f);
else if(definition.fly_type==4)amount=definition.amplitude*std::exp(-phase)*phase;
}
const float roll=definition.roll*3.14159265358979323846f/180;
float offset[3]={-std::sin(roll)*amount,-std::cos(roll)*amount,0};
RotateQuaternion(rotation,offset);for(int k=0;k<3;++k)position[k]+=offset[k];
}
if(entry.effect){float matrix[16];QuaternionMatrix(rotation,position,matrix);EffectManager::Instance().SetEffectInstanceGlobalMatrix(entry.effect,matrix);}
if(definition.has_tail)entry.tail.UpdateNewPosition(position[0],position[1],position[2],currentTime);
}
}
namespace {
float Length(const float* v) {return std::sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);}
// GrpMath SafeRotationNormalizedArc / FlyingInstance::AdjustDirectionForHoming.
// The source clamps quaternion HALF-angle, once per update (not multiplied by dt).
void Home(float* velocity,float* acceleration,const float* position,const float* target,float maxAngle,float* orientation) {
float from[3],to[3];for(int k=0;k<3;++k){from[k]=velocity[k];to[k]=target[k]-position[k];}
const float a=Length(from),b=Length(to);if(a==0 || b==0)return;
float diff=0,dot=0;for(int k=0;k<3;++k){from[k]/=a;to[k]/=b;diff+=(from[k]-to[k])*(from[k]-to[k]);dot+=from[k]*to[k];}
if(diff<0.001f)return;
dot=std::clamp(dot,-1.0f,1.0f);
float q[4]={0,1,0,0}; // native Z-axis becomes engine Y for exact antiparallel.
if(dot>-1) {
const float scale=std::sqrt((1+dot)*2);
q[0]=(from[1]*to[2]-from[2]*to[1])/scale;
q[1]=(from[2]*to[0]-from[0]*to[2])/scale;
q[2]=(from[0]*to[1]-from[1]*to[0])/scale;q[3]=scale*0.5f;
}
if(maxAngle<=180) {
const float angle=maxAngle*3.14159265358979323846f/180,c=std::cos(angle),sn=std::sin(angle);
if(q[3]<=c && q[3]<=1-0.0001f) {
const float factor=sn/std::sqrt(1-q[3]*q[3]);
for(int k=0;k<3;++k)q[k]*=factor;q[3]=c;
}
}
if (m_attachedEffectId != 0) {
EffectManager::Instance().SetEffectInstancePosition(m_attachedEffectId, m_position[0], m_position[1], m_position[2]);
RotateQuaternion(q,velocity);RotateQuaternion(q,acceleration);
if(maxAngle>180)Compose(q,orientation,orientation);else Compose(orientation,q,orientation);
}
float SegmentDistanceSquared(const float* start,const float* end,const float* point) {
float length=0,dot=0;for(int k=0;k<3;++k){const float d=end[k]-start[k];length+=d*d;dot+=(point[k]-start[k])*d;}
const float t=length>0?std::clamp(dot/length,0.0f,1.0f):0;
float distance=0;for(int k=0;k<3;++k){const float d=point[k]-start[k]-t*(end[k]-start[k]);distance+=d*d;}return distance;
}
// GameUtil DetectCollisionDynamicSphereVSDynamicSphere: closest points on
// the two swept sphere-center segments, inclusive sum-of-radii boundary.
float SegmentSegmentDistanceSquared(const float* a,const float* b,const float* c,const float* d) {
float u[3],v[3],r[3];float uu=0,vv=0,uv=0,ur=0,vr=0;
for(int k=0;k<3;++k){u[k]=b[k]-a[k];v[k]=d[k]-c[k];r[k]=a[k]-c[k];uu+=u[k]*u[k];vv+=v[k]*v[k];uv+=u[k]*v[k];ur+=u[k]*r[k];vr+=v[k]*r[k];}
float s=0,t=0;
if(uu==0 && vv==0)return SegmentDistanceSquared(a,b,c);
if(uu==0)t=std::clamp(vr/vv,0.0f,1.0f);
else if(vv==0)s=std::clamp(-ur/uu,0.0f,1.0f);
else {
const float denom=uu*vv-uv*uv;
if(denom>0)s=std::clamp((uv*vr-ur*vv)/denom,0.0f,1.0f);
t=(uv*s+vr)/vv;
if(t<0){t=0;s=std::clamp(-ur/uu,0.0f,1.0f);}
else if(t>1){t=1;s=std::clamp((uv-ur)/uu,0.0f,1.0f);}
}
m_tail.UpdateNewPosition(m_position[0], m_position[1], m_position[2], currentTime);
float result=0;for(int k=0;k<3;++k){const float delta=r[k]+s*u[k]-t*v[k];result+=delta*delta;}return result;
}
// Distance check to target
float d[3] = {m_targetPosition[0] - m_position[0], m_targetPosition[1] - m_position[1], m_targetPosition[2] - m_position[2]};
float dist = std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
float hitThreshold = m_data ? std::max(m_data->bomb_range, 25.0f) : 25.0f;
}
if (dist <= hitThreshold || m_age > 5.0f) {
// Hit target
m_isAlive = false;
if (m_data && !m_data->bomb_effect.empty()) {
EffectManager::Instance().CreateEffect(m_data->bomb_effect, m_position[0], m_position[1], m_position[2]);
void FlyingInstance::Bomb() {
if(m_data && !m_data->bomb_effect.empty())EffectManager::Instance().CreateEffect(m_data->bomb_effect,m_position[0],m_position[1],m_position[2]);
}
bool FlyingInstance::Explode(bool bomb) {
m_isAlive=false;if(bomb)Bomb();
ClearAttachments();
return false;
}
bool FlyingInstance::Update(float dt,float currentTime,const TerrainHeightSource* terrain,const MapObjectManager* objects,const std::function<float(float,float)>& groundHeight) {
if(!m_isAlive)return false;
if(dt<0 || !std::isfinite(dt))return true;
// CFlyTarget::NotifyTargetClear converts the object to its last sampled position.
if(m_targetResolver && !m_targetResolver(m_targetPosition))m_targetResolver={};
m_age+=dt;
if(m_data && m_data->homing_flag && m_targetResolver && m_age>m_data->homing_start_time)
Home(m_velocity,m_acceleration,m_position,m_targetPosition,m_data->homing_max_angle,m_orientation);
float last[3];std::copy(m_position,m_position+3,last);
float movement[3];
for(int k=0;k<3;++k){m_velocity[k]+=m_acceleration[k]*dt;}
if(m_data)m_velocity[1]+=m_data->gravity*dt;
for(int k=0;k<3;++k){movement[k]=m_velocity[k]*dt;m_position[k]+=movement[k];}
m_remainingRange-=Length(movement);
UpdateAttachments(dt,currentTime);
if(m_remainingRange<0) {if(m_rangeCallback)m_rangeCallback();return Explode(false);}
const float radius=m_data?m_data->bomb_range:10;
if((!m_targetResolver || !m_targetHit) && SegmentDistanceSquared(last,m_position,m_targetPosition)<radius*radius) {
if(m_targetResolver) {
m_targetHit=true;
if(m_targetHitCallback)m_targetHitCallback();
if(m_hitCallback)m_hitCallback(m_position);
if(m_pierceCount) {--m_pierceCount;Bomb();return true;}
} else if(m_hitCallback)m_hitCallback(m_position); // Existing native position callback.
return Explode(true);
}
if(m_data && m_data->hit_on_another_monster) {
auto& manager=NetworkActorManager::Instance();
std::vector<uint32_t> vids;for(const auto& [vid,data]:manager.GetActorDict())vids.push_back(vid);
std::sort(vids.begin(),vids.end()); // deterministic fallback; source culling traversal is not yet ported.
const std::owner_less<std::weak_ptr<const uint8_t>> less;
for(auto vid:vids) {
auto instance=manager.GetActorInstance(vid);if(!instance)continue;
const auto identity=instance->GetFlyCollisionIdentity();
if(!less(identity,m_collision.owner) && !less(m_collision.owner,identity))continue;
bool collided=false;
for(const auto& sphere:instance->GetBodyCollisionSpheres()) {
const float radius=10+sphere.radius;
if(SegmentSegmentDistanceSquared(last,m_position,sphere.lastPosition.data(),sphere.position.data())<=radius*radius){collided=true;break;}
}
if(!collided)continue;
// Source chooses its first colliding object BEFORE checking the hit set.
// An already hit object can mask another candidate; retain that ordering.
if(m_hitObjects.insert(identity).second) {
if(m_collision.onAnotherTarget)m_collision.onAnotherTarget(vid);
if(m_pierceCount){--m_pierceCount;Bomb();return true;}
return Explode(true);
}
break;
}
if (m_attachedEffectId != 0) {
EffectManager::Instance().DestroyEffectInstance(m_attachedEffectId);
m_attachedEffectId = 0;
}
if(m_data && m_data->hit_on_background) {
const bool ground=(groundHeight && groundHeight(m_position[0],m_position[2])>m_position[1])
|| (!groundHeight && terrain && terrain->GetHeightAtWorld(m_position[0],m_position[2])>m_position[1]);
if(ground || (objects && objects->CheckFlyingCollision(last,m_position,1))) {
if(m_collision.onBackground)m_collision.onBackground();
return Explode(true);
}
if (m_hitCallback) {
m_hitCallback(m_position);
}
return false;
}
return true;
}
void FlyingInstance::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
if (!m_tail.IsEmpty()) {
m_tail.BuildDrawCommands(viewMatrix, projMatrix, currentTime, outDraws);
}
void FlyingInstance::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws,const ViewFrustum* cachedFrustum,DepthState depthState) {
for(auto& entry:m_attachments)if(!entry.tail.IsEmpty())entry.tail.BuildDrawCommands(viewMatrix,projMatrix,currentTime,outDraws,cachedFrustum,depthState);
}
FlyingManager& FlyingManager::Instance() {
@@ -313,13 +494,13 @@ bool FlyingManager::RegisterIndexedFlyData(uint32_t index, uint8_t type, const s
return true;
}
uint32_t FlyingManager::CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb) {
uint32_t FlyingManager::CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb, FlyTargetResolver targetResolver, std::function<void()> targetHitCb,FlyCollisionCallbacks collision) {
uint32_t id = 0;
if (!RegisterFlyingData(filename, &id)) return 0;
return CreateFlyingInstance(id, startPos, targetPos, std::move(hitCb));
return CreateFlyingInstance(id, startPos, targetPos, std::move(hitCb), std::move(targetResolver), std::move(targetHitCb),std::move(collision));
}
uint32_t FlyingManager::CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb) {
uint32_t FlyingManager::CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb, FlyTargetResolver targetResolver, std::function<void()> targetHitCb,FlyCollisionCallbacks collision) {
auto it = m_dataCache.find(flyId);
if (it == m_dataCache.end()) {
auto indexedIt = m_indexedFlyData.find(flyId);
@@ -329,15 +510,49 @@ uint32_t FlyingManager::CreateFlyingInstance(uint32_t flyId, const float* startP
}
if (it == m_dataCache.end()) return 0;
auto inst = std::make_shared<FlyingInstance>(it->second, startPos, targetPos);
auto inst = std::make_shared<FlyingInstance>(it->second, startPos, targetPos, std::move(targetResolver));
if (hitCb) inst->SetHitCallback(std::move(hitCb));
inst->SetTargetHitCallback(std::move(targetHitCb));
inst->SetCollisionCallbacks(std::move(collision));
m_instances.push_back(inst);
return static_cast<uint32_t>(m_instances.size());
}
void FlyingManager::Update(float dt, float currentTime) {
void FlyingManager::CreateIndexedFly(uint32_t index, const float* startPos, float startRotation, const float* endTargetPos, FlyTargetResolver targetResolver) {
auto it = m_indexedFlyData.find(index);
if (it == m_indexedFlyData.end()) {
std::cerr << "[AVA2 TraceError] CFlyingManager::CreateIndexedFly(dwIndex=" << index << ") - Not registered index" << std::endl;
return;
}
using eter::frandom;
switch (it->second.type) {
case INDEX_FLY_TYPE_NORMAL:
CreateFlyingInstance(it->second.flyId, startPos, endTargetPos, {}, targetResolver);
break;
case INDEX_FLY_TYPE_FIRE_CRACKER: {
constexpr float DEG = 3.14159265358979323846f / 180.0f;
const float fRot = std::fmod(startRotation - 90.0f + 360.0f, 360.0f) + frandom(-30.0f, 30.0f);
const float fDistance = frandom(2000.0f, 5000.0f);
const float fxRand = fDistance * std::cos(fRot * DEG);
const float fyRand = fDistance * std::sin(fRot * DEG);
const float fzRand = frandom(1000.0f, 2500.0f);
// Native (x, y, z) = engine (x, -z, height).
const float start[3] = {startPos[0], startPos[1] + 200.0f, startPos[2]};
const float end[3] = {startPos[0] + fxRand, startPos[1] + fzRand, startPos[2] - fyRand};
CreateFlyingInstance(it->second.flyId, start, end);
break;
}
case INDEX_FLY_TYPE_AUTO_FIRE: {
const float start[3] = {startPos[0], startPos[1] + 100.0f, startPos[2]};
CreateFlyingInstance(it->second.flyId, start, endTargetPos, {}, targetResolver);
break;
}
}
}
void FlyingManager::Update(float dt,float currentTime,const TerrainHeightSource* terrain,const MapObjectManager* objects,const std::function<float(float,float)>& groundHeight) {
for (auto it = m_instances.begin(); it != m_instances.end();) {
if (!(*it)->Update(dt, currentTime)) {
if (!(*it)->Update(dt,currentTime,terrain,objects,groundHeight)) {
it = m_instances.erase(it);
} else {
++it;
@@ -345,10 +560,10 @@ void FlyingManager::Update(float dt, float currentTime) {
}
}
void FlyingManager::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
void FlyingManager::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws,const ViewFrustum* cachedFrustum,DepthState depthState) {
for (const auto& inst : m_instances) {
if (inst && inst->IsAlive()) {
inst->BuildDrawCommands(viewMatrix, projMatrix, currentTime, outDraws);
inst->BuildDrawCommands(viewMatrix, projMatrix, currentTime, outDraws,cachedFrustum,depthState);
}
}
}
+50 -10
View File
@@ -8,8 +8,11 @@
#include <memory>
#include <unordered_map>
#include <functional>
#include <set>
namespace ava2 {
class TerrainHeightSource;
class MapObjectManager;
struct FlyingAttachData {
int type = 1;
@@ -20,6 +23,7 @@ struct FlyingAttachData {
float tail_length = 0.2f;
float tail_size = 8.0f;
bool rect_shape = false;
float roll=0,distance=0,period=1,amplitude=0;
};
class FlyingData {
@@ -37,35 +41,67 @@ public:
bool homing_flag = false;
float homing_max_angle = 3.0f;
float range = 10000.0f;
float homing_start_time = 0;
int pierce_count = 0;
bool maintain_parallel = false;
float roll_angle=0, cone_angle=0;
bool spreading=false;
bool hit_on_background=false,hit_on_another_monster=false;
FlyingAttachData attach;
FlyingAttachData attach; // Legacy first attachment access.
std::vector<FlyingAttachData> attachments;
float angular_velocity[3]={};
};
using FlyTargetResolver = std::function<bool(float*)>; // false: object disappeared; keep last position.
struct FlyCollisionCallbacks {
std::weak_ptr<const uint8_t> owner;
std::function<void(uint32_t)> onAnotherTarget;
std::function<void()> onBackground;
};
class FlyingInstance {
public:
FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos);
FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos, FlyTargetResolver targetResolver = {});
~FlyingInstance();
bool Update(float dt, float currentTime);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
bool Update(float dt,float currentTime,const TerrainHeightSource* terrain=nullptr,const MapObjectManager* objects=nullptr,const std::function<float(float,float)>& groundHeight={});
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws, const ViewFrustum* cachedFrustum = nullptr, DepthState depthState = {});
bool IsAlive() const { return m_isAlive; }
const float* GetPosition() const { return m_position; }
void SetCollisionCallbacks(FlyCollisionCallbacks callbacks) { m_collision=std::move(callbacks); }
void SetTargetHitCallback(std::function<void()> cb) { m_targetHitCallback=std::move(cb); }
void SetRangeCallback(std::function<void()> cb) { m_rangeCallback=std::move(cb); }
void SetHitCallback(std::function<void(const float*)> cb) { m_hitCallback = std::move(cb); }
private:
std::shared_ptr<FlyingData> m_data;
bool m_isAlive = true;
float m_age = 0.0f;
float m_remainingRange = 0;
int m_pierceCount = 0;
bool m_targetHit = false;
FlyTargetResolver m_targetResolver;
float m_acceleration[3] = {};
FlyCollisionCallbacks m_collision;
std::set<std::weak_ptr<const uint8_t>,std::owner_less<std::weak_ptr<const uint8_t>>> m_hitObjects;
void Bomb();
bool Explode(bool bomb);
float m_position[3] = {0.0f, 0.0f, 0.0f};
float m_velocity[3] = {0.0f, 0.0f, 0.0f};
float m_targetPosition[3] = {0.0f, 0.0f, 0.0f};
uint32_t m_attachedEffectId = 0;
FlyTrace m_tail;
struct Attachment {FlyingAttachData data;uint32_t effect=0;FlyTrace tail;};
std::vector<Attachment> m_attachments;
float m_orientation[4]={0,0,0,1},m_attachRotation[4]={0,0,0,1};
void UpdateAttachments(float dt,float currentTime);
void ClearAttachments();
std::function<void(const float*)> m_hitCallback;
std::function<void()> m_targetHitCallback, m_rangeCallback;
};
class FlyingManager {
@@ -102,11 +138,15 @@ public:
bool RegisterFlyingData(const std::string& filename, uint32_t* outId = nullptr);
bool RegisterIndexedFlyData(uint32_t index, uint8_t type, const std::string& filename);
uint32_t CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr);
uint32_t CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr);
uint32_t CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr, FlyTargetResolver targetResolver = {}, std::function<void()> targetHitCb = {}, FlyCollisionCallbacks collision = {});
uint32_t CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr, FlyTargetResolver targetResolver = {}, std::function<void()> targetHitCb = {}, FlyCollisionCallbacks collision = {});
void Update(float dt, float currentTime);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
// CFlyingManager::CreateIndexedFly: start = the start actor's position (engine x, height, z) and
// rotation (native degrees), end = the end actor's fly-target position.
void CreateIndexedFly(uint32_t index, const float* startPos, float startRotation, const float* endTargetPos, FlyTargetResolver targetResolver = {});
void Update(float dt,float currentTime,const TerrainHeightSource* terrain=nullptr,const MapObjectManager* objects=nullptr,const std::function<float(float,float)>& groundHeight={});
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws, const ViewFrustum* cachedFrustum = nullptr, DepthState depthState = {});
void DeleteAllInstances();
size_t GetActiveInstanceCount() const { return m_instances.size(); }
+300 -17
View File
@@ -3,7 +3,9 @@
#include "eter_effect/EffectManager.h"
#include "nonplayer_data.h"
#include "eter_render/RaceData.h"
#include "eter_render/Gr2ModelRenderer.h"
#include <algorithm>
#include <bit>
#include <array>
#include <chrono>
#include <map>
@@ -15,6 +17,11 @@ namespace ava2 {
namespace {
void RefreshState(SNetworkActorData& actor, uint32_t motion, bool loop);
// InstanceBaseMovement.cpp: both raw packet speeds clamp >1100 to zero.
float PacketSpeedRatio(uint32_t speed) { return speed<=1100 ? float(speed)/100.0f : 0.0f; }
// AVA2 InstanceBase.cpp SHORSE::Create / __AttachHorseSaddle: mounts are
// separate actors, and the rider's main model follows their "saddle" bone.
void ConfigureMount(SNetworkActorData& data) {
@@ -28,13 +35,14 @@ void ConfigureMount(SNetworkActorData& data) {
if (mount->SetRace(data.m_dwMountVnum)) {
mount->SetShape(0);mount->SetScale(rider.GetScale());
mount->SetYaw(rider.GetYaw());mount->SetPosition(rider.GetX(),rider.GetY(),rider.GetZ());
mount->SetMoveAnimationSpeed(data.m_dwMovSpd<=1100 ? float(data.m_dwMovSpd)/100 : 0);
mount->SetAttackSpeed(PacketSpeedRatio(data.m_dwAtkSpd));
mount->PlayMotion(MotionType::Wait,true);
data.m_pMountInstance=std::move(mount);
}
}
const uint16_t mode=data.m_pMountInstance ? 9 : 1;
rider.SetMotionMode(mode);
rider.PlayMotion(MotionType::Wait,true);
// MountHorse / DismountHorse end in RefreshState(NAME_WAIT): the weapon picks the horse mode.
RefreshState(data, RaceData::NAME_WAIT, true);
}
// InstanceBaseEffect.cpp g_akD3DXClrName / g_akD3DXClrTitle / g_TitleNameMap: zero (transparent
@@ -74,6 +82,69 @@ bool ArmorVnumToShape(uint32_t vnum, uint32_t* shape) {
constexpr uint8_t kTypePC = 6; // CActorInstance::TYPE_PC
bool IsPC(const SNetworkActorData& actor) { return actor.m_bType == kTypePC; }
// CRaceMotionData::EMode (ENABLE_WOLFMAN_CHARACTER off) and CItemData weapon / item types.
enum {
MODE_GENERAL = 1, MODE_ONEHAND_SWORD, MODE_TWOHAND_SWORD, MODE_DUALHAND_SWORD, MODE_BOW, MODE_FAN,
MODE_BELL, MODE_FISHING, MODE_HORSE, MODE_HORSE_ONEHAND_SWORD, MODE_HORSE_TWOHAND_SWORD,
MODE_HORSE_DUALHAND_SWORD, MODE_HORSE_BOW, MODE_HORSE_FAN, MODE_HORSE_BELL, MODE_WEDDING_DRESS,
MODE_BOW_SPECIAL,
};
enum { WEAPON_SWORD, WEAPON_DAGGER, WEAPON_BOW, WEAPON_TWO_HANDED, WEAPON_BELL, WEAPON_FAN, WEAPON_ARROW,
WEAPON_MOUNT_SPEAR, WEAPON_CLAW, WEAPON_QUIVER };
enum { ITEM_TYPE_ROD = 13, ITEM_TYPE_COSTUME = 28 };
// CInstanceBase::RefreshState: picks the motion mode from the polymorph / dress / weapon / horse
// state, then intercepts the motion. The actor's attack speed follows m_dwAtkSpd (SetAttackSpeed).
void RefreshState(SNetworkActorData& actor, uint32_t motion, bool loop) {
if (!actor.m_pActorInstance) return;
auto& inst = *actor.m_pActorInstance;
const bool mounting = actor.m_pMountInstance != nullptr;
const uint32_t weapon = inst.GetPartItemID(RaceData::PART_WEAPON);
int itemType = 0xff, subType = 0xff;
SItemModelData item;
if (GetItemData(weapon, &item)) {
itemType = item.type;
subType = int(GetWeaponType(item));
}
int mode = MODE_GENERAL;
const bool pickAxe = actor.m_awPart[RaceData::PART_WEAPON] >= 29101 && actor.m_awPart[RaceData::PART_WEAPON] <= 29110;
if (inst.IsPolymorph()) {
mode = MODE_GENERAL;
} else if (actor.m_awPart[RaceData::PART_MAIN] == 201 || inst.GetShape() == 201) { // IsWearingDress
mode = MODE_WEDDING_DRESS;
} else if (pickAxe) {
mode = mounting ? MODE_HORSE : MODE_GENERAL;
} else if (itemType == ITEM_TYPE_ROD) {
mode = mounting ? MODE_HORSE : MODE_FISHING;
} else if (mounting) {
switch (subType) {
case WEAPON_SWORD: mode = MODE_HORSE_ONEHAND_SWORD; break;
case WEAPON_TWO_HANDED: mode = MODE_HORSE_TWOHAND_SWORD; break;
case WEAPON_DAGGER: mode = MODE_HORSE_DUALHAND_SWORD; break;
case WEAPON_FAN: mode = MODE_HORSE_FAN; break;
case WEAPON_BELL: mode = MODE_HORSE_BELL; break;
case WEAPON_BOW: mode = MODE_HORSE_BOW; break;
default: mode = MODE_HORSE; break;
}
} else {
switch (subType) {
case WEAPON_SWORD: mode = MODE_ONEHAND_SWORD; break;
case WEAPON_TWO_HANDED: mode = MODE_TWOHAND_SWORD; break;
case WEAPON_DAGGER: mode = MODE_DUALHAND_SWORD; break;
case WEAPON_BOW:
mode = actor.m_awPart[RaceData::PART_ARROW_TYPE] == WEAPON_QUIVER ? MODE_BOW_SPECIAL : MODE_BOW;
break;
case WEAPON_FAN: mode = MODE_FAN; break;
case WEAPON_BELL: mode = MODE_BELL; break;
default: mode = MODE_GENERAL; break;
}
}
inst.SetMotionMode(mode);
inst.SetMountingHorse(mounting);
inst.SetAttackSpeed(PacketSpeedRatio(actor.m_dwAtkSpd));
if (!inst.InterceptMotionIndex(motion, loop)) inst.PlayMotion(static_cast<MotionType>(motion), loop);
}
// InstanceBase.h RaceToJob / RaceToSex (ENABLE_WOLFMAN_CHARACTER off).
int RaceToJob(int race) { return race % 4; }
int RaceToSex(int race) {
@@ -177,6 +248,82 @@ void NetworkActorManager::CreateSpecialEffect(uint32_t vid, unsigned type) {
EffectManager::Instance().CreateEffect(GetEffectCRC(type), x, y, z, yaw);
}
void NetworkActorManager::AddDamageEffect(uint32_t vid, uint32_t damage, uint8_t flag, bool bSelf, bool bTarget) {
auto* actor = GetActorData(vid);
if (!actor) return; // the caller checks CPythonSystem::IsShowDamage (eter_render has no scripting)
actor->m_DamageQueue.push_back({damage, flag, bSelf, bTarget});
}
namespace {
// CInstanceBase::ProcessDamage. The camera comes from the current scene renderer: its view matrix
// rows are the camera axes in engine space (x right, z forward); native (x, y) = engine (x, -z).
void ProcessDamage(SNetworkActorData& actor) {
if (actor.m_DamageQueue.empty() || !actor.m_pActorInstance) return;
const auto sDamage = actor.m_DamageQueue.front();
actor.m_DamageQueue.pop_front();
uint32_t damage = sDamage.damage;
const uint8_t flag = sDamage.flag;
float rightX = 1.0f, rightY = 0.0f, rightZ = 0.0f, cameraAngle = 0.0f;
if (const auto* renderer = TextTailManager::Instance().GetCurrentSceneRenderer()) {
const float* view = renderer->GetViewMatrix();
rightX = view[0]; rightY = view[4]; rightZ = view[8];
// GetDegreeFromPosition2(target, eye): the native direction from the camera target to the eye.
const float dirX = -view[2], dirY = view[10];
const float len = std::sqrt(dirX * dirX + dirY * dirY);
if (len > 0.0f) {
cameraAngle = std::acos(std::clamp(-dirY / len, -1.0f, 1.0f)) * 180.0f / 3.14159265358979323846f;
if (dirX < 0.0f) cameraAngle = 360.0f - cameraAngle;
}
}
constexpr float FONT_WIDTH = 30.0f;
auto& rkEftMgr = EffectManager::Instance();
float x, y, z;
actor.m_pActorInstance->GetHeadPosition(x, y, z); // GetPosition() + GetHeight()
if ((flag & NetworkActorManager::DAMAGE_DODGE) || (flag & NetworkActorManager::DAMAGE_BLOCK)) {
rkEftMgr.CreateEffect(NetworkActorManager::GetEffectCRC(sDamage.bSelf ? NetworkActorManager::EFFECT_DAMAGE_MISS
: NetworkActorManager::EFFECT_DAMAGE_TARGETMISS),
x, y, z, cameraAngle);
return;
}
// DAMAGE_CRITICAL: the critical effect is commented out upstream; the number is still shown.
std::string strDamageType;
unsigned rdwCRCEft = 0;
if (sDamage.bSelf) {
strDamageType = "damage_";
rdwCRCEft = actor.m_bDamageEffectType ? NetworkActorManager::EFFECT_DAMAGE_SELFDAMAGE2 : NetworkActorManager::EFFECT_DAMAGE_SELFDAMAGE;
actor.m_bDamageEffectType = !actor.m_bDamageEffectType;
} else if (!sDamage.bTarget) {
return; // "nontarget_" / EFFECT_DAMAGE_NOT_TARGET: not applied upstream.
} else {
strDamageType = "target_";
rdwCRCEft = NetworkActorManager::EFFECT_DAMAGE_TARGET;
}
const uint32_t effectId = NetworkActorManager::GetEffectCRC(rdwCRCEft);
uint32_t index = 0;
while (damage > 0) {
if (index > 7) {
std::cerr << "[AVA2 TraceError] ProcessDamage Possibility of endless loop" << std::endl;
break;
}
const uint32_t num = damage % 10;
damage /= 10;
rkEftMgr.SetEffectTextures(effectId, {"d:/ymir work/effect/affect/damagevalue/" + strDamageType + std::to_string(num) + ".dds"});
// Translation by (-FONT_WIDTH * index, 0, 0) in view space.
const float offset = -FONT_WIDTH * static_cast<float>(index);
rkEftMgr.CreateEffect(effectId, x + rightX * offset, y + rightY * offset, z + rightZ * offset, cameraAngle);
++index;
}
}
} // namespace
bool NetworkActorManager::IsPossibleEmoticon(uint32_t vid) const {
const auto* actor = GetActorData(vid);
if (!actor) return false;
@@ -275,9 +422,9 @@ void NetworkActorManager::SetArmor(SNetworkActorData& actor, uint32_t armor) {
SetShape(actor, armor);
}
// CInstanceBase::SetShape (IsPoly() never holds for network actors in the port).
// CInstanceBase::SetShape: poly renders shape zero but retains requested part metadata.
void NetworkActorManager::SetShape(SNetworkActorData& actor, uint32_t shape, float specular) {
if (actor.m_pActorInstance) actor.m_pActorInstance->SetShape(shape, specular);
if (actor.m_pActorInstance) actor.m_pActorInstance->SetShape(actor.m_pActorInstance->IsPolymorph()?0:shape,specular);
actor.m_awPart[RaceData::PART_MAIN] = shape;
}
@@ -291,7 +438,7 @@ void NetworkActorManager::SetHair(SNetworkActorData& actor, uint32_t hair) {
// CInstanceBase::SetWeapon(eWeapon, eArrow). Weapon refine / shining effects are not ported.
bool NetworkActorManager::SetWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow) {
const uint32_t shape = actor.m_pActorInstance ? actor.m_pActorInstance->GetShape() : actor.m_awPart[RaceData::PART_MAIN];
const uint32_t shape = actor.m_awPart[RaceData::PART_MAIN];
if (shape >= 100 && shape <= 103) return false; // __IsShapeAnimalWear
actor.m_awPart[RaceData::PART_ARROW_TYPE] = arrow;
// __IsChangableWeapon: the wedding dress (shape 201) only holds the bouquets.
@@ -313,7 +460,7 @@ bool NetworkActorManager::SetWeapon(SNetworkActorData& actor, uint32_t weapon, u
bool NetworkActorManager::ChangeArmor(SNetworkActorData& actor, uint32_t armor) {
uint32_t shape;
ArmorVnumToShape(armor, &shape);
if (!actor.m_pActorInstance || actor.m_pActorInstance->GetShape() == shape) return false;
if (!actor.m_pActorInstance || actor.m_awPart[RaceData::PART_MAIN] == shape) return false;
const uint32_t hair = actor.m_awPart[RaceData::PART_HAIR];
const uint32_t sash = actor.m_awPart[RaceData::PART_SASH];
const uint32_t weapon = actor.m_awPart[RaceData::PART_WEAPON];
@@ -330,12 +477,16 @@ bool NetworkActorManager::ChangeArmor(SNetworkActorData& actor, uint32_t armor)
return true;
}
// CInstanceBase::ChangeWeapon(eWeapon, eArrow). The bow motion-mode switch is not ported.
// CInstanceBase::ChangeWeapon(eWeapon, eArrow).
void NetworkActorManager::ChangeWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow) {
actor.m_awPart[RaceData::PART_ARROW_TYPE] = arrow;
if (!actor.m_pActorInstance) return;
SItemModelData item;
if (!actor.m_pMountInstance && GetItemData(weapon, &item) &&
(item.subType == WEAPON_BOW || (item.type == ITEM_TYPE_COSTUME && item.values[3] == WEAPON_BOW)))
actor.m_pActorInstance->SetMotionMode(arrow == WEAPON_QUIVER ? MODE_BOW_SPECIAL : MODE_BOW);
if (weapon == actor.m_pActorInstance->GetPartItemID(RaceData::PART_WEAPON)) return;
if (SetWeapon(actor, weapon, arrow)) actor.m_pActorInstance->PlayMotion(MotionType::Wait, true);
if (SetWeapon(actor, weapon, arrow)) RefreshState(actor, RaceData::NAME_WAIT, true);
}
// CInstanceBase::ChangeHair.
@@ -433,7 +584,14 @@ NetworkActorManager& NetworkActorManager::Instance() {
return s_instance;
}
NetworkActorManager::NetworkActorManager() = default;
NetworkActorManager::NetworkActorManager() {
// CActorInstance::SetFlyTarget(CGraphicObjectInstance*): the port's motion events look fly
// targets up by VID so a destroyed instance never leaves a dangling pointer.
ActorInstance::SetActorResolver([](uint32_t vid) -> ActorInstance* {
auto* data = NetworkActorManager::Instance().GetActorData(vid);
return data ? data->m_pActorInstance.get() : nullptr;
});
}
void NetworkActorManager::SetMainActorVID(uint32_t vid) {
m_mainVID = vid;
@@ -471,9 +629,11 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
// Instantiate 3D ActorInstance
auto actor = std::make_shared<ActorInstance>();
actor->SetVID(data.m_dwVID);
actor->SetActorType(data.m_bType);
actor->SetName(data.m_stName);
actor->SetYaw(data.m_fRot);
actor->SetSpeed(static_cast<float>(data.m_dwMovSpd > 0 ? data.m_dwMovSpd : 100));
actor->SetSpeed(data.m_dwMovSpd<=1100 ? float(data.m_dwMovSpd) : 0);
actor->SetMoveAnimationSpeed(data.m_dwMovSpd<=1100 ? float(data.m_dwMovSpd)/100 : 0);
actor->SetScale(0.8f);
// World position: Metin2 coordinates X, Y(Z in 3D), Z(Y in 3D)
@@ -503,6 +663,8 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
}
actor->PlayMotion(MotionType::Wait, true);
ConfigureMount(actorData);
// CInstanceBase::Create ends in Refresh(NAME_WAIT, true).
RefreshState(actorData, RaceData::NAME_WAIT, true);
// AVA2 InstanceBase::SetAffect(AFFECT_STUN=5) controls the sleep action flag.
actor->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0);
@@ -543,6 +705,7 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
}
void NetworkActorManager::RemoveActor(uint32_t vid) {
CancelDualEmotions(vid);m_deferredMoves.erase(vid);
auto it = m_actors.find(vid);
if (it != m_actors.end()) {
if (IsMainActorVID(vid)) {
@@ -584,7 +747,10 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) {
actorData.m_dwMountVnum = data.m_dwMountVnum;
actorData.m_dwMovSpd = data.m_dwMovSpd;
actorData.m_dwAtkSpd = data.m_dwAtkSpd;
if (actorData.m_pActorInstance)
actorData.m_pActorInstance->SetAttackSpeed(PacketSpeedRatio(data.m_dwAtkSpd));
ConfigureMount(actorData);
if(actorData.m_pMountInstance) actorData.m_pMountInstance->SetAttackSpeed(PacketSpeedRatio(data.m_dwAtkSpd));
// CNetworkActorManager::UpdateActor: ChangeArmor, ChangeWeapon(weapon, arrow), ChangeHair, ChangeSash.
ChangeArmor(actorData, data.m_dwArmor);
@@ -592,9 +758,10 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) {
ChangeHair(actorData, data.m_dwHair);
if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0);
if (data.m_dwMovSpd > 0) {
actorData.m_pActorInstance->SetSpeed(static_cast<float>(data.m_dwMovSpd));
}
const float moveSpeed=data.m_dwMovSpd<=1100 ? float(data.m_dwMovSpd) : 0;
actorData.m_pActorInstance->SetSpeed(moveSpeed);
actorData.m_pActorInstance->SetMoveAnimationSpeed(moveSpeed/100);
if(actorData.m_pMountInstance)actorData.m_pMountInstance->SetMoveAnimationSpeed(moveSpeed/100);
}
for (unsigned i = 0; i < 64; ++i) {
@@ -625,6 +792,9 @@ void NetworkActorManager::MoveActor(const SNetworkMoveActorData& data) {
if (it == m_actors.end()) return;
auto& actorData = it->second;
if(IsEmotionLocked(data.m_dwVID) || (actorData.m_pActorInstance && actorData.m_pActorInstance->IsActingEmotion())) {
m_deferredMoves[data.m_dwVID].push_back(data);return;
}
actorData.m_lDstX = data.m_lPosX;
actorData.m_lDstY = data.m_lPosY;
actorData.m_fRot = data.m_fRot;
@@ -633,9 +803,32 @@ void NetworkActorManager::MoveActor(const SNetworkMoveActorData& data) {
if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetYaw(data.m_fRot);
if (data.m_dwFunc == 0) { // Stop
if (data.m_dwFunc & 0x80) {
// FUNC_SKILL (CInstanceBase::PushTCPState): snap to the packet position, then
// NEW_UseSkill(0, eFunc & 0x7f, uArg & 0x0f, uArg >> 4). Moving skills are not
// walked; the original walks there first when it is far away, the port snaps.
actorData.m_isMoving = false;
actorData.m_lCurX = data.m_lPosX;
actorData.m_lCurY = data.m_lPosY;
auto& inst = *actorData.m_pActorInstance;
inst.SetPosition(float(data.m_lPosX), inst.GetY(), float(data.m_lPosY));
if (!inst.IsDead() && !inst.IsStun())
inst.InterceptMotionIndex(RaceData::NAME_SKILL + (data.m_dwFunc & 0x7f), false, 0,
int(data.m_dwArg & 0x0f));
} else if (data.m_dwFunc == 0) { // Stop
actorData.m_isMoving = false;
actorData.m_pActorInstance->PlayMotion(MotionType::Wait);
} else if (data.m_dwFunc == 2 || data.m_dwFunc == 3) {
// FUNC_ATTACK / FUNC_COMBO (CInstanceBase::PushTCPState): RunNormalAttack /
// RunComboAttack(rot, arg) at the packet position. The original walks there first when
// it is 50 or more away; the port snaps.
actorData.m_isMoving = false;
actorData.m_lCurX = data.m_lPosX;
actorData.m_lCurY = data.m_lPosY;
auto& inst = *actorData.m_pActorInstance;
inst.SetPosition(float(data.m_lPosX), inst.GetY(), float(data.m_lPosY));
if (data.m_dwFunc == 2) inst.RunNormalAttack(data.m_fRot);
else inst.RunComboAttack(data.m_fRot, uint16_t(data.m_dwArg));
} else { // Move
actorData.m_isMoving = true;
actorData.m_pActorInstance->PlayMotion(MotionType::Run);
@@ -678,9 +871,96 @@ void NetworkActorManager::SetActorOwner(uint32_t ownerVID, uint32_t victimVID) {
}
}
// InstanceBaseMotion::ActDualEmotion / InstanceBase::__ProcessFunctionEmotion.
bool NetworkActorManager::IsEmotionLocked(uint32_t vid) const {
for(const auto& [source,pair]:m_dualEmotions) if(source==vid || pair.target==vid) return true;
return false;
}
bool NetworkActorManager::IsEmotionProcessing() const {return IsEmotionLocked(m_mainVID);}
void NetworkActorManager::CancelDualEmotions(uint32_t vid) {
for(auto it=m_dualEmotions.begin();it!=m_dualEmotions.end();) {
if(it->first!=vid && it->second.target!=vid) {++it;continue;}
for(uint32_t member:{it->first,it->second.target}) {
auto* data=GetActorData(member);
if(!data || !data->m_pActorInstance) continue;
data->m_pActorInstance->SetEmotionMovementLocked(false);
data->m_isMoving=false;data->m_pActorInstance->ClearMoveTarget();data->m_pActorInstance->StopMoving();
data->m_pActorInstance->SetLoopMotionIndex(RaceData::NAME_WAIT);
}
it=m_dualEmotions.erase(it);
}
}
bool NetworkActorManager::BeginDualEmotion(uint32_t src,uint32_t dst,uint16_t lowMotion,uint16_t highMotion) {
auto first=GetActorInstance(src),second=GetActorInstance(dst);
if(src==dst || !first || !second || IsEmotionLocked(src) || IsEmotionLocked(dst)) return false;
float dx=first->GetX()-second->GetX(),dz=first->GetZ()-second->GetZ();
const float distance=std::hypot(dx,dz);
if(!std::isfinite(distance)) return false;
if(distance>0.001f) {dx/=distance;dz/=distance;}
else {const float yaw=first->GetYaw()*3.14159265358979323846f/180;dx=-std::sin(yaw);dz=-std::cos(yaw);}
for(uint32_t member:{src,dst}) {
auto& data=*GetActorData(member);auto& actor=*data.m_pActorInstance;
data.m_isMoving=false;actor.ClearMoveTarget();actor.StopMoving();actor.SetEmotionMovementLocked(true);
if(actor.GetCurrentMotion()!=MotionType::Wait) actor.SetLoopMotionIndex(RaceData::NAME_WAIT);
}
const uint32_t now=m_now?NowMSec():(m_emotionNow?m_emotionNow():NowMSec());
m_dualEmotions.emplace(src,DualEmotion{dst,now+500,second->GetX()+dx*100,second->GetZ()+dz*100,lowMotion,highMotion});
return true;
}
void NetworkActorManager::ProcessDualEmotions(float dt,const TerrainHeightSource* terrain) {
if(!std::isfinite(dt) || dt<0) return;
const uint32_t now=m_now?NowMSec():(m_emotionNow?m_emotionNow():NowMSec());
for(auto it=m_dualEmotions.begin();it!=m_dualEmotions.end();) {
auto* source=GetActorData(it->first);auto* target=GetActorData(it->second.target);
if(!source || !target || !source->m_pActorInstance || !target->m_pActorInstance) {
const uint32_t vid=it->first;++it;CancelDualEmotions(vid);continue;
}
auto& pair=it->second;auto& first=*source->m_pActorInstance;auto& second=*target->m_pActorInstance;
if(std::bit_cast<int32_t>(now-pair.due)<0) {++it;continue;}
const float dx=pair.x-first.GetX(),dz=pair.z-first.GetZ(),distance=std::hypot(dx,dz);
if(!pair.walking && distance>100) {pair.walking=true;first.PlayMotion(MotionType::Run,true);}
const float step=std::max(0.0f,first.GetSpeed())*dt;
if(pair.walking && distance>step && distance>0.001f) {
const float x=first.GetX()+dx/distance*step,z=first.GetZ()+dz/distance*step;
first.SetPosition(x,terrain?terrain->GetHeightAtWorld(x,z):first.GetY(),z);
first.SetYaw(std::fmod(std::atan2(dx,dz)*180/3.14159265358979323846f+360,360));
source->m_lCurX=int32_t(x);source->m_lCurY=int32_t(z);source->m_lCurZ=int32_t(first.GetY());
if(IsMainActorVID(it->first)) {m_mainPosX=source->m_lCurX;m_mainPosY=source->m_lCurY;}
++it;continue;
}
first.SetPosition(pair.x,terrain?terrain->GetHeightAtWorld(pair.x,pair.z):first.GetY(),pair.z);
first.StopMoving();second.StopMoving();first.SetEmotionMovementLocked(false);second.SetEmotionMovementLocked(false);
source->m_isMoving=target->m_isMoving=false;
source->m_lCurX=int32_t(pair.x);source->m_lCurY=int32_t(pair.z);source->m_lCurZ=int32_t(first.GetY());
if(IsMainActorVID(it->first)) {m_mainPosX=source->m_lCurX;m_mainPosY=source->m_lCurY;}
const float turnX=second.GetX()-first.GetX(),turnZ=second.GetZ()-first.GetZ();
const float yaw=std::fmod(std::atan2(turnX,turnZ)*180/3.14159265358979323846f+360,360);
first.SetYaw(yaw);second.SetYaw(std::fmod(yaw+180,360));
// MAKELONG(low,high): source plays HIWORD + destination job, target LOWORD + source job.
first.InterceptMotionIndex(pair.high+uint32_t(RaceToJob(int(second.GetRace()))),false);
second.InterceptMotionIndex(pair.low+uint32_t(RaceToJob(int(first.GetRace()))),false);
it=m_dualEmotions.erase(it); // EndEmotionProcess occurs when both motions begin.
}
}
void NetworkActorManager::Update(float dt, const TerrainHeightSource* terrain) {
ProcessDualEmotions(dt,terrain);
for(auto it=m_deferredMoves.begin();it!=m_deferredMoves.end();) {
auto actor=GetActorInstance(it->first);
if(!actor) {it=m_deferredMoves.erase(it);continue;}
if(IsEmotionLocked(it->first) || actor->IsActingEmotion()) {++it;continue;}
const auto move=it->second.front();it->second.pop_front();
if(it->second.empty()) it=m_deferredMoves.erase(it);else ++it;
MoveActor(move);
}
for (auto& [vid, actorData] : m_actors) {
if (!actorData.m_pActorInstance) continue;
// CActorInstance::IsPC (m_eActorType == TYPE_PC): .mss frequency check and splash rules.
actorData.m_pActorInstance->SetActorType(actorData.m_bType);
if (actorData.m_isMoving) {
float curX = static_cast<float>(actorData.m_lCurX);
@@ -693,7 +973,7 @@ void NetworkActorManager::Update(float dt, const TerrainHeightSource* terrain) {
float dist = std::sqrt(dx * dx + dz * dz);
float speed = actorData.m_pActorInstance->GetSpeed();
if (speed <= 0.0f) speed = 250.0f;
speed = std::max(0.0f,speed);
float step = speed * dt;
if (dist <= step || dist < 1.0f) {
@@ -751,12 +1031,15 @@ void NetworkActorManager::Update(float dt, const TerrainHeightSource* terrain) {
eftMgr.SetEffectInstanceRotation(e->instanceId, inst.GetYaw(), 0.0f, 0.0f);
++e;
}
ProcessDamage(actorData);
}
}
void NetworkActorManager::Clear() {
m_dualEmotions.clear();m_deferredMoves.clear();
// CPythonCharacterManager::DeleteAllInstances: each CInstanceBase::Destroy detaches its text tail.
for (auto& [vid, actorData] : m_actors) {
if(actorData.m_pActorInstance)actorData.m_pActorInstance->SetEmotionMovementLocked(false);
DestroyAttachedEffects(actorData);
TextTailManager::Instance().DeleteCharacterTextTail(vid);
}
@@ -937,8 +1220,8 @@ std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime,
void NetworkActorManager::SetSash(uint32_t vid, uint32_t sash) {
auto* actor = GetActorData(vid);
if (!actor) return;
// IsPC() && IsPoly() can never both hold: both test the same instance type.
if (actor->m_bType != TYPE_PC && actor->m_dwRace > 8) return;
if (actor->m_bType==TYPE_PC && actor->m_pActorInstance && actor->m_pActorInstance->IsPolymorph()) return;
actor->m_dwSash = sash;
const uint32_t vnum = sash + 85000;
+24 -1
View File
@@ -7,6 +7,8 @@
#include <memory>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <utility>
namespace ava2 {
@@ -66,7 +68,6 @@ struct SNetworkActorData {
uint8_t m_duelMode = DUEL_NONE; // CInstanceBase::SetDuelMode
uint8_t m_walkMode = 0; // CInstanceBase::SetRunMode/SetWalkMode (WALKMODE_RUN=0)
bool m_isFishing = false; // IsFishing(): FISHING_WAIT/FISHING_REACT motion stand-in
bool m_isMoving = false;
float m_moveElapsed = 0.0f;
uint32_t m_dwEmoticonTime = 0; // CInstanceBase::m_dwEmoticonTime (ELTimer_GetMSec)
@@ -80,6 +81,10 @@ struct SNetworkActorData {
// packet copies above (SetHair/SetSash/SetWeapon may refuse a value the packet carried).
uint32_t m_awPart[7] = {};
std::vector<SAttachedEffect> m_attachedEffects;
// CInstanceBase::SEffectDamage / m_DamageQueue / m_bDamageEffectType (AddDamageEffect, ProcessDamage).
struct SEffectDamage { uint32_t damage = 0; uint8_t flag = 0; bool bSelf = false; bool bTarget = false; };
std::deque<SEffectDamage> m_DamageQueue;
bool m_bDamageEffectType = false;
// CInstanceBase::m_adwCRCAffectEffect[AFFECT_NUM]: the effect instance __SetAffect attached.
uint32_t m_adwAffectEffect[64] = {};
// CGraphicThingInstance::Hide/Show (chr.Hide/chr.Show); hidden instances are not drawn.
@@ -189,6 +194,14 @@ public:
void CreateSpecialEffect(uint32_t vid, unsigned type); // effect at the actor transform
bool IsPossibleEmoticon(uint32_t vid) const;
void SetEmoticon(uint32_t vid, unsigned emoticon);
// CInstanceBase::AddDamageEffect (the caller checks CPythonSystem::IsShowDamage) and ProcessDamage,
// which shows one queued entry per update as damagevalue digit effects.
enum { DAMAGE_DODGE = 1 << 2, DAMAGE_BLOCK = 1 << 3, DAMAGE_CRITICAL = 1 << 5 };
enum {
EFFECT_DAMAGE_TARGET = 254, EFFECT_DAMAGE_NOT_TARGET, EFFECT_DAMAGE_SELFDAMAGE, EFFECT_DAMAGE_SELFDAMAGE2,
EFFECT_DAMAGE_POISON, EFFECT_DAMAGE_MISS, EFFECT_DAMAGE_TARGETMISS, EFFECT_DAMAGE_CRITICAL,
};
void AddDamageEffect(uint32_t vid, uint32_t damage, uint8_t flag, bool bSelf, bool bTarget);
void SetTimeSourceForTest(uint32_t (*now)()) { m_now = now; }
// CInstanceBase name/title colour tables (InstanceBaseEffect.cpp g_akD3DXClrName/Title,
@@ -230,6 +243,9 @@ public:
void ChangeGVG(uint32_t srcGuild, uint32_t dstGuild); // CPythonCharacterManager::ChangeGVG
void Update(float dt, const TerrainHeightSource* terrain = nullptr);
bool BeginDualEmotion(uint32_t src, uint32_t dst, uint16_t lowMotion, uint16_t highMotion);
bool IsEmotionProcessing() const;
void SetEmotionTimeSource(uint32_t (*now)()) { m_emotionNow=now; }
void Clear();
// CPythonCharacterManager::Destroy: DeleteAllInstances + __Initialize (point effects too).
void Destroy();
@@ -300,6 +316,13 @@ private:
uint32_t m_adwPointEffect[255] = {}; // POINT_MAX_NUM
uint32_t (*m_now)() = nullptr;
uint32_t NowMSec() const;
uint32_t (*m_emotionNow)() = nullptr;
struct DualEmotion { uint32_t target, due; float x,z; uint16_t low,high; bool walking=false; };
std::map<uint32_t,DualEmotion> m_dualEmotions;
std::map<uint32_t,std::deque<SNetworkMoveActorData>> m_deferredMoves;
bool IsEmotionLocked(uint32_t vid) const;
void CancelDualEmotions(uint32_t vid);
void ProcessDualEmotions(float dt,const TerrainHeightSource* terrain);
uint32_t AttachEffectByID(SNetworkActorData& actor, const std::string& bone, uint32_t crc, float offsetHeight);
static void DestroyAttachedEffects(SNetworkActorData& actor);
static std::pair<uint32_t,uint32_t> PVPKey(uint32_t src, uint32_t dst) { return src>dst?std::make_pair(dst,src):std::make_pair(src,dst); }
+85 -48
View File
@@ -9,14 +9,13 @@
#include "shared/common/PythonUtils.h"
#include "nonplayer_data.h"
#include "python_app.h"
#include "python_system.h"
#include "python_gameplay_modules.h"
#include "python_chat.h"
#include "python_native_modules.h"
#include "PythonExchange.h"
#include "PythonSafeBox.h"
#include "eter_render/FloatingTextManager.h"
#include "eter_render/TextTailManager.h"
#include "eter_sound/SoundManager.h"
#include "eter_effect/EffectManager.h"
#include "eter_effect/FlyingManager.h"
#include <algorithm>
@@ -88,8 +87,9 @@ void PythonNetworkStream::StartGame() {
}
void PythonNetworkStream::ResetConnection() {
m_recvBuffer.clear();m_unportedPackets.clear();m_unknownPacketQuit=false;m_isObserverMode=m_bMobileFlag=false;std::memset(m_lastPacket,0,sizeof(m_lastPacket));ClearSendQueue();m_startGameRequested=m_refreshInventory=m_refreshStatus=m_refreshSkill=m_refreshCharacter=m_refreshShopSearch=m_stopGamePhase=false;
m_recvBuffer.clear();m_unportedPackets.clear();m_unknownPacketQuit=false;m_isObserverMode=m_bMobileFlag=false;std::memset(m_lastPacket,0,sizeof(m_lastPacket));ClearSendQueue();m_startGameRequested=m_refreshInventory=m_refreshStatus=m_refreshSkill=m_refreshCharacter=m_refreshShopSearch=m_stopGamePhase=m_warpRequested=m_selectRequested=false;m_selectLeftover.clear();
m_refreshGuildInfo=m_refreshGuildBoard=m_refreshGuildMember=m_refreshGuildCombo=m_refreshGuildSkill=m_refreshGuildGrade=m_refreshMessenger=false;
m_refreshSafebox=m_refreshMall=false;
m_guildID=0;
m_changeServerTime=m_changeClientTime=0;m_dungeonDestination={};
ResetPlayerState();NetworkActorManager::Instance().Clear();
@@ -244,6 +244,8 @@ bool PythonNetworkStream::ProcessRecvData() {
if(m_refreshCharacter) { m_refreshCharacter=false;inventory_callback(m_phaseWindows[5],"RefreshCharacter",nullptr); }
if(m_refreshInventory) { m_refreshInventory=false;inventory_callback(m_phaseWindows[5],"RefreshInventory",nullptr); }
if(m_refreshSkill) {m_refreshSkill=false;inventory_callback(m_phaseWindows[5],"RefreshSkill",nullptr);}
if(m_refreshSafebox) {m_refreshSafebox=false;inventory_callback(m_phaseWindows[5],"RefreshSafebox",nullptr);}
if(m_refreshMall) {m_refreshMall=false;inventory_callback(m_phaseWindows[5],"RefreshMall",nullptr);}
if(m_refreshStatus) { m_refreshStatus=false;inventory_callback(m_phaseWindows[5],"RefreshStatus",nullptr); }
if(m_refreshMessenger) { m_refreshMessenger=false;inventory_callback(m_phaseWindows[5],"RefreshMessenger",nullptr); }
if(m_refreshGuildInfo) { m_refreshGuildInfo=false;inventory_callback(m_phaseWindows[5],"RefreshGuildInfoPage",nullptr); }
@@ -445,7 +447,36 @@ bool PythonNetworkStream::DispatchPortedGamePhasePacket(uint8_t header) {
bool PythonNetworkStream::RecvPhasePacket() {
TPacketGCPhase p;
if (!Read(sizeof(p), &p)) return false;
SetPhase(static_cast<EPhase>(p.phase));
switch(p.phase) {
case PHASE_CLOSE: // ClosePhase
inventory_callback(m_poHandler,"SetLoginPhase",nullptr);
break;
case PHASE_HANDSHAKE:
case PHASE_LOGIN:
// SetHandShakePhase/SetLoginPhase leave the game phase; the login transport owns these phases.
NetworkActorManager::Instance().Clear();
SetPhase(static_cast<EPhase>(p.phase));
break;
case PHASE_SELECT:
// SetSelectPhase leaves the game phase (__LeaveGamePhase). The select-phase packets that follow
// (LOGIN_SUCCESS, EMPIRE, PLAYER_CREATE/DELETE, CHANGE_NAME) belong to LoginSession, so the
// unprocessed bytes go back to the transport. __DownloadMark: guild marks are not ported.
m_selectRequested=true;
m_selectLeftover.assign(m_recvBuffer.begin(),m_recvBuffer.end());
m_recvBuffer.clear();m_stopGamePhase=true;
break;
case PHASE_LOADING: // SetLoadingPhase: CPythonPlayer::Clear
ResetPlayerState();
m_dwInstTargetVID=0; // the instances it named are gone (CPythonCharacterManager::DeleteAllInstances)
SetPhase(PHASE_LOADING);
break;
case PHASE_GAME: // SetGamePhase: __RefreshStatus
SetPhase(PHASE_GAME);
m_refreshStatus=true;
break;
case PHASE_DEAD: // no-op on Windows; m_strPhase stays "Game"
break;
}
return true;
}
@@ -847,27 +878,15 @@ bool PythonNetworkStream::RecvDamageInfoPacket() {
TPacketGCDamageInfo p;
if (!Read(sizeof(p), &p)) return false;
auto actor = NetworkActorManager::Instance().GetActorInstance(p.dwVID);
float ax = 0.0f, ay = 0.0f, az = 0.0f;
if (actor) {
ax = actor->GetX();
ay = actor->GetY();
az = actor->GetZ();
actor->TakeDamage(p.damage);
}
// Spawn 3D floating damage number above target head
bool isCritical = (p.flag & 1) != 0;
FloatingTextManager::Instance().AddDamage(p.damage, ax, ay + 140.0f, az, isCritical, true);
// Hit particle sparks
EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", ax, ay + 70.0f, az);
// SFX
SoundManager::Instance().PlaySound2D("sound/ui/punch.wav");
if (m_damageCallback) {
m_damageCallback(p.dwVID, p.damage, p.flag);
auto& chrMgr = NetworkActorManager::Instance();
const bool bSelf = p.dwVID == chrMgr.GetMainActorVID();
const bool bTarget = p.dwVID == m_dwInstTargetVID;
if (chrMgr.GetActorData(p.dwVID)) {
if (p.damage >= 0) {
if (CPythonSystem::Instance().IsShowDamage()) // CInstanceBase::AddDamageEffect
chrMgr.AddDamageEffect(p.dwVID, uint32_t(p.damage), p.flag, bSelf, bTarget);
} else
std::cerr << "[AVA2 TraceError] Damage is equal or below 0." << std::endl;
}
return true;
}
@@ -912,7 +931,7 @@ bool PythonNetworkStream::RecvPointChange() {
namespace {
template<class Packet> TItemData item_data(const Packet& p) {
TItemData data{};data.vnum=p.vnum;data.count=p.count;
std::copy_n(p.alSockets,ITEM_SOCKET_SLOT_MAX_NUM,data.alSockets);
std::memcpy(data.alSockets,p.alSockets,sizeof(data.alSockets));
std::copy_n(p.aAttr,ITEM_ATTRIBUTE_SLOT_MAX_NUM,data.aAttr);
std::copy_n(p.randomAttr,GLOVE_ATTR_MAX_NUM,data.randomAttr);
std::copy_n(p.name,25,data.name);data.name[24]=0;
@@ -945,7 +964,7 @@ bool PythonNetworkStream::RecvItemUpdatePacket() {
TPacketGCItemUpdate p;
if(!Read(sizeof(p),&p)) return false;
auto data=GetPlayerItemData(p.Cell.window_type,p.Cell.cell);data.count=p.count;
std::copy_n(p.alSockets,ITEM_SOCKET_SLOT_MAX_NUM,data.alSockets);
std::memcpy(data.alSockets,p.alSockets,sizeof(data.alSockets));
std::copy_n(p.aAttr,ITEM_ATTRIBUTE_SLOT_MAX_NUM,data.aAttr);
std::copy_n(p.randomAttr,GLOVE_ATTR_MAX_NUM,data.randomAttr);
std::copy_n(p.name,25,data.name);data.name[24]=0;
@@ -1030,34 +1049,21 @@ bool PythonNetworkStream::RecvCreateFlyPacket() {
auto startActor = NetworkActorManager::Instance().GetActorInstance(p.dwStartVID);
auto endActor = NetworkActorManager::Instance().GetActorInstance(p.dwEndVID);
if (!startActor || !endActor) return true;
float startPos[3] = {0.0f, 100.0f, 0.0f};
float endPos[3] = {200.0f, 100.0f, 0.0f};
if (startActor) {
startPos[0] = startActor->GetX();
startPos[1] = startActor->GetY() + 60.0f;
startPos[2] = startActor->GetZ();
}
if (endActor) {
endPos[0] = endActor->GetX();
endPos[1] = endActor->GetY() + 60.0f;
endPos[2] = endActor->GetZ();
}
FlyingManager::Instance().CreateFlyingInstance(p.bType, startPos, endPos, [endVID = p.dwEndVID](const float* hitPos) {
EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", hitPos[0], hitPos[1], hitPos[2]);
});
if (m_flyCallback) {
m_flyCallback(p.bType, p.dwStartVID, p.dwEndVID);
}
const float startPos[3] = {startActor->GetX(), startActor->GetY(), startActor->GetZ()};
float endPos[3];
endActor->GetFlyTargetCenter(endPos);
FlyingManager::Instance().CreateIndexedFly(p.bType, startPos, startActor->GetYaw(), endPos, endActor->CaptureFlyTargetResolver());
return true;
}
bool PythonNetworkStream::RecvWarpPacket() {
TPacketGCWarp p;
if (!Read(sizeof(p), &p)) return false;
// CNetworkStream::Connect disconnects first: nothing after GC_WARP on the old socket is processed.
m_warpRequested=true;m_warpAddress=uint32_t(p.lAddr);m_warpPort=p.wPort;
m_recvBuffer.clear();m_stopGamePhase=true;
return true;
}
@@ -1289,6 +1295,27 @@ bool PythonNetworkStream::SendChatPacket(const std::string& input,uint8_t type)
bool PythonNetworkStream::SendWhisperPacket(const std::string& name,const std::string& text) {
auto bytes=wire::whisper(name,text);Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendMobileMessagePacket(const std::string& name,const std::string& text) {
auto bytes=wire::mobile_message(name,text);
if(bytes.empty()) return false;
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::Send67AttrPacket(int material,int support,int support_pos,int item_pos) {
auto bytes=wire::attribute67(material,support,support_pos,item_pos);Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::Send67AttrClosePacket() {
uint8_t header=HEADER_CG_CLOSE_67_ATTR;Send(&header,1);return true;
}
bool PythonNetworkStream::SendCalendarPacket(uint8_t subheader,int day,int event,const std::string& start,const std::string& end) {
if(!main_actor_can_act(m_dwMainActorVID)) return true;
auto bytes=wire::calendar(subheader,day,event,start,end);Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendCatchKingPacket(uint8_t subheader,int argument) {
auto bytes=wire::catch_king(subheader,argument);Send(bytes.data(),bytes.size());return true;
}
void PythonNetworkStream::OpenCatchKing() {
inventory_callback(m_phaseWindows[5],"StartCatchKing",nullptr);
}
bool PythonNetworkStream::SendItemUsePacket(uint8_t window, uint16_t cell) {
if(!main_actor_can_act(m_dwMainActorVID)) return true;
@@ -1390,6 +1417,7 @@ bool PythonNetworkStream::SendFlyTargetingPacket(uint32_t targetVID, int32_t x,
TPacketCGFlyTargeting p;
p.bHeader = HEADER_CG_FLY_TARGETING;
p.dwTargetVID = targetVID;
LocalToGlobalPosition(x,y); // __LocalPositionToGlobalPosition
p.x = x;
p.y = y;
Send(&p, sizeof(p));
@@ -1400,6 +1428,7 @@ bool PythonNetworkStream::SendAddFlyTargetingPacket(uint32_t targetVID, int32_t
TPacketCGFlyTargeting p;
p.bHeader = HEADER_CG_ADD_FLY_TARGETING;
p.dwTargetVID = targetVID;
LocalToGlobalPosition(x,y); // __LocalPositionToGlobalPosition
p.x = x;
p.y = y;
Send(&p, sizeof(p));
@@ -1598,6 +1627,7 @@ bool PythonNetworkStream::RecvSafeBoxSetPacket() {
if (!Read(sizeof(p), &p)) return false;
auto item=item_data(p);item.flags=p.flags;item.anti_flags=p.anti_flags;
CPythonSafeBox::Instance().SetItemData(p.Cell.cell, item);
m_refreshSafebox=true;
return true;
}
@@ -1605,12 +1635,14 @@ bool PythonNetworkStream::RecvSafeBoxDelPacket() {
TPacketGCItemDel p;
if (!Read(sizeof(p), &p)) return false;
CPythonSafeBox::Instance().DelItemData(p.pos);
m_refreshSafebox=true;
return true;
}
bool PythonNetworkStream::RecvSafeBoxWrongPasswordPacket() {
TPacketGCSafeboxWrongPassword p;
if (!Read(sizeof(p), &p)) return false;
PyCallClassMemberFunc(m_phaseWindows[5],"OnSafeBoxError",Py_BuildValue("()"));
return true;
}
@@ -1618,6 +1650,7 @@ bool PythonNetworkStream::RecvSafeBoxSizePacket() {
TPacketGCSafeboxSize p;
if (!Read(sizeof(p), &p)) return false;
CPythonSafeBox::Instance().OpenSafeBox(p.bSize);
inventory_callback(m_phaseWindows[5],"OpenSafeboxWindow",Py_BuildValue("(i)",p.bSize));
return true;
}
@@ -1625,6 +1658,7 @@ bool PythonNetworkStream::RecvSafeBoxMoneyChangePacket() {
TPacketGCSafeboxMoneyChange p;
if (!Read(sizeof(p), &p)) return false;
CPythonSafeBox::Instance().SetMoney(p.dwMoney);
inventory_callback(m_phaseWindows[5],"RefreshSafeboxMoney",nullptr);
return true;
}
@@ -1632,6 +1666,7 @@ bool PythonNetworkStream::RecvMallOpenPacket() {
TPacketGCSafeboxSize p;
if (!Read(sizeof(p), &p)) return false;
CPythonSafeBox::Instance().OpenMall(p.bSize);
inventory_callback(m_phaseWindows[5],"OpenMallWindow",Py_BuildValue("(i)",p.bSize));
return true;
}
@@ -1640,6 +1675,7 @@ bool PythonNetworkStream::RecvMallSetPacket() {
if (!Read(sizeof(p), &p)) return false;
auto item=item_data(p);item.flags=p.flags;item.anti_flags=p.anti_flags;
CPythonSafeBox::Instance().SetMallItemData(p.Cell.cell, item);
m_refreshMall=true;
return true;
}
@@ -1647,6 +1683,7 @@ bool PythonNetworkStream::RecvMallDelPacket() {
TPacketGCItemDel p;
if (!Read(sizeof(p), &p)) return false;
CPythonSafeBox::Instance().DelMallItemData(p.pos);
m_refreshMall=true;
return true;
}
+26 -6
View File
@@ -34,6 +34,7 @@ public:
// ── Phase Management ──
void SetPhaseWindow(int phase, PyObject* poWindow);
void ClearPhaseWindow(int phase, PyObject* poWindow);
PyObject* GetGamePhaseWindow() const { return m_phaseWindows[5]; } // Borrowed, PHASE_WINDOW_GAME.
void SetHandler(PyObject* poHandler);
void SetPhase(EPhase phase);
EPhase GetPhase() const { return m_phase; }
@@ -86,6 +87,12 @@ public:
bool SendAttackPacket(uint8_t type, uint32_t victimVID);
bool SendChatPacket(const std::string& text, uint8_t type = CHAT_TYPE_TALKING);
bool SendWhisperPacket(const std::string& name, const std::string& text);
bool SendMobileMessagePacket(const std::string& name,const std::string& text);
bool Send67AttrPacket(int material,int support,int support_pos,int item_pos);
bool Send67AttrClosePacket();
bool SendCalendarPacket(uint8_t subheader,int day=0,int event=0,const std::string& start="",const std::string& end="");
bool SendCatchKingPacket(uint8_t subheader,int argument=0);
void OpenCatchKing();
bool SendItemUsePacket(uint8_t window, uint16_t cell);
bool SendItemMovePacket(uint8_t srcWindow, uint16_t srcCell, uint8_t dstWindow, uint16_t dstCell, uint32_t count);
bool SendItemPickUpPacket(uint32_t vid);
@@ -177,8 +184,6 @@ public:
std::pair<int32_t,int32_t> GetDungeonDestination() const { return m_dungeonDestination; }
// Callback when damage occurs
using DamageCallback = std::function<void(uint32_t vid, int damage, uint8_t flag)>;
void SetDamageCallback(DamageCallback cb) { m_damageCallback = cb; }
// Callback when chat is received
@@ -213,8 +218,17 @@ public:
void SetGroundItemCallback(GroundItemCallback cb) { m_groundItemCallback = cb; }
// Callback when fly projectile is created
using FlyCallback = std::function<void(uint8_t flyType, uint32_t startVID, uint32_t endVID)>;
void SetFlyCallback(FlyCallback cb) { m_flyCallback = cb; }
// GC_WARP: the transport (LoginClient::warp) performs CNetworkStream::Connect(lAddr, wPort).
bool TakeWarpRequest(uint32_t& address,uint16_t& port) {
if(!m_warpRequested) return false;
m_warpRequested=false;address=m_warpAddress;port=m_warpPort;return true;
}
// GC_PHASE(SELECT) in game: returns the bytes after it for the login transport.
bool TakeSelectRequest(std::vector<uint8_t>& leftover) {
if(!m_selectRequested) return false;
m_selectRequested=false;leftover=std::move(m_selectLeftover);m_selectLeftover.clear();return true;
}
private:
bool CheckPacket(uint8_t* retHeader);
@@ -257,9 +271,15 @@ private:
bool m_refreshGuildCombo=false,m_refreshGuildSkill=false,m_refreshGuildGrade=false,m_refreshMessenger=false;
bool m_refreshShopSearch=false;
bool m_refreshInventory=false,m_refreshStatus=false,m_refreshCharacter=false;
bool m_refreshSafebox=false,m_refreshMall=false;
std::vector<bool> m_sendSequence;
// Handshake/HandshakeOK/HybridCrypt return from GamePhase() before the refresh block.
bool m_stopGamePhase=false;
bool m_warpRequested=false;
bool m_selectRequested=false;
std::vector<uint8_t> m_selectLeftover;
uint32_t m_warpAddress=0;
uint16_t m_warpPort=0;
uint32_t m_changeServerTime=0,m_changeClientTime=0; // CPythonNetworkStream::m_kServerTimeSync
std::pair<int32_t,int32_t> m_dungeonDestination{};
bool RecvItemSetPacket();
@@ -409,10 +429,10 @@ private:
// Temporary pending actor data when CharacterAdd arrives before CharacterAdditionalInfo
SNetworkActorData m_pendingActorData;
DamageCallback m_damageCallback;
// m_pInstTarget (RecvTargetPacket): RecvDamageInfoPacket shows "target_" numbers only for it.
uint32_t m_dwInstTargetVID = 0;
WhisperCallback m_whisperCallback;
GroundItemCallback m_groundItemCallback;
FlyCallback m_flyCallback;
};
} // namespace ava2
+23 -9
View File
@@ -1,14 +1,15 @@
// Port of AVA2 UserInterface/PythonNetworkStreamCommand.cpp (ServerCommand / SplitToken)
// and the emoticon helpers from PythonNetworkStreamPhaseGame.cpp / PythonNetworkStream.cpp.
// Commands that only forward to the game window are 1:1; commands that need actor/effect
// state the port does not have yet (emotions, StoneDetect, stamina) are TraceError'd and
// listed in docs/WINDOWS-PARITY.md.
// Commands forward to the game window or actor/effect systems. Dual-emotion
// blend/collision and complete TCP scheduling limits are tracked in the parity docs.
#include "PythonNetworkStream.h"
#include "ava2_text_file.h"
#include "shared/common/PythonUtils.h"
#include "NetworkActorManager.h"
#include "eter_render/RaceData.h"
#include "python_gameplay_modules.h"
#include "eter_effect/EffectManager.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
@@ -169,17 +170,30 @@ void PythonNetworkStream::ServerCommand(const std::string& command) {
} else if (!strcasecmp(szCmd, "StoneDetect")) {
if (4 != TokenVector.size()) { strangeCount(); return; }
// Needs CInstanceBase pixel position + CEffectManager compass effects.
TraceError("ServerCommand StoneDetect not ported (effect): " + command);
const auto* actor=NetworkActorManager::Instance().GetActorData(uint32_t(atoi(arg(1))));
if(!actor || !actor->m_pActorInstance) {TraceError("StoneDetect: missing actor");return;}
const uint8_t distance=uint8_t(atoi(arg(2)));
const float angle=std::fmod(540.0f-float(atof(arg(3))),360.0f);
if(distance>3 || !std::isfinite(angle)) {TraceError("StoneDetect: invalid distance/angle");return;}
static const char* filenames[]={
"d:/ymir work/effect/etc/firecracker/find_out.mse",
"d:/ymir work/effect/etc/compass/appear_small.mse",
"d:/ymir work/effect/etc/compass/appear_middle.mse",
"d:/ymir work/effect/etc/compass/appear_large.mse"};
const auto& instance=*actor->m_pActorInstance;
EffectManager::Instance().CreateEffect(filenames[distance],instance.GetX(),instance.GetY(),instance.GetZ(),angle);
} else if (!strcasecmp(szCmd, "StartStaminaConsume")) {
if (3 != TokenVector.size()) { strangeCount(); return; }
TraceError("ServerCommand StartStaminaConsume not ported (player stamina): " + command);
StartPlayerStaminaConsume(uint32_t(atoi(arg(1))),uint32_t(atoi(arg(2))));
} else if (!strcasecmp(szCmd, "StopStaminaConsume")) {
if (2 != TokenVector.size()) { strangeCount(); return; }
TraceError("ServerCommand StopStaminaConsume not ported (player stamina): " + command);
StopPlayerStaminaConsume(uint32_t(atoi(arg(1))));
} else if (!strcasecmp(szCmd, "sms")) {
m_bMobileFlag = true;
RefreshPlayerMobile();
} else if (!strcasecmp(szCmd, "nosms")) {
m_bMobileFlag = false;
RefreshPlayerMobile();
} else if (!strcasecmp(szCmd, "mobile_auth")) {
call("OnMobileAuthority", Py_BuildValue("()"));
} else if (!strcasecmp(szCmd, "messenger_auth")) {
@@ -198,7 +212,7 @@ void PythonNetworkStream::ServerCommand(const std::string& command) {
auto pInstance1 = NetworkActorManager::Instance().GetActorInstance(iVID1);
auto pInstance2 = NetworkActorManager::Instance().GetActorInstance(iVID2);
if (pInstance1 && pInstance2)
pInstance1->ActDualEmotion(*pInstance2, CRaceMotionData::NAME_FRENCH_KISS_START, CRaceMotionData::NAME_FRENCH_KISS_START);
NetworkActorManager::Instance().BeginDualEmotion(uint32_t(iVID1),uint32_t(iVID2),CRaceMotionData::NAME_FRENCH_KISS_START,CRaceMotionData::NAME_FRENCH_KISS_START);
}
} else if (!strcasecmp(szCmd, "kiss")) {
if (TokenVector.size() >= 3) {
@@ -207,7 +221,7 @@ void PythonNetworkStream::ServerCommand(const std::string& command) {
auto pInstance1 = NetworkActorManager::Instance().GetActorInstance(iVID1);
auto pInstance2 = NetworkActorManager::Instance().GetActorInstance(iVID2);
if (pInstance1 && pInstance2)
pInstance1->ActDualEmotion(*pInstance2, CRaceMotionData::NAME_KISS_START, CRaceMotionData::NAME_KISS_START);
NetworkActorManager::Instance().BeginDualEmotion(uint32_t(iVID1),uint32_t(iVID2),CRaceMotionData::NAME_KISS_START,CRaceMotionData::NAME_KISS_START);
}
} else if (!strcasecmp(szCmd, "slap")) {
if (TokenVector.size() >= 3) {
@@ -216,7 +230,7 @@ void PythonNetworkStream::ServerCommand(const std::string& command) {
auto pInstance1 = NetworkActorManager::Instance().GetActorInstance(iVID1);
auto pInstance2 = NetworkActorManager::Instance().GetActorInstance(iVID2);
if (pInstance1 && pInstance2)
pInstance1->ActDualEmotion(*pInstance2, CRaceMotionData::NAME_SLAP_HURT_START, CRaceMotionData::NAME_SLAP_HIT_START);
NetworkActorManager::Instance().BeginDualEmotion(uint32_t(iVID1),uint32_t(iVID2),CRaceMotionData::NAME_SLAP_HURT_START,CRaceMotionData::NAME_SLAP_HIT_START);
}
} else if (!strcasecmp(szCmd, "clap")) {
if (TokenVector.size() >= 2) {
@@ -6,7 +6,7 @@
// ENABLE_CHANNEL_CHANGE, ENABLE_ANTI_EXP, ENABLE_SASH_SYSTEM, ENABLE_KINGDOMS_WAR,
// ENABLE_MINI_GAME_CATCH_KING, ENABLE_DEFENSAWESHIP; no LOCALE_SERVICE_GLOBAL, no XTrap).
// Wire reads, Python callbacks and player/party state are 1:1. Work that needs systems the
// port does not have yet (minimap/atlas marks, background target effects, fly targets,
// port does not have yet (minimap/atlas marks, fly targets,
// motion queues, guild symbols, hybrid-crypt packs, anticheat, sash/bank/chest-drop native
// stores) is consumed and listed in docs/WINDOWS-PARITY.md.
#include "PythonNetworkStream.h"
@@ -25,12 +25,16 @@
#include "python_gameplay_modules.h"
#include "python_native_modules.h"
#include "python_minimap.h"
#include "python_background.h"
#include "eter_render/RaceData.h"
#include <cmath>
#include "nonplayer_data.h"
#include "python_event_manager.h"
#include "item_sound.h"
#include "python_sash.h"
#include "python_manager_bank.h"
#include "NetworkActorManager.h"
#include "python_background.h"
#include <cstring>
#include <iostream>
@@ -297,7 +301,7 @@ bool PythonNetworkStream::RecvSwitchbotPacket() {
if(update.slot<6) {
SetPlayerItemCount(11,update.slot,update.count);
auto item=GetPlayerItemData(11,update.slot);
std::copy_n(update.alSockets,ITEM_SOCKET_SLOT_MAX_NUM,item.alSockets);
std::memcpy(item.alSockets,update.alSockets,sizeof(item.alSockets));
std::copy_n(update.aAttr,ITEM_ATTRIBUTE_SLOT_MAX_NUM,item.aAttr);SetPlayerItemData(11,update.slot,item);
}
PyCallClassMemberFunc(m_phaseWindows[5],"RefreshSwitchbotItem",Py_BuildValue("(i)",int(update.slot)));
@@ -597,6 +601,7 @@ bool PythonNetworkStream::RecvTargetInfoPacket() {
PyCallClassMemberFunc(game,"BINARY_AddTargetMonsterDropInfo",Py_BuildValue("(iii)",int(p.race),int(p.dwVnum),int(p.count)));
PyCallClassMemberFunc(game,"BINARY_RefreshTargetMonsterDropInfo",Py_BuildValue("(i)",int(p.race)));
} else PyCallClassMemberFunc(game,"CloseTargetBoard",Py_BuildValue("()"));
m_dwInstTargetVID=p.dwVID;
}
} else PyCallClassMemberFunc(game,"CloseTargetBoard",Py_BuildValue("()"));
return true;
@@ -663,11 +668,22 @@ bool PythonNetworkStream::RecvKillLOG() {
bool PythonNetworkStream::RecvFlyTargetingPacket(bool add) {
TPacketGCFlyTargeting p;
if(!Read(sizeof(p),&p)) return false;
// __GlobalPositionToLocalPosition + AddFlyTarget/SetFlyTarget on the shooter's
// graphic instance: fly-target tracking is not ported. Windows logs the missing
// shooter only for AddFlyTargeting in release builds.
if(!NetworkActorManager::Instance().GetActorData(p.dwShooterVID) && add)
trace_error("CPythonNetworkStream::RecvFlyTargetingPacket() - dwShooterVID["+std::to_string(p.dwShooterVID)+"] NOT EXIST");
GlobalToLocalPosition(p.lX,p.lY);
// Windows logs the missing shooter only for AddFlyTargeting in release builds.
auto* shooter=NetworkActorManager::Instance().GetActorData(p.dwShooterVID);
if(!shooter || !shooter->m_pActorInstance) {
if(add) trace_error("CPythonNetworkStream::RecvFlyTargetingPacket() - dwShooterVID["+std::to_string(p.dwShooterVID)+"] NOT EXIST");
return true;
}
ActorInstance& inst=*shooter->m_pActorInstance;
auto* target=p.dwTargetVID ? NetworkActorManager::Instance().GetActorData(p.dwTargetVID) : nullptr;
if(target && target->m_pActorInstance) {
if(add) inst.AddFlyTarget(p.dwTargetVID); else inst.SetFlyTarget(p.dwTargetVID);
} else {
// GetHeight(lX, lY) + 60.0f: "TEMPORARY HEIGHT" on Windows. Engine axes are (x, h, y).
const float h=CPythonBackground::Instance().GetHeight(float(p.lX),float(p.lY))+60.0f;
if(add) inst.AddFlyTarget(float(p.lX),h,float(p.lY)); else inst.SetFlyTarget(float(p.lX),h,float(p.lY));
}
return true;
}
@@ -741,16 +757,29 @@ bool PythonNetworkStream::RecvFishing() {
SNetworkActorData* inst=nullptr;
if(p.subheader!=FISHING_SUBHEADER_GC_FISH) {
inst=NetworkActorManager::Instance().GetActorData(p.info);
if(!inst) return true;
if(!inst || !inst->m_pActorInstance) return true;
}
// Fishing motions/emoticons are not ported; m_isFishing mirrors IsFishing().
auto* actor=inst ? inst->m_pActorInstance.get() : nullptr;
// AVA2 InstanceBaseMotion: queue one-shot transitions followed by wait loops.
switch(p.subheader) {
case FISHING_SUBHEADER_GC_START: inst->m_isFishing=true;break;
case FISHING_SUBHEADER_GC_STOP: if(inst->m_isFishing) inst->m_isFishing=false;break;
case FISHING_SUBHEADER_GC_REACT: break;
case FISHING_SUBHEADER_GC_SUCCESS: inst->m_isFishing=false;break;
case FISHING_SUBHEADER_GC_START:
actor->SetYaw(float(p.dir)*5);
actor->PushMotionIndex(RaceData::NAME_FISHING_THROW,false);
actor->PushMotionIndex(RaceData::NAME_FISHING_WAIT,true);break;
case FISHING_SUBHEADER_GC_STOP:
if(actor->IsFishing()) {actor->InterceptMotionIndex(RaceData::NAME_FISHING_STOP,false);actor->PushMotionIndex(RaceData::NAME_WAIT,true);}
break;
case FISHING_SUBHEADER_GC_REACT:
if(actor->IsFishing()) {
NetworkActorManager::Instance().SetEmoticon(p.info,11); // EMOTICON_FISH
actor->PushMotionIndex(RaceData::NAME_FISHING_REACT,false);
actor->PushMotionIndex(RaceData::NAME_FISHING_WAIT,true);
}
break;
case FISHING_SUBHEADER_GC_SUCCESS:
actor->InterceptMotionIndex(RaceData::NAME_FISHING_CATCH,false);actor->PushMotionIndex(RaceData::NAME_WAIT,true);break;
case FISHING_SUBHEADER_GC_FAIL:
inst->m_isFishing=false;
actor->InterceptMotionIndex(RaceData::NAME_FISHING_FAIL,false);actor->PushMotionIndex(RaceData::NAME_WAIT,true);
if(inst==MainInstance()) PyCallClassMemberFunc(game,"OnFishingFailure",Py_BuildValue("()"));
break;
case FISHING_SUBHEADER_GC_FISH: {
@@ -760,7 +789,7 @@ bool PythonNetworkStream::RecvFishing() {
auto* main=MainInstance();
if(!main) return true;
constexpr int ITEM_TYPE_FISH=12;
PyCallClassMemberFunc(game,main->m_isFishing?"OnFishingNotify":"OnFishingSuccess",Py_BuildValue("(is)",int(type==ITEM_TYPE_FISH),name.c_str()));
PyCallClassMemberFunc(game,(main->m_pActorInstance && main->m_pActorInstance->IsFishing())?"OnFishingNotify":"OnFishingSuccess",Py_BuildValue("(is)",int(type==ITEM_TYPE_FISH),name.c_str()));
break;
}
}
@@ -898,14 +927,17 @@ bool PythonNetworkStream::RecvTargetUpdatePacket() {
TPacketGCTargetUpdate p;
if(!Read(sizeof(p),&p)) return false;
CPythonMiniMap::Instance().UpdateTarget(p.lID,p.lX,p.lY);
return true; // background CreateTargetEffect(Shop) (bType 5): not ported.
if(p.bType==5) CPythonBackground::Instance().CreateTargetEffectShop(p.lID,long(p.lX),long(p.lY));
else CPythonBackground::Instance().CreateTargetEffect(p.lID,long(p.lX),long(p.lY));
return true;
}
bool PythonNetworkStream::RecvTargetDeletePacket() {
TPacketGCTargetDelete p;
if(!Read(sizeof(p),&p)) return false;
CPythonMiniMap::Instance().DeleteTarget(p.lID);
return true; // background DeleteTargetEffect: not ported.
CPythonBackground::Instance().DeleteTargetEffect(p.lID);
return true;
}
bool PythonNetworkStream::RecvTargetCreatePacket() {
@@ -919,11 +951,13 @@ bool PythonNetworkStream::RecvTargetCreatePacket() {
bool PythonNetworkStream::RecvTargetCreatePacketNew() {
TPacketGCTargetCreateNew p;
if(!Read(sizeof(p),&p)) return false;
// CREATE_TARGET_TYPE_LOCATION (1); WJ_COMBAT_ZONE is off. Background CreateTargetEffect: not ported.
// CREATE_TARGET_TYPE_LOCATION (1); WJ_COMBAT_ZONE is off.
if(p.byType==1)
CPythonMiniMap::Instance().CreateTarget(p.lID,text(p.szTargetName).c_str());
else
else {
CPythonMiniMap::Instance().CreateTarget(p.lID,text(p.szTargetName).c_str(),p.dwVID);
CPythonBackground::Instance().CreateTargetEffect(p.lID,p.dwVID);
}
PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_OpenAtlasWindow",Py_BuildValue("()"));
return true;
}
@@ -958,7 +992,16 @@ bool PythonNetworkStream::RecvLovePointUpdatePacket() {
bool PythonNetworkStream::RecvDigMotionPacket() {
TPacketGCDigMotion p;
if(!Read(sizeof(p),&p)) return false;
return true; // NEW_LookAtDestInstance + PushOnceMotion(NAME_DIG): motion queue not ported.
auto& actors=NetworkActorManager::Instance();
auto actor=actors.GetActorInstance(p.vid);
if(!actor) return true;
auto target=actors.GetActorInstance(p.target_vid);
if(target) {
const float dx=target->GetX()-actor->GetX(),dz=target->GetZ()-actor->GetZ();
if(dx!=0 || dz!=0) actor->SetYaw(std::fmod(std::atan2(dx,dz)*180.0f/3.14159265358979323846f+360,360));
}
for(unsigned count=0;count<p.count;++count) actor->PushMotionIndex(RaceData::NAME_DIG,false);
return true;
}
bool PythonNetworkStream::RecvAccountBankPacket() {
+2 -2
View File
@@ -16,7 +16,7 @@ void CPythonSafeBox::OpenSafeBox(int iSize) {
m_dwMoney = 0;
m_itemInstanceVector.clear();
if (iSize > 0) {
m_itemInstanceVector.resize(SAFEBOX_PAGE_SIZE * iSize);
m_itemInstanceVector.resize(SAFEBOX_SLOT_X_COUNT * iSize);
}
}
@@ -51,7 +51,7 @@ bool CPythonSafeBox::GetItemDataPtr(uint32_t dwSlotIndex, TItemData** ppInstance
void CPythonSafeBox::OpenMall(int iSize) {
m_mallItemInstanceVector.clear();
if (iSize > 0) {
m_mallItemInstanceVector.resize(SAFEBOX_PAGE_SIZE * iSize);
m_mallItemInstanceVector.resize(SAFEBOX_SLOT_X_COUNT * iSize);
}
}
+1
View File
@@ -23,6 +23,7 @@ public:
~CPythonSafeBox() = default;
// Safebox (Personal Bank/Warehouse)
// iSize is the server row count, not a number of 45-slot pages.
void OpenSafeBox(int iSize);
void SetItemData(uint32_t dwSlotIndex, const TItemData& rItemData);
void DelItemData(uint32_t dwSlotIndex);
+488 -66
View File
@@ -5,6 +5,7 @@
#include "src/eter_resource/ResourceManager.h"
#include <filesystem>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iostream>
@@ -52,30 +53,113 @@ void ActorInstance::SetMainModel(std::shared_ptr<Gr2ModelInstance> model, const
auto it = m_motionPaths.find(m_currentMotion);
if (it != m_motionPaths.end()) {
std::string resolved = ResolvePath(it->second);
if (m_model->LoadExternalAnimation(resolved))
if (m_model->LoadExternalAnimation(resolved)) {
m_motionFile = resolved;
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
}
}
}
}
// Re-attaches the part slots to PART_MAIN: hair deforms with the main skeleton, the others follow
// their attaching bone; PART_SASH also takes the ENABLE_OBJ_SCALLING scale matrix.
// their attaching bone; PART_SASH also takes the ENABLE_OBJ_SCALLING scale matrix. Parts follow the
// current LOD instance (pSkelController->m_pCurrentModelInstance / AttachModelInstance).
void ActorInstance::RebindParts() {
if (!m_model) return;
m_model->DetachAll();
for (auto& lod : m_lodModels)
if (lod.model) lod.model->DetachAll();
Gr2ModelInstance* target = DrawModel();
for (uint32_t part = 1; part < kPartCount; ++part) {
const auto& slot = m_parts[part];
if (!slot.model) continue;
if (slot.bone.empty()) {
m_model->AttachPart(slot.model);
target->AttachPart(slot.model);
continue;
}
m_model->AttachModel(slot.bone, slot.model);
target->AttachModel(slot.bone, slot.model);
if (part == RaceData::PART_SASH) {
m_model->SetAttachmentAnimated(slot.bone, true);
if (m_hasSashScale) m_model->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]);
target->SetAttachmentAnimated(slot.bone, true);
if (m_hasSashScale) target->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]);
}
}
for (const auto& extra : m_extraAttachments) {
if (extra.bone.empty()) target->AttachPart(extra.model);
else target->AttachModel(extra.bone, extra.model);
}
}
void ActorInstance::DropExtraAttachment(const std::string& bone) {
if (bone.empty()) return;
m_extraAttachments.erase(std::remove_if(m_extraAttachments.begin(), m_extraAttachments.end(),
[&](const SExtraAttachment& e) { return e.bone == bone; }),
m_extraAttachments.end());
}
Gr2ModelInstance* ActorInstance::DrawModel() const {
if (m_lodLevel < m_lodModels.size() && m_lodModels[m_lodLevel].model) return m_lodModels[m_lodLevel].model.get();
return m_model.get();
}
static bool HasBone(const Gr2ModelInstance& model, const std::string& name) {
const auto& skeletons = model.GetInfo().skeletons;
if (skeletons.empty()) return false;
for (const auto& bone : skeletons[0].bones)
if (bone.name == name) return true;
return false;
}
// Some shipped LODs drop attaching bones (lion2_lod_02/03 lose "saddle", shaman_miyeom_lod_* lose
// equip_left/right). Drawing those would detach the rider or a part, so such a level falls back to
// PART_MAIN.
bool ActorInstance::LodHasAttachBones(const Gr2ModelInstance& lod) const {
for (uint32_t part = 1; part < kPartCount; ++part) {
const auto& slot = m_parts[part];
if (slot.model && !slot.bone.empty() && !HasBone(lod, slot.bone)) return false;
}
for (const auto& extra : m_extraAttachments)
if (!extra.bone.empty() && !HasBone(lod, extra.bone)) return false;
static const std::string kSaddle = "saddle";
return !HasBone(*m_model, kSaddle) || HasBone(lod, kSaddle);
}
// CGrannyLODController::SetLODLevel + SetCurrentModelInstance.
void ActorInstance::SetLodLevel(uint32_t level) {
level = std::min<uint32_t>(level, uint32_t(m_lodPaths.size()));
if (level < m_lodPaths.size()) {
if (m_lodModels.size() != m_lodPaths.size()) m_lodModels.resize(m_lodPaths.size());
auto& lod = m_lodModels[level];
if (!lod.model) {
lod.model = LoadPartModel(m_lodPaths[level]);
if (!lod.model) { // unreadable LOD: keep drawing the current instance
m_lodPaths.resize(level);
m_lodModels.resize(level);
return;
}
for (const auto& skin : m_mainSkins) lod.model->SetSkin(skin.first, skin.second);
}
if (!LodHasAttachBones(*lod.model)) level = uint32_t(m_lodPaths.size());
}
if (level == m_lodLevel) return;
m_lodLevel = level;
RebindParts();
SyncLodMotion();
}
// CGrannyLODController::SetMotionPointer applies the motion to every LOD instance; only the drawn
// one is kept in step here.
void ActorInstance::SyncLodMotion() {
if (m_lodLevel >= m_lodModels.size() || !m_lodModels[m_lodLevel].model) return;
auto& lod = m_lodModels[m_lodLevel];
bool loaded = false;
if (lod.motionFile != m_motionFile && !m_motionFile.empty() && lod.model->LoadExternalAnimation(m_motionFile)) {
lod.motionFile = m_motionFile;
loaded = true;
}
if (loaded || lod.motionLoop != m_loopMotion) {
lod.motionLoop = m_loopMotion;
lod.model->SetAnimationLoop(m_loopMotion, m_loopMotion);
}
}
bool ActorInstance::SetRace(uint32_t race) {
@@ -85,15 +169,19 @@ bool ActorInstance::SetRace(uint32_t race) {
m_raceData = nullptr;
return false;
}
m_bodyPreviousCenters.clear();
m_race = race;
m_raceData = raceData;
// memset(m_adwPartItemID) + CGraphicThingInstance::Clear(): every part model is dropped.
std::fill(std::begin(m_partItemID), std::end(m_partItemID), 0u);
for (auto& slot : m_parts) slot = SPartSlot{};
m_extraAttachments.clear();
m_model.reset();
m_modelPath.clear();
m_shapeFile.clear();
m_mainSkins.clear();
ResetLodModel();
// SetMotionIndex(eRace): the race's GENERAL motion set (motlist.txt for NPC races, the
// chrmgr.RegisterMotionData calls for races built from Python).
@@ -108,7 +196,7 @@ bool ActorInstance::SetRace(uint32_t race) {
for (auto name : kNames) {
const auto* motions = raceData->GetMotions(name);
if (!motions || motions->empty()) continue;
// The percent-weighted random pick of CActorInstance is not ported: the first entry plays.
// Preload a fallback path; playback resolves the active mode and weighted variant.
std::string gr2 = ReadMotionFileName(motions->front().fileName);
if (!gr2.empty()) RegisterMotion(static_cast<MotionType>(name), gr2);
}
@@ -118,6 +206,7 @@ bool ActorInstance::SetRace(uint32_t race) {
void ActorInstance::SetShape(uint32_t shape, float specular) {
(void)specular; // SMaterialData specular / sphere map: not rendered by the port yet.
m_bodyPreviousCenters.clear();
m_shape = shape;
RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(m_race);
if (!raceData) return;
@@ -125,19 +214,22 @@ void ActorInstance::SetShape(uint32_t shape, float specular) {
const RaceData::Shape* pkShape = raceData->FindShape(shape);
if (pkShape) {
const std::string& file = pkShape->model.empty() ? raceData->GetBaseModelFileName() : pkShape->model;
// The _lod_01.._03 LOD things are not ported: LOD 0 always draws.
auto model = LoadPartModel(file);
m_mainSkins.clear();
for (const auto& skin : pkShape->skins) m_mainSkins.emplace_back(skin.srcFileName, skin.dstFileName);
if (model) {
for (const auto& skin : pkShape->skins) model->SetSkin(skin.srcFileName, skin.dstFileName);
for (const auto& skin : m_mainSkins) model->SetSkin(skin.first, skin.second);
}
m_shapeFile = file;
SetMainModel(std::move(model), file);
} else if (raceData->IsTree()) {
// __CreateTree (SpeedTree actors) is not ported.
m_mainSkins.clear();
m_shapeFile.clear();
SetMainModel(nullptr, std::string());
} else {
const std::string& file = raceData->GetBaseModelFileName();
m_mainSkins.clear();
m_shapeFile = file;
SetMainModel(LoadPartModel(file), file);
}
@@ -166,6 +258,7 @@ void ActorInstance::AttachWeaponPart(uint32_t part, const SPartItem& item) {
m_parts[part].model = LoadPartModel(item.model);
m_parts[part].file = item.model;
m_parts[part].bone = bone;
DropExtraAttachment(bone);
// USE_WEAPON_SPECULAR sphere map and CWeaponTrace are not ported.
}
@@ -195,6 +288,7 @@ void ActorInstance::AttachSash(const SPartItem* item, float specular) {
m_parts[RaceData::PART_SASH].model = LoadPartModel(item->model);
m_parts[RaceData::PART_SASH].file = item->model;
m_parts[RaceData::PART_SASH].bone = "Bip01 Spine2";
DropExtraAttachment(m_parts[RaceData::PART_SASH].bone);
}
RebindParts();
}
@@ -211,11 +305,22 @@ void ActorInstance::ResetLodModel() {
m_hasLodModel = false;
m_lodAniFps = 120;
m_poseTimeValid = false;
m_lodPaths.clear();
m_lodModels.clear();
m_lodLevel = 0;
if (!m_model) return;
const size_t dot = m_modelPath.find_last_of('.');
const bool hasExtension = dot != std::string::npos && m_modelPath.find_first_of("/\\", dot) == std::string::npos;
std::error_code error;
m_hasLodModel = std::filesystem::is_regular_file(ResolvePath((hasExtension ? m_modelPath.substr(0, dot) : m_modelPath) + "_lod_01.gr2"), error);
const std::string stem = hasExtension ? m_modelPath.substr(0, dot) : m_modelPath;
// _lod_01.._03 until the first missing file; push_front keeps the main model last.
for (int index = 1; index <= 3; ++index) {
const std::string lod = stem + "_lod_0" + std::to_string(index) + ".gr2";
std::error_code error;
if (!std::filesystem::is_regular_file(ResolvePath(lod), error)) break;
m_lodPaths.insert(m_lodPaths.begin(), lod);
}
m_lodLevel = uint32_t(m_lodPaths.size());
m_hasLodModel = !m_lodPaths.empty();
// CGrannyLODController::AddModel: models of 500 units or more use the building LOD distance.
float loX, loY, loZ, hiX, hiY, hiZ;
m_lodDistance = 5000.0f; // LODDISTANCE_ACTOR
@@ -233,6 +338,8 @@ bool ActorInstance::SetModel(const std::string& modelPath) {
m_model = Gr2ModelInstance::Load(resolved);
if (!m_model) return false;
m_modelPath = modelPath;
m_mainSkins.clear();
m_extraAttachments.clear(); // a fresh instance carries none of the old attachments
ResetLodModel();
return true;
}
@@ -249,7 +356,10 @@ bool ActorInstance::SetWeapon(const std::string& weaponPath, const std::string&
}
}
if (!weaponModel) return false;
m_model->AttachModel(boneName, std::move(weaponModel));
std::shared_ptr<Gr2ModelInstance> weapon(std::move(weaponModel));
DropExtraAttachment(boneName);
m_extraAttachments.push_back({boneName, weapon});
DrawModel()->AttachModel(boneName, std::move(weapon));
return true;
}
@@ -259,7 +369,9 @@ bool ActorInstance::AttachPart(const std::string& partPath) {
if (!std::filesystem::exists(resolved)) return false;
auto partModel = Gr2ModelInstance::Load(resolved);
if (!partModel) return false;
m_model->AttachPart(std::move(partModel));
std::shared_ptr<Gr2ModelInstance> part(std::move(partModel));
m_extraAttachments.push_back({std::string(), part});
DrawModel()->AttachPart(std::move(part));
return true;
}
@@ -268,6 +380,10 @@ void ActorInstance::RegisterMotion(MotionType type, const std::string& motionGr2
}
bool ActorInstance::PlayMotion(MotionType type, bool loop) {
return PlayMotionResolved(type,loop,true);
}
bool ActorInstance::PlayMotionResolved(MotionType type, bool loop, bool randomVariants) {
if (!m_model) return false;
auto it = m_motionPaths.find(type);
if (it == m_motionPaths.end()) {
@@ -276,14 +392,26 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) {
it = m_motionPaths.find(MotionType::Attack);
}
}
std::string motionPath;
std::string motionPath,selectedMsa;
// Resolve the active mode at playback time; SetRace/armor rebuilds must not
// silently replace riding motions with GENERAL standing/walking motions.
if (m_raceData && m_motionMode != 1) {
if (m_raceData) {
uint16_t actualMode = uint16_t(m_motionMode);
if (m_raceData->GetMotionKey(actualMode, uint16_t(type), &actualMode)) {
const auto* entries = m_raceData->GetMotions(actualMode, uint32_t(type));
if (entries && !entries->empty()) motionPath = ReadMotionFileName(entries->front().fileName);
if (entries && !entries->empty()) {
size_t selected=0;
if(randomVariants && entries->size()>1) {
int percentage=int((m_motionRandom?m_motionRandom():uint32_t(std::rand()))%100);
for(size_t i=0;i<entries->size();++i) {
percentage-=uint8_t((*entries)[i].percent);
if(percentage<0) {selected=i;break;}
}
}
selectedMsa=(*entries)[selected].fileName;
motionPath=ReadMotionFileName(selectedMsa);
if(motionPath.empty()) return false;
}
}
}
if (motionPath.empty()) {
@@ -297,33 +425,271 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) {
if (!loaded) return false;
m_currentMotion = type;
m_boundMotionMsa = std::move(selectedMsa);
m_motionFile = resolved;
m_animTime = 0.0f;
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
m_loopMotion = loop;
m_model->SetAnimationLoop(loop, loop);
SyncLodMotion();
if (type == MotionType::Attack || type == MotionType::ComboAttack1 ||
type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3 ||
type == MotionType::Skill1 || type == MotionType::Skill2 ||
type == MotionType::Skill3 || type == MotionType::Skill4 ||
type == MotionType::Skill5) {
m_isAttacking = true;
} else {
m_isAttacking = false;
}
const uint32_t index = uint32_t(type);
m_isAttacking = (index >= RaceData::NAME_NORMAL_ATTACK && index <= RaceData::NAME_COMBO_ATTACK_8) ||
(index >= RaceData::NAME_SKILL && index < RaceData::NAME_SKILL_END);
OnMotionBound(index);
return true;
}
bool ActorInstance::PlayMotionIndex(uint32_t index, bool loop) {
void ActorInstance::OnMotionBound(uint32_t type) {
// __SetMotion: a hidden actor shows again; the motion node restarts at frame 0.
m_isHiding = false;
m_curFrame = 0;
m_frameCount = uint32_t(m_motionDuration * 60.0f);
m_curSkill = m_pendingSkill;
const int skillLoopCount = m_pendingLoopCount;
m_pendingSkill = 0;
m_pendingLoopCount = 0;
// ActorInstanceMotion.cpp __BindMotionData: the race motion data of the new motion.
m_curRaceMotion = nullptr;
if(!m_boundMotionMsa.empty()) m_curRaceMotion=GetRaceMotionData(m_boundMotionMsa);
// SetMotionLoopCount(__GetLoopCount()) for once motions; NEW_UseSkill sets the skill's count.
m_loopCount = (!m_loopMotion && m_curRaceMotion) ? m_curRaceMotion->loopCount : 0;
if (skillLoopCount > 0) m_loopCount = skillLoopCount;
// InterceptMotion: the fly event handler picks its target for WARP / FLY / EFFECT_TO_TARGET motions.
if (m_flyEventHandler.onSetFlyTarget && IsNeedFlyTargetMotion()) m_flyEventHandler.onSetFlyTarget();
if (!m_curRaceMotion) {
m_comboIndex = 0;
m_motionSpeed = (m_currentMotion==MotionType::Walk || m_currentMotion==MotionType::Run) ? m_moveAnimationSpeed : 1.0f;
return;
}
if (m_curRaceMotion->isAttackingMotion) m_hitDataMap.clear();
if (m_comboIndex != 0 && !m_curRaceMotion->isComboMotion) m_comboIndex = 0;
// InterceptOnceMotion(..., __GetAttackSpeed()) for normal and combo attacks.
const bool attackMotion = m_curRaceMotion->isAttackingMotion &&
(m_curRaceMotion->motionType == RaceMotionData::MOTION_TYPE_NORMAL ||
m_curRaceMotion->motionType == RaceMotionData::MOTION_TYPE_COMBO);
m_motionSpeed = (m_currentMotion==MotionType::Walk || m_currentMotion==MotionType::Run)
? m_moveAnimationSpeed : (attackMotion ? m_atkSpd : 1.0f);
}
bool ActorInstance::IsWaiting() const {
const uint32_t index = uint32_t(m_currentMotion);
return index == RaceData::NAME_WAIT || index == RaceData::NAME_INTRO_WAIT || index == RaceData::NAME_STOP;
}
void ActorInstance::SetAttackSpeed(float ratio) {
// AVA2 stores zero too. A speed change applies when the next attack binds;
// unlike SetMoveSpeed it does not restart or retime the current motion.
if(std::isfinite(ratio) && ratio>=0) m_atkSpd=ratio;
}
void ActorInstance::SetMoveAnimationSpeed(float ratio) {
if(!std::isfinite(ratio) || ratio<0 || ratio==m_moveAnimationSpeed) return;
m_moveAnimationSpeed=ratio;
// Original SetMoveSpeed restarts the current move loop at the new ratio.
if(m_currentMotion==MotionType::Walk || m_currentMotion==MotionType::Run) PlayMotion(m_currentMotion,true);
}
bool ActorInstance::IsEmotionMovementLocked() const {
const uint32_t index=uint32_t(m_currentMotion);
return m_emotionMovementLocked || (index>=RaceData::NAME_KISS_START && index<RaceData::NAME_SLAP_HURT_START+4);
}
bool ActorInstance::IsActingEmotion() const {
const uint32_t index=uint32_t(m_currentMotion);
return (index>=RaceData::NAME_KISS_START && index<RaceData::NAME_KISS_START+4)
|| (index>=RaceData::NAME_FRENCH_KISS_START && index<RaceData::NAME_FRENCH_KISS_START+4);
}
bool ActorInstance::IsFishing() const {
const uint32_t index=uint32_t(m_currentMotion);
return m_curRaceMotion && (index==RaceData::NAME_FISHING_WAIT || index==RaceData::NAME_FISHING_REACT);
}
bool ActorInstance::IsUsingSkill() const {
const uint32_t index = uint32_t(m_currentMotion);
return (index >= RaceData::NAME_SKILL && index < RaceData::NAME_SKILL_END) ||
(index >= RaceData::NAME_SPECIAL_1 && index <= RaceData::NAME_SPECIAL_6);
}
bool ActorInstance::CanUseSkill() const {
if(!CanAct()) return false;
const uint32_t motion=uint32_t(m_currentMotion);
if(motion>=RaceData::NAME_FISHING_THROW && motion<=RaceData::NAME_FISHING_FAIL) return true;
return !IsUsingSkill() || (m_curRaceMotion && m_curRaceMotion->loopCancelEnable!=0);
}
float ActorInstance::GetDefendingRadius() const {
return m_raceData ? m_raceData->GetDefendingRadius() * m_scale : 0.0f;
}
bool ActorInstance::CanCheckAttacking() const {
// isAttacking: isNormalAttacking || isComboAttacking || IsSplashAttacking.
if (!m_curRaceMotion || IsMotionFinished()) return false;
if (m_curRaceMotion->hasSplashEvent) return true;
if (!m_curRaceMotion->isAttackingMotion) return false;
return m_curRaceMotion->motionType == RaceMotionData::MOTION_TYPE_NORMAL ||
m_curRaceMotion->motionType == RaceMotionData::MOTION_TYPE_COMBO;
}
uint16_t ActorInstance::GetCurrentComboType() const {
// __GetCurrentComboType
if (IsBowMode() || IsHandMode() || m_isMountingHorse) return 0;
return m_wcurComboType;
}
void ActorInstance::RunNextCombo() {
++m_comboIndex;
if (!m_raceData) return;
const auto* combo = m_raceData->GetComboData(uint16_t(m_motionMode), GetCurrentComboType());
// The original TraceErrors these two cases on every input; the port stays quiet.
if (!combo) return;
const uint32_t arrayIndex = m_comboIndex - 1;
if (arrayIndex >= combo->size()) return;
const uint32_t comboSize = uint32_t(combo->size());
const uint16_t motion = uint16_t((*combo)[arrayIndex]);
RunComboAttack(m_atkDirYaw, motion);
if (m_comboIndex == comboSize) {
// __OnEndCombo: mounted combos wrap; on foot the index resets when Wait binds.
if (m_isMountingHorse) m_comboIndex = 1;
}
}
bool ActorInstance::InputComboAttackCommand(float dirYaw) {
m_atkDirYaw = dirYaw;
if (m_isPreInput) return false;
if (m_comboIndex == 0) {
RunNextCombo();
return true;
}
if (!m_curRaceMotion) return false;
const float elapsed = GetAttackingElapsedTime();
if (m_curRaceMotion->isComboMotion) {
if (elapsed > m_curRaceMotion->inputEndTime) {
if (IsBowMode()) m_isNextPreInput = true;
return false;
}
if (elapsed > m_curRaceMotion->nextComboTime) {
RunNextCombo();
return true;
}
if (elapsed > m_curRaceMotion->inputStartTime) m_isPreInput = true;
} else if (elapsed > m_curRaceMotion->motionDuration * 0.9f) {
RunNextCombo();
return true;
}
return false;
}
bool ActorInstance::InputNormalAttackCommand(float dirYaw) {
// __CanInputNormalAttackCommand + NormalAttack
bool canInput = IsWaiting();
if (!canInput && m_curRaceMotion && m_curRaceMotion->isAttackingMotion &&
m_curRaceMotion->motionType == RaceMotionData::MOTION_TYPE_NORMAL)
canInput = GetAttackingElapsedTime() > m_curRaceMotion->motionDuration * 0.9f;
if (!canInput) return false;
return RunNormalAttack(dirYaw);
}
bool ActorInstance::RunNormalAttack(float dirYaw) {
uint16_t motion;
if (!m_raceData || !m_raceData->GetNormalAttackIndex(uint16_t(m_motionMode), &motion)) return false;
m_yaw = dirYaw;
if (!InterceptMotionIndex(motion, false)) return false;
if (m_reportAttacks) m_attackMotions.push_back(motion); // __OnAttack
return true;
}
bool ActorInstance::RunComboAttack(float dirYaw, uint16_t motion) {
// ComboAttack: rotate, InterceptOnceMotion at the attack speed, __OnAttack. The combo index is
// kept across the bind (the original binds before it compares the new motion's combo data).
m_yaw = dirYaw;
if (!InterceptMotionIndex(motion, false)) return false;
if (m_reportAttacks) m_attackMotions.push_back(motion);
return true;
}
void ActorInstance::ComboProcess() {
if (m_comboIndex != 0) {
if (!m_curRaceMotion) {
m_comboIndex = 0; // __ClearCombo
m_isPreInput = false;
return;
}
if (m_isPreInput && GetAttackingElapsedTime() > m_curRaceMotion->nextComboTime) {
RunNextCombo();
m_isPreInput = false;
}
} else {
m_isPreInput = false;
if (!IsUsingSkill() && m_isNextPreInput) {
RunNextCombo();
m_isNextPreInput = false;
}
}
}
bool ActorInstance::PopAttackMotion(uint16_t* motion) {
if (m_attackMotions.empty()) return false;
*motion = m_attackMotions.front();
m_attackMotions.pop_front();
return true;
}
bool ActorInstance::TestAttackHit(uint32_t victimVID, float x, float z, float radius, float frameDt, bool huge) {
// __NormalAttackProcess. The original's distance vector is (dx, dz, dz); horizontal distance here.
const float distX = x - m_posX, distZ = z - m_posZ;
const float range = huge ? 500.0f : 300.0f;
if (distX * distX + distZ * distZ >= range * range) return false;
if (!CanCheckAttacking()) return false;
const float attackRadius = 20.0f;
const float victimRadius = radius > 0.0f ? radius : 50.0f;
const float limit = attackRadius + victimRadius;
const auto& pad = *m_curRaceMotion;
const float motionTime = GetAttackingElapsedTime();
const float c = std::cos(m_yaw * DEG_TO_RAD), s = std::sin(m_yaw * DEG_TO_RAD);
// Graphic space (x, y) -> port (X, Z = -y); the port yaw is the graphic rotation.
auto toWorld = [&](const float* local, float& outX, float& outZ) {
outX = m_posX + local[0] * c - local[1] * s;
outZ = m_posZ - (local[0] * s + local[1] * c);
};
for (size_t hitIndex = 0; hitIndex < pad.hitData.size(); ++hitIndex) {
const auto& hit = pad.hitData[hitIndex];
auto& hitted = m_hitDataMap[hitIndex];
const auto already = hitted.find(victimVID);
if (already != hitted.end() &&
(pad.motionType == RaceMotionData::MOTION_TYPE_COMBO || already->second > m_localTime))
continue;
auto it = hit.hitPositions.lower_bound(motionTime - frameDt);
const auto end = hit.hitPositions.upper_bound(motionTime);
for (; it != end; ++it) {
// __GetReachScale() is 1: v3Position itself.
float ax, az, bx, bz;
toWorld(it->second.last, ax, az);
toWorld(it->second.pos, bx, bz);
// Segment (a, b) against the static victim point.
const float sx = bx - ax, sz = bz - az;
const float lenSq = sx * sx + sz * sz;
float t = lenSq > 1e-6f ? ((x - ax) * sx + (z - az) * sz) / lenSq : 0.0f;
t = std::clamp(t, 0.0f, 1.0f);
const float px = ax + sx * t - x, pz = az + sz * t - z;
if (px * px + pz * pz > limit * limit) continue;
// insert keeps an existing entry, like std::map::insert in the original.
hitted.insert({victimVID, m_localTime + pad.invisibleTime});
const size_t count = hitted.size();
const bool normal = pad.motionType == RaceMotionData::MOTION_TYPE_COMBO ||
pad.motionType == RaceMotionData::MOTION_TYPE_NORMAL;
if (normal ? count > 16 : int(count) > pad.hitLimitCount) return false;
return true;
}
}
return false;
}
bool ActorInstance::PlayMotionIndex(uint32_t index, bool loop, bool randomVariants) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
const auto* motions = m_raceData->GetMotions(keyMode, index);
if (!motions || motions->empty()) return false;
const std::string gr2 = ReadMotionFileName(motions->front().fileName);
if (gr2.empty()) return false;
RegisterMotion(static_cast<MotionType>(index), gr2);
return PlayMotion(static_cast<MotionType>(index), loop);
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode),uint16_t(index),&keyMode)) return false;
return PlayMotionResolved(static_cast<MotionType>(index),loop,randomVariants);
}
bool ActorInstance::SetLoopMotionIndex(uint32_t index) {
@@ -337,23 +703,51 @@ bool ActorInstance::InterceptMotionIndex(uint32_t index, bool loop) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
m_motionQueue.clear(); // __ClearMotion
return PlayMotionIndex(index, loop);
const bool played=PlayMotionIndex(index,loop,!IsPolymorph());
// AVA2 InterceptMotion passes the base key for poly actors and normalizes
// its clip duration to 1.1 seconds before applying the requested ratio.
if(played && IsPolymorph()) m_motionSpeed*=m_motionDuration/1.1f;
return played;
}
bool ActorInstance::InterceptMotionIndex(uint32_t index, bool loop, uint32_t skill, int loopCount) {
m_pendingSkill = skill;
m_pendingLoopCount = loopCount;
const bool played = InterceptMotionIndex(index, loop);
m_pendingSkill = 0;
m_pendingLoopCount = 0;
return played;
}
bool ActorInstance::PushMotionIndex(uint32_t index, bool loop) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
m_motionQueue.emplace_back(index, loop);
m_motionQueue.push_back({index,loop});
return true;
}
// Original motion nodes retain fSpeedRatio until activation. Existing two-argument
// native calls keep attack-speed selection; explicit ratios override it.
bool ActorInstance::SetLoopMotionIndex(uint32_t index,float speedRatio) {
if(!std::isfinite(speedRatio) || speedRatio<=0 || !SetLoopMotionIndex(index)) return false;
m_motionSpeed=speedRatio;return true;
}
bool ActorInstance::InterceptMotionIndex(uint32_t index,bool loop,float speedRatio) {
if(!std::isfinite(speedRatio) || speedRatio<=0 || !InterceptMotionIndex(index,loop)) return false;
m_motionSpeed=speedRatio*(IsPolymorph()?m_motionDuration/1.1f:1.0f);return true;
}
bool ActorInstance::PushMotionIndex(uint32_t index,bool loop,float speedRatio) {
if(!std::isfinite(speedRatio) || speedRatio<=0 || !PushMotionIndex(index,loop)) return false;
m_motionQueue.back().speed=speedRatio;m_motionQueue.back().explicitSpeed=true;return true;
}
bool ActorInstance::IsMotionFinished() const {
if (m_loopMotion) return false;
return m_animTime >= m_motionDuration;
}
void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
if (dt <= 0.0f || IsEmotionMovementLocked()) return;
float rad = moveYaw * DEG_TO_RAD;
m_yaw = moveYaw;
@@ -364,8 +758,15 @@ void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeight
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(testX, testZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) {
return true;
}
if (mapObjects && mapObjects->CheckCollision(testX, testZ, 30.0f)) {
return true;
if(mapObjects) {
const auto body=GetBodyCollisionSpheres();
if(body.empty()) {
const float start[3]={m_posX,m_posY+30,m_posZ},end[3]={testX,m_posY+30,testZ};
if(mapObjects->CheckMovementCollision(start,end,30))return true;
} else for(const auto& sphere:body) {
const float end[3]={sphere.position[0]+testX-m_posX,sphere.position[1],sphere.position[2]+testZ-m_posZ};
if(mapObjects->CheckMovementCollision(sphere.position.data(),end,sphere.radius))return true;
}
}
return false;
};
@@ -417,7 +818,10 @@ void ActorInstance::StopMoving() {
}
void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
if (dt <= 0.0f) {UpdateShake();return;}
std::fill(m_shakeOffset,m_shakeOffset+3,0.0f); // Transform resets last frame's graphic shake.
const auto body=GetBodyCollisionSpheres();
m_bodyPreviousCenters.clear();for(const auto& sphere:body)m_bodyPreviousCenters.push_back(sphere.position);
// 0. Click-to-Move destination pathing (aligned with 40250 CPythonPlayer)
if (m_hasMoveTarget && !m_isAttacking && m_curHP > 0) {
@@ -428,7 +832,10 @@ void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const M
if (dist <= 15.0f || dist <= step) {
bool blocked = false;
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(m_targetX, m_targetZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) blocked = true;
if (mapObjects && mapObjects->CheckCollision(m_targetX, m_targetZ, 30.0f)) blocked = true;
if(mapObjects) {
const float start[3]={m_posX,m_posY+30,m_posZ},end[3]={m_targetX,m_posY+30,m_targetZ};
if(mapObjects->CheckMovementCollision(start,end,30))blocked=true;
}
if (!blocked) {
m_posX = m_targetX;
m_posZ = m_targetZ;
@@ -475,14 +882,26 @@ void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const M
}
}
// Advance animation time
m_animTime += dt;
// Advance animation time (attack motions run at the attack speed ratio).
m_animTime += dt * m_motionSpeed;
m_localTime += dt;
m_lodLocalTime += dt; // CGrannyModelInstance::UpdateLocalTime
// MotionProcess: __MotionEventProcess, then CurrentMotionProcess (loop data).
m_eventTerrain = terrain;
MotionEventProcess();
m_eventTerrain = nullptr;
const bool looped = CurrentMotionLoopProcess();
if (!looped && m_animTime >= m_motionDuration && m_backupFlyTarget.valid) {
m_flyTarget = m_backupFlyTarget;
m_backupFlyTarget = FlyTarget();
}
UpdateAttachedEffects();
UpdateShake();
if (!m_motionQueue.empty() && m_animTime >= m_motionDuration) {
// ReservingMotionProcess: the next pushed motion takes over when the current one ends.
const auto next = m_motionQueue.front();
m_motionQueue.pop_front();
PlayMotionIndex(next.first, next.second);
if(PlayMotionIndex(next.index,next.loop) && next.explicitSpeed) m_motionSpeed=next.speed;
} else if (m_loopMotion) {
if (m_motionDuration > 0.001f && m_animTime >= m_motionDuration) {
m_animTime = std::fmod(m_animTime, m_motionDuration);
@@ -505,17 +924,17 @@ bool ActorInstance::Attack() {
if (m_curHP <= 0) return false;
if (!m_isAttacking) {
m_comboIndex = 1;
m_previewComboIndex = 1;
if (!PlayMotion(MotionType::ComboAttack1, false)) {
PlayMotion(MotionType::Attack, false);
}
return true;
} else if (m_animTime > m_motionDuration * 0.35f) {
// Advance combo chain
m_comboIndex = (m_comboIndex % 3) + 1;
m_previewComboIndex = (m_previewComboIndex % 3) + 1;
MotionType next = MotionType::ComboAttack1;
if (m_comboIndex == 2) next = MotionType::ComboAttack2;
else if (m_comboIndex == 3) next = MotionType::ComboAttack3;
if (m_previewComboIndex == 2) next = MotionType::ComboAttack2;
else if (m_previewComboIndex == 3) next = MotionType::ComboAttack3;
if (!PlayMotion(next, false)) {
PlayMotion(MotionType::Attack, false);
@@ -605,10 +1024,10 @@ bool ActorInstance::IsTargetInAttackRange(const ActorInstance& target, float max
}
std::vector<Render3DDraw> ActorInstance::BuildDrawCommands(const float* worldOverride) {
if (!m_model) return {};
if (!m_model || m_isHiding) return {}; // __HideEvent: alpha 0
float world[16];
MakeTransformMatrix(m_yaw, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, world);
auto draws = m_model->BuildDrawCommands(PoseTime(), worldOverride ? worldOverride : world);
GetWorldMatrix(world);
auto draws = DrawModel()->BuildDrawCommands(PoseTime(), worldOverride ? worldOverride : world);
// Shining system (ENABLE_SHINING_SYSTEM): weapon aura / glow
if (m_weaponShining > 0) {
@@ -686,24 +1105,36 @@ std::vector<Render3DDraw> ActorInstance::BuildDrawCommands(const float* worldOve
void ActorInstance::UpdateLODLevel(float eyeX, float eyeY, float eyeZ, float targetX, float targetZ) {
// CGrannyLODController::UpdateLODLevel; the distance from the camera target ignores height.
m_lodAniFps = 120;
const uint32_t count = GetLODCount();
uint32_t level = count - 1; // m_que_pkModelInst.back(): the main model
if (m_hasLodModel) {
const float centerX = targetX - m_posX, centerZ = targetZ - m_posZ;
if (std::sqrt(centerX * centerX + centerZ * centerZ) > 500.0f) { // LOD_APPLY_MIN
const float dx = eyeX - m_posX, dy = eyeY - m_posY, dz = eyeZ - m_posZ;
const float factor = std::clamp(m_lodDistance - std::sqrt(dx * dx + dy * dy + dz * dz), 0.0f, m_lodDistance);
const float camera = std::sqrt(dx * dx + dy * dy + dz * dz);
const float factor = std::clamp(m_lodDistance - camera, 0.0f, m_lodDistance);
m_lodAniFps = static_cast<uint32_t>((120 - 30) * factor / m_lodDistance + 30) / 10 * 10; // ANIFPS_MAX/MIN
uint8_t lodLevel = uint8_t(factor / (m_lodDistance / float(count)));
if (m_lodDistance <= 5000.0f) {
const uint32_t band = camera < 500.0f ? 0 : camera < 1500.0f ? 1 : camera < 2500.0f ? 2 : 3;
// BYTE arithmetic as in the original: band == count wraps to 255, which SetLODLevel
// clamps back to the main model (e.g. a single _lod_01 beyond 1500 units).
lodLevel = uint8_t(count - std::min(band, count) - 1);
}
level = std::min<uint32_t>(count - 1, lodLevel);
}
}
SetLodLevel(level);
// CGrannyModelInstance::Update: hold the pose until the next ANIFPS_STEP frame. A restarted or
// switched motion (time going back, new model) re-samples at once instead of mixing clips.
const uint32_t frame = static_cast<uint32_t>(m_lodLocalTime * 120.0f);
const uint32_t step = 120 / m_lodAniFps;
if (m_poseTimeValid && m_poseModel == m_model.get() && m_animTime >= m_poseAnimTime
if (m_poseTimeValid && m_poseModel == DrawModel() && m_animTime >= m_poseAnimTime
&& frame > step && frame / step == m_oldUpdateFrame / step)
return;
m_oldUpdateFrame = frame;
m_poseAnimTime = m_animTime;
m_poseModel = m_model.get();
m_poseModel = DrawModel();
m_poseTimeValid = step > 1; // full rate: always draw the current time
}
@@ -748,20 +1179,11 @@ bool ActorInstance::HitTestScreen(float clickX, float clickY, const Gr2SceneRend
}
bool ActorInstance::GetBoneWorldTransform(const std::string& boneName, float* outWorld16) const {
if (!m_model || !outWorld16) return false;
if (!outWorld16) return false;
float localBone[16];
if (!m_model->GetBoneWorldTransform(boneName, localBone, PoseTime())) {
return false;
}
// Bone poses are still Granny Z-up, just like the mesh vertices. Convert
// before composing with the engine world matrix (SDK R_GRANNY_TO_ENGINE).
for (int row=0;row<4;++row) {
const float y=localBone[row*4+1], z=localBone[row*4+2];
localBone[row*4+1]=z;
localBone[row*4+2]=-y;
}
if (!GetBoneLocalMatrix(boneName, localBone)) return false;
float actorWorld[16];
MakeTransformMatrix(m_yaw, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, actorWorld);
GetWorldMatrix(actorWorld);
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
+216 -13
View File
@@ -3,6 +3,8 @@
#include "Gr2ModelRenderer.h"
#include "TerrainHeightmap.h"
#include <deque>
#include <array>
#include <functional>
#include <string>
#include <unordered_map>
#include <memory>
@@ -11,6 +13,7 @@
namespace ava2 {
class RaceData;
struct RaceMotionData;
// Metin2 standard motion types (aligned with 40250 CRaceMotionData::EName)
enum class MotionType {
@@ -25,6 +28,11 @@ enum class MotionType {
ComboAttack1 = 14,
ComboAttack2 = 15,
ComboAttack3 = 16,
ComboAttack4 = 17,
ComboAttack5 = 18,
ComboAttack6 = 19,
ComboAttack7 = 20,
ComboAttack8 = 21,
Skill1 = 101, // Samyeon (三连击)
Skill2 = 102, // Palbang (八方风雨)
Skill3 = 103, // Jeongwi (狂战士)
@@ -36,7 +44,10 @@ enum class MotionType {
class ActorInstance {
public:
ActorInstance();
~ActorInstance() = default;
~ActorInstance();
// Attached motion-event effects are owned instances; copies would destroy them twice.
ActorInstance(const ActorInstance&) = delete;
ActorInstance& operator=(const ActorInstance&) = delete;
// Load base character mesh
bool SetModel(const std::string& modelPath);
@@ -90,20 +101,24 @@ public:
bool IsAttacking() const { return m_isAttacking; }
// CActorInstance::SetMotionMode / GetMotionMode (m_wcurMotionMode; polymorphs stay GENERAL).
void SetMotionMode(int mode) { m_motionMode = m_isPolymorph ? 1 : mode; }
void SetMotionMode(int mode) { m_motionMode = IsPolymorph() ? 1 : mode; }
int GetMotionMode() const { return m_motionMode; }
// CActorInstance::SetLoopMotion / InterceptMotion / PushOnceMotion / PushLoopMotion: the motion
// index resolves through CRaceData::GetMotionKey(m_wcurMotionMode, index). Blend times, speed
// ratios and the percent-weighted random pick are not ported (the first registered motion plays);
// Index resolves through the active mode. Blend times remain unported;
// explicit speeds are retained, and variants use original percentage selection.
// a pushed motion starts when the current one ends (a loop at its cycle end).
bool SetLoopMotionIndex(uint32_t index);
bool SetLoopMotionIndex(uint32_t index, float speedRatio);
bool InterceptMotionIndex(uint32_t index, bool loop);
bool InterceptMotionIndex(uint32_t index, bool loop, float speedRatio);
// CInstanceBase::NEW_UseSkill -> InterceptOnceMotion(motion, speed, uSkill) + SetMotionLoopCount:
// uSkill is reported by FLY / SPECIAL_ATTACKING events; loopCount > 0 overrides the race loop count.
bool InterceptMotionIndex(uint32_t index, bool loop, uint32_t skill, int loopCount);
bool PushMotionIndex(uint32_t index, bool loop);
bool PushMotionIndex(uint32_t index, bool loop, float speedRatio);
void SetMotionRandomSourceForTest(uint32_t (*random)()) { m_motionRandom=random; }
void ActEmotion(uint32_t motionIndex) { PushMotionIndex(motionIndex, false); }
void ActDualEmotion(ActorInstance& target, uint32_t motion1, uint32_t motion2) {
PushMotionIndex(motion1, false);
target.PushMotionIndex(motion2, false);
}
// World transform
void SetPosition(float x, float y, float z) { m_posX = x; m_posY = y; m_posZ = z; }
@@ -124,6 +139,7 @@ public:
// Click-to-Move Target Destination (aligned with 40250 CPythonPlayer)
void SetMoveTarget(float targetX, float targetZ) {
if (IsEmotionMovementLocked()) return;
m_targetX = targetX;
m_targetZ = targetZ;
m_hasMoveTarget = true;
@@ -145,7 +161,8 @@ public:
// Polymorph System (变身系统)
bool SetPolymorph(uint32_t mobVnum);
void ClearPolymorph();
bool IsPolymorph() const { return m_isPolymorph; }
bool IsPolymorph() const { return m_isPolymorph || m_actorType==7 || (m_actorType==6 && m_race>=8); }
void SetActorType(uint8_t type) { m_actorType=type; m_isPC=type==6; }
uint32_t GetPolymorphVnum() const { return m_polymorphVnum; }
// Shining System (ENABLE_SHINING_SYSTEM 高强装备流光系统)
@@ -172,6 +189,7 @@ public:
// CActorInstance::Revive: clears the sleep/paralysis/faint/dead/stun states (HP back to max).
void Revive() { m_sleep=m_paralysis=m_faint=m_stunned=false; m_curHP=m_maxHP; }
bool CanAct() const { return !IsDead() && !m_stunned && !m_paralysis && !m_faint && !m_sleep; }
bool CanUseSkill() const;
bool IsDead() const { return m_curHP <= 0; }
void SetName(const std::string& name) { m_name = name; }
@@ -185,6 +203,100 @@ public:
void SetComboType(uint16_t comboType) { m_wcurComboType = comboType; }
uint16_t GetComboType() const { return m_wcurComboType; }
// GameLib ActorInstanceBattle.cpp combo state machine. Direction is a port yaw (degrees).
// InputComboAttackCommand / ComboProcess / __RunNextCombo / __OnEndCombo follow the original;
// each started attack motion is queued for the caller (CPythonPlayerEventHandler::OnAttack sends
// it as a FUNC_COMBO state packet) and read with PopAttackMotion.
bool InputComboAttackCommand(float dirYaw);
bool InputNormalAttackCommand(float dirYaw);
// NormalAttack (CInstanceBase::RunNormalAttack for remote FUNC_ATTACK) and ComboAttack
// (RunComboAttack for FUNC_COMBO): play the motion facing dirYaw without the input checks.
bool RunNormalAttack(float dirYaw);
bool RunComboAttack(float dirYaw, uint16_t motion);
// Only the main actor reports its attacks (CPythonPlayerEventHandler is the main actor's handler).
void SetReportAttacks(bool report) { m_reportAttacks = report; if (!report) m_attackMotions.clear(); }
void ComboProcess();
bool PopAttackMotion(uint16_t* motion);
uint32_t GetComboIndex() const { return m_comboIndex; }
// m_fAtkSpd (atkspd / 100): attack motions advance this much faster, like the original motion
// speed ratio passed to InterceptOnceMotion.
void SetAttackSpeed(float ratio);
float GetAttackSpeed() const { return m_atkSpd; }
void SetMoveAnimationSpeed(float ratio);
float GetMoveAnimationSpeed() const { return m_moveAnimationSpeed; }
// GetAttackingElapsedTime: motion local time scaled by the attack speed.
float GetAttackingElapsedTime() const { return m_animTime; }
const RaceMotionData* GetCurrentRaceMotionData() const { return m_curRaceMotion; }
bool IsWaiting() const; // __IsWaitMotion: WAIT / INTRO_WAIT / STOP
void SetEmotionMovementLocked(bool locked) { m_emotionMovementLocked=locked; }
bool IsEmotionMovementLocked() const;
bool IsActingEmotion() const; // AVA2: only KISS/FRENCH_KISS variants, not all emotes.
bool IsFishing() const; // AVA2: current WAIT or REACT, not queued THROW.
bool IsUsingSkill() const; // NAME_SKILL..NAME_SKILL_END or SPECIAL_1..6
bool IsBowMode() const { return m_motionMode == 5 || m_motionMode == 13 || m_motionMode == 17; }
bool IsHandMode() const { return m_motionMode == 1 || m_motionMode == 9; }
bool IsMountingHorse() const { return m_isMountingHorse; }
void SetMountingHorse(bool mounted) { m_isMountingHorse = mounted; }
// CanCheckAttacking: the current motion is a NORMAL or COMBO attacking motion.
bool CanCheckAttacking() const;
// ActorInstanceCollisionDetection.cpp __NormalAttackProcess against one victim. The victim's
// defending spheres are approximated by an upright cylinder of `radius` around (x, z) (0 radius:
// 50); DetectCollisionDynamicZCylinderVSDynamicZCylinder ignores height anyway. frameDt is the
// real frame time (hit positions in [t - dt, t]). Returns true for a new hit; a victim is hit
// once per hit data in a combo motion, else again after the invisible time.
// The race's DEFENDING sphere radius (.msm AttachingData), 0 when unknown.
float GetDefendingRadius() const;
bool IsClickableDistanceDestInstance(const ActorInstance& target, float distance) const;
bool TestAttackHit(uint32_t victimVID, float x, float z, float radius, float frameDt, bool huge = false);
// ActorInstanceMotionEvent.cpp: .msa motion events and .mss sounds fire per 60 Hz motion frame
// (CActorInstance::__MotionEventProcess). SetIsPC: PCs play their sounds without the frequency check.
void SetIsPC(bool isPC) { m_isPC = isPC; }
bool IsPC() const { return m_isPC; }
bool IsHiding() const { return m_isHiding; } // CHARACTER_HIDE: the actor is not drawn
// CFlyTarget (GameLib FlyTarget.cpp): an actor VID (resolved each use) or a fixed engine position.
// The VID resolver is CPythonCharacterManager::GetInstancePtr (set by NetworkActorManager).
using ActorResolver = std::function<ActorInstance*(uint32_t vid)>;
static void SetActorResolver(ActorResolver resolver);
static ActorInstance* ResolveActor(uint32_t vid);
void SetFlyTarget(uint32_t vid);
void SetFlyTarget(float x, float y, float z);
void AddFlyTarget(uint32_t vid); // queued (one per loop) when a target is set, like AddFlyTarget
void AddFlyTarget(float x, float y, float z);
void ClearFlyTarget();
bool HasFlyTarget() const; // IsValidTarget (an actor target must still exist)
uint32_t GetFlyTargetVID() const { return m_flyTarget.vid; }
bool GetFlyTargetPosition(float* outXYZ) const;
// OnGetFlyTargetPosition: bounding-sphere centre (approximated by half the head height), +110 mounted.
void GetFlyTargetCenter(float* outXYZ) const;
std::function<bool(float*)> CaptureFlyTargetResolver() const;
void OnShootDamage();
void SetShakeSourcesForTest(uint32_t (*now)(),uint32_t (*random)()) {m_shakeNow=now;m_shakeRandom=random;}
std::weak_ptr<const uint8_t> GetFlyCollisionIdentity() const { return m_flyLifetime; }
struct BodyCollisionSphere {float radius=0;std::array<float,3> position{},lastPosition{};};
std::vector<BodyCollisionSphere> GetBodyCollisionSpheres() const;
// IFlyEventHandler (CPythonPlayerEventHandler::CNormalBowAttack_FlyEventHandler_AutoClear).
struct FlyEventHandler {
std::function<void()> onSetFlyTarget;
std::function<void(uint32_t skill)> onShoot;
std::function<void(uint32_t skill)> onExplodingAtTarget;
std::function<void(uint32_t skill,uint32_t vid)> onExplodingAtAnotherTarget;
std::function<void()> onExplodingAtBackground;
};
void SetFlyEventHandler(FlyEventHandler handler) { m_flyEventHandler = std::move(handler); }
void ClearFlyEventHandler() { m_flyEventHandler = FlyEventHandler(); }
// __OnWarp (WARP event): the main actor sends a FUNC_WAIT state packet at its new position.
bool PopWarpEvent() { const bool warped = m_warped; m_warped = false; return warped; }
// AttachEffectByID(0, bone, effect, offset): offset in model space (Z-up), empty bone = the root.
// The instance follows the actor until the effect dies or the actor is destroyed.
uint32_t AttachEffectByID(uint32_t effectId, const std::string& boneName, const float* offset);
void ClearAttachedEffects();
// __SplashAttackProcess against one victim: a SPECIAL_ATTACKING sphere set hits the victim's
// defending cylinder (radius 0: 50). Returns true for a new hit with the skill to report and
// whether the hit is sent (isEnableHitProcess).
bool SplashAttackHit(const ActorInstance& victim, float radius, uint32_t* skill, bool* sendPacket);
uint32_t GetCurrentSkill() const { return m_curSkill; }
// Cast specific skill motion (stops movement, sets attack state, plays one-shot)
bool CastSkill(MotionType skillMotion);
@@ -214,6 +326,10 @@ public:
// _lod_ models far from the camera sample their pose at a reduced animation FPS (Y-up world).
void UpdateLODLevel(float eyeX, float eyeY, float eyeZ, float targetX, float targetZ);
uint32_t GetLODAniFPS() const { return m_lodAniFps; }
// Index into the CGrannyLODController queue {_lod_N .. _lod_01, main}; the last entry is the main model.
uint32_t GetLODLevel() const { return m_lodLevel; }
uint32_t GetLODCount() const { return uint32_t(m_lodPaths.size()) + 1; }
Gr2ModelInstance* GetDrawModel() { return DrawModel(); }
Gr2ModelInstance* GetModel() { return m_model.get(); }
const std::string& GetModelPath() const { return m_modelPath; }
@@ -223,6 +339,10 @@ private:
std::shared_ptr<Gr2ModelInstance> LoadPartModel(const std::string& path) const;
void SetMainModel(std::shared_ptr<Gr2ModelInstance> model, const std::string& path);
void ResetLodModel();
Gr2ModelInstance* DrawModel() const;
void SetLodLevel(uint32_t level);
bool LodHasAttachBones(const Gr2ModelInstance& lod) const;
void SyncLodMotion();
void AttachWeaponPart(uint32_t part, const SPartItem& item);
void RebindParts();
@@ -238,6 +358,14 @@ private:
uint32_t m_hair = 0;
RaceData* m_raceData = nullptr;
SPartSlot m_parts[kPartCount];
// SetWeapon/AttachPart helpers outside the part slots, re-attached on every rebind after the
// slots (empty bone: skinned part). A slot taking the same bone drops the helper.
struct SExtraAttachment {
std::string bone;
std::shared_ptr<Gr2ModelInstance> model;
};
std::vector<SExtraAttachment> m_extraAttachments;
void DropExtraAttachment(const std::string& bone);
uint32_t m_partItemID[kPartCount] = {};
bool m_hasSashScale = false;
float m_sashScale[3] = {1.0f, 1.0f, 1.0f};
@@ -246,8 +374,20 @@ private:
mutable const Gr2ModelInstance* m_boundsModel = nullptr;
mutable float m_boundsRadius = 500.f;
std::string m_modelPath;
// LOD animation rate (CGrannyLODController); the meshes of _lod_01.._03 are still not ported.
// CGrannyLODController: _lod_01.._03 instances (queue order, coarsest first), animation rate.
float PoseTime() const { return m_poseTimeValid ? m_poseAnimTime : m_animTime; }
struct SLodModel {
std::shared_ptr<Gr2ModelInstance> model;
std::string motionFile; // external animation currently loaded on this instance
bool motionLoop = true;
};
std::vector<std::string> m_lodPaths; // queue order: _lod_N first
std::vector<SLodModel> m_lodModels; // loaded on first use, same order as m_lodPaths
uint32_t m_lodLevel = 0; // == m_lodPaths.size(): main model
std::vector<std::pair<std::string, std::string>> m_mainSkins; // shape skins, applied to every LOD
std::string m_boundMotionMsa;
uint32_t (*m_motionRandom)() = nullptr;
std::string m_motionFile; // resolved animation on m_model
bool m_hasLodModel = false;
float m_lodDistance = 5000.0f; // LODDISTANCE_ACTOR, LODDISTANCE_BUILDING for size >= 500
float m_lodLocalTime = 0.0f;
@@ -263,10 +403,71 @@ private:
float m_motionDuration = 1.0f;
bool m_loopMotion = true;
int m_motionMode = 1; // CRaceMotionData::MODE_GENERAL
std::deque<std::pair<uint32_t, bool>> m_motionQueue; // m_MotionDeque (index, loop)
bool PlayMotionIndex(uint32_t index, bool loop);
struct QueuedMotion {uint32_t index;bool loop;float speed=1;bool explicitSpeed=false;};
std::deque<QueuedMotion> m_motionQueue; // m_MotionDeque (index, loop)
bool PlayMotionIndex(uint32_t index, bool loop, bool randomVariants=true);
bool PlayMotionResolved(MotionType type, bool loop, bool randomVariants);
bool m_isAttacking = false;
int m_comboIndex = 0;
uint32_t m_comboIndex = 0;
// Combo state (CActorInstance m_isPreInput / m_isNextPreInput / m_fAtkDirRot / m_HitDataMap).
const RaceMotionData* m_curRaceMotion = nullptr;
bool m_isPreInput = false, m_isNextPreInput = false, m_isMountingHorse = false, m_reportAttacks = false;
float m_atkDirYaw = 0.0f, m_atkSpd = 1.0f, m_motionSpeed = 1.0f, m_moveAnimationSpeed = 1.0f;
std::deque<uint16_t> m_attackMotions;
// m_HitDataMap: hit data index -> (vid -> local time the victim may be hit again).
std::unordered_map<size_t, std::unordered_map<uint32_t, float>> m_hitDataMap;
float m_localTime = 0.0f;
int m_previewComboIndex = 0; // Attack() (offline preview) cycle, separate from the real combo
uint16_t GetCurrentComboType() const;
void RunNextCombo();
void OnMotionBound(uint32_t type);
// Motion events (ActorInstanceMotionEvent.cpp).
void MotionEventProcess();
void ProcessMotionEventFrame(uint32_t frame);
void UpdateAttachedEffects();
bool CurrentMotionLoopProcess();
bool IsNeedFlyTargetMotion() const;
bool GetBoneLocalMatrix(const std::string& boneName, float* outLocal16) const;
void GetWorldMatrix(float* out16,bool includeShake=true) const;
void UpdateShake();
uint32_t m_shakeEnd=0;
float m_shakeOffset[3]={};
uint32_t (*m_shakeNow)()=nullptr;
uint32_t (*m_shakeRandom)()=nullptr;
uint32_t m_curFrame = 0, m_frameCount = 0; // m_kCurMotNode.dwcurFrame / dwFrameCount
uint32_t m_curSkill = 0; // m_kCurMotNode.uSkill
int m_loopCount = 0; // m_kCurMotNode.iLoopCount
uint32_t m_pendingSkill = 0;
int m_pendingLoopCount = 0;
bool m_isPC = false, m_isHiding = false, m_warped = false;
const TerrainHeightSource* m_eventTerrain = nullptr; // WARP IsBlock during Update
struct FlyTarget {
bool valid = false;
uint32_t vid = 0; // 0: position target
float pos[3] = {};
};
FlyTarget m_flyTarget, m_backupFlyTarget;
std::deque<FlyTarget> m_flyTargetQueue;
FlyEventHandler m_flyEventHandler;
std::vector<std::array<float,3>> m_bodyPreviousCenters;
std::shared_ptr<const uint8_t> m_flyLifetime=std::make_shared<const uint8_t>(0);
struct AttachedEffect {
uint32_t instanceId = 0;
std::string bone; // empty: actor root
float offset[3] = {}; // model space (Z-up)
};
std::vector<AttachedEffect> m_attachedEffects;
// m_kSplashArea: spheres in engine space, victim vid -> local time it may be hit again.
struct SplashSphere { float radius = 0.0f; float pos[3] = {}; };
struct SplashArea {
const void* event = nullptr; // the RaceMotionData::MotionEvent that opened it
bool isEnableHitProcess = true;
uint32_t skill = 0;
float disappearTime = 0.0f;
std::vector<SplashSphere> spheres;
std::unordered_map<uint32_t, float> hitted;
};
SplashArea m_splash;
uint16_t m_wcurComboType = 0;
std::unordered_map<std::string, float> m_buffs;
@@ -292,12 +493,14 @@ private:
float m_heightOffset = 180.0f;
// Click-to-Move Target
bool m_emotionMovementLocked = false;
bool m_hasMoveTarget = false;
float m_targetX = 0.0f;
float m_targetZ = 0.0f;
// Polymorph state
bool m_isPolymorph = false;
uint8_t m_actorType = 0; // AVA2 TYPE_PC=6, TYPE_POLY=7; playable races 0..7.
uint32_t m_polymorphVnum = 0;
std::string m_origModelPath;
float m_origScale = 1.0f;
@@ -0,0 +1,509 @@
// CActorInstance motion events, fly targets and splash attacks.
// Provenance: upstream/ava2-client GameLib ActorInstanceMotionEvent.cpp (MotionEventProcess,
// ProcessMotionEvent*Event, __ShowEvent/__HideEvent), ActorInstanceMotion.cpp (__MotionEventProcess,
// CurrentMotionProcess loop data, __IsNeedFlyTargetMotion), ActorInstanceFly.cpp / FlyTarget.cpp
// (fly targets), ActorInstanceAttach.cpp (AttachEffectByID / UpdateAttachingInstances) and
// ActorInstanceCollisionDetection.cpp (__SplashAttackProcess).
//
// Coordinates: the original works in graphic space (x, y, z up; y = -port Z). Model-space offsets
// (x, y, z) become engine-local (x, z, -y), the same conversion GetBoneWorldTransform applies to
// Granny bones; graphic positions (x, y, z) become engine (x, z, -y).
#include "ActorInstance.h"
#include "RaceData.h"
#include "src/eter_effect/EffectManager.h"
#include "src/eter_effect/FlyingManager.h"
#include "src/eter_sound/SoundManager.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include "eter_base/Timer.h"
namespace ava2 {
namespace {
constexpr float kGameFPS = 60.0f; // g_fGameFPS
constexpr float kPi = 3.14159265358979323846f;
ActorInstance::ActorResolver& Resolver() {
static ActorInstance::ActorResolver resolver;
return resolver;
}
void ModelToEngine(const float* model, float* engine) {
engine[0] = model[0];
engine[1] = model[2];
engine[2] = -model[1];
}
void Multiply(const float* a, const float* b, float* out) {
for (int r = 0; r < 4; ++r)
for (int c = 0; c < 4; ++c) {
float sum = 0.0f;
for (int k = 0; k < 4; ++k) sum += a[r * 4 + k] * b[k * 4 + c];
out[r * 4 + c] = sum;
}
}
void Translation(const float* engineOffset, float* out) {
for (int i = 0; i < 16; ++i) out[i] = (i % 5 == 0) ? 1.0f : 0.0f;
out[12] = engineOffset[0];
out[13] = engineOffset[1];
out[14] = engineOffset[2];
}
} // namespace
ActorInstance::~ActorInstance() {
ClearAttachedEffects();
}
void ActorInstance::SetActorResolver(ActorResolver resolver) {
Resolver() = std::move(resolver);
}
ActorInstance* ActorInstance::ResolveActor(uint32_t vid) {
return Resolver() ? Resolver()(vid) : nullptr;
}
void ActorInstance::GetWorldMatrix(float* out16,bool includeShake) const {
MakeTransformMatrix(m_yaw, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, out16);
if(includeShake)for(int k=0;k<3;++k)out16[12+k]+=m_shakeOffset[k];
}
void ActorInstance::GetFlyTargetCenter(float* out) const {
out[0] = m_posX;
out[1] = m_posY + (m_heightOffset * 0.5f + m_modelYOffset) * m_scale;
out[2] = m_posZ;
if (m_isMountingHorse) out[1] += 110.0f;
for(int k=0;k<3;++k)out[k]+=m_shakeOffset[k];
}
// ActorInstanceBattle.cpp: strict 3D sphere-distance test, no fallback when a
// race has no defending spheres. GetPixelPosition on CActorInstance already
// returns graphic coordinates (SetCurPixelPosition negates the game Y).
bool ActorInstance::IsClickableDistanceDestInstance(const ActorInstance& target, float distance) const {
if(!target.m_raceData) return false;
float world[16];target.GetWorldMatrix(world,false);
for(const auto& sphere:target.m_raceData->GetDefendingSpheres()) {
float transform[16];std::copy(world,world+16,transform);
float bone[16];
if(sphere.attached && target.GetBoneLocalMatrix(sphere.bone,bone)) Multiply(bone,world,transform);
float local[3];ModelToEngine(sphere.position,local);
float center[3];
for(int k=0;k<3;++k)center[k]=local[0]*transform[k]+local[1]*transform[4+k]+local[2]*transform[8+k]+transform[12+k];
const float dx=center[0]-m_posX,dh=center[1]-m_posY,dy=center[2]-m_posZ;
// Original instance sphere radius is not multiplied by actor scale.
if(sphere.radius+distance>std::sqrt(dx*dx+dh*dh+dy*dy)) return true;
}
return false;
}
std::vector<ActorInstance::BodyCollisionSphere> ActorInstance::GetBodyCollisionSpheres() const {
std::vector<BodyCollisionSphere> result;
if(!m_raceData)return result;
float world[16];GetWorldMatrix(world,false);
for(const auto& sphere:m_raceData->GetBodySpheres()) {
float transform[16];std::copy(world,world+16,transform);
float bone[16];if(sphere.attached && GetBoneLocalMatrix(sphere.bone,bone))Multiply(bone,world,transform);
float local[3];ModelToEngine(sphere.position,local);
BodyCollisionSphere output;output.radius=sphere.radius;
for(int k=0;k<3;++k)output.position[k]=local[0]*transform[k]+local[1]*transform[4+k]+local[2]*transform[8+k]+transform[12+k];
output.lastPosition=result.size()<m_bodyPreviousCenters.size()?m_bodyPreviousCenters[result.size()]:output.position;
result.push_back(output);
}
return result;
}
std::function<bool(float*)> ActorInstance::CaptureFlyTargetResolver() const {
// Weak identity prevents a replacement actor with the same VID inheriting a flight.
std::weak_ptr<const uint8_t> lifetime=m_flyLifetime;
const uint32_t vid=m_vid;
return [lifetime,vid,this](float* out) {
if(lifetime.expired() || ResolveActor(vid)!=this)return false;
GetFlyTargetCenter(out);return true;
};
}
// ActorInstanceBattle ShakeProcess: sample once per transform, never move game coordinates.
void ActorInstance::UpdateShake() {
std::fill(m_shakeOffset,m_shakeOffset+3,0.0f);
if(!m_shakeEnd)return;
const uint32_t now=m_shakeNow?m_shakeNow():ELTimer_GetMSec();
if(m_shakeEnd<now){m_shakeEnd=0;return;}
auto random=[&](){return m_shakeRandom?m_shakeRandom():uint32_t(std::rand());};
float native[3];for(int k=0;k<3;++k){const auto sign=random()%2;const float amount=float(random()%10);native[k]=sign?-amount:amount;}
ModelToEngine(native,m_shakeOffset);
}
void ActorInstance::OnShootDamage() {
// ActorInstanceBattle.cpp: visual reaction only, not client-side HP deduction.
if(IsStun()){Die();return;}
m_shakeEnd=(m_shakeNow?m_shakeNow():ELTimer_GetMSec())+100u;
const uint32_t motion=uint32_t(m_currentMotion);
const bool locked=(motion>=RaceData::NAME_NORMAL_ATTACK && motion<=RaceData::NAME_COMBO_ATTACK_8)
|| (motion>=RaceData::NAME_SPECIAL_1 && motion<=RaceData::NAME_SPECIAL_6)
|| (motion>=RaceData::NAME_FISHING_THROW && motion<=RaceData::NAME_FISHING_FAIL)
|| (motion>=RaceData::NAME_CLAP && motion<RaceData::NAME_DIG)
|| (motion>=RaceData::NAME_DANCE_1 && motion<=RaceData::NAME_DANCE_6)
|| (motion>=RaceData::NAME_CONGRATULATION && motion<=RaceData::NAME_JOY)
|| (IsUsingSkill() && (!m_curRaceMotion || !m_curRaceMotion->loopCancelEnable));
if(IsDead() || locked || motion==RaceData::NAME_DAMAGE_FLYING || motion==RaceData::NAME_DAMAGE_FLYING_BACK
|| motion==RaceData::NAME_STAND_UP || motion==RaceData::NAME_STAND_UP_BACK)return;
if(InterceptMotionIndex(RaceData::NAME_DAMAGE,false))PushMotionIndex(RaceData::NAME_WAIT,true);
}
// CFlyTarget::SetFlyTarget / AddFlyTarget / Clear.
void ActorInstance::SetFlyTarget(uint32_t vid) {
m_flyTarget = FlyTarget();
m_flyTarget.valid = vid != 0;
m_flyTarget.vid = vid;
}
void ActorInstance::SetFlyTarget(float x, float y, float z) {
m_flyTarget = FlyTarget();
m_flyTarget.valid = true;
m_flyTarget.pos[0] = x;
m_flyTarget.pos[1] = y;
m_flyTarget.pos[2] = z;
}
void ActorInstance::AddFlyTarget(uint32_t vid) {
if (HasFlyTarget()) {
FlyTarget target;
target.valid = vid != 0;
target.vid = vid;
m_flyTargetQueue.push_back(target);
} else {
SetFlyTarget(vid);
}
}
void ActorInstance::AddFlyTarget(float x, float y, float z) {
if (HasFlyTarget()) {
FlyTarget target;
target.valid = true;
target.pos[0] = x;
target.pos[1] = y;
target.pos[2] = z;
m_flyTargetQueue.push_back(target);
} else {
SetFlyTarget(x, y, z);
}
}
void ActorInstance::ClearFlyTarget() {
m_flyTarget = FlyTarget();
m_backupFlyTarget = FlyTarget();
m_flyTargetQueue.clear();
}
bool ActorInstance::HasFlyTarget() const {
if (!m_flyTarget.valid) return false;
return m_flyTarget.vid == 0 || ResolveActor(m_flyTarget.vid) != nullptr;
}
bool ActorInstance::GetFlyTargetPosition(float* out) const {
if (!m_flyTarget.valid) return false;
if (m_flyTarget.vid == 0) {
std::copy(m_flyTarget.pos, m_flyTarget.pos + 3, out);
return true;
}
const ActorInstance* target = ResolveActor(m_flyTarget.vid);
if (!target) return false;
target->GetFlyTargetCenter(out);
return true;
}
bool ActorInstance::IsNeedFlyTargetMotion() const {
if (!m_curRaceMotion) return true;
for (const auto& ev : m_curRaceMotion->events)
if (ev.type == RaceMotionData::MOTION_EVENT_TYPE_WARP || ev.type == RaceMotionData::MOTION_EVENT_TYPE_FLY ||
ev.type == RaceMotionData::MOTION_EVENT_TYPE_EFFECT_TO_TARGET)
return true;
return false;
}
bool ActorInstance::GetBoneLocalMatrix(const std::string& boneName, float* localBone) const {
if (!m_model || boneName.empty()) return false;
// A bone the LOD skeleton dropped is still read from PART_MAIN.
if (!DrawModel()->GetBoneWorldTransform(boneName, localBone, PoseTime()) &&
(DrawModel() == m_model.get() || !m_model->GetBoneWorldTransform(boneName, localBone, PoseTime())))
return false;
// Bone poses are still Granny Z-up, just like the mesh vertices. Convert
// before composing with the engine world matrix (SDK R_GRANNY_TO_ENGINE).
for (int row = 0; row < 4; ++row) {
const float y = localBone[row * 4 + 1], z = localBone[row * 4 + 2];
localBone[row * 4 + 1] = z;
localBone[row * 4 + 2] = -y;
}
return true;
}
uint32_t ActorInstance::AttachEffectByID(uint32_t effectId, const std::string& boneName, const float* offset) {
const uint32_t instance = EffectManager::Instance().CreateEffect(effectId);
if (!instance) return 0;
AttachedEffect attached;
attached.instanceId = instance;
attached.bone = boneName;
if (offset) std::copy(offset, offset + 3, attached.offset);
m_attachedEffects.push_back(attached);
UpdateAttachedEffects();
return instance;
}
void ActorInstance::ClearAttachedEffects() {
for (const auto& attached : m_attachedEffects) EffectManager::Instance().DestroyEffectInstance(attached.instanceId);
m_attachedEffects.clear();
}
// UpdateAttachingInstances: bone * translation * world, or translation * world when the bone is
// missing (iBoneIndex -1). Dead instances are dropped.
void ActorInstance::UpdateAttachedEffects() {
if (m_attachedEffects.empty()) return;
auto& effects = EffectManager::Instance();
float world[16];
GetWorldMatrix(world);
for (auto it = m_attachedEffects.begin(); it != m_attachedEffects.end();) {
if (!effects.IsAliveEffect(it->instanceId)) {
it = m_attachedEffects.erase(it);
continue;
}
float offset[3], local[16], global[16];
ModelToEngine(it->offset, offset);
if (GetBoneLocalMatrix(it->bone, local)) {
// D3DX bone * T(offset): the offset is added to the bone translation unrotated.
local[12] += offset[0];
local[13] += offset[1];
local[14] += offset[2];
} else {
Translation(offset, local);
}
Multiply(local, world, global);
effects.SetEffectInstanceGlobalMatrix(it->instanceId, global);
++it;
}
}
// __MotionEventProcess: every 60 Hz motion frame up to the elapsed motion time runs its events and
// sounds once. The original steps one frame per update outside attacks; stepping by time keeps the
// same frames at any frame rate. A looping motion restarts at frame 0 when its time wraps.
void ActorInstance::MotionEventProcess() {
if (!m_curRaceMotion) return;
const uint32_t target = uint32_t(std::max(0.0f, m_animTime) * kGameFPS);
if (target < m_curFrame) {
if (!m_loopMotion) return;
for (; m_curFrame < m_frameCount; ++m_curFrame) ProcessMotionEventFrame(m_curFrame);
m_curFrame = 0;
}
for (; m_curFrame < target; ++m_curFrame) ProcessMotionEventFrame(m_curFrame);
}
void ActorInstance::ProcessMotionEventFrame(uint32_t frame) {
const RaceMotionData* motion = m_curRaceMotion;
for (const auto& ev : motion->events) {
if (ev.frame != frame) continue;
switch (ev.type) {
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT: {
float offset[3];
ModelToEngine(ev.position, offset);
float world[16];
GetWorldMatrix(world);
if (ev.isIndependent) {
const uint32_t instance = EffectManager::Instance().CreateEffect(ev.index);
float local[16], global[16];
Translation(offset, local);
Multiply(local, world, global);
if (instance) EffectManager::Instance().SetEffectInstanceGlobalMatrix(instance, global);
} else if (ev.isAttaching) {
if (ev.isFollowing) {
AttachEffectByID(ev.index, ev.boneName, ev.position);
} else {
float local[16], global[16];
if (GetBoneLocalMatrix(ev.boneName, local)) {
local[12] += offset[0];
local[13] += offset[1];
local[14] += offset[2];
Multiply(local, world, global);
const uint32_t instance = EffectManager::Instance().CreateEffect(ev.index);
if (instance) EffectManager::Instance().SetEffectInstanceGlobalMatrix(instance, global);
}
}
} else {
AttachEffectByID(ev.index, std::string(), ev.position);
}
break;
}
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT_TO_TARGET: {
// Fishing effects need m_v3FishingPosition, which only the (unported) fishing flow sets.
if (ev.isFishingEffect || !HasFlyTarget()) break;
ActorInstance* target = m_flyTarget.vid ? ResolveActor(m_flyTarget.vid) : nullptr;
if (ev.isFollowing && target) {
target->AttachEffectByID(ev.index, std::string(), ev.position);
} else {
float pos[3], offset[3];
GetFlyTargetPosition(pos);
ModelToEngine(ev.position, offset);
EffectManager::Instance().CreateEffect(ev.index, pos[0] + offset[0], pos[1] + offset[1], pos[2] + offset[2]);
}
break;
}
case RaceMotionData::MOTION_EVENT_TYPE_SCREEN_WAVING:
// CGameEventManager::ProcessEventScreenWaving only shakes within iAffectingRange of the
// event-manager centre, which python-root never sets (SetCenterPosition is unused), and the
// screen-waving effect itself is a no-op in the AVA2 build.
break;
case RaceMotionData::MOTION_EVENT_TYPE_SPECIAL_ATTACKING: {
const float radian = (270.0f + 360.0f - m_yaw) * kPi / 180.0f;
const float s = std::sin(radian), c = std::cos(radian);
const float gx = m_posX, gy = -m_posZ, gz = m_posY;
m_splash.event = &ev;
m_splash.isEnableHitProcess = ev.isEnableHitProcess;
m_splash.skill = m_curSkill;
m_splash.disappearTime = m_localTime + ev.durationTime;
m_splash.hitted.clear();
m_splash.spheres.clear();
for (const auto& sphere : ev.spheres) {
SplashSphere instance;
instance.radius = sphere.radius;
const float x = gx + sphere.position[0] * s + sphere.position[1] * c;
const float y = gy + sphere.position[0] * c - sphere.position[1] * s;
const float z = gz + sphere.position[2];
instance.pos[0] = x;
instance.pos[1] = z;
instance.pos[2] = -y;
m_splash.spheres.push_back(instance);
}
break;
}
case RaceMotionData::MOTION_EVENT_TYPE_SOUND:
SoundManager::Instance().PlaySound3D(m_posX, m_posY, m_posZ, ev.fileName);
break;
case RaceMotionData::MOTION_EVENT_TYPE_FLY: {
float targetPos[3];
if (!HasFlyTarget() || !GetFlyTargetPosition(targetPos)) break;
float start[3];
ModelToEngine(ev.position, start);
start[0] += m_posX;
start[1] += m_posY;
start[2] += m_posZ;
float bone[16];
if (ev.isAttaching && GetBoneLocalMatrix(ev.boneName, bone)) {
start[0] += bone[12];
start[1] += bone[13];
start[2] += bone[14];
}
FlyTargetResolver resolver;
std::function<void()> hit;
if(auto* target=m_flyTarget.vid?ResolveActor(m_flyTarget.vid):nullptr) {
resolver=target->CaptureFlyTargetResolver();
const auto handler=m_flyEventHandler.onExplodingAtTarget;
const uint32_t skill=m_curSkill;
hit=[target,identity=resolver,handler,skill]() {
float position[3];if(!identity(position))return;
target->OnShootDamage();
if(handler)handler(skill);
};
}
FlyCollisionCallbacks collision;
collision.owner=m_flyLifetime;
const auto another=m_flyEventHandler.onExplodingAtAnotherTarget;
const uint32_t skill=m_curSkill;
if(another)collision.onAnotherTarget=[another,skill](uint32_t vid){another(skill,vid);};
collision.onBackground=m_flyEventHandler.onExplodingAtBackground;
FlyingManager::Instance().CreateFlyingInstance(ev.index,start,targetPos,{},std::move(resolver),std::move(hit),std::move(collision));
if (m_flyEventHandler.onShoot) m_flyEventHandler.onShoot(m_curSkill);
break;
}
case RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_SHOW:
m_isHiding = false;
break;
case RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_HIDE:
m_isHiding = true;
break;
case RaceMotionData::MOTION_EVENT_TYPE_WARP: {
float target[3];
if (!HasFlyTarget() || !GetFlyTargetPosition(target)) break;
static const float kDistanceFromTarget = 270.0f;
float d[3] = {target[0] - m_posX, target[1] - m_posY, target[2] - m_posZ};
const float length = std::sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
if (length > 0.0f) for (float& v : d) v /= length;
const float destX = target[0] - d[0] * kDistanceFromTarget;
const float destZ = target[2] - d[2] * kDistanceFromTarget;
const bool blocked = m_eventTerrain && m_eventTerrain->HasAttrMap() &&
m_eventTerrain->IsAttrOn(destX, destZ, TerrainHeightmap::ATTR_FLAG_BLOCK);
if (!blocked) {
m_posX = destX;
m_posY = target[1] - d[1] * kDistanceFromTarget;
m_posZ = destZ;
if (m_eventTerrain) m_posY = m_eventTerrain->GetHeightAtWorld(m_posX, m_posZ);
}
const float dx = target[0] - m_posX, dz = target[2] - m_posZ;
if (dx * dx + dz * dz > 0.0f) m_yaw = std::atan2(dx, dz) * 180.0f / kPi; // LookAt
m_warped = true; // __OnWarp
break;
}
default:
break;
}
if (m_curRaceMotion != motion) return; // an event rebound the motion
}
// SoundEventProcess(!isPC) -> CSoundManager::UpdateSoundInstance.
for (const auto& sound : motion->sounds)
if (sound.frame == frame)
SoundManager::Instance().PlayCharacterSound3D(m_posX, m_posY, m_posZ, sound.fileName, !m_isPC);
}
// CurrentMotionProcess loop data: a loop motion jumps back to its loop start while loop counts (or
// queued fly targets) remain. Returns true when it looped.
bool ActorInstance::CurrentMotionLoopProcess() {
if (IsDead() || !m_motionQueue.empty() || !m_curRaceMotion || !m_curRaceMotion->isLoopMotion) return false;
const RaceMotionData& motion = *m_curRaceMotion;
if (m_animTime <= motion.loopEndTime) return false;
if (m_loopCount > 1 || m_loopCount == -1) {
if (m_loopCount != -1) --m_loopCount;
} else if (!m_flyTargetQueue.empty()) {
if (!m_backupFlyTarget.valid) m_backupFlyTarget = m_flyTarget;
m_flyTarget = m_flyTargetQueue.front();
m_flyTargetQueue.pop_front();
} else {
return false;
}
m_curFrame = uint32_t(motion.loopStartTime * kGameFPS);
m_animTime = motion.loopStartTime;
return true;
}
bool ActorInstance::SplashAttackHit(const ActorInstance& victim, float radius, uint32_t* skill, bool* sendPacket) {
// The original measures (dx, dz, dz) in graphic space (z is height).
const float dx = victim.m_posX - m_posX, dh = victim.m_posY - m_posY;
if (dx * dx + 2.0f * dh * dh >= 1000.0f * 1000.0f) return false;
// __IsInSplashTime
if (!m_splash.event || m_localTime >= m_splash.disappearTime) return false;
const auto& ev = *static_cast<const RaceMotionData::MotionEvent*>(m_splash.event);
if (m_splash.hitted.count(victim.m_vid)) return false;
// ATTACK_TYPE_SNIPE: with a PC fly target only that PC can be hit.
if (ev.attackType == 1 && m_flyTarget.valid && m_flyTarget.vid) {
const ActorInstance* target = ResolveActor(m_flyTarget.vid);
if (target && target->IsPC() && target != &victim) return false;
}
// CheckCollisionDetection: the victim's defending spheres are approximated by an upright
// cylinder, like TestAttackHit (height is ignored).
const float limitRadius = radius > 0.0f ? radius : 50.0f;
bool hit = false;
for (const auto& sphere : m_splash.spheres) {
const float sx = sphere.pos[0] - victim.m_posX, sz = sphere.pos[2] - victim.m_posZ;
const float limit = sphere.radius + limitRadius;
if (sx * sx + sz * sz <= limit * limit) {
hit = true;
break;
}
}
if (!hit) return false;
m_splash.hitted.insert({victim.m_vid, m_localTime + ev.invisibleTime});
const int maxHitCount = ev.hitLimitCount == 0 ? 16 : ev.hitLimitCount;
if (int(m_splash.hitted.size()) > maxHitCount) return false;
if (skill) *skill = m_splash.skill;
if (sendPacket) *sendPacket = m_splash.isEnableHitProcess;
return true;
}
} // namespace ava2
+20 -14
View File
@@ -163,30 +163,30 @@ void CRenderTarget::ResetModel() {
m_acceVnum = 0;
m_rotation = 0.0f;
m_scale = 1.0f;
m_actor = ActorInstance{};
m_actor = std::make_unique<ActorInstance>();
}
void CRenderTarget::SelectModel(uint32_t vnum) {
m_hasModel = true;
m_modelVnum = vnum;
std::string path = ResolveNpcModel(vnum);
m_actor.SetModel(path);
m_actor->SetModel(path);
if (vnum <= 8) {
m_camDistance = 240.0f;
m_camTargetHeight = 90.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/pc/warrior/general/wait.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
m_actor->RegisterMotion(MotionType::Wait, "ymir work/pc/warrior/general/wait.gr2");
m_actor->PlayMotion(MotionType::Wait, true);
} else if (vnum >= 8000 && vnum <= 8100) {
m_camDistance = 380.0f;
m_camTargetHeight = 120.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/monster/metinstone/metinstone_loop.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
m_actor->RegisterMotion(MotionType::Wait, "ymir work/monster/metinstone/metinstone_loop.gr2");
m_actor->PlayMotion(MotionType::Wait, true);
} else {
m_camDistance = 260.0f;
m_camTargetHeight = 60.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/monster/stray_dog/wait.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
m_actor->RegisterMotion(MotionType::Wait, "ymir work/monster/stray_dog/wait.gr2");
m_actor->PlayMotion(MotionType::Wait, true);
}
}
@@ -198,7 +198,7 @@ void CRenderTarget::SetArmor(uint32_t vnum) {
void CRenderTarget::SetWeapon(uint32_t vnum) {
m_weaponVnum = vnum;
std::string path = ResolveItemModel(vnum);
m_actor.SetWeapon(path, "equip_right_hand");
m_actor->SetWeapon(path, "equip_right_hand");
}
void CRenderTarget::SetHair(uint32_t vnum) {
@@ -216,7 +216,7 @@ void CRenderTarget::SetAcce(uint32_t vnum) {
"ymir work/item/wing/acce_16_86_055.gr2"
};
uint32_t idx = (vnum > 0 ? (vnum % acceCandidates.size()) : 0);
m_actor.AttachPart(acceCandidates[idx]);
m_actor->AttachPart(acceCandidates[idx]);
}
void CRenderTarget::SetBackground(const std::string& path) {
@@ -253,7 +253,7 @@ void CRenderTarget::SetModelV3Target(float x, float y, float z) {
void CRenderTarget::Update(float dt) {
if (m_bShowModel) {
m_actor.Update(dt);
m_actor->Update(dt);
m_rotation += dt * 25.0f; // gentle auto-rotation preview
if (m_rotation >= 360.0f) m_rotation -= 360.0f;
}
@@ -265,7 +265,11 @@ void CRenderTarget::Render(SDL_Renderer* renderer, const SDL_FRect& destRect) {
EnsureTextures(renderer);
if (!m_surface || !m_texture) return;
Update(1.0f / 60.0f);
// Real elapsed time between renders, so preview animation/rotation speed is frame-rate independent.
const uint64_t now = SDL_GetTicksNS();
const float dt = m_lastUpdateNs ? std::clamp(float(now - m_lastUpdateNs) * 1e-9f, 0.0f, 0.25f) : 1.0f / 60.0f;
m_lastUpdateNs = now;
Update(dt);
// If background exists, render background first directly to UI
if (m_background) {
@@ -292,7 +296,7 @@ void CRenderTarget::Render(SDL_Renderer* renderer, const SDL_FRect& destRect) {
// Render Actor
if (m_bShowModel) {
auto draws = m_actor.BuildDrawCommands();
auto draws = m_actor->BuildDrawCommands();
m_renderer3d.RenderScene(m_surface, draws);
}
@@ -312,9 +316,11 @@ CRenderTargetManager& CRenderTargetManager::Instance() {
CRenderTargetManager::CRenderTargetManager() = default;
CRenderTargetManager::~CRenderTargetManager() {
m_targets.clear();
Destroy();
}
void CRenderTargetManager::Destroy() { m_targets.clear(); }
std::shared_ptr<CRenderTarget> CRenderTargetManager::GetRenderTarget(int index) {
auto it = m_targets.find(index);
if (it != m_targets.end()) return it->second;
+4 -2
View File
@@ -42,7 +42,7 @@ public:
void Update(float dt);
void Render(SDL_Renderer* renderer, const SDL_FRect& destRect);
ActorInstance* GetModel() { return &m_actor; }
ActorInstance* GetModel() { return m_actor.get(); }
static std::string ResolveNpcModel(uint32_t vnum);
static std::string ResolveItemModel(uint32_t vnum);
@@ -56,7 +56,7 @@ private:
bool m_bShowModel = true;
bool m_hasModel = false;
ActorInstance m_actor;
std::unique_ptr<ActorInstance> m_actor = std::make_unique<ActorInstance>(); // owns effect instances: not copyable
Gr2SceneRenderer m_renderer3d;
SDL_Surface* m_surface = nullptr;
SDL_Texture* m_texture = nullptr;
@@ -70,6 +70,7 @@ private:
uint32_t m_acceVnum = 0;
float m_rotation = 0.0f;
uint64_t m_lastUpdateNs = 0;
float m_scale = 1.0f;
float m_zoom = 1.0f;
float m_pitch = 12.0f;
@@ -90,6 +91,7 @@ public:
std::shared_ptr<CRenderTarget> GetRenderTarget(int index);
std::shared_ptr<CRenderTarget> CreateRenderTarget(int index, int w = 384, int h = 384);
void DestroyRenderTarget(int index);
void Destroy();
int GetFreeIndex(int minIdx, int maxIdx);
private:
+1
View File
@@ -71,6 +71,7 @@ struct LensFlareData {
struct EnvironmentData {
std::string name;
float wind_strength = 0.2f; // AVA2 MapUtil.cpp Environment_Init default.
bool reserve = false; // MapUtil.cpp Environment_Load "reserved" (bReserve)
DirectionalLight dir_light;
MaterialData material;
+66 -18
View File
@@ -186,6 +186,7 @@ const std::string& Gr2ModelInstance::GetFilePath() const {
}
void Gr2ModelInstance::SetHardwareSkinningEnabled(bool enabled){hardwareSkinningEnabled=enabled;}
bool Gr2ModelInstance::IsHardwareSkinningEnabled(){return hardwareSkinningEnabled;}
std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommands(float animation_time, const float* world_matrix, bool forceCPU) {
std::vector<Render3DDraw> out;
@@ -338,6 +339,7 @@ void Gr2SceneRenderer::SetCameraLookAtRH(float eyeX, float eyeY, float eyeZ,
}
void Gr2SceneRenderer::SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar) {
m_perspective={fovYDegrees,aspect,zNear,zFar};
float fovRad = fovYDegrees * 3.1415926535f / 180.0f;
float h = 1.0f / std::tan(fovRad * 0.5f);
float w = h / aspect;
@@ -351,6 +353,18 @@ void Gr2SceneRenderer::SetPerspective(float fovYDegrees, float aspect, float zNe
m_proj[14] = -q * zNear;
}
void Gr2SceneRenderer::SetOrtho3D(float width,float height,float nearPlane,float farPlane) {
std::fill_n(m_proj,16,0.f);m_proj[0]=2/width;m_proj[5]=2/height;
m_proj[10]=1/(farPlane-nearPlane);m_proj[14]=-nearPlane/(farPlane-nearPlane);m_proj[15]=1;
}
void Gr2SceneRenderer::SetOrtho2D(float width,float height,float length) {
SetOrtho3D(width,height,0,length);m_proj[5]=-2/height;m_proj[12]=-1;m_proj[13]=1;
}
void Gr2SceneRenderer::SetProjectionMatrix(const float* matrix) {std::copy_n(matrix,16,m_proj);}
void Gr2SceneRenderer::BuildViewFrustum() {
const std::array<float,3> eye={m_eye[0],m_eye[1],m_eye[2]},forward={m_view[2],m_view[6],m_view[10]};
m_frustum=std::make_unique<ViewFrustum>(m_view,m_proj,eye,forward,&m_perspective);
}
void Gr2SceneRenderer::Clear(uint32_t color, float depth) {
std::fill(m_depthBuffer.begin(), m_depthBuffer.end(), depth);
}
@@ -565,7 +579,7 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
int depth_y = py - m_viewport[1];
if (depth_x < 0 || depth_x >= vpWidth || depth_y < 0 || depth_y >= vpHeight) continue;
int depth_idx = depth_y * vpWidth + depth_x;
if (depth >= 0.0f && depth <= 1.0f && (!draw.z_enable || depth <= m_depthBuffer[depth_idx])) {
if (depth >= 0.0f && depth <= 1.0f && (!draw.z_enable || (draw.depth_less ? depth < m_depthBuffer[depth_idx] : depth <= m_depthBuffer[depth_idx]))) {
// Smooth Phong Normal Interpolation
float nx = b0 * v0.nx + b1 * v1.nx + b2 * v2.nx;
float ny = b0 * v0.ny + b1 * v1.ny + b2 * v2.ny;
@@ -588,10 +602,6 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
int tex_idx = (ty * diffuse_tex->width + tx) * 4;
uint8_t ta = diffuse_tex->rgba[tex_idx + 3];
if (draw.alpha_test) {
uint32_t aref = draw.alpha_ref ? draw.alpha_ref : 70;
if (ta < aref) continue;
}
pr = diffuse_tex->rgba[tex_idx + 0];
pg = diffuse_tex->rgba[tex_idx + 1];
@@ -603,7 +613,7 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
float vr = (b0 * ((d0 >> 16) & 0xFF) + b1 * ((d1 >> 16) & 0xFF) + b2 * ((d2 >> 16) & 0xFF)) / 255.0f;
float vg = (b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF)) / 255.0f;
float vb = (b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF)) / 255.0f;
float va = (b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF)) / 255.0f;
float va = (float((d0 >> 24) & 0xFF) + b1 * (int((d1 >> 24) & 0xFF)-int((d0 >> 24) & 0xFF)) + b2 * (int((d2 >> 24) & 0xFF)-int((d0 >> 24) & 0xFF))) / 255.0f;
if (draw.lighting) {
// D3D8 fixed-function: Emissive + MatAmb*LightAmb + Diffuse*LightDiff*N.L.
float lr = std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + vr * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f);
@@ -624,7 +634,7 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
pr = b0 * ((d0 >> 16) & 0xFF) + b1 * ((d1 >> 16) & 0xFF) + b2 * ((d2 >> 16) & 0xFF);
pg = b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF);
pb = b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF);
frag_alpha = b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF);
frag_alpha = float((d0 >> 24) & 0xFF) + b1 * (int((d1 >> 24) & 0xFF)-int((d0 >> 24) & 0xFF)) + b2 * (int((d2 >> 24) & 0xFF)-int((d0 >> 24) & 0xFF));
if (draw.lighting) {
pr = 255.0f * std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + pr / 255.0f * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f);
pg = 255.0f * std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + pg / 255.0f * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f);
@@ -645,6 +655,8 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
pb = (1.0f - fog_factor) * fog_b + fog_factor * pb;
}
if(!mesh.diffuse.empty())frag_alpha*=std::clamp(draw.material_diffuse[3],0.f,1.f);
if(draw.alpha_test && frag_alpha<=float(draw.alpha_ref))continue;
bool is_blended = draw.alpha_blend || (draw.blend_mode != 0) || (!diffuse_tex && frag_alpha < 250.0f);
if (is_blended) {
uint32_t bg = dst_pixels[py * dst_pitch_pixels + px];
@@ -664,7 +676,7 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
}
}
if (draw.z_write && !is_blended) {
if (draw.z_enable && draw.z_write) {
m_depthBuffer[depth_idx] = depth;
}
@@ -819,6 +831,38 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
RenderSceneGPU(renderer, m_scratchDrawPtrs);
}
void Gr2SceneRenderer::DrawSortCenter(const Render3DDraw& draw, float out[3]) {
const auto& mesh = draw.Mesh();
const auto indices = draw.Indices();
SortCenterKey key{draw.geometry.get(), draw.first_index, draw.index_count};
if (draw.geometry) {
auto it = m_sortCenterCache.find(key);
if (it != m_sortCenterCache.end()) {
if (it->second.owner.lock() == draw.geometry) {
std::memcpy(out, it->second.c, sizeof(it->second.c));
return;
}
m_sortCenterCache.erase(it); // freed geometry whose address was reused
}
}
const size_t vertexCount = mesh.positions.size() / 3;
float lo[3] = {INFINITY, INFINITY, INFINITY}, hi[3] = {-INFINITY, -INFINITY, -INFINITY};
for (size_t i = 0; i < indices.size; ++i) {
const uint32_t v = indices.data[i];
if (v >= vertexCount) continue;
const float* p = &mesh.positions[size_t(v) * 3];
for (int a = 0; a < 3; ++a) { lo[a] = std::min(lo[a], p[a]); hi[a] = std::max(hi[a], p[a]); }
}
if (lo[0] > hi[0]) return; // no valid vertex: keep the caller's fallback
for (int a = 0; a < 3; ++a) out[a] = 0.5f * (lo[a] + hi[a]);
if (draw.geometry) {
if (m_sortCenterCache.size() >= 8192) m_sortCenterCache.clear();
auto& entry = m_sortCenterCache[key];
entry.owner = draw.geometry;
std::memcpy(entry.c, out, sizeof(entry.c));
}
}
void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<const Render3DDraw*>& draws) {
if (!renderer || draws.empty()) return;
++m_textureFrame;
@@ -853,15 +897,6 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
ord.texture=m_hardware->Texture(d.texture0,data->width,data->height,data->rgba.data());}
if(!ord.texture)continue;
}
{
float cx = sortedMesh.positions[0], cy = sortedMesh.positions[1], cz = sortedMesh.positions[2];
float wx = cx * d.world[0] + cy * d.world[4] + cz * d.world[8] + d.world[12];
float wy = cx * d.world[1] + cy * d.world[5] + cz * d.world[9] + d.world[13];
float wz = cx * d.world[2] + cy * d.world[6] + cz * d.world[10] + d.world[14];
float dx = wx - m_eye[0], dy = wy - m_eye[1], dz = wz - m_eye[2];
ord.depth = dx * dx + dy * dy + dz * dz;
}
if (!d.z_enable) {
ord.priority = 0; // Skybox
} else if (d.terrain) {
@@ -875,6 +910,19 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
} else {
ord.priority = 1; // Opaque
}
{
// Order-dependent draws (blended, no depth write) sort by the bounds centre of the
// vertices they reference; for depth-writing opaque draws depth is only a tie-break.
float c[3] = {sortedMesh.positions[0], sortedMesh.positions[1], sortedMesh.positions[2]};
if (ord.priority >= 4 || d.alpha_blend || !d.z_write) DrawSortCenter(d, c);
float cx = c[0], cy = c[1], cz = c[2];
float wx = cx * d.world[0] + cy * d.world[4] + cz * d.world[8] + d.world[12];
float wy = cx * d.world[1] + cy * d.world[5] + cz * d.world[9] + d.world[13];
float wz = cx * d.world[2] + cy * d.world[6] + cz * d.world[10] + d.world[14];
float dx = wx - m_eye[0], dy = wy - m_eye[1], dz = wz - m_eye[2];
ord.depth = dx * dx + dy * dy + dz * dz;
}
m_scratchSortedDraws.push_back(ord);
}
@@ -929,7 +977,7 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
if (m_hardware) {
SDL_GPUTexture* texture=ord.texture;
HardwareBatch batch{};batch.texture=texture;batch.cull=draw.cull_mode;
batch.depth=draw.z_enable;batch.depthWrite=draw.z_enable&&draw.z_write;
batch.depthLess=draw.depth_less;batch.depth=draw.z_enable;batch.depthWrite=draw.z_enable&&draw.z_write;
batch.blend=draw.alpha_blend;batch.additive=draw.blend_mode==1;
batch.alphaRef=draw.alpha_test ? draw.alpha_ref/255.f : -1.f;
batch.geometry=draw.geometry;
+25
View File
@@ -2,6 +2,7 @@
#include "RenderCommands3D.h"
#include "HardwareScene.h"
#include "ViewFrustum.h"
#include <gr2/gr2.h>
#include <gr2_render/gr2_render.h>
#include <SDL3/SDL.h>
@@ -16,6 +17,7 @@ class Gr2ModelInstance {
public:
Gr2ModelInstance() = default;
static void SetHardwareSkinningEnabled(bool enabled);
static bool IsHardwareSkinningEnabled();
explicit Gr2ModelInstance(std::shared_ptr<gr2_render::Gr2ModelInstance> impl)
: m_impl(std::move(impl)) {}
@@ -81,6 +83,13 @@ public:
void SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar);
void SetOrtho2D(float width,float height,float length);
void SetOrtho3D(float width,float height,float nearPlane,float farPlane);
void SetProjectionMatrix(const float* matrix); // Retains the last perspective metadata.
void BuildViewFrustum(); // Explicit UpdateGame boundary; setters do not invalidate the snapshot.
const ViewFrustum* GetCachedViewFrustum() const {return m_frustum.get();}
DepthState GetDepthState() const {return m_depthState;}
void SetDepthState(DepthState state) {m_depthState=state;}
void SetViewport(int x, int y, int width, int height);
void Clear(uint32_t color = 0xFF101520, float depth = 1.0f);
@@ -158,6 +167,9 @@ private:
float m_eye[3] = {0.0f, 0.0f, 0.0f};
float m_view[16];
float m_proj[16];
PerspectiveMetadata m_perspective;
std::unique_ptr<ViewFrustum> m_frustum;
DepthState m_depthState;
int m_viewport[4];
int m_logicalWidth = 0;
int m_logicalHeight = 0;
@@ -170,6 +182,19 @@ private:
// Persistent scratch buffers to eliminate per-draw heap allocation churn in RenderSceneGPU
std::vector<DrawOrder> m_scratchSortedDraws;
// Local bounds centre of a shared geometry's index range (immutable, so cached across frames).
struct SortCenterKey {
const Render3DDraw* geometry; std::uint32_t first, count;
bool operator==(const SortCenterKey& o) const { return geometry==o.geometry && first==o.first && count==o.count; }
};
struct SortCenterHash {
size_t operator()(const SortCenterKey& k) const {
return std::hash<const void*>{}(k.geometry) ^ (size_t(k.first) * 0x9E3779B97F4A7C15ull) ^ (size_t(k.count) << 1);
}
};
struct SortCenter { std::weak_ptr<const Render3DDraw> owner; float c[3]; };
std::unordered_map<SortCenterKey, SortCenter, SortCenterHash> m_sortCenterCache;
void DrawSortCenter(const Render3DDraw& draw, float out[3]);
std::vector<const Render3DDraw*> m_scratchDrawPtrs;
std::vector<GpuTransformedVertex> m_scratchGpuXverts;
std::vector<SDL_Vertex> m_scratchSdlVertices;
+2 -2
View File
@@ -149,7 +149,7 @@ SDL_GPUGraphicsPipeline* HardwareScene::Pipeline(const HardwareBatch& b) {
info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
info.rasterizer_state.front_face=SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
info.rasterizer_state.cull_mode=b.cull==1 ? SDL_GPU_CULLMODE_NONE : b.cull==2 ? SDL_GPU_CULLMODE_BACK : SDL_GPU_CULLMODE_FRONT;
info.depth_stencil_state.compare_op=SDL_GPU_COMPAREOP_LESS_OR_EQUAL;
info.depth_stencil_state.compare_op=b.depthLess?SDL_GPU_COMPAREOP_LESS:SDL_GPU_COMPAREOP_LESS_OR_EQUAL;
info.depth_stencil_state.enable_depth_test=b.depth;
info.depth_stencil_state.enable_depth_write=b.depthWrite;
SDL_GPUColorTargetDescription target{};target.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
@@ -311,7 +311,7 @@ bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std
if(mesh && !batch.blend && !batch.additive && batch.depthWrite && batch.transform.skin[0]==0 && batch.transform.modes[0]>0.5f)
while(i+count<batches.size()) {
const auto& next=batches[i+count];
if(meshes[i+count]!=mesh || next.firstIndex!=batch.firstIndex || next.indexCount!=batch.indexCount || next.texture!=batch.texture || next.cull!=batch.cull || next.depth!=batch.depth || next.depthWrite!=batch.depthWrite || next.blend || next.additive || next.alphaRef!=batch.alphaRef || next.transform.skin[0]!=0 || next.transform.modes[0]<.5f)break;
if(meshes[i+count]!=mesh || next.firstIndex!=batch.firstIndex || next.indexCount!=batch.indexCount || next.texture!=batch.texture || next.cull!=batch.cull || next.depth!=batch.depth || next.depthWrite!=batch.depthWrite || next.depthLess!=batch.depthLess || next.blend || next.additive || next.alphaRef!=batch.alphaRef || next.transform.skin[0]!=0 || next.transform.modes[0]<.5f)break;
++count;
}
SDL_GPUBuffer* vertexBuffer=mesh ? mesh->vertices : vertices_;SDL_GPUBuffer* indexBuffer=mesh ? mesh->indices : indices_;
+2 -1
View File
@@ -33,12 +33,13 @@ struct HardwareBatch {
uint32_t cull;
bool depth, depthWrite, blend, additive;
float alphaRef;
bool depthLess=false;
HardwareTransform transform{};
std::shared_ptr<const Render3DDraw> geometry;
std::shared_ptr<const std::vector<float>> palette;
};
inline unsigned PipelineKey(const HardwareBatch& b) {
return b.cull|(unsigned(b.depth)<<3)|(unsigned(b.depthWrite)<<4)|(unsigned(b.blend)<<5)|(unsigned(b.additive)<<6);
return b.cull|(unsigned(b.depth)<<3)|(unsigned(b.depthWrite)<<4)|(unsigned(b.blend)<<5)|(unsigned(b.additive)<<6)|(unsigned(b.depthLess)<<7);
}
class HardwareScene {
public:
+116 -5
View File
@@ -7,6 +7,7 @@
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstring>
namespace ava2 {
@@ -48,6 +49,75 @@ inline void MakeFullTransformMatrix(float yawDeg, float pitchDeg, float rollDeg,
} // namespace
bool MapCollisionPlane::Intersects(const float* start,const float* end,float radius,bool movement) const {
float before=0,after=0,u=0,v=0;
for(int k=0;k<3;++k) {
before+=(start[k]-center[k])*normal[k];after+=(end[k]-center[k])*normal[k];
u+=(end[k]-center[k])*axisU[k];v+=(end[k]-center[k])*axisV[k];
}
// EterLib/CollisionData.cpp CPlaneCollisionInstance: endpoint rectangle,
// plane crossing/radius band, and approaching-only movement (permits escape).
const bool crossing=(before<0 && after>0)||(before>0 && after<0);
return (crossing || std::abs(after)<=radius) && std::abs(u)<halfWidth+radius && std::abs(v)<halfHeight+radius
&& (!movement || std::abs(after)<std::abs(before));
}
bool MapObjectManager::LoadAuthoredPlanes(MapObjectInstance& obj) {
auto path=std::filesystem::path(MapObjectManager::NormalizePath(obj.model_path));
path.replace_extension(".mdatr");
std::ifstream file(path,std::ios::binary);
if(!file)return false;
const std::vector<char> bytes{std::istreambuf_iterator<char>(file),{}};
if(bytes.size()<22 || std::memcmp(bytes.data(),"AttributeData\0",14)!=0)return false;
size_t cursor=14;
auto read32=[&](uint32_t& value) {
if(bytes.size()-cursor<4)return false;
const auto* p=reinterpret_cast<const unsigned char*>(bytes.data()+cursor);
value=uint32_t(p[0])|(uint32_t(p[1])<<8)|(uint32_t(p[2])<<16)|(uint32_t(p[3])<<24);cursor+=4;return true;
};
auto readFloat=[&](float& value) {uint32_t bits;if(!read32(bits))return false;std::memcpy(&value,&bits,4);return std::isfinite(value);};
uint32_t count,heightCount;if(!read32(count)||!read32(heightCount)||count>(bytes.size()-cursor)/68)return false;
float world[16];MakeFullTransformMatrix(obj.yaw,obj.pitch,obj.roll,obj.x,obj.y,obj.z,obj.scale,world);
std::vector<MapCollisionPlane> planes;
for(uint32_t i=0;i<count;++i) {
uint32_t type;if(!read32(type)||bytes.size()-cursor<32)return false;cursor+=32;
// This pass supports the authored plane sets used by town gates/walls.
// Mixed primitive files retain their existing proxy until all types are ported.
if(type!=0)return false;
float position[3],dimensions[2],q[4];
for(float& v:position)if(!readFloat(v))return false;
for(float& v:dimensions)if(!readFloat(v)||v<0)return false;
for(float& v:q)if(!readFloat(v))return false;
const float qnorm=std::sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]+q[3]*q[3]);
if(!std::isfinite(qnorm)||qnorm<1e-6f)return false;for(float& v:q)v/=qnorm;
const float x=q[0],y=q[1],z=q[2],w=q[3];
const float u[3]={1-2*(y*y+z*z),2*(x*y+z*w),2*(x*z-y*w)};
const float v[3]={2*(x*y-z*w),1-2*(x*x+z*z),2*(y*z+x*w)};
auto transform=[&](const float* native,std::array<float,3>& result,bool point) {
// Same Granny Z-up -> engine Y-up basis as the rendered mesh: (x,z,-y).
const float local[3]={native[0],native[2],-native[1]};
for(int k=0;k<3;++k)result[k]=local[0]*world[k]+local[1]*world[4+k]+local[2]*world[8+k]+(point?world[12+k]:0);
};
MapCollisionPlane plane;transform(position,plane.center,true);transform(u,plane.axisU,false);transform(v,plane.axisV,false);
auto normalize=[](std::array<float,3>& a) {const float len=std::sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);if(len>0)for(float& n:a)n/=len;return len;};
plane.halfWidth=dimensions[0]*0.5f*normalize(plane.axisU);
plane.halfHeight=dimensions[1]*0.5f*normalize(plane.axisV);
if(!std::isfinite(plane.halfWidth)||!std::isfinite(plane.halfHeight)||plane.halfWidth<=0 || plane.halfHeight<=0)return false;
for(float value:plane.center)if(!std::isfinite(value))return false;
plane.normal={plane.axisU[1]*plane.axisV[2]-plane.axisU[2]*plane.axisV[1],
plane.axisU[2]*plane.axisV[0]-plane.axisU[0]*plane.axisV[2],
plane.axisU[0]*plane.axisV[1]-plane.axisU[1]*plane.axisV[0]};
planes.push_back(plane);
}
// Validate the height records too before replacing a solid proxy with authored data.
for(uint32_t i=0;i<heightCount;++i) {
if(bytes.size()-cursor<32)return false;cursor+=32;
uint32_t vertices;if(!read32(vertices)||vertices>(bytes.size()-cursor)/12)return false;cursor+=size_t(vertices)*12;
}
obj.collision_planes=std::move(planes);obj.has_authored_planes=true;obj.has_collision=!obj.collision_planes.empty();
return true;
}
MapObjectManager::MapObjectManager() = default;
std::string MapObjectManager::NormalizePath(const std::string& path) {
@@ -132,6 +202,7 @@ std::shared_ptr<Gr2ModelInstance> MapObjectManager::GetOrLoadModel(const std::st
}
bool MapObjectManager::LoadAreaData(const std::string& areadata_path, float coord_scale, SpeedTreeForest* forest, bool native_y) {
if(forest)SetTreeForest(forest);
std::ifstream file(areadata_path);
if (!file.is_open()) {
std::cerr << "MapObjectManager::LoadAreaData failed to open: " << areadata_path << std::endl;
@@ -202,8 +273,7 @@ bool MapObjectManager::LoadAreaData(const std::string& areadata_path, float coor
}
if (forest && forest->HasMainTree(crc)) {
forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale);
loaded_count++;
if(forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale))loaded_count++;
continue;
}
@@ -211,8 +281,7 @@ bool MapObjectManager::LoadAreaData(const std::string& areadata_path, float coor
if (prop_it != m_property_map.end()) {
const std::string& mfile = prop_it->second;
if (forest && (mfile.find(".spt") != std::string::npos || mfile.find(".SPT") != std::string::npos)) {
forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale, mfile.c_str());
loaded_count++;
if(forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale, mfile.c_str()))loaded_count++;
continue;
}
@@ -230,6 +299,7 @@ bool MapObjectManager::LoadAreaData(const std::string& areadata_path, float coor
obj.scale = coord_scale;
obj.model = model;
ComputeObjectOBB(obj);
LoadAuthoredPlanes(obj);
m_objects.push_back(std::move(obj));
loaded_count++;
}
@@ -301,6 +371,7 @@ bool MapObjectManager::AddObject(const std::string& model_path, float x, float y
obj.scale = scale;
obj.model = model;
ComputeObjectOBB(obj);
LoadAuthoredPlanes(obj);
m_objects.push_back(std::move(obj));
return true;
}
@@ -312,7 +383,11 @@ const std::vector<size_t>& MapObjectManager::CollisionCandidates(float x,float z
for(size_t i=0;i<m_objects.size();++i) {
const auto& obj=m_objects[i];if(!obj.has_collision)continue;
m_allCollisionObjects.push_back(i);
const double r=std::max(std::abs(obj.obb.halfExtents[0]),std::abs(obj.obb.halfExtents[2]))*1.5;
double r=std::max(std::abs(obj.obb.halfExtents[0]),std::abs(obj.obb.halfExtents[2]))*1.5;
for(const auto& plane:obj.collision_planes)for(int axis:{0,2}) {
const float center=axis==0?obj.obb.centerX:obj.obb.centerZ;
r=std::max(r,double(std::abs(plane.center[axis]-center)+std::abs(plane.axisU[axis])*plane.halfWidth+std::abs(plane.axisV[axis])*plane.halfHeight));
}
const double cx=obj.obb.centerX,cz=obj.obb.centerZ;
if(!std::isfinite(r) || !std::isfinite(cx) || !std::isfinite(cz) || std::abs(cx)+r>1e9 || std::abs(cz)+r>1e9 || r>4096) {
m_largeCollisionObjects.push_back(i);continue;
@@ -356,6 +431,42 @@ bool MapObjectManager::CheckCollision(float worldX, float worldZ, float actorRad
return false;
}
// FlyingInstance FCheckBackgroundDuringFlying uses radius 1 and the two
// endpoints for OBBs. Authored .mdatr plane sets use source plane tests; other
// primitive types still use mesh OBB proxies.
void MapObjectManager::SetTreeForest(SpeedTreeForest* forest) {
m_treeForest=forest;m_treeLifetime=forest?forest->GetLifetimeToken():std::weak_ptr<const uint8_t>{};
}
bool MapObjectManager::CheckMovementCollision(const float* start,const float* end,float radius) const {
if(!start || !end || !std::isfinite(radius) || radius<0)return false;
// Actor BODY spheres have an altitude. Flattening them to a circle turns
// platforms, bridge decks and overhead geometry into infinitely tall walls.
// AVA2 CollisionData.cpp tests the dynamic sphere against a 3D box.
for(auto index:CollisionCandidates(end[0],end[2],radius)) {
const auto& object=m_objects[index];
if(object.has_authored_planes) {
for(const auto& plane:object.collision_planes)if(plane.Intersects(start,end,radius,true))return true;
continue;
}
if(object.has_collision && object.obb.IntersectsSphere3D(end,radius))return true;
}
return !m_treeLifetime.expired() && m_treeForest->CheckMovementCollision(start,end,radius,true);
}
bool MapObjectManager::CheckFlyingCollision(const float* start,const float* end,float radius) const {
if(!m_treeLifetime.expired() && m_treeForest->CheckMovementCollision(start,end,radius,false))return true;
const float dx=end[0]-start[0],dy=end[1]-start[1],dz=end[2]-start[2];
const float query=2*std::sqrt(dx*dx+dy*dy+dz*dz)+radius;
for(auto index:CollisionCandidates(start[0],start[2],query)) {
const auto& object=m_objects[index];
if(object.has_authored_planes) {
for(const auto& plane:object.collision_planes)if(plane.Intersects(start,end,radius,false))return true;
continue;
}
if(object.has_collision && (object.obb.IntersectsSphere3D(start,radius) || object.obb.IntersectsSphere3D(end,radius)))return true;
}
return false;
}
bool MapObjectManager::CheckCollisionNormal(float worldX, float worldZ, float actorRadius, float& outNx, float& outNz) const {
for (auto index : CollisionCandidates(worldX,worldZ,actorRadius)) {
const auto& obj=m_objects[index];
+22
View File
@@ -12,6 +12,7 @@
#include <cmath>
#include <algorithm>
#include <array>
namespace ava2 {
@@ -40,6 +41,13 @@ struct OrientedBoundingBox {
return (diffX * diffX + diffZ * diffZ) < (radius * radius);
}
bool IntersectsSphere3D(const float* point,float radius) const {
const float dx=point[0]-centerX,dz=point[2]-centerZ,c=std::cos(yawRad),s=std::sin(yawRad);
const float local[3]={dx*c+dz*s,point[1]-centerY,-dx*s+dz*c};
float distance=0;for(int k=0;k<3;++k){const float d=local[k]-std::clamp(local[k],-halfExtents[k],halfExtents[k]);distance+=d*d;}
return distance<=radius*radius;
}
bool GetPenetrationAndNormal(float circleX, float circleZ, float radius, float& outNx, float& outNz, float& outPenetration) const {
float dx = circleX - centerX;
float dz = circleZ - centerZ;
@@ -85,6 +93,12 @@ struct OrientedBoundingBox {
}
};
struct MapCollisionPlane {
std::array<float,3> center{}, axisU{}, axisV{}, normal{};
float halfWidth = 0, halfHeight = 0;
bool Intersects(const float* start,const float* end,float radius,bool movement) const;
};
struct MapObjectInstance {
std::string model_path;
uint32_t property_crc = 0;
@@ -98,6 +112,8 @@ struct MapObjectInstance {
std::shared_ptr<Gr2ModelInstance> model;
OrientedBoundingBox obb;
bool has_collision = true;
bool has_authored_planes = false;
std::vector<MapCollisionPlane> collision_planes;
mutable float bounds_min[3]{}, bounds_max[3]{};
mutable bool draws_cached = false;
mutable std::vector<Render3DDraw> cached_draws;
@@ -130,6 +146,9 @@ public:
// 3D Oriented Bounding Box (OBB) Building Collision Detection
bool CheckCollision(float worldX, float worldZ, float actorRadius = 30.0f) const;
void SetTreeForest(SpeedTreeForest* forest);
bool CheckMovementCollision(const float* start,const float* end,float radius=30) const;
bool CheckFlyingCollision(const float* start,const float* end,float radius=1) const;
bool CheckCollisionNormal(float worldX, float worldZ, float actorRadius, float& outNx, float& outNz) const;
// Build 3D draw commands for all instantiated objects
@@ -154,12 +173,15 @@ public:
void SetLoadingCenter(float x, float z, float maxDistance) { m_centerX = x; m_centerZ = z; m_maxDistanceSq = maxDistance > 0.0f ? maxDistance * maxDistance : 0.0f; }
private:
SpeedTreeForest* m_treeForest=nullptr;
std::weak_ptr<const uint8_t> m_treeLifetime;
const std::vector<size_t>& CollisionCandidates(float x,float z,float radius) const;
mutable size_t m_collisionCount=std::numeric_limits<size_t>::max();
mutable std::map<std::pair<int64_t,int64_t>,std::vector<size_t>> m_collisionCells;
mutable std::vector<size_t> m_largeCollisionObjects,m_allCollisionObjects,m_collisionCandidates;
std::shared_ptr<Gr2ModelInstance> GetOrLoadModel(const std::string& path);
static std::string NormalizePath(const std::string& path);
static bool LoadAuthoredPlanes(MapObjectInstance& obj);
std::unordered_map<uint32_t, std::string> m_property_map;
std::unordered_map<std::string, std::shared_ptr<Gr2ModelInstance>> m_model_cache;
+581 -16
View File
@@ -2,6 +2,9 @@
#include "ava2_text_file.h"
#include "ava2_text_file_loader.h"
#include "src/eter_resource/ResourceManager.h"
#include "eter_effect/EffectManager.h"
#include "eter_effect/FlyingManager.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -124,10 +127,307 @@ bool RaceData::LoadRaceData(const std::string& fileName) {
}
loader.setParent();
}
// AttachingData (collision spheres, attached effects) is not ported.
// Keep DEFENDING positions for skill range checks; normal attacks still use the
// largest-radius cylinder. Attached effects remain separate.
m_defendingSpheres.clear();m_bodySpheres.clear();
m_defendingRadius=0;
if (loader.setChildNode("attachingdata")) {
for (size_t i = 0; i < loader.childCount(); ++i) {
if (!loader.setChild(i)) continue;
int collisionType = 0;
if (loader.tokenInteger("collisiontype", &collisionType) && (collisionType == 3 || collisionType == 1)) {
int attached=0;std::string bone;
loader.tokenInteger("isattaching", &attached);
loader.tokenString("attachingbonename", &bone);
for (size_t j = 0; j < loader.childCount(); ++j) {
if (!loader.setChild(j)) continue;
std::string radius;
if (loader.tokenString("radius", &radius)) {
DefendingSphere sphere;sphere.radius=float(std::atof(radius.c_str()));
sphere.attached=attached!=0;sphere.bone=bone;
const auto* position=loader.tokenVector("position");
if(position && position->size()==3) {
for(int k=0;k<3;++k)sphere.position[k]=float(std::atof((*position)[k].c_str()));
(collisionType==3?m_defendingSpheres:m_bodySpheres).push_back(sphere);
}
if(collisionType==3)m_defendingRadius=std::max(m_defendingRadius,sphere.radius);
}
loader.setParent();
}
}
loader.setParent();
}
loader.setParent();
}
return true;
}
namespace {
bool TokenFloat(const TextFileLoader& loader, const char* key, float* value) {
std::string token;
if (!loader.tokenString(key, &token)) return false;
*value = float(std::atof(token.c_str()));
return true;
}
// NRaceData::THitData::Load.
bool LoadHitData(const TextFileLoader& loader, RaceMotionData::HitData* hit) {
if (!TokenFloat(loader, "attackingstarttime", &hit->attackStartTime)) return false;
if (!TokenFloat(loader, "attackingendtime", &hit->attackEndTime)) return false;
if (!loader.tokenString("attackingbone", &hit->boneName)) hit->boneName.clear();
if (!TokenFloat(loader, "weaponlength", &hit->weaponLength)) hit->weaponLength = 0.0f;
hit->hitPositions.clear();
if (const auto* tv = loader.tokenVector("hitposition")) {
// The original walks the list 7 tokens at a time without a bounds check; a short tail is dropped.
for (size_t i = 0; i + 7 <= tv->size(); i += 7) {
RaceMotionData::HitTimePosition hp;
const float time = float(std::atof((*tv)[i].c_str()));
for (int k = 0; k < 3; ++k) {
hp.last[k] = float(std::atof((*tv)[i + 1 + k].c_str()));
hp.pos[k] = float(std::atof((*tv)[i + 4 + k].c_str()));
}
hit->hitPositions[time] = hp;
}
}
return true;
}
// NRaceData::LoadAttackData + LoadMotionAttackData.
bool LoadMotionAttackData(TextFileLoader& loader, RaceMotionData* data) {
if (!loader.tokenInteger("attacktype", &data->attackType)) data->attackType = 0; // ATTACK_TYPE_SPLASH
if (!loader.tokenInteger("hittingtype", &data->hittingType)) return false;
if (!TokenFloat(loader, "stiffentime", &data->stiffenTime)) return false;
if (!TokenFloat(loader, "invisibletime", &data->invisibleTime)) return false;
if (!TokenFloat(loader, "externalforce", &data->externalForce)) return false;
if (!loader.tokenInteger("hitlimitcount", &data->hitLimitCount)) data->hitLimitCount = 0;
// AttackingType was renamed MotionType; old files still carry the former key.
if (!loader.tokenInteger("motiontype", &data->motionType) &&
!loader.tokenInteger("attackingtype", &data->motionType))
return false;
data->hitData.clear();
int count = 0;
if (!loader.tokenInteger("hitdatacount", &count)) {
data->hitData.emplace_back();
return LoadHitData(loader, &data->hitData.back());
}
for (int i = 0; i < count; ++i) {
if (!loader.setChild(size_t(i))) return false;
data->hitData.emplace_back();
if (!LoadHitData(loader, &data->hitData.back())) return false;
loader.setParent();
}
return true;
}
// CTextFileLoader::GetTokenPosition (GetTokenVector3): exactly three values.
bool TokenPosition(const TextFileLoader& loader, const char* key, float* out) {
const auto* tv = loader.tokenVector(key);
if (!tv || tv->size() != 3) return false;
for (int k = 0; k < 3; ++k) out[k] = float(std::atof((*tv)[k].c_str()));
return true;
}
// GetTokenBoolean: BOOL(atoi(first token)).
bool TokenBool(const TextFileLoader& loader, const char* key, bool* out) {
const auto* tv = loader.tokenVector(key);
if (!tv || tv->empty()) return false;
*out = std::atoi((*tv)[0].c_str()) != 0;
return true;
}
// NRaceData::LoadCollisionData into a SPECIAL_ATTACKING event.
bool LoadCollisionData(TextFileLoader& loader, RaceMotionData::MotionEvent* ev) {
if (!loader.tokenInteger("collisiontype", &ev->collisionType)) return false;
int count = 0;
if (!loader.tokenInteger("spheredatacount", &count)) return false;
ev->spheres.clear();
ev->spheres.resize(uint32_t(count));
for (uint32_t i = 0; i < ev->spheres.size(); ++i) {
if (!loader.setChildNode("spheredata", i)) return false;
if (!TokenFloat(loader, "radius", &ev->spheres[i].radius)) return false;
if (!TokenPosition(loader, "position", ev->spheres[i].position)) return false;
loader.setParent();
}
return true;
}
// The per-type SMotionEventData*::Load (RaceMotionDataEvent.h). The caller ignores the result.
bool LoadMotionEvent(TextFileLoader& loader, RaceMotionData::MotionEvent* ev) {
switch (ev->type) {
case RaceMotionData::MOTION_EVENT_TYPE_SCREEN_WAVING:
if (!TokenFloat(loader, "duringtime", &ev->durationTime)) return false;
if (!loader.tokenInteger("power", &ev->power)) return false;
if (!loader.tokenInteger("affectingrange", &ev->affectingRange)) ev->affectingRange = 0;
return true;
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT:
if (!TokenBool(loader, "independentflag", &ev->isIndependent)) ev->isIndependent = false;
if (!TokenBool(loader, "attachingenable", &ev->isAttaching)) return false;
if (!loader.tokenString("attachingbonename", &ev->boneName)) return false;
if (!loader.tokenString("effectfilename", &ev->fileName)) return false;
if (!TokenPosition(loader, "effectposition", ev->position)) return false;
if (!TokenBool(loader, "followingenable", &ev->isFollowing)) ev->isFollowing = false;
EffectManager::Instance().RegisterEffect(ev->fileName, &ev->index);
return true;
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT_TO_TARGET:
if (!loader.tokenString("effectfilename", &ev->fileName)) return false;
if (!TokenPosition(loader, "effectposition", ev->position)) return false;
if (!TokenBool(loader, "followingenable", &ev->isFollowing)) ev->isFollowing = false;
if (!TokenBool(loader, "fishingeffectflag", &ev->isFishingEffect)) ev->isFishingEffect = false;
EffectManager::Instance().RegisterEffect(ev->fileName, &ev->index);
return true;
case RaceMotionData::MOTION_EVENT_TYPE_FLY:
if (!TokenBool(loader, "attachingenable", &ev->isAttaching)) return false;
if (!loader.tokenString("attachingbonename", &ev->boneName)) return false;
if (!loader.tokenString("flyfilename", &ev->fileName)) return false;
if (!TokenPosition(loader, "flyposition", ev->position)) return false;
FlyingManager::Instance().RegisterFlyingData(ev->fileName, &ev->index);
return true;
case RaceMotionData::MOTION_EVENT_TYPE_SPECIAL_ATTACKING:
if (!TokenFloat(loader, "duringtime", &ev->durationTime)) return false;
if (!TokenBool(loader, "enablehitprocess", &ev->isEnableHitProcess)) ev->isEnableHitProcess = true;
// NRaceData::LoadAttackData
if (!loader.tokenInteger("attacktype", &ev->attackType)) ev->attackType = 0; // ATTACK_TYPE_SPLASH
if (!loader.tokenInteger("hittingtype", &ev->hittingType)) return false;
if (!TokenFloat(loader, "stiffentime", &ev->stiffenTime)) return false;
if (!TokenFloat(loader, "invisibletime", &ev->invisibleTime)) return false;
if (!TokenFloat(loader, "externalforce", &ev->externalForce)) return false;
if (!loader.tokenInteger("hitlimitcount", &ev->hitLimitCount)) ev->hitLimitCount = 0;
return LoadCollisionData(loader, ev);
case RaceMotionData::MOTION_EVENT_TYPE_SOUND:
return loader.tokenString("soundfilename", &ev->fileName);
default: // CHARACTER_SHOW / CHARACTER_HIDE / WARP carry no data
return true;
}
}
constexpr float kFrameTime = 1.0f / 60.0f; // c_fFrameTime (g_fGameFPS)
} // namespace
bool ParseSoundScriptData(const std::string& text, std::vector<RaceMotionData::SoundInstance>* sounds) {
TextFileLoader loader;
if (!loader.load(text)) return false;
loader.setTop();
int count = 0;
if (!loader.tokenInteger("sounddatacount", &count)) return false;
std::vector<RaceMotionData::SoundInstance> data(uint32_t(count < 0 ? 0 : count));
for (uint32_t i = 0; i < data.size(); ++i) {
char key[33];
std::snprintf(key, sizeof(key), "sounddata%02u", i);
const auto* tv = loader.tokenVector(key);
if (!tv || tv->size() != 2) return false;
data[i].time = float(std::atof((*tv)[0].c_str()));
data[i].fileName = (*tv)[1];
data[i].frame = uint32_t(data[i].time / kFrameTime); // NSound::DataToInstance
}
*sounds = std::move(data);
return true;
}
bool ParseRaceMotionData(const std::string& text, RaceMotionData* data, const std::string& msaFileName) {
TextFileLoader loader;
if (!loader.load(text)) return false;
loader.setTop();
if (!loader.tokenString("motionfilename", &data->motionFileName)) return false;
if (!TokenFloat(loader, "motionduration", &data->motionDuration)) return false;
if (const auto* acc = loader.tokenVector("accumulation")) {
if (acc->size() != 3) {
TraceError("CRaceMotioNData::LoadMotionData : syntax error on accumulation, vector size " + std::to_string(acc->size()));
return false;
}
for (int k = 0; k < 3; ++k) data->accumulation[k] = float(std::atof((*acc)[k].c_str()));
}
for (size_t i = 0; i < loader.childCount(); ++i) {
loader.setChild(i); // CGotoChild
const std::string name = loader.nodeName();
bool ok = true;
if (name == "comboinputdata") {
data->isComboMotion = true;
ok = TokenFloat(loader, "preinputtime", &data->inputStartTime) &&
TokenFloat(loader, "directinputtime", &data->nextComboTime) &&
TokenFloat(loader, "inputlimittime", &data->inputEndTime);
} else if (name == "attackingdata") {
data->isAttackingMotion = true;
ok = LoadMotionAttackData(loader, data);
} else if (name == "loopdata") {
data->isLoopMotion = true;
if (!loader.tokenInteger("motionloopcount", &data->loopCount)) data->loopCount = -1;
if (!loader.tokenInteger("loopcancelenable", &data->loopCancelEnable)) data->loopCancelEnable = 0;
ok = TokenFloat(loader, "loopstarttime", &data->loopStartTime) &&
TokenFloat(loader, "loopendtime", &data->loopEndTime);
} else if (name == "motioneventdata") {
int count = 0;
if (loader.tokenInteger("motioneventdatacount", &count)) {
data->events.clear();
data->events.resize(uint32_t(count));
for (uint32_t j = 0; ok && j < data->events.size(); ++j) {
auto& ev = data->events[j];
int type = 0;
if (!loader.setChildNode("event", j) || !loader.tokenInteger("motioneventtype", &type)) {
ok = false;
break;
}
switch (type) {
case RaceMotionData::MOTION_EVENT_TYPE_SPECIAL_ATTACKING:
data->hasSplashEvent = true;
[[fallthrough]];
case RaceMotionData::MOTION_EVENT_TYPE_FLY:
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT:
case RaceMotionData::MOTION_EVENT_TYPE_SCREEN_WAVING:
case RaceMotionData::MOTION_EVENT_TYPE_SOUND:
case RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_SHOW:
case RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_HIDE:
case RaceMotionData::MOTION_EVENT_TYPE_WARP:
case RaceMotionData::MOTION_EVENT_TYPE_EFFECT_TO_TARGET:
break;
default: // "Strange Event Type" (SCREEN_FLASHING has no event class)
ok = false;
break;
}
if (!ok) break;
ev.type = type;
LoadMotionEvent(loader, &ev); // the original ignores Load()'s result
if (!TokenFloat(loader, "startingtime", &ev.startingTime)) {
ok = false;
break;
}
ev.frame = uint32_t(ev.startingTime / kFrameTime);
loader.setParent();
}
}
}
loader.setTop();
if (!ok) return false;
}
// Sound script: NoExtension(msa) + ".mss", the 13-character "d:/ymir work/" head becomes "sound/".
if (!msaFileName.empty()) {
std::string mss = msaFileName;
const size_t slash = mss.find_last_of("/\\");
const size_t dot = mss.find_last_of('.');
if (dot != std::string::npos && (slash == std::string::npos || dot > slash)) mss.erase(dot);
mss += ".mss";
if (mss.length() > 13) {
data->soundScriptFileName = "sound/" + mss.substr(13);
std::string mssText;
if (ReadRaceResourceFile(data->soundScriptFileName, &mssText)) ParseSoundScriptData(mssText, &data->sounds);
}
}
return true;
}
const RaceMotionData* GetRaceMotionData(const std::string& msaFileName) {
static std::map<std::string, std::unique_ptr<RaceMotionData>> cache;
const std::string key = CResourceManager::NormalizePath(msaFileName.c_str());
auto it = cache.find(key);
if (it != cache.end()) return it->second.get();
std::unique_ptr<RaceMotionData> data;
std::string text;
if (ReadRaceResourceFile(msaFileName, &text)) {
data = std::make_unique<RaceMotionData>();
if (!ParseRaceMotionData(text, data.get(), msaFileName)) data.reset();
}
return cache.emplace(key, std::move(data)).first->second.get();
}
void RaceData::SetShapeModel(uint32_t index, const std::string& model) { m_shapes[index].model = model; }
void RaceData::AppendShapeSkin(uint32_t index, uint32_t, const std::string& src, const std::string& dst) {
@@ -425,6 +725,285 @@ bool RaceManager::LoadGameNPC(const std::string& fileName) {
return true;
}
namespace {
// CPythonPlayerSettingsModule (UserInterface/PythonPlayerSettingsModule.cpp) motion tables.
enum {
MODE_GENERAL = 1, MODE_ONEHAND_SWORD, MODE_TWOHAND_SWORD, MODE_DUALHAND_SWORD, MODE_BOW, MODE_FAN, MODE_BELL,
MODE_FISHING, MODE_HORSE, MODE_HORSE_ONEHAND_SWORD, MODE_HORSE_TWOHAND_SWORD, MODE_HORSE_DUALHAND_SWORD,
MODE_HORSE_BOW, MODE_HORSE_FAN, MODE_HORSE_BELL, MODE_WEDDING_DRESS, MODE_BOW_SPECIAL,
};
enum { JOB_WARRIOR, JOB_ASSASSIN, JOB_SURA, JOB_SHAMAN };
enum {
HORSE_SKILL_WILDATTACK = RaceData::NAME_SKILL + 121,
HORSE_SKILL_CHARGE = RaceData::NAME_SKILL + 122,
HORSE_SKILL_SPLASH = RaceData::NAME_SKILL + 123,
};
enum { COMBO_TYPE_1, COMBO_TYPE_2, COMBO_TYPE_3 };
struct PlayerMotionLoader {
RaceData& race;
std::string path; // CRaceManager::SetPathName
int job;
// __RegisterCacheMotionData: CRaceData::RegisterMotionData drops a motion whose .msa fails to load.
void Register(uint16_t mode, uint16_t name, const char* file, int percent = 100) const {
const std::string fileName = path + file;
if (!GetRaceMotionData(fileName)) {
TraceError("CRaceData::RegisterMotionData - LoadMotionData(c_szFileName=" + fileName + ") ERROR");
return;
}
race.RegisterMotion(mode, name, fileName, percent);
}
void Combo(uint16_t mode, uint16_t type, std::initializer_list<uint16_t> motions) const {
race.ReserveComboAttack(mode, type, uint32_t(motions.size()));
uint32_t index = 0;
for (uint16_t motion : motions) race.RegisterComboAttack(mode, type, index++, motion);
}
// __SetGeneralMotions.
void GeneralMotions(uint16_t mode) const {
race.RegisterMotionMode(mode);
Register(mode, RaceData::NAME_WAIT, "wait.msa");
Register(mode, RaceData::NAME_WALK, "walk.msa");
Register(mode, RaceData::NAME_RUN, "run.msa");
Register(mode, RaceData::NAME_DAMAGE, "damage.msa", 50);
Register(mode, RaceData::NAME_DAMAGE, "damage_1.msa", 50);
Register(mode, RaceData::NAME_DAMAGE_BACK, "damage_2.msa", 50);
Register(mode, RaceData::NAME_DAMAGE_BACK, "damage_3.msa", 50);
Register(mode, RaceData::NAME_DAMAGE_FLYING, "damage_flying.msa");
Register(mode, RaceData::NAME_STAND_UP, "falling_stand.msa");
Register(mode, RaceData::NAME_DAMAGE_FLYING_BACK, "back_damage_flying.msa");
Register(mode, RaceData::NAME_STAND_UP_BACK, "back_falling_stand.msa");
Register(mode, RaceData::NAME_DEAD, "dead.msa");
Register(mode, RaceData::NAME_DIG, "dig.msa");
}
// __LoadCombo. MODE_BOW_SPECIAL takes the sword branch like the original.
void LoadCombo(uint16_t mode) const {
using R = RaceData;
if (mode == MODE_BOW) {
Combo(MODE_BOW, COMBO_TYPE_1, {R::NAME_COMBO_ATTACK_1});
return;
}
Combo(mode, COMBO_TYPE_1, {R::NAME_COMBO_ATTACK_1, R::NAME_COMBO_ATTACK_2, R::NAME_COMBO_ATTACK_3, R::NAME_COMBO_ATTACK_4});
Combo(mode, COMBO_TYPE_2, {R::NAME_COMBO_ATTACK_1, R::NAME_COMBO_ATTACK_2, R::NAME_COMBO_ATTACK_3, R::NAME_COMBO_ATTACK_5,
R::NAME_COMBO_ATTACK_7});
Combo(mode, COMBO_TYPE_3, {R::NAME_COMBO_ATTACK_1, R::NAME_COMBO_ATTACK_2, R::NAME_COMBO_ATTACK_3, R::NAME_COMBO_ATTACK_5,
R::NAME_COMBO_ATTACK_6,
uint16_t(mode == MODE_DUALHAND_SWORD ? R::NAME_COMBO_ATTACK_8 : R::NAME_COMBO_ATTACK_4)});
}
// __LoadWeaponMotion.
void WeaponMotion(uint16_t mode, const std::string& folder) {
path = folder;
race.RegisterMotionMode(mode);
switch (job) {
case JOB_WARRIOR: {
const bool oneHand = mode == MODE_ONEHAND_SWORD;
Register(mode, RaceData::NAME_WAIT, "wait.msa", oneHand ? 50 : 70);
Register(mode, RaceData::NAME_WAIT, "wait_1.msa", oneHand ? 50 : 30);
break;
}
case JOB_ASSASSIN:
Register(mode, RaceData::NAME_WAIT, "wait.msa", 70);
Register(mode, RaceData::NAME_WAIT, "wait_1.msa", 30);
break;
case JOB_SURA:
Register(mode, RaceData::NAME_WAIT, "wait.msa");
Register(mode, RaceData::NAME_DAMAGE, "damage.msa");
break;
case JOB_SHAMAN:
Register(mode, RaceData::NAME_WAIT, "wait.msa");
break;
}
Register(mode, RaceData::NAME_WALK, "walk.msa");
Register(mode, RaceData::NAME_RUN, "run.msa");
Register(mode, RaceData::NAME_DAMAGE, "damage.msa", 50);
Register(mode, RaceData::NAME_DAMAGE, "damage_1.msa", 50);
Register(mode, RaceData::NAME_DAMAGE_BACK, "damage_2.msa", 50);
Register(mode, RaceData::NAME_DAMAGE_BACK, "damage_3.msa", 50);
if (mode == MODE_BOW) {
Register(mode, RaceData::NAME_COMBO_ATTACK_1, "attack.msa");
} else if (mode == MODE_BOW_SPECIAL) {
Register(mode, RaceData::NAME_COMBO_ATTACK_1, "attack_special.msa");
} else {
static const char* kCombo[] = {"combo_01.msa", "combo_02.msa", "combo_03.msa", "combo_04.msa",
"combo_05.msa", "combo_06.msa", "combo_07.msa"};
for (uint16_t k = 0; k < 7; ++k) Register(mode, uint16_t(RaceData::NAME_COMBO_ATTACK_1 + k), kCombo[k]);
if (job == JOB_ASSASSIN && mode == MODE_DUALHAND_SWORD)
Register(mode, RaceData::NAME_COMBO_ATTACK_8, "combo_08.msa");
}
LoadCombo(mode);
}
};
// GetHorsePathNameByMode is not in the reference sources; the folders are the pack's horse_* names.
const char* HorsePathName(uint16_t mode) {
switch (mode) {
case MODE_HORSE_ONEHAND_SWORD: return "horse_onehand_sword/";
case MODE_HORSE_TWOHAND_SWORD: return "horse_twohand_sword/";
case MODE_HORSE_DUALHAND_SWORD: return "horse_dualhand_sword/";
case MODE_HORSE_FAN: return "horse_fan/";
case MODE_HORSE_BELL: return "horse_bell/";
default: return "horse/";
}
}
void LoadPlayerMotions(RaceData& race, const std::string& folder) {
using R = RaceData;
PlayerMotionLoader l{race, folder + "intro/", int(race.GetRace() % 4)};
// __SetIntroMotions
race.RegisterMotionMode(MODE_GENERAL);
l.Register(MODE_GENERAL, R::NAME_INTRO_WAIT, "wait.msa");
l.Register(MODE_GENERAL, R::NAME_INTRO_SELECTED, "selected.msa");
l.Register(MODE_GENERAL, R::NAME_INTRO_NOT_SELECTED, "not_selected.msa");
// __LoadGameRace (emotions are not ported; guild skills and skills are loaded after fishing)
l.path = folder + "general/";
l.GeneralMotions(MODE_GENERAL);
if (l.job == JOB_WARRIOR || l.job == JOB_ASSASSIN) {
race.SetMotionRandomWeight(MODE_GENERAL, R::NAME_WAIT, 0, 70);
l.Register(MODE_GENERAL, R::NAME_WAIT, "wait_1.msa", 30);
}
l.Register(MODE_GENERAL, R::NAME_COMBO_ATTACK_1, "attack.msa", 50);
l.Register(MODE_GENERAL, R::NAME_COMBO_ATTACK_1, "attack_1.msa", 50);
l.Combo(MODE_GENERAL, COMBO_TYPE_1, {R::NAME_COMBO_ATTACK_1});
switch (l.job) {
case JOB_WARRIOR:
l.WeaponMotion(MODE_ONEHAND_SWORD, folder + "onehand_sword/");
l.WeaponMotion(MODE_TWOHAND_SWORD, folder + "twohand_sword/");
break;
case JOB_ASSASSIN:
l.WeaponMotion(MODE_ONEHAND_SWORD, folder + "onehand_sword/");
l.WeaponMotion(MODE_DUALHAND_SWORD, folder + "dualhand_sword/");
l.WeaponMotion(MODE_BOW, folder + "bow/");
l.WeaponMotion(MODE_BOW_SPECIAL, folder + "bow/");
break;
case JOB_SURA:
l.WeaponMotion(MODE_ONEHAND_SWORD, folder + "onehand_sword/");
break;
case JOB_SHAMAN:
l.WeaponMotion(MODE_FAN, folder + "fan/");
l.WeaponMotion(MODE_BELL, folder + "Bell/");
break;
}
// __LoadHorse
l.path = folder + "horse/";
race.RegisterMotionMode(MODE_HORSE);
l.Register(MODE_HORSE, R::NAME_WAIT, "wait.msa", 90);
l.Register(MODE_HORSE, R::NAME_WALK, "walk.msa");
l.Register(MODE_HORSE, R::NAME_RUN, "run.msa");
l.Register(MODE_HORSE, R::NAME_DEAD, "dead.msa");
l.Register(MODE_HORSE, HORSE_SKILL_CHARGE, "skill_charge.msa");
l.Register(MODE_HORSE, R::NAME_WAIT, "wait_1.msa", 9);
l.Register(MODE_HORSE, R::NAME_WAIT, "wait_2.msa", 1);
l.Register(MODE_HORSE, R::NAME_DAMAGE, "damage.msa");
l.Register(MODE_HORSE, R::NAME_DAMAGE_BACK, "damage.msa");
if (l.job == JOB_SHAMAN || l.job == JOB_SURA) l.Register(MODE_HORSE, HORSE_SKILL_SPLASH, "skill_splash.msa");
static const std::vector<uint16_t> kHorseModes[] = {
{MODE_HORSE_ONEHAND_SWORD, MODE_HORSE_TWOHAND_SWORD}, // m_vecHorse JOB_WARRIOR
{MODE_HORSE_ONEHAND_SWORD, MODE_HORSE_DUALHAND_SWORD}, // JOB_ASSASSIN
{MODE_HORSE_ONEHAND_SWORD}, // JOB_SURA
{MODE_HORSE_FAN, MODE_HORSE_BELL}, // JOB_SHAMAN
};
for (uint16_t mode : kHorseModes[l.job]) {
l.path = folder + HorsePathName(mode);
race.RegisterMotionMode(mode);
l.Register(mode, R::NAME_COMBO_ATTACK_1, "combo_01.msa");
l.Register(mode, R::NAME_COMBO_ATTACK_2, "combo_02.msa");
l.Register(mode, R::NAME_COMBO_ATTACK_3, "combo_03.msa");
l.Combo(mode, COMBO_TYPE_1, {R::NAME_COMBO_ATTACK_1, R::NAME_COMBO_ATTACK_2, R::NAME_COMBO_ATTACK_3});
l.Register(mode, HORSE_SKILL_WILDATTACK, "skill_wildattack.msa");
if (l.job == JOB_WARRIOR || l.job == JOB_ASSASSIN) l.Register(mode, HORSE_SKILL_SPLASH, "skill_splash.msa");
}
if (l.job == JOB_ASSASSIN) {
l.path = folder + "horse_bow/";
race.RegisterMotionMode(MODE_HORSE_BOW);
l.Register(MODE_HORSE_BOW, R::NAME_WAIT, "wait.msa", 90);
l.Register(MODE_HORSE_BOW, R::NAME_WAIT, "wait_1.msa", 9);
l.Register(MODE_HORSE_BOW, R::NAME_WAIT, "wait_2.msa", 1);
l.Register(MODE_HORSE_BOW, R::NAME_RUN, "run.msa");
l.Register(MODE_HORSE_BOW, R::NAME_DAMAGE, "damage.msa");
l.Register(MODE_HORSE_BOW, R::NAME_DEAD, "dead.msa");
l.Register(MODE_HORSE_BOW, R::NAME_COMBO_ATTACK_1, "attack.msa");
l.Register(MODE_HORSE_BOW, HORSE_SKILL_WILDATTACK, "skill_wildattack.msa");
l.Register(MODE_HORSE_BOW, HORSE_SKILL_SPLASH, "skill_splash.msa");
l.Combo(MODE_HORSE_BOW, COMBO_TYPE_1, {R::NAME_COMBO_ATTACK_1});
}
// __LoadFishing
l.path = folder + "fishing/";
race.RegisterMotionMode(MODE_FISHING);
l.Register(MODE_FISHING, R::NAME_WAIT, "wait.msa");
l.Register(MODE_FISHING, R::NAME_WALK, "walk.msa");
l.Register(MODE_FISHING, R::NAME_RUN, "run.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_THROW, "throw.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_WAIT, "fishing_wait.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_STOP, "fishing_cancel.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_REACT, "fishing_react.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_CATCH, "fishing_catch.msa");
l.Register(MODE_FISHING, R::NAME_FISHING_FAIL, "fishing_fail.msa");
// __LoadGuildSkill (GUILD_SKILL_* = NAME_SKILL + 101..106)
l.path = folder + "skill/";
l.Register(MODE_GENERAL, R::NAME_SKILL + 101, "guild_yongsinuipi.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 102, "guild_yongsinuichukbok.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 103, "guild_seonghwigap.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 104, "guild_gasokhwa.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 105, "guild_yongsinuibunno.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 106, "guild_jumunsul.msa");
// __LoadSkill (m_vecSkillFileName: {job, vecFileName, vecExtraFileName}). Rows skip 7..15;
// grade g (SKILL_EFFECT_COUNT 4, SKILL_GRADEGAP 25) uses suffix _<g+1>; shamans take grade 0
// from the extra (_target) names.
struct SkillFiles { int job; std::vector<const char*> files, extra; };
static const SkillFiles kSkillFiles[] = {
{JOB_WARRIOR, {"samyeon", "palbang", "jeongwi", "geomgyeong", "tanhwan", "gihyeol", "gigongcham", "gyeoksan", "daejin", "cheongeun", "geompung", "noegeom"}, {}},
{JOB_ASSASSIN, {"amseup", "gungsin", "charyun", "eunhyeong", "sangong", "seomjeon", "yeonsa", "gwangyeok", "hwajo", "gyeonggong", "dokgigung", "seomgwang"}, {}},
{JOB_SHAMAN, {"bipabu", "yongpa", "paeryong", "hosin", "boho", "gicheon", "noejeon", "byeorak", "pokroe", "jeongeop", "kwaesok", "jeungryeok"},
{"bipabu", "yongpa", "paeryong", "hosin_target", "boho_target", "gicheon_target", "noejeon", "byeorak", "pokroe", "jeongeop_target", "kwaesok_target", "jeungryeok_target"}},
{JOB_SURA, {"swaeryeong", "yonggwon", "gwigeom", "gongpo", "jumagap", "pabeop", "maryeong", "hwayeom", "muyeong", "heuksin", "tusok", "mahwan"}, {}},
};
const int gradeStart = l.job == JOB_SHAMAN ? 1 : 0;
auto suffix = [](int grade) { return grade ? "_" + std::to_string(grade + 1) : std::string(); };
for (const auto& skill : kSkillFiles) {
if (skill.job != l.job) continue;
int row = 1;
for (const char* name : skill.extra) {
if (row == 7) row += 9;
l.Register(MODE_GENERAL, uint16_t(R::NAME_SKILL + row), (std::string(name) + ".msa").c_str());
++row;
}
for (int grade = gradeStart; grade < 4; ++grade) {
row = 1;
for (const char* name : skill.files) {
if (row == 7) row += 9;
l.Register(MODE_GENERAL, uint16_t(R::NAME_SKILL + grade * 25 + row), (name + suffix(grade) + ".msa").c_str());
++row;
}
}
break;
}
// __LoadNinethSkill (ENABLE_CONQUEROR_LEVEL on, wolfman off): rows 9 and 24.
static const std::vector<const char*> kNinethSkills[] = {
{"finish", "finish"}, {"ilgangpyo", "pungraepo"}, {"akgi", "akgi_dark"}, {"meteo", "chunwoon"},
};
if (l.job == JOB_SHAMAN) {
l.Register(MODE_GENERAL, R::NAME_SKILL + 9, "meteo.msa");
l.Register(MODE_GENERAL, R::NAME_SKILL + 24, "chunwoon.msa");
}
for (int grade = gradeStart; grade < 4; ++grade) {
int row = 0;
for (const char* name : kNinethSkills[l.job]) {
l.Register(MODE_GENERAL, uint16_t(R::NAME_SKILL + grade * 25 + (!row ? 9 : 24)), (name + suffix(grade) + ".msa").c_str());
++row;
}
}
}
} // namespace
void RaceManager::LoadPlayerRaces() {
// CPythonPlayerSettingsModule m_vecRaceData.
static const struct { const char* msm; const char* path; } kRaces[] = {
@@ -449,21 +1028,7 @@ void RaceManager::LoadPlayerRaces() {
case 2: race->RegisterAttachingBoneName(RaceData::PART_WEAPON, "equip_right"); break;
}
race->RegisterAttachingBoneName(RaceData::PART_SASH, "Bip01 Spine2"); // ENABLE_SASH_SYSTEM
race->RegisterMotionData(RaceData::NAME_INTRO_WAIT, kRaces[i].path + std::string("intro/wait.msa"), 100);
race->RegisterMotionData(RaceData::NAME_INTRO_SELECTED, kRaces[i].path + std::string("intro/selected.msa"), 100);
race->RegisterMotionData(RaceData::NAME_INTRO_NOT_SELECTED, kRaces[i].path + std::string("intro/not_selected.msa"), 100);
race->RegisterMotionData(RaceData::NAME_WAIT, kRaces[i].path + std::string("general/wait.msa"), 100);
race->RegisterMotionData(RaceData::NAME_WALK, kRaces[i].path + std::string("general/walk.msa"), 100);
race->RegisterMotionData(RaceData::NAME_RUN, kRaces[i].path + std::string("general/run.msa"), 100);
race->RegisterMotionData(RaceData::NAME_DEAD, kRaces[i].path + std::string("general/dead.msa"), 100);
// CPythonPlayerSettingsModule::__LoadHorse: mounted riders use a distinct pose.
race->RegisterMotionMode(9);
for (const auto& motion : {std::pair{RaceData::NAME_WAIT, "wait.msa"},
std::pair{RaceData::NAME_WALK, "walk.msa"},
std::pair{RaceData::NAME_RUN, "run.msa"},
std::pair{RaceData::NAME_DEAD, "dead.msa"}})
race->RegisterMotion(9, motion.first, kRaces[i].path + std::string("horse/") + motion.second, 100);
LoadPlayerMotions(*race, kRaces[i].path);
}
}
+86 -2
View File
@@ -2,8 +2,11 @@
// Port of AVA2 GameLib CRaceData (RaceData.h/.cpp, RaceDataFile.cpp LoadRaceData) and CRaceManager
// (RaceManager.cpp): .msm shape/hair tables, attaching bone names, the npclist race-name registry,
// the per-race resource path search and the motlist.txt GENERAL motion list.
// Not ported: smoke effects, AttachingData (collision spheres / attached effects), the CRaceMotionData
// .msa event payload (only MotionFileName is read), motion modes other than GENERAL.
// Player weapon / horse / fishing motion modes and combo tables follow UserInterface
// PythonPlayerSettingsModule.cpp, including the skill and guild-skill motions. .msa motion events
// and loop data plus the per-motion .mss sound script are parsed (CRaceMotionData). Not ported:
// smoke effects, attached effects, emotion motions. Of AttachingData only the DEFENDING sphere
// radius is kept (hit test approximation).
#include <cstdint>
#include <map>
#include <memory>
@@ -119,7 +122,19 @@ public:
void RegisterComboAttack(uint16_t mode, uint16_t comboType, uint32_t comboIndex, uint16_t motion);
const std::vector<uint32_t>* GetComboData(uint16_t mode, uint16_t comboType) const;
struct DefendingSphere {
float radius=0, position[3]={}; // Granny/model space (Z up).
bool attached=false;
std::string bone;
};
const std::vector<DefendingSphere>& GetDefendingSpheres() const { return m_defendingSpheres; }
const std::vector<DefendingSphere>& GetBodySpheres() const { return m_bodySpheres; }
// Largest COLLISION_TYPE_DEFENDING sphere radius of the .msm AttachingData (0 when none).
float GetDefendingRadius() const { return m_defendingRadius; }
private:
float m_defendingRadius = 0.0f;
std::vector<DefendingSphere> m_defendingSpheres, m_bodySpheres;
uint32_t m_race = 0;
std::string m_baseModelFileName, m_treeFileName, m_attributeFileName, m_smokeBoneName;
std::string m_motionListFileName = "motlist.txt";
@@ -175,6 +190,75 @@ bool ReadRaceResourceFile(const std::string& fileName, std::string* text);
// .msa "MotionFileName" (CRaceMotionData::LoadMotionData); returns the gr2 path or "" on failure.
std::string ReadMotionFileName(const std::string& msaFileName);
// CRaceMotionData::LoadMotionData (GameLib RaceMotionData.cpp, RaceMotionDataEvent.h, GameType.cpp
// NRaceData::LoadMotionAttackData / THitData::Load / LoadCollisionData) and the per-motion .mss sound
// script (milesLib Type.cpp NSound::LoadSoundInformationPiece + DataToInstance).
struct RaceMotionData {
// CRaceMotionData::EMotionEventType (ENABLE_WOLFMAN_CHARACTER is off: 11/12 are invalid).
enum {
MOTION_EVENT_TYPE_NONE, MOTION_EVENT_TYPE_EFFECT, MOTION_EVENT_TYPE_SCREEN_WAVING,
MOTION_EVENT_TYPE_SCREEN_FLASHING, MOTION_EVENT_TYPE_SPECIAL_ATTACKING, MOTION_EVENT_TYPE_SOUND,
MOTION_EVENT_TYPE_FLY, MOTION_EVENT_TYPE_CHARACTER_SHOW, MOTION_EVENT_TYPE_CHARACTER_HIDE,
MOTION_EVENT_TYPE_WARP, MOTION_EVENT_TYPE_EFFECT_TO_TARGET,
};
struct SphereData { float radius = 0.0f; float position[3] = {}; }; // TSphereData (model local)
// TMotionEventData and its per-type subclasses in one record. Fields a failed Load() did not reach
// keep these defaults (the original leaves them uninitialised; the event is kept either way).
struct MotionEvent {
int type = MOTION_EVENT_TYPE_NONE;
uint32_t frame = 0; // dwFrame = startingTime / (1 / 60)
float startingTime = 0.0f;
float durationTime = 0.0f; // SCREEN_WAVING / SPECIAL_ATTACKING duringtime
int power = 0, affectingRange = 0; // SCREEN_WAVING
bool isIndependent = false, isAttaching = false, isFollowing = false, isFishingEffect = false;
bool isEnableHitProcess = true;
std::string boneName; // attachingbonename
std::string fileName; // effect / fly / sound file
float position[3] = {}; // effectposition / flyposition (model local)
uint32_t index = 0; // dwEffectIndex / dwFlyIndex (CRC of fileName); 0 until Load() ends
// SPECIAL_ATTACKING: NRaceData::TAttackData + TCollisionData.
int attackType = 0, hittingType = 0, hitLimitCount = 0, collisionType = 0;
float stiffenTime = 0.0f, invisibleTime = 0.0f, externalForce = 0.0f;
std::vector<SphereData> spheres;
};
struct SoundInstance { float time = 0.0f; uint32_t frame = 0; std::string fileName; }; // NSound::TSoundInstance
enum { MOTION_TYPE_NONE, MOTION_TYPE_NORMAL, MOTION_TYPE_COMBO, MOTION_TYPE_SKILL };
struct HitTimePosition { float last[3] = {}; float pos[3] = {}; }; // v3LastPosition / v3Position (local)
struct HitData {
float attackStartTime = 0.0f, attackEndTime = 0.0f, weaponLength = 0.0f;
std::string boneName;
std::map<float, HitTimePosition> hitPositions; // mapHitPosition, keyed by motion time
};
std::string motionFileName;
float motionDuration = 0.0f;
float accumulation[3] = {};
bool isComboMotion = false;
float inputStartTime = 0.0f, nextComboTime = 0.0f, inputEndTime = 0.0f; // pre / direct / limit
bool isAttackingMotion = false;
int attackType = 0, hittingType = 0, motionType = MOTION_TYPE_NONE, hitLimitCount = 0;
float stiffenTime = 0.0f, invisibleTime = 0.0f, externalForce = 0.0f;
std::vector<HitData> hitData;
// LoopData.
bool isLoopMotion = false;
int loopCount = 0; // motionloopcount (-1 when the LoopData group omits it)
int loopCancelEnable = 0;
float loopStartTime = 0.0f, loopEndTime = 0.0f;
// MotionEventData.
bool hasSplashEvent = false; // a SPECIAL_ATTACKING event exists
std::vector<MotionEvent> events;
// "sound/" + (msa without extension + ".mss").substr(13); sounds stay empty if it fails to load.
std::string soundScriptFileName;
std::vector<SoundInstance> sounds;
};
// Parses an .msa text; false where CRaceMotionData::LoadMotionData fails. With msaFileName the .mss
// sound script is loaded as well (its failure is ignored, like the original).
bool ParseRaceMotionData(const std::string& text, RaceMotionData* data, const std::string& msaFileName = std::string());
// NSound::LoadSoundInformationPiece + DataToInstance on a .mss text; false leaves *sounds untouched.
bool ParseSoundScriptData(const std::string& text, std::vector<RaceMotionData::SoundInstance>* sounds);
// Cached by .msa path (CResourceManager static cache); nullptr when the file is missing or invalid.
const RaceMotionData* GetRaceMotionData(const std::string& msaFileName);
struct CRaceMotionData {
using EName = RaceData::EMotion;
enum {
+1
View File
@@ -97,6 +97,7 @@ struct Render3DDraw {
// Render states
bool z_enable = true;
bool z_write = true;
bool depth_less = false; // D3DCMP_LESS; default is LESSEQUAL.
std::uint32_t cull_mode = 2; // 1: None, 2: CW, 3: CCW
bool alpha_blend = false;
std::uint32_t blend_mode = 0; // 0: Alpha (D3DBLEND_INVSRCALPHA), 1: Additive (D3DBLEND_ONE)
+85 -18
View File
@@ -82,6 +82,7 @@ bool IsSphereInFrustum(const float planes[6][4], float cx, float cy, float cz, f
SpeedTreeForest::SpeedTreeForest() {}
SpeedTreeForest::~SpeedTreeForest() {
m_lifetime.reset();
Clear();
}
@@ -132,11 +133,17 @@ SpeedTreeForest::TreeInstance* SpeedTreeForest::CreateInstance(float x, float y,
uint32_t dwTreeCRC,
float yaw, float scale,
const char* name) {
if(!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !std::isfinite(yaw))return nullptr;
std::shared_ptr<SpeedTreeModel> model = GetMainTree(dwTreeCRC);
if (!model) {
// Fallback procedural model
std::string tname = name ? name : ("Tree_" + std::to_string(dwTreeCRC));
model = SpeedTreeModel::CreateProcedural(tname, 1000.0f);
auto extension=std::filesystem::path(tname).extension().string();
std::transform(extension.begin(),extension.end(),extension.begin(),[](unsigned char c){return char(std::tolower(c));});
// A failed real resource must not silently turn into an unrelated procedural tree.
if(m_properties.count(dwTreeCRC)) {std::cerr<<"SpeedTreeForest: failed tree property "<<dwTreeCRC<<'\n';return nullptr;}
if(extension==".spt")model=SpeedTreeModel::Create(tname,0,0);
else model=SpeedTreeModel::CreateProcedural(tname,1000);
if(!model)return nullptr;
m_tree_templates[dwTreeCRC] = model;
}
@@ -151,6 +158,7 @@ SpeedTreeForest::TreeInstance* SpeedTreeForest::CreateInstance(float x, float y,
inst->model = model;
TreeInstance* ptr = inst.get();
inst->leafWind.Update(m_wind_time,inst->windStrength);
m_instances.push_back(std::move(inst));
return ptr;
}
@@ -189,14 +197,23 @@ bool SpeedTreeForest::HasMainTree(uint32_t crc) const {
m_properties.find(crc) != m_properties.end();
}
void SpeedTreeForest::SetWindStrength(float strength) {
if(!std::isfinite(strength) || strength<0 || strength==m_wind_strength)return;
m_wind_strength=strength;
for(auto& instance:m_instances) {
instance->windStrength=strength;instance->leafWind.Update(m_wind_time,strength);
}
}
void SpeedTreeForest::UpdateSystem(float dt) {
if (!std::isfinite(dt) || dt<0 || !std::isfinite(m_wind_time+dt)) return;
m_wind_time += dt;
m_frame_wind.time = m_wind_time;
m_frame_wind.strength = m_wind_strength * 0.05f;
m_frame_wind.strength = m_wind_strength;
m_wind_controller.Update(m_frame_wind.time, m_frame_wind.strength);
m_frame_wind.matrices = m_wind_controller.GetMatrices();
m_frame_wind.legacy_leaf_rocking = true;
m_frame_wind.legacy_leaf_phase = m_wind_controller.GetLeafPhase();
for(auto& instance:m_instances)instance->leafWind.Update(m_wind_time,instance->windStrength);
}
std::vector<Render3DDraw> SpeedTreeForest::BuildDrawCommands(const float* viewMatrix,
@@ -211,31 +228,31 @@ std::vector<Render3DDraw> SpeedTreeForest::BuildDrawCommands(const float* viewMa
float planes[6][4];
ExtractFrustumPlanes(vp, planes);
float maxDistSq = maxDist * maxDist;
for (const auto& inst : m_instances) {
if (!inst || !inst->model) continue;
float dx = inst->x - camEyeX;
float dy = inst->y - camEyeY;
float dz = inst->z - camEyeZ;
float distSq = dx * dx + dz * dz;
if (distSq > maxDistSq) continue;
// Frustum culling bounding sphere
float h = inst->model->GetHeight() * inst->scale;
float r = std::max(inst->model->GetRadius() * inst->scale, h * 0.5f);
float cy = inst->y + h * 0.5f;
if (!IsSphereInFrustum(planes, inst->x, cy, inst->z, r)) {
continue;
std::array<float,3> center;float radius;
inst->model->GetWorldBounds(inst->x,inst->y,inst->z,inst->yaw,inst->scale,center,radius);
if(m_cpuWind) {
// Weighted rigid wind matrices rotate around the local origin. An origin sphere
// also contains every rotated leaf/card and the convex weighted interpolation.
radius+=std::sqrt((center[0]-inst->x)*(center[0]-inst->x)+(center[1]-inst->y)*(center[1]-inst->y)+(center[2]-inst->z)*(center[2]-inst->z));
center={inst->x,inst->y,inst->z};
}
const float dx=center[0]-camEyeX,dz=center[2]-camEyeZ;
// Cull only when the whole crown is beyond the distance, not just its origin.
if(maxDist>0 && std::hypot(dx,dz)>maxDist+radius)continue;
if(!IsSphereInFrustum(planes,center[0],center[1],center[2],radius))continue;
const std::array<float,3> camera{camEyeX,camEyeY,camEyeZ};
auto frame=m_frame_wind;frame.strength=inst->windStrength;
frame.legacy_leaf_phase=inst->leafWind.GetLeafPhase();frame.legacy_leaf_rocking=true;
auto inst_draws = inst->model->BuildDrawCommands(inst->x, inst->y, inst->z,
inst->yaw, inst->scale,
m_wind_time, m_wind_strength,
m_frame_wind.matrices.empty() ? nullptr : &m_frame_wind, &camera);
&frame, &camera, m_cpuWind,true);
for (auto& id : inst_draws) {
draws.push_back(std::move(id));
}
@@ -244,4 +261,54 @@ std::vector<Render3DDraw> SpeedTreeForest::BuildDrawCommands(const float* viewMa
return draws;
}
namespace {
float SegmentDistance(const std::array<float,3>& a,const std::array<float,3>& b,const std::array<float,3>& c,const std::array<float,3>& d) {
std::array<float,3> u,v,w;float uu=0,vv=0,uv=0,uw=0,vw=0;
for(int k=0;k<3;++k){u[k]=b[k]-a[k];v[k]=d[k]-c[k];w[k]=a[k]-c[k];uu+=u[k]*u[k];vv+=v[k]*v[k];uv+=u[k]*v[k];uw+=u[k]*w[k];vw+=v[k]*w[k];}
float s=0,t=0;
if(uu<=1e-8f){if(vv>1e-8f)t=std::clamp(vw/vv,0.f,1.f);}
else if(vv<=1e-8f)s=std::clamp(-uw/uu,0.f,1.f);
else {
const float denom=uu*vv-uv*uv;
if(denom>1e-8f)s=std::clamp((uv*vw-uw*vv)/denom,0.f,1.f);
t=(uv*s+vw)/vv;
if(t<0){t=0;s=std::clamp(-uw/uu,0.f,1.f);}
else if(t>1){t=1;s=std::clamp((uv-uw)/uu,0.f,1.f);}
}
float result=0;for(int k=0;k<3;++k){const float delta=w[k]+s*u[k]-t*v[k];result+=delta*delta;}return result;
}
}
bool SpeedTreeForest::CheckMovementCollision(const float* start,const float* end,float radius,bool approachingOnly) const {
if(!start || !end || !std::isfinite(radius) || radius<0)return false;
for(int k=0;k<3;++k)if(!std::isfinite(start[k]) || !std::isfinite(end[k]))return false;
const std::array<float,3> a{start[0],start[1],start[2]},b{end[0],end[1],end[2]};
for(const auto& instance:m_instances) {
if(!instance || !instance->model)continue;
for(const auto& object:instance->model->GetSptInfo().collision_objects) {
// AVA2 OnUpdateCollisionData ignores CO_BOX and translates primitives only.
if(object.type==speedtree::CollisionObject::Type::Box)continue;
const std::array<float,3> center{instance->x+object.position[0],instance->y+object.position[2],instance->z+object.position[1]};
const float r=object.dimensions[0];if(!std::isfinite(r) || r<0)continue;
auto top=center;const bool cylinder=object.type==speedtree::CollisionObject::Type::Cylinder;
if(cylinder) {
const float h=object.dimensions[1];if(!std::isfinite(h) || h<0)continue;
top[1]+=h;
if(b[1]+radius<center[1] || b[1]-radius>top[1])continue;
}
bool separated=false;
for(int k=0;k<3;++k)if(std::max(a[k],b[k])+radius<std::min(center[k],top[k])-r
|| std::min(a[k],b[k])-radius>std::max(center[k],top[k])+r) {separated=true;break;}
if(separated)continue;
const float distance=SegmentDistance(a,b,center,top),reach=(r+radius)*(r+radius);
if(cylinder?distance<=reach:distance<reach) {
// Original movement sphere test permits escaping an overlap; flying test doesn't.
float before=0,after=0;for(int k=0;k<3;++k){before+=(a[k]-center[k])*(a[k]-center[k]);after+=(b[k]-center[k])*(b[k]-center[k]);}
const bool crossing=SegmentDistance(a,a,center,top)>reach && SegmentDistance(b,b,center,top)>reach;
// Complete crossings must not tunnel through a trunk at mobile frame gaps.
if(!approachingOnly || after<before || crossing)return true;
}
}
}
return false;
}
} // namespace ava2
+11 -2
View File
@@ -19,6 +19,8 @@ public:
float scale = 1.0f;
std::string name;
std::shared_ptr<SpeedTreeModel> model;
float windStrength=1; // Original Wrapper::LoadTree; environment changes update existing instances.
speedtree::LegacyWindController leafWind;
};
SpeedTreeForest();
@@ -41,6 +43,8 @@ public:
float camEyeX, float camEyeY, float camEyeZ,
float maxDist = 6500.0f) const;
std::weak_ptr<const uint8_t> GetLifetimeToken() const {return m_lifetime;}
bool CheckMovementCollision(const float* start,const float* end,float radius=30,bool approachingOnly=true) const;
size_t GetInstanceCount() const { return m_instances.size(); }
size_t GetMainTreeCount() const { return m_tree_templates.size(); }
const std::vector<std::unique_ptr<TreeInstance>>& GetInstances() const { return m_instances; }
@@ -48,14 +52,19 @@ public:
std::shared_ptr<SpeedTreeModel> GetMainTree(uint32_t crc);
bool HasMainTree(uint32_t crc) const;
void SetWindStrength(float s) { m_wind_strength = s; }
void SetWindStrength(float s);
float GetWindStrength() const { return m_wind_strength; }
// The shipped AVA2 configuration uses WIND_NONE. CPU deformation is opt-in.
void SetCpuWindEnabled(bool enabled) { m_cpuWind = enabled; }
bool IsCpuWindEnabled() const { return m_cpuWind; }
private:
std::shared_ptr<const uint8_t> m_lifetime=std::make_shared<const uint8_t>(0);
speedtree::LegacyWindController m_wind_controller;
speedtree::WindParameters m_frame_wind;
bool m_cpuWind = false;
float m_wind_time = 0.0f;
float m_wind_strength = 16.0f;
float m_wind_strength = 0.0f;
std::map<uint32_t, SpeedTreeProperty> m_properties;
std::map<uint32_t, std::shared_ptr<SpeedTreeModel>> m_tree_templates;
+62 -45
View File
@@ -3,6 +3,7 @@
#include <filesystem>
#include <algorithm>
#include <cmath>
#include <iostream>
namespace ava2 {
@@ -13,6 +14,8 @@ std::shared_ptr<SpeedTreeModel> SpeedTreeModel::Create(const std::string& sptPat
}
auto impl = speedtree::SpeedTreeModel::CreateFromSpt(resolved, treeSize, treeVariance);
if (!impl) return nullptr;
if(!impl->GetSptInfo().metadata_complete)
std::cerr<<"SpeedTree: partial metadata, token "<<impl->GetSptInfo().unsupported_token<<", "<<resolved<<'\n';
auto model = std::make_shared<SpeedTreeModel>(std::move(impl));
model->m_textureDirectory = std::filesystem::path(resolved).parent_path().string();
return model;
@@ -29,31 +32,52 @@ std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateProcedural(const std::stri
std::vector<Render3DDraw> SpeedTreeModel::BuildDrawCommands(float worldX, float worldY, float worldZ,
float yawDeg, float scale,
float windTime, float windStrength, const speedtree::WindParameters* frameWind,
const std::array<float,3>* camera) const {
const std::array<float,3>* camera, bool cpuWind,bool shareStatic) const {
std::vector<Render3DDraw> results;
if (!m_impl) return results;
speedtree::WindParameters wind;
wind.time = windTime;
wind.strength = windStrength * 0.05f;
wind.strength = std::isfinite(windStrength)?std::max(0.f,windStrength):0;
if (frameWind) wind = *frameWind;
if (!cpuWind) {
// WRAPPER_USE_NO_WIND disables branch/frond deformation and leaf-center
// translation, but SetLeafRockingState(true) still rotates leaf cards.
// Empty matrices would select synthesized SDK wind, not WIND_NONE.
wind.matrices.assign(1, std::array<float,16>{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1});
}
auto build_draw = [&](const speedtree::SpeedTreeMesh& mesh, bool is_canopy, float alpha = 84) {
if (mesh.vertices.empty() || mesh.indices.empty()) return;
const bool shared=shareStatic && !cpuWind && !mesh.is_leaf;
auto cached=m_staticDraws.find(&mesh);
if(shared && cached!=m_staticDraws.end()) {
auto draw=cached->second;
const float a=yawDeg*speedtree::kPI/180,c=std::cos(a)*scale,s=std::sin(a)*scale;
const float world[16]={c,0,-s,0,0,scale,0,0,s,0,c,0,worldX,worldY,worldZ,1};
std::copy_n(world,16,draw.world);results.push_back(std::move(draw));return;
}
Render3DDraw draw;
draw.texture0 = mesh.texture;
if (!m_textureDirectory.empty() && !mesh.texture.empty()) {
// SPT materials often contain only a filename, relative to the tree file.
auto texture=m_resolvedTextures.find(mesh.texture);
if(texture!=m_resolvedTextures.end())draw.texture0=texture->second;
if (texture==m_resolvedTextures.end() && !m_textureDirectory.empty() && !mesh.texture.empty()) {
// CSpeedTreeWrapper::LoadTree: GetPath(spt) + NoExtension(texture name) + ".dds". SPT
// materials hold a bare name, often without extension ("CompositeMap", "plant_grass").
auto name = CResourceManager::NormalizePath(mesh.texture.c_str());
auto candidate = std::filesystem::path(m_textureDirectory) / std::filesystem::path(name).filename();
if (std::filesystem::is_regular_file(candidate)) draw.texture0 = candidate.string();
auto file = std::filesystem::path(name).filename();
for (const auto& leaf : {file.replace_extension(".dds"), std::filesystem::path(name).filename()}) {
auto candidate = std::filesystem::path(m_textureDirectory) / leaf;
if (std::filesystem::is_regular_file(candidate)) { draw.texture0 = candidate.string(); break; }
}
}
m_resolvedTextures[mesh.texture]=draw.texture0;
draw.indices = mesh.indices;
m_impl->EvaluateCpuTransformedVertices(mesh, draw.positions, draw.normals,
worldX, worldY, worldZ,
yawDeg, scale, wind, camera);
shared?0:worldX, shared?0:worldY, shared?0:worldZ,
shared?0:yawDeg, shared?1:scale, wind, camera);
size_t nverts = mesh.vertices.size();
draw.uv0.resize(nverts * 2);
@@ -64,55 +88,48 @@ std::vector<Render3DDraw> SpeedTreeModel::BuildDrawCommands(float worldX, float
draw.diffuse[i] = mesh.vertices[i].diffuse;
}
// AVA2 SpeedTreeConfig selects static lighting; ForestDirectX8 renders
// the SDK vertex diffuse colors with D3DRS_LIGHTING=FALSE.
if (is_canopy) {
draw.alpha_test = true;
draw.alpha_ref = static_cast<uint8_t>(std::clamp(alpha,0.0f,255.0f));
draw.cull_mode = 1; // Double sided
draw.lighting = true;
draw.lighting = false;
} else {
draw.alpha_test = alpha>84;
draw.alpha_ref = alpha>84 ? static_cast<uint8_t>(std::clamp(alpha,0.0f,255.0f)) : 0;
draw.alpha_test = true;
draw.alpha_ref = static_cast<uint8_t>(std::clamp(alpha,0.0f,255.0f));
draw.cull_mode = 2; // CW
draw.lighting = true;
draw.lighting = false;
}
if(shared) {
draw=Render3DDraw::ShareGeometry(std::move(draw));m_staticDraws.emplace(&mesh,draw);
const float a=yawDeg*speedtree::kPI/180,c=std::cos(a)*scale,s=std::sin(a)*scale;
const float world[16]={c,0,-s,0,0,scale,0,0,s,0,c,0,worldX,worldY,worldZ,1};
std::copy_n(world,16,draw.world);
}
results.push_back(std::move(draw));
};
float geometryAlpha=84, billboardAlpha=255;
std::array<float,3> localCamera{};
const auto& info=m_impl->GetSptInfo();
if(camera && std::all_of(camera->begin(),camera->end(),[](float value){return std::isfinite(value);})
&& scale>0 && std::isfinite(scale) && info.lod_far>info.lod_near
&& !info.billboard_uv_quads.empty() && info.leaf_lod_levels>0 && info.leaf_lod_levels<32767) {
float dx=(*camera)[0]-worldX,dy=(*camera)[1]-worldY,dz=(*camera)[2]-worldZ;
float angle=yawDeg*speedtree::kPI/180,c=std::cos(angle),s=std::sin(angle);
localCamera={(dx*c-dz*s)/scale,dy/scale,(dx*s+dz*c)/scale};
float lod=info.EvaluateLod(std::sqrt(dx*dx+dy*dy+dz*dz));
auto transition=speedtree::SelectLodTransition(lod,info.leaf_lod_levels+1,
info.lod_transition_width,info.lod_transition_overlap,info.lod_alpha_exponent);
// Detailed per-level meshes are not yet recovered. Keep the generated
// geometry until the last leaf level transitions to the billboard.
geometryAlpha=255;
auto select=[&](int level,float alpha) {
if(level<0) return;
if(level==int(info.leaf_lod_levels)) billboardAlpha=std::min(billboardAlpha,alpha);
else geometryAlpha=std::min(geometryAlpha,alpha);
};
select(transition.first,transition.first_alpha);
select(transition.second,transition.second_alpha);
}
if(geometryAlpha<255) {
build_draw(m_impl->GetTrunkMesh(),false,geometryAlpha);
build_draw(m_impl->GetLeafMesh(),true,geometryAlpha);
for(const auto& mesh:m_impl->GetFrondMeshes()) build_draw(mesh,true,geometryAlpha);
}
if(billboardAlpha<255) {
for(const auto& mesh:m_impl->BuildBillboardMeshes(localCamera,billboardAlpha))
build_draw(mesh,true,mesh.alpha_ref*255);
}
// CSpeedTreeWrapper::Advance calls ComputeLodLevel() and then always
// SetLodLevel(1.0f), so the original client draws the full geometry at
// c_nDefaultAlphaTestValue (84) and never shows the billboards. Comparing
// the world camera distance with the raw .spt lod_near/lod_far (100/1100)
// dropped nearby trees to their billboards (dark composite silhouettes).
constexpr float geometryAlpha=84;
build_draw(m_impl->GetTrunkMesh(),false,geometryAlpha);
build_draw(m_impl->GetLeafMesh(),true,geometryAlpha);
for(const auto& mesh:m_impl->GetFrondMeshes()) build_draw(mesh,true,geometryAlpha);
return results;
}
void SpeedTreeModel::GetWorldBounds(float x,float y,float z,float yaw,float scale,std::array<float,3>& center,float& radius) const {
if(!m_impl){center={x,y,z};radius=0;return;}
const auto& lo=m_impl->GetBoundsMin();const auto& hi=m_impl->GetBoundsMax();
const float a=yaw*speedtree::kPI/180,c=std::cos(a),s=std::sin(a);
const float lx=(lo[0]+hi[0])*0.5f*scale,ly=(lo[1]+hi[1])*0.5f*scale,lz=(lo[2]+hi[2])*0.5f*scale;
center={x+c*lx+s*lz,y+ly,z-s*lx+c*lz};
const float ex=(hi[0]-lo[0])*0.5f,ey=(hi[1]-lo[1])*0.5f,ez=(hi[2]-lo[2])*0.5f;
radius=std::sqrt(ex*ex+ey*ey+ez*ez)*std::abs(scale);
}
} // namespace ava2
+6 -2
View File
@@ -27,9 +27,11 @@ public:
std::vector<Render3DDraw> BuildDrawCommands(float worldX, float worldY, float worldZ,
float yawDeg, float scale,
float windTime, float windStrength = 15.0f,
float windTime, float windStrength = 1.0f,
const speedtree::WindParameters* frameWind = nullptr,
const std::array<float,3>* camera = nullptr) const;
const std::array<float,3>* camera = nullptr,
bool cpuWind = false, bool shareStatic = false) const;
void GetWorldBounds(float x,float y,float z,float yaw,float scale,std::array<float,3>& center,float& radius) const;
float GetHeight() const { return m_impl ? m_impl->GetHeight() : 1000.0f; }
float GetRadius() const { return m_impl ? m_impl->GetRadius() : 350.0f; }
@@ -44,6 +46,8 @@ public:
private:
std::shared_ptr<speedtree::SpeedTreeModel> m_impl;
std::string m_textureDirectory;
mutable std::map<const speedtree::SpeedTreeMesh*,Render3DDraw> m_staticDraws;
mutable std::map<std::string,std::string> m_resolvedTextures;
};
} // namespace ava2
+225 -94
View File
@@ -109,6 +109,7 @@ bool TerrainHeightmap::LoadFromBuffer(const uint16_t* raw_data, size_t count, fl
m_width = RAW_XSIZE;
m_height = RAW_YSIZE;
m_patch_count_x = m_patch_count_z = PATCH_COUNT;
m_cell_scale = cell_scale;
m_height_scale = height_scale;
@@ -129,6 +130,114 @@ bool TerrainHeightmap::LoadFromBuffer(const uint16_t* raw_data, size_t count, fl
return true;
}
namespace {
template <typename T>
bool ReadExact(const std::string& path, std::vector<T>& out, size_t count, size_t skip = 0) {
std::ifstream file(path, std::ios::binary);
if (!file) return false;
file.seekg(0, std::ios::end);
const auto size = static_cast<size_t>(file.tellg());
if (size < skip + count * sizeof(T)) return false;
file.seekg(static_cast<std::streamoff>(skip), std::ios::beg);
out.resize(count);
return static_cast<bool>(file.read(reinterpret_cast<char*>(out.data()), static_cast<std::streamsize>(count * sizeof(T))));
}
} // namespace
bool TerrainHeightmap::LoadBlockDirs(int nx, int nz, const std::vector<std::string>& dirs, float origin_x, float origin_z,
float height_scale, float cell_scale) {
if (nx < 1 || nz < 1 || dirs.size() != static_cast<size_t>(nx * nz)) return false;
m_patchDrawCache.clear();
m_cell_scale = cell_scale;
m_height_scale = height_scale;
m_width = MAP_XSIZE * nx + 3;
m_height = MAP_YSIZE * nz + 3;
m_patch_count_x = PATCH_COUNT * nx;
m_patch_count_z = PATCH_COUNT * nz;
m_has_origin = true;
m_origin_x = origin_x - cell_scale;
m_origin_z = origin_z - cell_scale;
m_heights.assign(static_cast<size_t>(m_width) * m_height, 0.0f);
m_tiles.clear();
m_attr.clear();
m_tile_width = m_tile_height = m_attr_width = m_attr_height = 0;
std::vector<uint8_t> tiles(static_cast<size_t>(ATTRMAP_XSIZE * nx + 2) * (ATTRMAP_YSIZE * nz + 2), 0);
std::vector<uint8_t> attr(static_cast<size_t>(ATTRMAP_XSIZE * nx) * (ATTRMAP_YSIZE * nz), 0);
const int tile_w = ATTRMAP_XSIZE * nx + 2, attr_w = ATTRMAP_XSIZE * nx;
std::vector<bool> present(dirs.size(), false);
bool any_tiles = false, any_attr = false, any = false;
m_min_height = 1e9f;
m_max_height = -1e9f;
std::vector<uint16_t> raw;
std::vector<uint8_t> bytes;
for (int bz = 0; bz < nz; ++bz) {
for (int bx = 0; bx < nx; ++bx) {
const auto& dir = dirs[bz * nx + bx];
if (dir.empty() || !ReadExact(dir + "/height.raw", raw, RAW_XSIZE * RAW_YSIZE)) continue;
present[bz * nx + bx] = any = true;
// Neighbouring blocks share their border samples; each block owns raw [1, 128] inside the set
// and its outer border only on the set's edge.
const int k0x = bx == 0 ? 0 : 1, k1x = bx == nx - 1 ? RAW_XSIZE - 1 : MAP_XSIZE;
const int k0z = bz == 0 ? 0 : 1, k1z = bz == nz - 1 ? RAW_YSIZE - 1 : MAP_YSIZE;
for (int kz = k0z; kz <= k1z; ++kz) {
for (int kx = k0x; kx <= k1x; ++kx) {
const float h = static_cast<float>(raw[kz * RAW_XSIZE + kx]) * height_scale;
m_heights[static_cast<size_t>(bz * MAP_YSIZE + kz) * m_width + bx * MAP_XSIZE + kx] = h;
m_min_height = std::min(m_min_height, h);
m_max_height = std::max(m_max_height, h);
}
}
if (ReadExact(dir + "/tile.raw", bytes, TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE)) {
any_tiles = true;
const int t0x = bx == 0 ? 0 : 1, t1x = bx == nx - 1 ? TILEMAP_RAW_XSIZE - 1 : ATTRMAP_XSIZE;
const int t0z = bz == 0 ? 0 : 1, t1z = bz == nz - 1 ? TILEMAP_RAW_YSIZE - 1 : ATTRMAP_YSIZE;
for (int tz = t0z; tz <= t1z; ++tz)
for (int tx = t0x; tx <= t1x; ++tx)
tiles[static_cast<size_t>(bz * ATTRMAP_YSIZE + tz) * tile_w + bx * ATTRMAP_XSIZE + tx] = bytes[tz * TILEMAP_RAW_XSIZE + tx];
}
std::ifstream attr_file(dir + "/attr.atr", std::ios::binary);
if (attr_file) {
attr_file.seekg(0, std::ios::end);
const auto size = static_cast<size_t>(attr_file.tellg());
// Same header rule as LoadAttrFromBuffer: magic 2634 + 256x256, else headerless.
const size_t skip = size >= 6 + ATTRMAP_XSIZE * ATTRMAP_YSIZE ? 6 : 0;
attr_file.close();
if (ReadExact(dir + "/attr.atr", bytes, ATTRMAP_XSIZE * ATTRMAP_YSIZE, skip)) {
any_attr = true;
for (int az = 0; az < ATTRMAP_YSIZE; ++az)
std::copy_n(bytes.begin() + az * ATTRMAP_XSIZE, ATTRMAP_XSIZE,
attr.begin() + static_cast<size_t>(bz * ATTRMAP_YSIZE + az) * attr_w + bx * ATTRMAP_XSIZE);
}
}
}
}
if (!any) {
m_heights.clear();
m_patches.clear();
m_quadtreeRoot.reset();
m_width = m_height = 0;
return false;
}
if (any_tiles) {
m_tile_width = tile_w;
m_tile_height = ATTRMAP_YSIZE * nz + 2;
m_tiles = std::move(tiles);
}
if (any_attr) {
m_attr_width = attr_w;
m_attr_height = ATTRMAP_YSIZE * nz;
m_attr = std::move(attr);
}
UpdateBounds();
CalculateNormals();
BuildPatchesAndQuadtree();
for (auto& patch : m_patches)
patch.present = present[(patch.patch_y / PATCH_COUNT) * nx + patch.patch_x / PATCH_COUNT];
m_quadtreeRoot = BuildQuadtreeNode(0, m_patch_count_x, 0, m_patch_count_z, 0);
return true;
}
bool TerrainHeightmap::LoadTileRaw(const std::string& tile_path) {
std::ifstream file(tile_path, std::ios::binary);
if (!file.is_open()) {
@@ -231,54 +340,58 @@ bool TerrainHeightmap::LoadTextureSet(const std::string& textureset_path) {
}
bool TerrainHeightmap::LoadTextureSetFromString(const std::string& content) {
m_patchDrawCache.clear();
std::istringstream file(content);
std::string line;
int current_id = 0;
bool in_texture = false;
while (std::getline(file, line)) {
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) {
line.pop_back();
}
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos) continue;
std::string trim = line.substr(start);
if (trim.rfind("Start Texture", 0) == 0) {
std::string id_str = trim.substr(13);
current_id = std::atoi(id_str.c_str());
in_texture = true;
} else if (trim.rfind("End Texture", 0) == 0) {
in_texture = false;
current_id = 0;
} else if (in_texture && current_id > 0) {
if (trim.front() == '"' || trim.find(".dds") != std::string::npos || trim.find(".tga") != std::string::npos) {
std::string path = trim;
if (path.front() == '"' && path.back() == '"') {
path = path.substr(1, path.size() - 2);
std::istringstream file(content);std::string line,path;
std::unordered_map<uint8_t,std::string> textures;
std::unordered_map<uint8_t,TextureCoordinates> coordinates;
int id=0,field=0;TextureCoordinates current;
while(std::getline(file,line)) {
size_t start=line.find_first_not_of(" \t\r"),end=line.find_last_not_of(" \t\r");
if(start==std::string::npos) continue;
std::string trim=line.substr(start,end-start+1);
if(trim.rfind("Start Texture",0)==0) {id=std::atoi(trim.substr(13).c_str());field=0;path.clear();current={};}
else if(trim.rfind("End Texture",0)==0) {
if(id>0 && id<=255 && !path.empty()) {textures[uint8_t(id)]=path;coordinates[uint8_t(id)]=current;}
id=0;
} else if(id>0 && id<=255) {
if(field==0) {
path=trim;if(path.front()=='"' && path.back()=='"')path=path.substr(1,path.size()-2);
if(path.size()>=3 && (path[0]=='d'||path[0]=='D') && path[1]==':')path.erase(0,3);
std::replace(path.begin(),path.end(),'\\','/');
while(!path.empty() && path.front()=='/')path.erase(0,1);
} else {
std::istringstream value(trim);float number;
if(!(value>>number) || !std::isfinite(number)) return false;
if(field>=6 && (double(number)<-2147483648.0 || double(number)>2147483647.0)) return false;
switch(field) {
case 1:current.u_scale=number;break;case 2:current.v_scale=number;break;
case 3:current.u_offset=number;break;case 4:current.v_offset=number;break;
case 5:current.splat=number!=0;break;
case 6:current.begin=uint16_t(int(number));break;case 7:current.end=uint16_t(int(number));break;
default:return false;
}
if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':') {
path = path.substr(3);
}
for (char& c : path) {
if (c == '\\') c = '/';
}
while (!path.empty() && path.front() == '/') {
path = path.substr(1);
}
m_textureSet[static_cast<uint8_t>(current_id)] = path;
in_texture = false;
}
++field;
}
}
return !m_textureSet.empty();
if(textures.empty()) return false;
m_textureSet=std::move(textures);m_textureCoordinates=std::move(coordinates);m_patchDrawCache.clear();
return true;
}
std::array<float,2> TerrainHeightmap::GetTextureUv(uint8_t tile,float x,float z) const {
auto found=m_textureCoordinates.find(tile);
if(found==m_textureCoordinates.end()) return {(x-m_world_min_x)/500,(z-m_world_min_z)/500};
// TextureSet::SetTexture, row-vector world texgen. Source rendering Y is
// -map Y, so the SDK positive map-Z axis gives +VScale and -VOffset.
const auto& t=found->second;float base=1.0f/(16*m_cell_scale);
return {x*base*t.u_scale+t.u_offset,z*base*t.v_scale-t.v_offset};
}
void TerrainHeightmap::GenerateProcedural(int width, int height, float cell_scale, float hill_amplitude) {
m_patchDrawCache.clear();
m_width = std::max(width, 16);
m_height = std::max(height, 16);
m_patch_count_x = m_patch_count_z = PATCH_COUNT;
m_cell_scale = cell_scale;
m_height_scale = 1.0f;
@@ -449,10 +562,11 @@ uint8_t TerrainHeightmap::GetAttrAtGrid(int x, int y) const {
uint8_t TerrainHeightmap::GetAttrAtWorld(float world_x, float world_z) const {
if (m_attr.empty() || m_attr_width <= 0 || m_attr_height <= 0 || m_width < 2 || m_height < 2) return 0;
float grid_x = (world_x - m_world_min_x) / (static_cast<float>(m_width - 1) * m_cell_scale) * static_cast<float>(m_attr_width - 1);
float grid_z = (world_z - m_world_min_z) / (static_cast<float>(m_height - 1) * m_cell_scale) * static_cast<float>(m_attr_height - 1);
int ax = std::clamp(static_cast<int>(std::round(grid_x)), 0, m_attr_width - 1);
int az = std::clamp(static_cast<int>(std::round(grid_z)), 0, m_attr_height - 1);
// attr.atr has no border: cell 0 starts at the block origin (raw index 1), half a height cell wide.
float grid_x = (world_x - m_world_min_x - m_cell_scale) / (m_cell_scale * 0.5f);
float grid_z = (world_z - m_world_min_z - m_cell_scale) / (m_cell_scale * 0.5f);
int ax = std::clamp(static_cast<int>(std::floor(grid_x)), 0, m_attr_width - 1);
int az = std::clamp(static_cast<int>(std::floor(grid_z)), 0, m_attr_height - 1);
return m_attr[az * m_attr_width + ax];
}
@@ -463,14 +577,14 @@ bool TerrainHeightmap::IsAttrOn(float world_x, float world_z, uint8_t flag) cons
void TerrainHeightmap::BuildPatchesAndQuadtree() {
if (m_width < 16 || m_height < 16) return;
m_patches.resize(PATCH_COUNT * PATCH_COUNT);
m_patches.assign(static_cast<size_t>(m_patch_count_x) * m_patch_count_z, TerrainPatch{});
int patch_cells_x = (m_width - 1) / PATCH_COUNT;
int patch_cells_z = (m_height - 1) / PATCH_COUNT;
int patch_cells_x = (m_width - 1) / m_patch_count_x;
int patch_cells_z = (m_height - 1) / m_patch_count_z;
for (int py = 0; py < PATCH_COUNT; ++py) {
for (int px = 0; px < PATCH_COUNT; ++px) {
int p_idx = py * PATCH_COUNT + px;
for (int py = 0; py < m_patch_count_z; ++py) {
for (int px = 0; px < m_patch_count_x; ++px) {
int p_idx = py * m_patch_count_x + px;
auto& patch = m_patches[p_idx];
patch.patch_x = px;
patch.patch_y = py;
@@ -518,56 +632,44 @@ void TerrainHeightmap::BuildPatchesAndQuadtree() {
}
}
m_quadtreeRoot = BuildQuadtreeNode(m_world_min_x, m_world_max_x, m_world_min_z, m_world_max_z, 0);
m_quadtreeRoot = BuildQuadtreeNode(0, m_patch_count_x, 0, m_patch_count_z, 0);
}
std::unique_ptr<TerrainQuadNode> TerrainHeightmap::BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth) {
std::unique_ptr<TerrainQuadNode> TerrainHeightmap::BuildQuadtreeNode(int px0, int px1, int pz0, int pz1, int depth) {
if (px0 >= px1 || pz0 >= pz1) return nullptr;
auto node = std::make_unique<TerrainQuadNode>();
node->depth = depth;
node->aabb_min[0] = min_x;
node->aabb_max[0] = max_x;
node->aabb_min[2] = min_z;
node->aabb_max[2] = max_z;
node->aabb_min[1] = m_min_height;
node->aabb_max[1] = m_max_height;
if (depth >= 3) {
float cx = (min_x + max_x) * 0.5f;
float cz = (min_z + max_z) * 0.5f;
float u = (cx - m_world_min_x) / (m_world_max_x - m_world_min_x);
float v = (cz - m_world_min_z) / (m_world_max_z - m_world_min_z);
int px = std::clamp(static_cast<int>(u * static_cast<float>(PATCH_COUNT)), 0, PATCH_COUNT - 1);
int py = std::clamp(static_cast<int>(v * static_cast<float>(PATCH_COUNT)), 0, PATCH_COUNT - 1);
int idx = py * PATCH_COUNT + px;
if (px1 - px0 == 1 && pz1 - pz0 == 1) {
const int idx = pz0 * m_patch_count_x + px0;
const auto& patch = m_patches[idx];
if (!patch.present) return nullptr;
node->patch_idx = idx;
if (idx < static_cast<int>(m_patches.size())) {
node->aabb_min[1] = m_patches[idx].aabb_min[1];
node->aabb_max[1] = m_patches[idx].aabb_max[1];
}
std::copy_n(patch.aabb_min, 3, node->aabb_min);
std::copy_n(patch.aabb_max, 3, node->aabb_max);
return node;
}
float mid_x = (min_x + max_x) * 0.5f;
float mid_z = (min_z + max_z) * 0.5f;
const int mid_x = (px0 + px1 + 1) / 2, mid_z = (pz0 + pz1 + 1) / 2;
node->children[0] = BuildQuadtreeNode(px0, mid_x, pz0, mid_z, depth + 1);
node->children[1] = BuildQuadtreeNode(mid_x, px1, pz0, mid_z, depth + 1);
node->children[2] = BuildQuadtreeNode(px0, mid_x, mid_z, pz1, depth + 1);
node->children[3] = BuildQuadtreeNode(mid_x, px1, mid_z, pz1, depth + 1);
node->children[0] = BuildQuadtreeNode(min_x, mid_x, min_z, mid_z, depth + 1);
node->children[1] = BuildQuadtreeNode(mid_x, max_x, min_z, mid_z, depth + 1);
node->children[2] = BuildQuadtreeNode(min_x, mid_x, mid_z, max_z, depth + 1);
node->children[3] = BuildQuadtreeNode(mid_x, max_x, mid_z, max_z, depth + 1);
float cmin_y = 1e9f, cmax_y = -1e9f;
for (int k = 0; k < 4; ++k) {
if (node->children[k]) {
cmin_y = std::min(cmin_y, node->children[k]->aabb_min[1]);
cmax_y = std::max(cmax_y, node->children[k]->aabb_max[1]);
bool any = false;
for (int axis = 0; axis < 3; ++axis) {
node->aabb_min[axis] = 1e30f;
node->aabb_max[axis] = -1e30f;
}
for (const auto& child : node->children) {
if (!child) continue;
any = true;
for (int axis = 0; axis < 3; ++axis) {
node->aabb_min[axis] = std::min(node->aabb_min[axis], child->aabb_min[axis]);
node->aabb_max[axis] = std::max(node->aabb_max[axis], child->aabb_max[axis]);
}
}
node->aabb_min[1] = cmin_y;
node->aabb_max[1] = cmax_y;
return node;
return any ? std::move(node) : nullptr;
}
void TerrainHeightmap::QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector<int>& out_visible_patches) const {
@@ -623,7 +725,7 @@ void TerrainHeightmap::AppendCulledDrawRefs(const float view[16], const float pr
};
std::vector<int> visible_patches;
visible_patches.reserve(64);
visible_patches.reserve(m_patches.size());
QueryQuadtree(m_quadtreeRoot.get(), planes, eye, max_distance, visible_patches);
for (int p_idx : visible_patches) {
@@ -656,7 +758,7 @@ Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step
Render3DDraw draw;
if (m_heights.empty() || m_width < 2 || m_height < 2) return draw;
int p_idx = patch_y * PATCH_COUNT + patch_x;
int p_idx = patch_y * m_patch_count_x + patch_x;
uint8_t dom_tile = 4;
if (p_idx >= 0 && p_idx < static_cast<int>(m_patches.size())) {
dom_tile = m_patches[p_idx].dominant_tile;
@@ -666,8 +768,8 @@ Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step
draw.cull_mode = 1; // D3DCULL_NONE: double-sided for terrain meshes
step = std::max(1, step);
int patch_cells_x = (m_width - 1) / PATCH_COUNT;
int patch_cells_z = (m_height - 1) / PATCH_COUNT;
int patch_cells_x = (m_width - 1) / m_patch_count_x;
int patch_cells_z = (m_height - 1) / m_patch_count_z;
int start_x = patch_x * patch_cells_x;
int end_x = std::min((patch_x + 1) * patch_cells_x, m_width - 1);
@@ -702,8 +804,8 @@ Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step
draw.normals.push_back(ny);
draw.normals.push_back(nz);
float u = (vx - m_world_min_x) / 500.0f;
float v = (vz - m_world_min_z) / 500.0f;
auto uv=GetTextureUv(4,vx,vz);
float u=uv[0],v=uv[1];
draw.uv0.push_back(u);
draw.uv0.push_back(v);
@@ -729,6 +831,31 @@ Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step
}
}
// A step-2 patch next to a step-1 patch leaves T-junction cracks along the shared edge, which
// showed the cleared background as white seams/blocks. Hang a vertical skirt below each edge.
const float skirt = m_cell_scale * 2.0f;
auto add_skirt = [&](uint32_t first, uint32_t stride, int count) {
const auto base = static_cast<uint32_t>(draw.positions.size() / 3);
for (int k = 0; k < count; ++k) {
const uint32_t v = first + static_cast<uint32_t>(k) * stride;
draw.positions.insert(draw.positions.end(), {draw.positions[v * 3], draw.positions[v * 3 + 1] - skirt, draw.positions[v * 3 + 2]});
draw.normals.insert(draw.normals.end(), {draw.normals[v * 3], draw.normals[v * 3 + 1], draw.normals[v * 3 + 2]});
draw.uv0.insert(draw.uv0.end(), {draw.uv0[v * 2], draw.uv0[v * 2 + 1]});
draw.diffuse.push_back(draw.diffuse[v]);
}
for (int k = 0; k + 1 < count; ++k) {
const uint32_t a = first + static_cast<uint32_t>(k) * stride, b = a + stride;
const uint32_t sa = base + static_cast<uint32_t>(k), sb = sa + 1;
draw.indices.insert(draw.indices.end(), {a, sa, b, b, sa, sb});
}
};
if (grid_w > 1 && grid_h > 1) {
add_skirt(0, 1, grid_w);
add_skirt(static_cast<uint32_t>((grid_h - 1) * grid_w), 1, grid_w);
add_skirt(0, static_cast<uint32_t>(grid_w), grid_h);
add_skirt(static_cast<uint32_t>(grid_w - 1), static_cast<uint32_t>(grid_w), grid_h);
}
return draw;
}
@@ -753,6 +880,10 @@ std::vector<Render3DDraw> TerrainHeightmap::BuildPatchDraws(int patch_x, int pat
for (const auto& [tile, layer] : weights) {
auto draw = base;
draw.texture0 = GetTexturePathForTile(tile);
for(size_t v=0;v<count;++v) {
auto uv=GetTextureUv(tile,draw.positions[v*3],draw.positions[v*3+2]);
draw.uv0[v*2]=uv[0];draw.uv0[v*2+1]=uv[1];
}
draw.alpha_blend = true;
draw.z_write = false;
draw.indices.clear();
@@ -809,8 +940,8 @@ Render3DDraw TerrainHeightmap::BuildDrawCommand(const float world[16], int step)
draw.normals.push_back(ny);
draw.normals.push_back(nz);
float u = (vx - m_world_min_x) / 500.0f;
float v = (vz - m_world_min_z) / 500.0f;
auto uv=GetTextureUv(4,vx,vz);
float u=uv[0],v=uv[1];
draw.uv0.push_back(u);
draw.uv0.push_back(v);
+21 -7
View File
@@ -2,6 +2,7 @@
#include "RenderCommands3D.h"
#include <cstdint>
#include <array>
#include <string>
#include <vector>
#include <unordered_map>
@@ -20,8 +21,9 @@ enum TerrainAttr : uint8_t {
};
struct TerrainPatch {
int patch_x = 0; // 0..7
int patch_y = 0; // 0..7
int patch_x = 0; // 0..patch count - 1
int patch_y = 0;
bool present = true; // false where a stitched block had no height.raw
float aabb_min[3] = {0};
float aabb_max[3] = {0};
uint8_t dominant_tile = 0;
@@ -31,12 +33,11 @@ struct TerrainQuadNode {
float aabb_min[3] = {0};
float aabb_max[3] = {0};
int depth = 0;
int patch_idx = -1; // -1 if internal, >=0 if leaf (0..63)
int patch_idx = -1; // -1 if internal, >=0 if leaf
std::unique_ptr<TerrainQuadNode> children[4];
};
// Height/attribute query surface shared by a single TerrainHeightmap and the
// 3x3 CMapOutdoor block set (game_scene.cpp) so actors walk on whichever is active.
// Height/attribute query surface actors walk on.
class TerrainHeightSource {
public:
virtual ~TerrainHeightSource() = default;
@@ -88,9 +89,18 @@ public:
bool LoadAttr(const std::string& attr_path);
bool LoadAttrFromBuffer(const uint8_t* attr_data, size_t count);
// CMapOutdoor::Update loads the (up to) 3x3 CTerrain blocks around the player. Stitch them into
// one heightmap: dirs is nx*nz block directories, row-major by z, "" for a block without data.
// Each block's raw index 1 sits on its pixel origin; origin_x/z is the first block's origin.
bool LoadBlockDirs(int nx, int nz, const std::vector<std::string>& dirs, float origin_x, float origin_z,
float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE);
// Load TextureSet file (e.g. textureset/metin2_map1.txt)
bool LoadTextureSet(const std::string& textureset_path);
bool LoadTextureSetFromString(const std::string& content);
void ClearTextureSet() { m_textureSet.clear(); m_textureCoordinates.clear(); m_patchDrawCache.clear(); }
struct TextureCoordinates { float u_scale=1,v_scale=1,u_offset=0,v_offset=0; bool splat=false; uint16_t begin=0,end=0; };
std::array<float,2> GetTextureUv(uint8_t tile,float x,float z) const;
// Procedural terrain generation for testing
void GenerateProcedural(int width = 64, int height = 64, float cell_scale = 100.0f, float hill_amplitude = 80.0f);
@@ -158,7 +168,7 @@ private:
void CalculateNormals();
void UpdateBounds();
void BuildPatchesAndQuadtree();
std::unique_ptr<TerrainQuadNode> BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth);
std::unique_ptr<TerrainQuadNode> BuildQuadtreeNode(int px0, int px1, int pz0, int pz1, int depth);
void QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector<int>& out_visible_patches) const;
int m_width = 0;
@@ -172,6 +182,9 @@ private:
float m_min_height = 0.0f;
float m_max_height = 0.0f;
int m_patch_count_x = PATCH_COUNT;
int m_patch_count_z = PATCH_COUNT;
bool m_has_origin = false;
float m_origin_x = 0.0f;
float m_origin_z = 0.0f;
@@ -188,9 +201,10 @@ private:
std::vector<uint8_t> m_attr; // m_attr_width * m_attr_height attribute flags
std::unordered_map<uint8_t, std::string> m_textureSet; // tile_id -> texture dds path
std::unordered_map<uint8_t,TextureCoordinates> m_textureCoordinates;
mutable std::map<std::tuple<int,int,int>, std::vector<Render3DDraw>> m_patchDrawCache;
std::vector<TerrainPatch> m_patches; // 8x8 = 64 patches
std::vector<TerrainPatch> m_patches; // m_patch_count_x * m_patch_count_z (8x8 per block)
std::unique_ptr<TerrainQuadNode> m_quadtreeRoot;
};
+12 -1
View File
@@ -265,7 +265,7 @@ void TextTailManager::HideAllTextTail() {
m_itemList.clear();
}
int TextTailManager::Pick(int ixMouse, int iyMouse) {
int TextTailManager::Pick(int ixMouse, int iyMouse,float padding) {
float mx = static_cast<float>(ixMouse);
float my = static_cast<float>(iyMouse);
@@ -281,6 +281,17 @@ int TextTailManager::Pick(int ixMouse, int iyMouse) {
return static_cast<int>(tail->dwVirtualID);
}
}
if(padding>0) {
std::shared_ptr<TextTailItem> picked;float best=padding*padding;
for(const auto& tail:m_itemList) {
if(!tail)continue;
const float dx=mx-std::clamp(mx,tail->x+tail->xStart,tail->x+tail->xEnd);
const float dy=my-std::clamp(my,tail->y+tail->yStart,tail->y+tail->yEnd);
const float distance=dx*dx+dy*dy;
if(distance<best || (distance==best && (!picked || tail->dwVirtualID<picked->dwVirtualID))) {best=distance;picked=tail;}
}
if(picked){SelectItemName(picked->dwVirtualID);return int(picked->dwVirtualID);}
}
return -1;
}

Some files were not shown because too many files have changed in this diff Show More