diff --git a/CMakeLists.txt b/CMakeLists.txt index e96c3425..9f9705be 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,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_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) diff --git a/docs/PORT-PLAN.md b/docs/PORT-PLAN.md index 0bd9d971..699b0548 100644 --- a/docs/PORT-PLAN.md +++ b/docs/PORT-PLAN.md @@ -1731,6 +1731,7 @@ P0, the real-server flow stops: 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/.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); diff --git a/src/eter_net/NetworkActorManager.cpp b/src/eter_net/NetworkActorManager.cpp index 756fdfc2..e021e4fe 100644 --- a/src/eter_net/NetworkActorManager.cpp +++ b/src/eter_net/NetworkActorManager.cpp @@ -501,7 +501,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; @@ -705,7 +712,19 @@ 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) { @@ -764,6 +783,8 @@ void NetworkActorManager::SetActorOwner(uint32_t ownerVID, uint32_t victimVID) { void NetworkActorManager::Update(float dt, const TerrainHeightSource* terrain) { 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->SetIsPC(actorData.m_bType == TYPE_PC); if (actorData.m_isMoving) { float curX = static_cast(actorData.m_lCurX); diff --git a/src/eter_net/PythonNetworkStream.cpp b/src/eter_net/PythonNetworkStream.cpp index b83e4363..03eb9d56 100644 --- a/src/eter_net/PythonNetworkStream.cpp +++ b/src/eter_net/PythonNetworkStream.cpp @@ -1421,6 +1421,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)); @@ -1431,6 +1432,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)); diff --git a/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp b/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp index bdc1c7ec..4f9dbf9d 100644 --- a/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp +++ b/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp @@ -31,6 +31,7 @@ #include "python_sash.h" #include "python_manager_bank.h" #include "NetworkActorManager.h" +#include "python_background.h" #include #include @@ -663,11 +664,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; } diff --git a/src/eter_render/ActorInstance.cpp b/src/eter_render/ActorInstance.cpp index 65907ba9..8ec25251 100644 --- a/src/eter_render/ActorInstance.cpp +++ b/src/eter_render/ActorInstance.cpp @@ -421,6 +421,14 @@ bool ActorInstance::PlayMotion(MotionType type, 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; uint16_t keyMode; @@ -428,6 +436,11 @@ void ActorInstance::OnMotionBound(uint32_t type) { const auto* entries = m_raceData->GetMotions(keyMode, type); if (entries && !entries->empty()) m_curRaceMotion = GetRaceMotionData(entries->front().fileName); } + // 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 = 1.0f; @@ -458,7 +471,10 @@ float ActorInstance::GetDefendingRadius() const { } bool ActorInstance::CanCheckAttacking() const { - if (!m_curRaceMotion || !m_curRaceMotion->isAttackingMotion || IsMotionFinished()) return false; + // 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; } @@ -642,6 +658,15 @@ bool ActorInstance::InterceptMotionIndex(uint32_t index, bool loop) { return PlayMotionIndex(index, loop); } +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; @@ -781,6 +806,16 @@ void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const M 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(); 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(); @@ -908,7 +943,7 @@ bool ActorInstance::IsTargetInAttackRange(const ActorInstance& target, float max } std::vector 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 = DrawModel()->BuildDrawCommands(PoseTime(), worldOverride ? worldOverride : world); @@ -1063,22 +1098,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]; - // 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; - } + 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) { diff --git a/src/eter_render/ActorInstance.h b/src/eter_render/ActorInstance.h index bd871775..98f549ff 100644 --- a/src/eter_render/ActorInstance.h +++ b/src/eter_render/ActorInstance.h @@ -3,6 +3,7 @@ #include "Gr2ModelRenderer.h" #include "TerrainHeightmap.h" #include +#include #include #include #include @@ -42,7 +43,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); @@ -104,6 +108,9 @@ public: // a pushed motion starts when the current one ends (a loop at its cycle end). bool SetLoopMotionIndex(uint32_t index); bool InterceptMotionIndex(uint32_t index, bool loop); + // 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); void ActEmotion(uint32_t motionIndex) { PushMotionIndex(motionIndex, false); } void ActDualEmotion(ActorInstance& target, uint32_t motion1, uint32_t motion2) { @@ -230,6 +237,45 @@ public: float GetDefendingRadius() 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; + 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; + // IFlyEventHandler (CPythonPlayerEventHandler::CNormalBowAttack_FlyEventHandler_AutoClear). + struct FlyEventHandler { + std::function onSetFlyTarget; + std::function onShoot; + }; + 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); @@ -350,6 +396,46 @@ private: 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) const; + 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 m_flyTargetQueue; + FlyEventHandler m_flyEventHandler; + struct AttachedEffect { + uint32_t instanceId = 0; + std::string bone; // empty: actor root + float offset[3] = {}; // model space (Z-up) + }; + std::vector 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 spheres; + std::unordered_map hitted; + }; + SplashArea m_splash; uint16_t m_wcurComboType = 0; std::unordered_map m_buffs; diff --git a/src/eter_render/ActorInstanceMotionEvent.cpp b/src/eter_render/ActorInstanceMotionEvent.cpp new file mode 100644 index 00000000..766cfc88 --- /dev/null +++ b/src/eter_render/ActorInstanceMotionEvent.cpp @@ -0,0 +1,415 @@ +// 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 +#include + +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) const { + MakeTransformMatrix(m_yaw, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, out16); +} + +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; +} + +// 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]; + } + // The flying instance flies to the target position at launch (CFlyTarget tracking of a + // moving actor is not modelled by FlyingManager). + FlyingManager::Instance().CreateFlyingInstance(ev.index, start, targetPos); + 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(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 diff --git a/src/eter_render/CRenderTarget.cpp b/src/eter_render/CRenderTarget.cpp index 53b67125..dd04d516 100644 --- a/src/eter_render/CRenderTarget.cpp +++ b/src/eter_render/CRenderTarget.cpp @@ -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(); } 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; } @@ -296,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); } diff --git a/src/eter_render/CRenderTarget.h b/src/eter_render/CRenderTarget.h index 8b865685..f3b15838 100644 --- a/src/eter_render/CRenderTarget.h +++ b/src/eter_render/CRenderTarget.h @@ -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 m_actor = std::make_unique(); // owns effect instances: not copyable Gr2SceneRenderer m_renderer3d; SDL_Surface* m_surface = nullptr; SDL_Texture* m_texture = nullptr; diff --git a/src/eter_render/RaceData.cpp b/src/eter_render/RaceData.cpp index 0d1f26cd..c6c7822b 100644 --- a/src/eter_render/RaceData.cpp +++ b/src/eter_render/RaceData.cpp @@ -2,6 +2,8 @@ #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 #include #include @@ -179,7 +181,7 @@ bool LoadHitData(const TextFileLoader& loader, RaceMotionData::HitData* hit) { // NRaceData::LoadAttackData + LoadMotionAttackData. bool LoadMotionAttackData(TextFileLoader& loader, RaceMotionData* data) { - if (!loader.tokenInteger("attacktype", &data->attackType)) data->attackType = 2; // ATTACK_TYPE_SPLASH + 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; @@ -203,9 +205,112 @@ bool LoadMotionAttackData(TextFileLoader& loader, RaceMotionData* data) { } 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 ParseRaceMotionData(const std::string& text, RaceMotionData* data) { +bool ParseSoundScriptData(const std::string& text, std::vector* sounds) { + TextFileLoader loader; + if (!loader.load(text)) return false; + loader.setTop(); + int count = 0; + if (!loader.tokenInteger("sounddatacount", &count)) return false; + std::vector 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(); @@ -230,10 +335,69 @@ bool ParseRaceMotionData(const std::string& text, RaceMotionData* data) { } 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; } @@ -246,7 +410,7 @@ const RaceMotionData* GetRaceMotionData(const std::string& msaFileName) { std::string text; if (ReadRaceResourceFile(msaFileName, &text)) { data = std::make_unique(); - if (!ParseRaceMotionData(text, data.get())) data.reset(); + if (!ParseRaceMotionData(text, data.get(), msaFileName)) data.reset(); } return cache.emplace(key, std::move(data)).first->second.get(); } @@ -681,7 +845,7 @@ void LoadPlayerMotions(RaceData& race, const std::string& folder) { l.Register(MODE_GENERAL, R::NAME_INTRO_SELECTED, "selected.msa"); l.Register(MODE_GENERAL, R::NAME_INTRO_NOT_SELECTED, "not_selected.msa"); - // __LoadGameRace (emotions, guild skills and skills are not ported) + // __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) { @@ -767,6 +931,63 @@ void LoadPlayerMotions(RaceData& race, const std::string& folder) { 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 _; shamans take grade 0 + // from the extra (_target) names. + struct SkillFiles { int job; std::vector 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 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 diff --git a/src/eter_render/RaceData.h b/src/eter_render/RaceData.h index f88bcbd9..21e1dbcf 100644 --- a/src/eter_render/RaceData.h +++ b/src/eter_render/RaceData.h @@ -3,9 +3,10 @@ // (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. // Player weapon / horse / fishing motion modes and combo tables follow UserInterface -// PythonPlayerSettingsModule.cpp. Not ported: smoke effects, attached effects, the .msa motion -// events / loop data, emotion and skill motions. Of AttachingData only the DEFENDING sphere radius -// is kept (hit test approximation). +// 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 #include #include @@ -181,9 +182,39 @@ 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 combat payload (GameLib RaceMotionData.cpp, GameType.cpp -// NRaceData::LoadMotionAttackData / THitData::Load). Loop data, motion events and sound are not read. +// 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 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 { @@ -200,9 +231,23 @@ struct RaceMotionData { int attackType = 0, hittingType = 0, motionType = MOTION_TYPE_NONE, hitLimitCount = 0; float stiffenTime = 0.0f, invisibleTime = 0.0f, externalForce = 0.0f; std::vector 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 events; + // "sound/" + (msa without extension + ".mss").substr(13); sounds stay empty if it fails to load. + std::string soundScriptFileName; + std::vector sounds; }; -// Parses an .msa text; false where CRaceMotionData::LoadMotionData fails. -bool ParseRaceMotionData(const std::string& text, RaceMotionData* data); +// 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* sounds); // Cached by .msa path (CResourceManager static cache); nullptr when the file is missing or invalid. const RaceMotionData* GetRaceMotionData(const std::string& msaFileName); diff --git a/src/eter_sound/SoundManager.cpp b/src/eter_sound/SoundManager.cpp index 9381667b..6fa5e65d 100644 --- a/src/eter_sound/SoundManager.cpp +++ b/src/eter_sound/SoundManager.cpp @@ -328,6 +328,19 @@ void SoundManager::PlaySound2D(const std::string& filename) { } } +void SoundManager::PlayCharacterSound3D(float fx, float fy, float fz, const std::string& filename, bool checkFrequency) { + if (0.0f == GetSoundVolume()) return; + if (checkFrequency) { + const float dx = fx - m_listenerX, dz = fz - m_listenerZ; + if (dx * dx + dz * dz > 5000.0f * 5000.0f) return; + const double now = double(SDL_GetTicksNS()) / 1e9; // CTimer::GetCurrentSecond + auto it = m_playSoundHistory.find(filename); + if (it != m_playSoundHistory.end() && now - it->second < 0.3) return; + m_playSoundHistory[filename] = now; + } + PlaySound3D(fx, fy, fz, filename); +} + void SoundManager::PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount) { if (m_soundVolume <= 0.0f) return; const auto* audio = GetOrLoadAudio(filename); diff --git a/src/eter_sound/SoundManager.h b/src/eter_sound/SoundManager.h index e10bae31..f98e8a29 100644 --- a/src/eter_sound/SoundManager.h +++ b/src/eter_sound/SoundManager.h @@ -60,6 +60,10 @@ public: // 2D & 3D Sound Effects void PlaySound2D(const std::string& filename); void PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1); + // CSoundManager::PlayCharacterSound3D (milesLib/SoundManager.cpp): with checkFrequency (non-PC + // actors) a sound farther than 5000 horizontally from the listener, or the same file again + // within 0.3 s, is skipped. Engine coordinates (the horizontal plane is x, z). + void PlayCharacterSound3D(float fx, float fy, float fz, const std::string& filename, bool checkFrequency); int PlayAmbienceSound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1); void StopSound3D(int index); void StopAllSound3D(); @@ -139,6 +143,7 @@ private: float m_musicVolume = 1.0f; float m_backupSoundVolume = 1.0f; float m_backupMusicVolume = 1.0f; + std::unordered_map m_playSoundHistory; // m_PlaySoundHistoryMap float m_soundScale = 200.0f; float m_ambienceScale = 1000.0f; diff --git a/src/scripting/python_app.cpp b/src/scripting/python_app.cpp index b99f2928..3a3be872 100644 --- a/src/scripting/python_app.cpp +++ b/src/scripting/python_app.cpp @@ -1204,5 +1204,6 @@ void UpdateCameraFromHost(float distance,float pitch,float yaw,float height) { s_camera_distance=distance;s_camera_pitch=pitch;s_camera_rotation=yaw;s_camera_height=height; } float GetCameraZoomSpeed() { return s_camera_zoom_speed; } +bool IsSkillEffectUpgradeEnabled() { return s_skillEffectUpgradeEnable; } } // namespace ava2 diff --git a/src/scripting/python_app.h b/src/scripting/python_app.h index ed49b558..24ef57f2 100644 --- a/src/scripting/python_app.h +++ b/src/scripting/python_app.h @@ -6,6 +6,8 @@ namespace ava2 { int GetTwoHandedAttackSpeedDecrease(); void initapp(); bool IsYmirLocale(); +// SKILL_EFFECT_UPGRADE_ENABLE (app.SetSkillEffectUpgradeEnable): TSkillData::GetSkillMotionIndex uses grade motions. +bool IsSkillEffectUpgradeEnabled(); std::int32_t GetServerTimeStamp(); void SetServerTime(std::int32_t time); void ResetPythonAppState(); diff --git a/src/scripting/python_gameplay_modules.cpp b/src/scripting/python_gameplay_modules.cpp index 1ee8e853..78b1cad0 100644 --- a/src/scripting/python_gameplay_modules.cpp +++ b/src/scripting/python_gameplay_modules.cpp @@ -8,6 +8,7 @@ #include "python_gameplay_modules.h" #include "python_runtime.h" #include "python_app.h" +#include "eter_render/RaceData.h" #include "shared/common/PythonUtils.h" #include "python_native_modules.h" #include "map_coordinates.h" @@ -1092,12 +1093,40 @@ bool ProcessPlayerAttack(float cameraYaw, float frameDt, bool wasMoving) { } // CInstanceBase::AttackProcess: hit-test every attackable instance (enemies and stones; PvP // rules are not ported). Each hit is OnHit: SetTarget + SendAttackPacket(0, vid). + // CNormalBowAttack_FlyEventHandler_AutoClear (SetTarget): the fly event handler reports the + // fly target and every shot. SetTarget sets the main fly target; a skill target set by + // ClickSkillSlot is kept while its motion runs. + if (s_targetVID != inst.GetFlyTargetVID() && !inst.IsUsingSkill()) { + if (s_targetVID && manager.GetActorData(s_targetVID)) inst.SetFlyTarget(s_targetVID); + else if (!s_targetVID) inst.ClearFlyTarget(); + } + inst.SetFlyEventHandler({ + [&inst]() { + float pos[3]; + if (!inst.GetFlyTargetPosition(pos)) return; + PythonNetworkStream::Instance().SendFlyTargetingPacket(inst.GetFlyTargetVID(), int32_t(pos[0]), int32_t(pos[2])); + }, + [](uint32_t skill) { PythonNetworkStream::Instance().SendShootPacket(skill); }, + }); + // CPythonPlayerEventHandler::OnWarp (motion event WARP): SendCharacterStatePacket(FUNC_WAIT). + if (inst.PopWarpEvent()) + PythonNetworkStream::Instance().SendCharacterMovePacket(0, 0, + uint8_t(std::fmod(inst.GetYaw() + 360.0f, 360.0f) / 5.0f), + int32_t(inst.GetX()), int32_t(inst.GetZ()), GetServerMSec()); if (!inst.CanCheckAttacking()) return stopSent; for (const auto& [vid, victim] : manager.GetActorDict()) { if (vid == main->m_dwVID || !victim.m_pActorInstance) continue; if (victim.m_bType != 0 && victim.m_bType != 2) continue; // TYPE_ENEMY / TYPE_STONE const auto& v = *victim.m_pActorInstance; if (v.IsDead()) continue; + // __SplashAttackProcess (SPECIAL_ATTACKING motion events): OnHit + SendAttackPacket(skill). + uint32_t splashSkill = 0; + bool splashSend = false; + if (inst.SplashAttackHit(v, v.GetDefendingRadius(), &splashSkill, &splashSend)) { + SetPlayerHitTarget(vid); + if (splashSend) PythonNetworkStream::Instance().SendAttackPacket(splashSkill, vid); + continue; + } if (inst.TestAttackHit(vid, v.GetX(), v.GetZ(), v.GetDefendingRadius(), frameDt, IsBossRace(victim.m_dwRace))) { SetPlayerHitTarget(vid); PythonNetworkStream::Instance().SendAttackPacket(0, vid); @@ -1342,6 +1371,30 @@ void ClickSkillSlot(int skillSlot) { return; } + // __UseSkill: SetFlyTargetInstance(target, or self for CAN_USE_FOR_ME), then + // NEW_UseSkill(index, GetSkillMotionIndex(grade), GetMotionLoopCount(power)). Fan/circle + // multi-target AddFlyTargetInstance, moving skills and the look-at turn are not ported. + if (pSkillData && !pSkillData->noMotion) { + auto* main = NetworkActorManager::Instance().GetMainInstance(); + if (main && main->m_pActorInstance) { + auto& inst = *main->m_pActorInstance; + if (inst.IsDead() || inst.IsStun()) return; + const int grade = it->second.grade; + uint32_t motion = pSkillData->motion; + if (IsSkillEffectUpgradeEnabled() && grade >= 0 && grade < 4) motion = pSkillData->gradeMotions[size_t(grade)]; + const int loopCount = pSkillData->motionLoopCountFormula.empty() ? 0 + : int(uint32_t(EvaluateSkillFormula(pSkillData->motionLoopCountFormula, it->second.currentPower))); + if (targetVID && NetworkActorManager::Instance().GetActorData(targetVID)) inst.SetFlyTarget(targetVID); + else if (canUseForMe) inst.SetFlyTarget(PythonNetworkStream::Instance().GetMainActorVID()); + inst.InterceptMotionIndex(RaceData::NAME_SKILL + motion, false, uint32_t(skillIndex), loopCount); + // __OnUseSkill -> CPythonPlayerEventHandler::OnUseSkill: FUNC_SKILL|motion, arg = loop + // count (| 1 << 4 for moving skills, not ported). + PythonNetworkStream::Instance().SendCharacterMovePacket(uint8_t(0x80 | (motion & 0x7f)), uint8_t(loopCount), + uint8_t(std::fmod(inst.GetYaw() + 360.0f, 360.0f) / 5.0f), + int32_t(inst.GetX()), int32_t(inst.GetZ()), GetServerMSec()); + } + } + // Send use skill packet PythonNetworkStream::Instance().SendUseSkillPacket(uint32_t(skillIndex), targetVID); diff --git a/tests/attack_combo_test.cpp b/tests/attack_combo_test.cpp index bca6be6a..407e6aed 100644 --- a/tests/attack_combo_test.cpp +++ b/tests/attack_combo_test.cpp @@ -39,7 +39,7 @@ void TestParse() { assert(Near(a.motionDuration, 1.0f)); assert(a.isComboMotion && Near(a.inputStartTime, 1.0f) && Near(a.nextComboTime, 1.0f) && Near(a.inputEndTime, 0.602564f)); assert(a.isAttackingMotion && a.motionType == RaceMotionData::MOTION_TYPE_NORMAL); - assert(a.attackType == 2 && a.hitLimitCount == 0); // AttackType missing: ATTACK_TYPE_SPLASH + assert(a.attackType == 0 && a.hitLimitCount == 0); // AttackType missing: ATTACK_TYPE_SPLASH (0) assert(Near(a.invisibleTime, 0.5f)); assert(a.hitData.size() == 1 && a.hitData[0].boneName == "equip_right_hand"); assert(Near(a.hitData[0].attackStartTime, 0.456410f) && a.hitData[0].hitPositions.size() == 2); @@ -219,10 +219,59 @@ void TestHitDetection(const char* model) { } } +void TestMotionEvents() { + // LoopData + MotionEventData (sound, special attacking with collision spheres, show/hide). + const char* skillMsa = + "ScriptType MotionData\n" + "MotionFileName \"d:/ymir work/pc/warrior/skill/palbang.gr2\"\n" + "MotionDuration 2.0\n" + "Group LoopData\n{\n MotionLoopCount 3\n LoopStartTime 0.5\n LoopEndTime 1.25\n}\n" + "Group MotionEventData\n{\n MotionEventDataCount 4\n" + " Group Event00\n {\n MotionEventType 5\n StartingTime 0.1\n" + " SoundFileName \"sound/pc/warrior/palbang.wav\"\n }\n" + " Group Event01\n {\n MotionEventType 4\n StartingTime 0.6\n" + " DuringTime 0.3\n EnableHitProcess 1\n AttackType 1\n HittingType 3\n" + " StiffenTime 0.1\n InvisibleTime 0.2\n ExternalForce 4.0\n HitLimitCount 5\n" + " CollisionType 0\n SphereDataCount 1\n" + " Group SphereData00\n {\n Radius 150.0\n Position 0.0 -120.0 80.0\n }\n }\n" + " Group Event02\n {\n MotionEventType 8\n StartingTime 0.7\n }\n" + " Group Event03\n {\n MotionEventType 7\n StartingTime 1.0\n }\n" + "}\n"; + RaceMotionData m; + assert(ava2::ParseRaceMotionData(skillMsa, &m)); + assert(m.isLoopMotion && m.loopCount == 3 && Near(m.loopStartTime, 0.5f) && Near(m.loopEndTime, 1.25f)); + assert(m.events.size() == 4 && m.hasSplashEvent); + assert(m.events[0].type == RaceMotionData::MOTION_EVENT_TYPE_SOUND && m.events[0].frame == 6); + assert(m.events[0].fileName == "sound/pc/warrior/palbang.wav"); + const auto& splash = m.events[1]; + assert(splash.type == RaceMotionData::MOTION_EVENT_TYPE_SPECIAL_ATTACKING && splash.frame == 36); + assert(Near(splash.durationTime, 0.3f) && splash.attackType == 1 && splash.hittingType == 3 && splash.hitLimitCount == 5); + assert(splash.spheres.size() == 1 && Near(splash.spheres[0].radius, 150.0f) && Near(splash.spheres[0].position[1], -120.0f)); + assert(m.events[2].type == RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_HIDE && m.events[3].type == RaceMotionData::MOTION_EVENT_TYPE_CHARACTER_SHOW); + + // An unknown event type fails the whole .msa, like "Strange Event Type". + const char* badMsa = + "MotionFileName \"x.gr2\"\nMotionDuration 1.0\n" + "Group MotionEventData\n{\n MotionEventDataCount 1\n" + " Group Event00\n {\n MotionEventType 3\n StartingTime 0.1\n }\n}\n"; + RaceMotionData bad; + assert(!ava2::ParseRaceMotionData(badMsa, &bad)); + + // Per-motion .mss sound script. + std::vector sounds; + assert(ava2::ParseSoundScriptData( + "ScriptType CharacterSoundData\nSoundDataCount 2\n" + "SoundData00 0.726000 \"sound/common/walk_dirt_n.wav\"\n" + "SoundData01 0.100000 \"sound/common/walk_dirt_1.wav\"\n", &sounds)); + assert(sounds.size() == 2 && sounds[0].fileName == "sound/common/walk_dirt_n.wav" && sounds[0].frame == 43); + assert(!ava2::ParseSoundScriptData("SoundDataCount 1\nSoundData00 0.5\n", &sounds) && sounds.size() == 2); +} + } // namespace int main(int argc, char** argv) { TestParse(); + TestMotionEvents(); std::cout << "msa parsing ok\n"; if (argc < 2) return 0; if (!ava2_test::EnterTestRunDir()) return ava2_test::kSkip;