From fc6a7fbd529063607c47784b18af5932bfa582c2 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:33:45 -0700 Subject: [PATCH] feat: Add a bunch of behaviors (All rotations, DoDamage, OnTimer, OnStartup, MoveBackToStart) and make models move based on normals, not world axes (#2038) * add rotation behavior logic (not working correctly for multiple axes) * Fix FetchContent_Declare speed * remove manual quaternion math * feat: working rotations * remove flag * feat: make directional movements based on model rotation and not world axes * poggers rotation on the strip * Add OnStartup and OnTimer * go home works * Add DoDamage behavior and dont try and start the same node multiple times * fix: pause bbb models * interrupt rotations and save interrupt count across resets --- dCommon/dEnums/dCommonVars.h | 2 +- dCommon/dMath.h | 23 ++ dGame/dComponents/DestroyableComponent.cpp | 2 +- dGame/dComponents/ModelComponent.cpp | 146 ++++++++++--- dGame/dComponents/ModelComponent.h | 101 +++++++-- .../PropertyManagementComponent.cpp | 4 +- .../dComponents/PropertyManagementComponent.h | 2 +- dGame/dComponents/SimplePhysicsComponent.cpp | 24 ++- dGame/dComponents/SimplePhysicsComponent.h | 8 + dGame/dGameMessages/CMakeLists.txt | 2 + dGame/dGameMessages/GameMessageHandler.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 3 + dGame/dGameMessages/GameMessages.h | 16 ++ dGame/dPropertyBehaviors/PropertyBehavior.cpp | 8 +- dGame/dPropertyBehaviors/PropertyBehavior.h | 4 +- dGame/dPropertyBehaviors/State.cpp | 8 +- dGame/dPropertyBehaviors/State.h | 4 +- dGame/dPropertyBehaviors/Strip.cpp | 198 ++++++++++++------ dGame/dPropertyBehaviors/Strip.h | 33 ++- dWorldServer/WorldServer.cpp | 2 +- 20 files changed, 465 insertions(+), 127 deletions(-) create mode 100644 dCommon/dMath.h diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index c3ed1b145..85dc9c1bc 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -60,7 +60,7 @@ constexpr LWOMAPID LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID constexpr uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID constexpr uint32_t MAX_MESSAGE_LENGTH = 0x500000; //!< Prevent exceptionally large msgs from being processed. Should always be used to check user provided inputs. -constexpr float PI = 3.14159f; +constexpr float PI = 3.14159265358979323846264338327950288f; //============ STRUCTS ============== diff --git a/dCommon/dMath.h b/dCommon/dMath.h new file mode 100644 index 000000000..f62313358 --- /dev/null +++ b/dCommon/dMath.h @@ -0,0 +1,23 @@ +// Darkflame Universe +// Copyright 2025 + +#ifndef DMATH_H +#define DMATH_H + +#include + +namespace Math { + constexpr float PI = 3.14159265358979323846264338327950288f; + constexpr float RATIO_DEG_TO_RAD = PI / 180.0f; + constexpr float RATIO_RAD_TO_DEG = 180.0f / PI; + + inline float DegToRad(float degrees) { + return degrees * RATIO_DEG_TO_RAD; + } + + inline float RadToDeg(float radians) { + return radians * RATIO_RAD_TO_DEG; + } +}; + +#endif //!DMATH_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 877fe4fa8..c561ce85f 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -588,7 +588,7 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 // Client does the same check, so we're doing it too auto* const modelComponent = m_Parent->GetComponent(); if (modelComponent) { - modelComponent->OnHit(); + modelComponent->OnHit(source); // Don't actually deal the damage so the model doesn't die return; } diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index 248cbbac3..b09c655a0 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -1,8 +1,12 @@ #include "ModelComponent.h" + +#include + #include "Entity.h" #include "Game.h" #include "Logger.h" +#include "dMath.h" #include "BehaviorStates.h" #include "ControlBehaviorMsgs.h" @@ -12,6 +16,7 @@ #include "SimplePhysicsComponent.h" #include "eMissionTaskType.h" #include "eObjectBits.h" +#include "DestroyableComponent.h" #include "Database.h" #include "DluAssert.h" @@ -42,8 +47,13 @@ bool ModelComponent::OnResetModelToDefaults(GameMessages::ResetModelToDefaults& if (reset.bResetPos) m_Parent->SetPosition(m_OriginalPosition); if (reset.bResetRot) m_Parent->SetRotation(m_OriginalRotation); m_Parent->SetVelocity(NiPoint3Constant::ZERO); + // Save and increment the interrupt count so other behaviors on this model move to their next action instead of getting stuck + const auto moveInterruptCount = m_Move.interruptCount + 1; + m_Move = MoveState{}; + m_Move.interruptCount = moveInterruptCount; + SyncLinearVelocity(); + ResetRotationState(m_Parent->GetRotation()); - m_Speed = 3.0f; m_NumListeningInteract = 0; m_NumActiveAttack = 0; @@ -71,11 +81,21 @@ bool ModelComponent::OnRequestUse(GameMessages::RequestUse& requestUse) { void ModelComponent::Update(float deltaTime) { if (m_IsPaused) return; + m_DamageCooldown -= deltaTime; + + // Arrived once this frame's movement reached or passed the target + if (m_Move.target && (*m_Move.target - m_Parent->GetPosition()).DotProduct(m_Move.targetDirection) <= 0.0f) { + m_Parent->SetPosition(*m_Move.target); + m_Move.target.reset(); + } for (auto& behavior : m_Behaviors) { behavior.Update(deltaTime, *this); } + // Done after all behaviors so the heading reflects any rotation applied this frame + SyncLinearVelocity(); + if (!m_RestartAtEndOfFrame) return; GameMessages::ResetModelToDefaults reset{}; @@ -284,41 +304,102 @@ void ModelComponent::RemoveUnSmash() { m_NumActiveUnSmash--; } -bool ModelComponent::TrySetVelocity(const NiPoint3& velocity) const { - auto currentVelocity = m_Parent->GetVelocity(); +bool ModelComponent::TryStartMove(const int axis, const float direction, const float speed) { + if (axis < 0 || axis > 2 || direction == 0.0f || speed <= 0.0f) return false; + if (m_Move.velocity[axis] != 0.0f) return false; - // If we're currently moving on an axis, prevent the move so only 1 behavior can have control over an axis - if (velocity != NiPoint3Constant::ZERO) { - const auto [x, y, z] = velocity * m_Speed; - if (x != 0.0f) { - if (currentVelocity.x != 0.0f) return false; - currentVelocity.x = x; - } else if (y != 0.0f) { - if (currentVelocity.y != 0.0f) return false; - currentVelocity.y = y; - } else if (z != 0.0f) { - if (currentVelocity.z != 0.0f) return false; - currentVelocity.z = z; - } - } else { - currentVelocity = velocity; - } - - m_Parent->SetVelocity(currentVelocity); + m_Move.target.reset(); + m_Move.velocity[axis] = std::copysign(speed, direction); return true; } -void ModelComponent::SetVelocity(const NiPoint3& velocity) const { - m_Parent->SetVelocity(velocity); +void ModelComponent::StopMove(const int axis) { + if (axis < 0 || axis > 2) return; + m_Move.velocity[axis] = 0.0f; } -void ModelComponent::OnChatMessageReceived(const std::string& sMessage) { - for (auto& behavior : m_Behaviors) behavior.OnChatMessageReceived(sMessage); +void ModelComponent::StartMoveTo(const NiPoint3& target, const float speed) { + m_Move.velocity = NiPoint3Constant::ZERO; + m_Move.interruptCount++; + m_Move.target = target; + m_Move.targetSpeed = speed; } -void ModelComponent::OnHit() { +void ModelComponent::SyncLinearVelocity() { + const auto& rotation = m_Parent->GetRotation(); + m_Move.basis = { QuatUtils::Right(rotation), QuatUtils::Up(rotation), QuatUtils::Forward(rotation) }; + + NiPoint3 velocity = NiPoint3Constant::ZERO; + for (int axis = 0; axis < 3; axis++) velocity += m_Move.basis[axis] * m_Move.velocity[axis]; + + if (m_Move.target) { + const auto toTarget = *m_Move.target - m_Parent->GetPosition(); + const float distance = toTarget.Length(); + m_Move.targetDirection = distance > 0.0f ? toTarget / distance : NiPoint3Constant::ZERO; + velocity += m_Move.targetDirection * m_Move.targetSpeed; + } + + // Leave velocity alone unless a move owns it, e.g. pets are driven elsewhere + const bool isMoving = velocity != NiPoint3Constant::ZERO; + if (!isMoving && !m_Move.wasMoving) return; + m_Move.wasMoving = isMoving; + + // Setting velocity always marks it dirty for serialization + if (velocity != m_Parent->GetVelocity()) m_Parent->SetVelocity(velocity); +} + +bool ModelComponent::TryStartRotation(const int axis, const float direction, const float speed) { + if (axis < 0 || axis > 2 || direction == 0.0f || speed <= 0.0f) return false; + if (m_Rotation.velocity[axis] != 0.0f) return false; + + // Rebase only when nothing is rotating so simultaneous rotations stay relative to the same base + if (m_Rotation.velocity == NiPoint3Constant::ZERO) ResetRotationState(m_Parent->GetRotation()); + + m_Rotation.degrees[axis] = std::fmod(m_Rotation.degrees[axis], 360.0f); + m_Rotation.actionStart[axis] = m_Rotation.degrees[axis]; + m_Rotation.velocity[axis] = std::copysign(BASE_ANGULAR_SPEED * speed, direction); + SyncAngularVelocity(); + return true; +} + +void ModelComponent::SetRotationProgress(const int axis, const float degrees) { + if (axis < 0 || axis > 2) return; + m_Rotation.degrees[axis] = m_Rotation.actionStart[axis] + degrees; + + // Whole turns wrap to exactly 0 so e.g. 720 degrees yields exactly the base rotation + const NiPoint3 radians( + Math::DegToRad(std::fmod(m_Rotation.degrees.x, 360.0f)), + Math::DegToRad(std::fmod(m_Rotation.degrees.y, 360.0f)), + Math::DegToRad(std::fmod(m_Rotation.degrees.z, 360.0f)) + ); + m_Parent->SetRotation(QuatUtils::FromEuler(radians) * m_Rotation.base); +} + +void ModelComponent::StopRotation(const int axis) { + if (axis < 0 || axis > 2) return; + m_Rotation.velocity[axis] = 0.0f; + SyncAngularVelocity(); +} + +void ModelComponent::SyncAngularVelocity() const { + GameMessages::SetAngularVelocity setAngVel{}; + setAngVel.target = m_Parent->GetObjectID(); + setAngVel.angVelocity = m_Rotation.velocity * Math::DegToRad(1.0f); + setAngVel.Send(); +} + +void ModelComponent::ResetRotationState(const NiQuaternion& newBase) { + m_Rotation = RotationState{ .base = newBase }; + SyncAngularVelocity(); +} + +void ModelComponent::OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) { + for (auto& behavior : m_Behaviors) behavior.OnChatMessageReceived(sMessage, sender); +} + +void ModelComponent::OnHit(const LWOOBJID attacker) { for (auto& behavior : m_Behaviors) { - behavior.OnHit(); + behavior.OnHit(attacker); } } @@ -362,3 +443,14 @@ bool ModelComponent::OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& re return true; } + +void ModelComponent::DoDamage(const LWOOBJID target) { + // dont do damage if we've done damage recently + if (m_DamageCooldown > 0.0f) return; + m_DamageCooldown = 1.0f; + auto* const initiator = Game::entityManager->GetEntity(target); + if (initiator) { + auto* const destComp = initiator->GetComponent(); + if (destComp) destComp->Damage(1, GetParent()->GetObjectID()); + } +} diff --git a/dGame/dComponents/ModelComponent.h b/dGame/dComponents/ModelComponent.h index e821406b0..1e6fdf9ef 100644 --- a/dGame/dComponents/ModelComponent.h +++ b/dGame/dComponents/ModelComponent.h @@ -1,7 +1,9 @@ #pragma once #include +#include #include +#include #include "dCommonVars.h" #include "RakNetTypes.h" @@ -139,20 +141,41 @@ public: void Resume(); - // Attempts to set the velocity of an axis for movement. - // If the axis currently has a velocity of zero, returns true. - // If the axis is currently controlled by a behavior, returns false. - bool TrySetVelocity(const NiPoint3& velocity) const; + // Attempts to claim a local axis (0 = right, 1 = up, 2 = forward) for movement in direction (+1 or -1) at speed units per second. + // Returns false if the axis is already controlled by a behavior. Cancels any active StartMoveTo. + bool TryStartMove(const int axis, const float direction, const float speed); - // Force sets the velocity to a value. - void SetVelocity(const NiPoint3& velocity) const; + // Releases the local axis so another behavior can move along it. + void StopMove(const int axis); - void OnChatMessageReceived(const std::string& sMessage); + // World space direction of the local axis used for the most recently applied velocity. + const NiPoint3& GetMoveAxis(const int axis) const { return m_Move.basis[axis]; } - void OnHit(); + // Interrupts all active moves and moves in a straight line to target at speed units per second. + void StartMoveTo(const NiPoint3& target, const float speed); - // Sets the speed of the model - void SetSpeed(const float newSpeed) { m_Speed = newSpeed; } + // Whether a StartMoveTo move has yet to arrive or be overridden. + bool IsMovingToTarget() const noexcept { return m_Move.target.has_value(); } + + // Changes whenever active moves are interrupted, so strips can tell their move was cancelled. + uint32_t GetMoveInterruptCount() const noexcept { return m_Move.interruptCount; } + + // Attempts to claim a world axis (0 = x, 1 = y, 2 = z) for rotation in direction (+1 or -1) at the given behavior speed. + // Returns false if the axis is already controlled by a behavior. + bool TryStartRotation(const int axis, const float direction, const float speed); + + // Sets how many signed degrees the active rotation on axis has progressed and updates the entity. + void SetRotationProgress(const int axis, const float degrees); + + // Releases the axis so another behavior can rotate it. + void StopRotation(const int axis); + + // Degrees per second of the active rotation on axis. + float GetAngularSpeed(const int axis) const noexcept { return std::abs(m_Rotation.velocity[axis]); } + + void OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender); + + void OnHit(const LWOOBJID attacker); // Whether or not to restart at the end of the frame void RestartAtEndOfFrame() { m_RestartAtEndOfFrame = true; } @@ -164,7 +187,56 @@ public: // Decrements the number of strips listening for an attack. // If this is the last strip removing an attack, it will reset the factions to the default of -1. void RemoveAttack(); + void DoDamage(const LWOOBJID target); private: + // Degrees per second per unit of behavior speed + static constexpr float BASE_ANGULAR_SPEED = 15.0f; + + struct RotationState { + // The rotation that degrees is applied on top of + NiQuaternion base = QuatUtils::IDENTITY; + + // Accumulated signed degrees per world axis since base was set + NiPoint3 degrees{}; + + // degrees at the moment the current rotation on each axis started + NiPoint3 actionStart{}; + + // Signed degrees per second per world axis. Non-zero means a behavior owns that axis. + NiPoint3 velocity{}; + }; + + struct MoveState { + // Signed units per second along local right, up and forward. Non-zero means a behavior owns that axis. + NiPoint3 velocity{}; + + // Right, up and forward in world space as of the last velocity update + std::array basis{ NiPoint3Constant::UNIT_X, NiPoint3Constant::UNIT_Y, NiPoint3Constant::UNIT_Z }; + + // Whether the last velocity update came from an active move + bool wasMoving{ false }; + + // World position of an active StartMoveTo move + std::optional target; + + // Units per second of the move to target + float targetSpeed{}; + + // Direction to target as of the last velocity update, zero once there + NiPoint3 targetDirection{}; + + // Incremented each time StartMoveTo interrupts the active moves + uint32_t interruptCount{}; + }; + + // Sends the client-side angular velocity for the currently active rotation axes. + void SyncAngularVelocity() const; + + // Recomputes the linear velocity from the active move axes and the current rotation. + void SyncLinearVelocity(); + + // Clears all rotation state and makes rotation relative to newBase. + void ResetRotationState(const NiQuaternion& newBase); // Loads a behavior from the database. void LoadBehavior(const LWOOBJID behaviorID, const size_t index, const bool isIndexed); @@ -208,9 +280,12 @@ private: */ LWOOBJID m_userModelID; - // The speed at which this model moves - float m_Speed{ 3.0f }; - // Whether or not to restart at the end of the frame. bool m_RestartAtEndOfFrame{ false }; + + RotationState m_Rotation; + + MoveState m_Move; + + float m_DamageCooldown { 0.0f }; }; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index f38b58ca1..ee10c0691 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -802,13 +802,13 @@ const std::map& PropertyManagementComponent::GetModels() con return models; } -void PropertyManagementComponent::OnChatMessageReceived(const std::string& sMessage) const { +void PropertyManagementComponent::OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) const { for (const auto& modelID : models | std::views::keys) { auto* const model = Game::entityManager->GetEntity(modelID); if (!model) continue; auto* const modelComponent = model->GetComponent(); if (!modelComponent) continue; - modelComponent->OnChatMessageReceived(sMessage); + modelComponent->OnChatMessageReceived(sMessage, sender); } } diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index c13fe9911..0e217a4fe 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -165,7 +165,7 @@ public: LWOOBJID GetId() const noexcept { return propertyId; } - void OnChatMessageReceived(const std::string& sMessage) const; + void OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) const; private: /** * This diff --git a/dGame/dComponents/SimplePhysicsComponent.cpp b/dGame/dComponents/SimplePhysicsComponent.cpp index cb888459b..f699938c5 100644 --- a/dGame/dComponents/SimplePhysicsComponent.cpp +++ b/dGame/dComponents/SimplePhysicsComponent.cpp @@ -16,6 +16,8 @@ #include "Amf3.h" SimplePhysicsComponent::SimplePhysicsComponent(Entity* parent, const int32_t componentID) : PhysicsComponent(parent, componentID) { + RegisterMsg(&SimplePhysicsComponent::OnGetAngularVelocity); + RegisterMsg(&SimplePhysicsComponent::OnSetAngularVelocity); RegisterMsg(&SimplePhysicsComponent::OnGetObjectReportInfo); m_Position = m_Parent->GetDefaultPosition(); @@ -38,6 +40,7 @@ SimplePhysicsComponent::~SimplePhysicsComponent() { } void SimplePhysicsComponent::Update(const float deltaTime) { + // Rotation is driven by ModelComponent; angular velocity is only relayed to clients. if (m_Velocity == NiPoint3Constant::ZERO) return; m_Position += m_Velocity * deltaTime; m_DirtyPosition = true; @@ -52,8 +55,12 @@ void SimplePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIs outBitStream.Write(m_DirtyVelocity || bIsInitialUpdate); if (m_DirtyVelocity || bIsInitialUpdate) { - outBitStream.Write(m_Velocity); - outBitStream.Write(m_AngularVelocity); + outBitStream.Write(m_Velocity.x); + outBitStream.Write(m_Velocity.y); + outBitStream.Write(m_Velocity.z); + outBitStream.Write(m_AngularVelocity.x); + outBitStream.Write(m_AngularVelocity.y); + outBitStream.Write(m_AngularVelocity.z); m_DirtyVelocity = false; } @@ -85,3 +92,16 @@ bool SimplePhysicsComponent::OnGetObjectReportInfo(GameMessages::GetObjectReport info.PushDebug("Climbable Type") = StringifiedEnum::ToString(m_ClimbableType).data(); return true; } + +bool SimplePhysicsComponent::OnSetAngularVelocity(GameMessages::SetAngularVelocity& setAngVel) { + m_DirtyVelocity |= setAngVel.bForceFlagDirty || (m_AngularVelocity != setAngVel.angVelocity); + m_AngularVelocity = setAngVel.angVelocity; + LOG_DEBUG("Angular velocity is now %f %f %f", m_AngularVelocity.x, m_AngularVelocity.y, m_AngularVelocity.z); + Game::entityManager->SerializeEntity(m_Parent); + return true; +} + +bool SimplePhysicsComponent::OnGetAngularVelocity(GameMessages::GetAngularVelocity& getAngVel) { + getAngVel.angVelocity = m_AngularVelocity; + return true; +} diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index 402689221..bf9b7f176 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -22,6 +22,11 @@ enum class eClimbableType : int32_t { CLIMBABLE_TYPE_WALL_STICK }; +namespace GameMessages { + struct SetAngularVelocity; + struct GetAngularVelocity; +} + /** * Component that serializes locations of entities to the client @@ -61,6 +66,9 @@ public: */ void SetAngularVelocity(const NiPoint3& value) { m_AngularVelocity = value; m_DirtyVelocity = true; } + bool OnSetAngularVelocity(GameMessages::SetAngularVelocity& setAngVel); + bool OnGetAngularVelocity(GameMessages::GetAngularVelocity& getAngVel); + /** * Returns the physics motion state * @return the physics motion state diff --git a/dGame/dGameMessages/CMakeLists.txt b/dGame/dGameMessages/CMakeLists.txt index 0f28dea4f..90a4388c2 100644 --- a/dGame/dGameMessages/CMakeLists.txt +++ b/dGame/dGameMessages/CMakeLists.txt @@ -14,10 +14,12 @@ target_include_directories(dGameMessages PUBLIC "." "${PROJECT_SOURCE_DIR}/dGame/dComponents" # direct MissionComponent.h "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # direct SlashCommandHandler.h "${PROJECT_SOURCE_DIR}/dGame/dPropertyBehaviors" # direct ControlBehaviors.h + "${PROJECT_SOURCE_DIR}/dGame/dPropertyBehaviors/ControlBehaviorMessages" # direct ControlBehaviors.h "${PROJECT_SOURCE_DIR}/dGame/dMission" # via MissionComponent.h "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # via InventoryComponent.h "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via InventoryComponent.h "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager/Spawner.h "${PROJECT_SOURCE_DIR}/dZoneManager" # via GameMessages.cpp, GameMessageHandler.cpp + "${PROJECT_SOURCE_DIR}/dGame/d" ) target_precompile_headers(dGameMessages REUSE_FROM dGameBase) diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 1918ca2ef..ef53cbd1b 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -86,7 +86,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const System return; } } - + msg->target = objectID; msg->Deserialize(inStream); msg->Handle(*entity, sysAddr); return; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index f40e79a45..19d5859d6 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -42,6 +42,7 @@ #include "eStateChangeType.h" #include "ServiceType.h" #include "ePlayerFlag.h" +#include "ModelComponent.h" #include #include @@ -2627,6 +2628,8 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream& inStream, Entity* ent Entity* newEntity = Game::entityManager->CreateEntity(info, nullptr); if (newEntity) { Game::entityManager->ConstructEntity(newEntity); + auto* const modelComponent = newEntity->GetComponent(); + if (modelComponent) modelComponent->Pause(); //Make sure the propMgmt doesn't delete our model after the server dies //Trying to do this after the entity is constructed. Shouldn't really change anything but diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index ce70a42c5..924daf43f 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -880,6 +880,22 @@ namespace GameMessages { bool bIgnoreChecks{ false }; }; + struct GetAngularVelocity : public GameMsg { + GetAngularVelocity() : GameMsg(MessageType::Game::GET_ANGULAR_VELOCITY) {} + + NiPoint3 angVelocity{}; + }; + + struct SetAngularVelocity : public GameMsg { + SetAngularVelocity() : GameMsg(MessageType::Game::SET_ANGULAR_VELOCITY) {} + + NiPoint3 angVelocity{}; + + bool bIgnoreDirtyFlags{}; + + bool bForceFlagDirty{}; + }; + struct DropClientLoot : public GameMsg { DropClientLoot() : GameMsg(MessageType::Game::DROP_CLIENT_LOOT) {} diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.cpp b/dGame/dPropertyBehaviors/PropertyBehavior.cpp index c19c4d2fe..f30a622d7 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.cpp +++ b/dGame/dPropertyBehaviors/PropertyBehavior.cpp @@ -211,14 +211,14 @@ void PropertyBehavior::Update(float deltaTime, ModelComponent& modelComponent) { } } -void PropertyBehavior::OnChatMessageReceived(const std::string& sMessage) { +void PropertyBehavior::OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) { auto& activeState = GetActiveState(); - activeState.OnChatMessageReceived(sMessage); + activeState.OnChatMessageReceived(sMessage, sender); } -void PropertyBehavior::OnHit() { +void PropertyBehavior::OnHit(const LWOOBJID attacker) { auto& activeState = GetActiveState(); - activeState.OnHit(); + activeState.OnHit(attacker); } State& PropertyBehavior::GetActiveState() { diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.h b/dGame/dPropertyBehaviors/PropertyBehavior.h index 4fca613bc..9e0712829 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.h +++ b/dGame/dPropertyBehaviors/PropertyBehavior.h @@ -46,8 +46,8 @@ public: void Deserialize(const tinyxml2::XMLElement& behavior); void Update(float deltaTime, ModelComponent& modelComponent); - void OnChatMessageReceived(const std::string& sMessage); - void OnHit(); + void OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender); + void OnHit(const LWOOBJID attacker); private: State& GetActiveState(); diff --git a/dGame/dPropertyBehaviors/State.cpp b/dGame/dPropertyBehaviors/State.cpp index 82d7ae0ba..2ffe10d0c 100644 --- a/dGame/dPropertyBehaviors/State.cpp +++ b/dGame/dPropertyBehaviors/State.cpp @@ -167,10 +167,10 @@ void State::Update(float deltaTime, ModelComponent& modelComponent, UpdateResult for (auto& strip : m_Strips) strip.Update(deltaTime, modelComponent, updateResult); } -void State::OnChatMessageReceived(const std::string& sMessage) { - for (auto& strip : m_Strips) strip.OnChatMessageReceived(sMessage); +void State::OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) { + for (auto& strip : m_Strips) strip.OnChatMessageReceived(sMessage, sender); } -void State::OnHit() { - for (auto& strip : m_Strips) strip.OnHit(); +void State::OnHit(const LWOOBJID attacker) { + for (auto& strip : m_Strips) strip.OnHit(attacker); } diff --git a/dGame/dPropertyBehaviors/State.h b/dGame/dPropertyBehaviors/State.h index 436bb2105..50e00ffc3 100644 --- a/dGame/dPropertyBehaviors/State.h +++ b/dGame/dPropertyBehaviors/State.h @@ -24,8 +24,8 @@ public: void Update(float deltaTime, ModelComponent& modelComponent, UpdateResult& updateResult); - void OnChatMessageReceived(const std::string& sMessage); - void OnHit(); + void OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender); + void OnHit(const LWOOBJID attacker); private: // The strips contained within this state. diff --git a/dGame/dPropertyBehaviors/Strip.cpp b/dGame/dPropertyBehaviors/Strip.cpp index 4ddc96cb7..889a3596b 100644 --- a/dGame/dPropertyBehaviors/Strip.cpp +++ b/dGame/dPropertyBehaviors/Strip.cpp @@ -9,6 +9,7 @@ #include "PropertyManagementComponent.h" #include "PlayerManager.h" #include "SimplePhysicsComponent.h" +#include "DestroyableComponent.h" #include "dChatFilter.h" @@ -97,6 +98,7 @@ void Strip::HandleMsg(GameMessages::RequestUse& msg) { if (nextAction.GetType() == "OnInteract") { IncrementAction(); m_WaitingForAction = false; + m_StripInitiatorID = msg.target; } } @@ -105,27 +107,34 @@ void Strip::HandleMsg(GameMessages::ResetModelToDefaults& msg) { m_WaitingForAction = false; m_PausedTime = 0.0f; m_NextActionIndex = 0; - m_InActionMove = NiPoint3Constant::ZERO; + m_InActionTranslation = NiPoint3Constant::ZERO; m_PreviousFramePosition = NiPoint3Constant::ZERO; + m_InActionRotation = NiPoint3Constant::ZERO; + m_RotationProgress = 0.0f; + m_Speed = DEFAULT_SPEED; + m_PausedFromOnTimer = false; + m_MovingToStart = false; } -void Strip::OnChatMessageReceived(const std::string& sMessage) { +void Strip::OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender) { if (m_PausedTime > 0.0f || !HasMinimumActions()) return; const auto& nextAction = GetNextAction(); if (nextAction.GetType() == "OnChat" && nextAction.GetValueParameterString() == sMessage) { IncrementAction(); m_WaitingForAction = false; + m_StripInitiatorID = sender; } } -void Strip::OnHit() { +void Strip::OnHit(const LWOOBJID attacker) { if (m_PausedTime > 0.0f || !HasMinimumActions()) return; const auto& nextAction = GetNextAction(); if (nextAction.GetType() == "OnAttack") { IncrementAction(); m_WaitingForAction = false; + m_StripInitiatorID = attacker; } } @@ -172,39 +181,67 @@ void Strip::ProcNormalAction(float deltaTime, ModelComponent& modelComponent, Up // TODO replace with switch case and nextActionType with enum /* BEGIN Move */ if (nextActionType == "MoveRight" || nextActionType == "MoveLeft") { - // X axis - bool isMoveLeft = nextActionType == "MoveLeft"; - int negative = isMoveLeft ? -1 : 1; - // Default velocity is 3 units per second. - if (modelComponent.TrySetVelocity(NiPoint3Constant::UNIT_X * negative)) { + // Local right axis + const bool isMoveLeft = nextActionType == "MoveLeft"; + if (modelComponent.TryStartMove(0, isMoveLeft ? -1.0f : 1.0f, m_Speed)) { m_PreviousFramePosition = entity.GetPosition(); - m_InActionMove.x = isMoveLeft ? -number : number; + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionTranslation.x = isMoveLeft ? -number : number; } } else if (nextActionType == "FlyUp" || nextActionType == "FlyDown") { - // Y axis - bool isFlyDown = nextActionType == "FlyDown"; - int negative = isFlyDown ? -1 : 1; - // Default velocity is 3 units per second. - if (modelComponent.TrySetVelocity(NiPoint3Constant::UNIT_Y * negative)) { + // Local up axis + const bool isFlyDown = nextActionType == "FlyDown"; + if (modelComponent.TryStartMove(1, isFlyDown ? -1.0f : 1.0f, m_Speed)) { m_PreviousFramePosition = entity.GetPosition(); - m_InActionMove.y = isFlyDown ? -number : number; + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionTranslation.y = isFlyDown ? -number : number; } - } else if (nextActionType == "MoveForward" || nextActionType == "MoveBackward") { - // Z axis - bool isMoveBackward = nextActionType == "MoveBackward"; - int negative = isMoveBackward ? -1 : 1; - // Default velocity is 3 units per second. - if (modelComponent.TrySetVelocity(NiPoint3Constant::UNIT_Z * negative)) { + // Local forward axis + const bool isMoveBackward = nextActionType == "MoveBackward"; + if (modelComponent.TryStartMove(2, isMoveBackward ? -1.0f : 1.0f, m_Speed)) { m_PreviousFramePosition = entity.GetPosition(); - m_InActionMove.z = isMoveBackward ? -number : number; + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionTranslation.z = isMoveBackward ? -number : number; } } /* END Move */ + /* BEGIN Rotate */ + else if (nextActionType == "Spin" || nextActionType == "SpinNegative") { + // Y axis + const float direction = nextActionType == "SpinNegative" ? -1.0f : 1.0f; + if (number != 0.0 && modelComponent.TryStartRotation(1, direction, m_Speed)) { + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionRotation.y = direction * number; + m_RotationProgress = 0.0f; + } + } else if (nextActionType == "Tilt" || nextActionType == "TiltNegative") { + // X axis + const float direction = nextActionType == "TiltNegative" ? -1.0f : 1.0f; + if (number != 0.0 && modelComponent.TryStartRotation(0, direction, m_Speed)) { + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionRotation.x = direction * number; + m_RotationProgress = 0.0f; + } + } else if (nextActionType == "Roll" || nextActionType == "RollNegative") { + // Z axis + const float direction = nextActionType == "RollNegative" ? -1.0f : 1.0f; + if (number != 0.0 && modelComponent.TryStartRotation(2, direction, m_Speed)) { + m_MoveInterruptCount = modelComponent.GetMoveInterruptCount(); + m_InActionRotation.z = direction * number; + m_RotationProgress = 0.0f; + } + } + /* END Rotate */ + /* BEGIN Navigation */ else if (nextActionType == "SetSpeed") { - modelComponent.SetSpeed(number); + // Floored so a move or rotation can never stall forever + m_Speed = std::max(static_cast(number), MIN_SPEED); + } else if (nextActionType == "MoveBackToStart") { + modelComponent.StartMoveTo(modelComponent.GetOriginalPosition(), m_Speed); + m_MovingToStart = true; } /* END Navigation */ @@ -233,9 +270,9 @@ void Strip::ProcNormalAction(float deltaTime, ModelComponent& modelComponent, Up // In case a word is removed from the whitelist after it was approved const auto modelName = "%[Objects_" + std::to_string(entity.GetLOT()) + "_name]"; if (isOk) ChatPackets::SendChatMessage(UNASSIGNED_SYSTEM_ADDRESS, 12, modelName, entity.GetObjectID(), false, GeneralUtils::ASCIIToUTF16(valueStr)); - PropertyManagementComponent::Instance()->OnChatMessageReceived(valueStr.data()); + PropertyManagementComponent::Instance()->OnChatMessageReceived(valueStr.data(), m_StripInitiatorID); } else if (nextActionType == "PrivateMessage") { - PropertyManagementComponent::Instance()->OnChatMessageReceived(valueStr.data()); + PropertyManagementComponent::Instance()->OnChatMessageReceived(valueStr.data(), m_StripInitiatorID); } else if (nextActionType == "PlaySound") { GameMessages::PlayBehaviorSound sound; sound.target = modelComponent.GetParent()->GetObjectID(); @@ -252,6 +289,8 @@ void Strip::ProcNormalAction(float deltaTime, ModelComponent& modelComponent, Up Spawn(10497, entity); // Maelstrom Pirate property } else if (nextActionType == "SpawnRonin") { Spawn(10498, entity); // Dark Ronin property + } else if (nextActionType == "DoDamage") { + modelComponent.DoDamage(m_StripInitiatorID); } else if (nextActionType == "DropImagination") { for (; numberAsInt > 0; numberAsInt--) SpawnDrop(935, entity); // 1 Imagination powerup } else if (nextActionType == "DropHealth") { @@ -302,49 +341,66 @@ void Strip::RemoveStates(ModelComponent& modelComponent) const { } bool Strip::CheckMovement(float deltaTime, ModelComponent& modelComponent) { + if (m_MovingToStart) { + if (modelComponent.IsMovingToTarget()) return false; + m_MovingToStart = false; + } + + // A MoveBackToStart cancelled our move, so skip to the next action + if (m_MoveInterruptCount != modelComponent.GetMoveInterruptCount()) m_InActionTranslation = NiPoint3Constant::ZERO; + auto& entity = *modelComponent.GetParent(); const auto& currentPos = entity.GetPosition(); const auto diff = currentPos - m_PreviousFramePosition; - const auto [moveX, moveY, moveZ] = m_InActionMove; m_PreviousFramePosition = currentPos; - // Only want to subtract from the move if one is being performed. - // Starts at true because we may not be doing a move at all. - // If one is being done, then one of the move_ variables will be non-zero - bool moveFinished = true; - NiPoint3 finalPositionAdjustment = NiPoint3Constant::ZERO; - if (moveX != 0.0f) { - m_InActionMove.x -= diff.x; - // If the sign bit is different between the two numbers, then we have finished our move. - moveFinished = std::signbit(m_InActionMove.x) != std::signbit(moveX); - finalPositionAdjustment.x = m_InActionMove.x; - } else if (moveY != 0.0f) { - m_InActionMove.y -= diff.y; - // If the sign bit is different between the two numbers, then we have finished our move. - moveFinished = std::signbit(m_InActionMove.y) != std::signbit(moveY); - finalPositionAdjustment.y = m_InActionMove.y; - } else if (moveZ != 0.0f) { - m_InActionMove.z -= diff.z; - // If the sign bit is different between the two numbers, then we have finished our move. - moveFinished = std::signbit(m_InActionMove.z) != std::signbit(moveZ); - finalPositionAdjustment.z = m_InActionMove.z; - } + for (int axis = 0; axis < 3; axis++) { + const float target = m_InActionTranslation[axis]; + if (target == 0.0f) continue; - // Once done, set the in action move & velocity to zero - if (moveFinished && m_InActionMove != NiPoint3Constant::ZERO) { - auto entityVelocity = entity.GetVelocity(); - // Zero out only the velocity that was acted on - if (moveX != 0.0f) entityVelocity.x = 0.0f; - else if (moveY != 0.0f) entityVelocity.y = 0.0f; - else if (moveZ != 0.0f) entityVelocity.z = 0.0f; - modelComponent.SetVelocity(entityVelocity); + // The local axes are orthonormal so this isolates our axis from any other active moves + const auto& axisVector = modelComponent.GetMoveAxis(axis); + m_InActionTranslation[axis] -= diff.DotProduct(axisVector); + + // If the sign bit is different between the two numbers, then we have finished our move. + if (std::signbit(m_InActionTranslation[axis]) == std::signbit(target)) return false; // Do the final adjustment so we will have moved exactly the requested units - entity.SetPosition(entity.GetPosition() + finalPositionAdjustment); - m_InActionMove = NiPoint3Constant::ZERO; + entity.SetPosition(entity.GetPosition() + axisVector * m_InActionTranslation[axis]); + modelComponent.StopMove(axis); + m_InActionTranslation = NiPoint3Constant::ZERO; } - return moveFinished; + return true; +} + +bool Strip::CheckRotation(float deltaTime, ModelComponent& modelComponent) { + if (m_MoveInterruptCount != modelComponent.GetMoveInterruptCount()) { + for (int axis = 0; axis < 3; axis++) { + if (m_InActionRotation[axis] != 0.0f) modelComponent.StopRotation(axis); + } + m_InActionRotation = NiPoint3Constant::ZERO; + m_RotationProgress = 0.0f; + } + + for (int axis = 0; axis < 3; axis++) { + const float target = m_InActionRotation[axis]; + if (target == 0.0f) continue; + + // Snapping to the target keeps the final angle exact regardless of speed or frame time + const float step = modelComponent.GetAngularSpeed(axis) * deltaTime; + if (std::abs(target - m_RotationProgress) <= step) m_RotationProgress = target; + else m_RotationProgress += std::copysign(step, target); + + modelComponent.SetRotationProgress(axis, m_RotationProgress); + if (m_RotationProgress != target) return false; + + modelComponent.StopRotation(axis); + m_InActionRotation = NiPoint3Constant::ZERO; + m_RotationProgress = 0.0f; + } + + return true; } void Strip::Update(float deltaTime, ModelComponent& modelComponent, UpdateResult& updateResult) { @@ -352,8 +408,9 @@ void Strip::Update(float deltaTime, ModelComponent& modelComponent, UpdateResult // Strips are also designed to have 2 actions or more to run. if (!HasMinimumActions()) return; - // Return if this strip has an active movement action + // Return if this strip has an active movement or rotation action if (!CheckMovement(deltaTime, modelComponent)) return; + if (!CheckRotation(deltaTime, modelComponent)) return; // Don't run this strip if we're paused. m_PausedTime -= deltaTime; @@ -371,16 +428,35 @@ void Strip::Update(float deltaTime, ModelComponent& modelComponent, UpdateResult // Check for trigger blocks and if not a trigger block proc this blocks action if (m_NextActionIndex == 0) { + m_StripInitiatorID = LWOOBJID_EMPTY; LOG("Behavior strip started %s", nextAction.GetType().data()); + m_Speed = DEFAULT_SPEED; if (nextAction.GetType() == "OnInteract") { modelComponent.AddInteract(); + m_WaitingForAction = true; } else if (nextAction.GetType() == "OnChat") { - // logic here if needed + m_WaitingForAction = true; } else if (nextAction.GetType() == "OnAttack") { modelComponent.AddAttack(); + m_WaitingForAction = true; + } else if (nextAction.GetType() == "OnStartup") { + IncrementAction(); + } else if (nextAction.GetType() == "OnTimer") { + if (!m_PausedFromOnTimer) { + m_PausedTime = nextAction.GetValueParameterDouble(); + m_PausedFromOnTimer = true; + } else { + IncrementAction(); + m_PausedFromOnTimer = false; + } + } else { + // in case we run into an unimplemented action or one that isnt a start node + // mark as waiting for action so we dont waste time re-starting the same logic and serializing + // every frame + m_WaitingForAction = true; } + Game::entityManager->SerializeEntity(entity); - m_WaitingForAction = true; } else { // should be a normal block ProcNormalAction(deltaTime, modelComponent, updateResult); } diff --git a/dGame/dPropertyBehaviors/Strip.h b/dGame/dPropertyBehaviors/Strip.h index 330aafbc3..d29ca7b54 100644 --- a/dGame/dPropertyBehaviors/Strip.h +++ b/dGame/dPropertyBehaviors/Strip.h @@ -34,6 +34,10 @@ public: // Checks the movement logic for whether or not to proceed // Returns true if the movement can continue, false if it needs to wait more. bool CheckMovement(float deltaTime, ModelComponent& modelComponent); + + // Checks the rotation logic for whether or not to proceed + // Returns true if the rotation can continue, false if it needs to wait more. + bool CheckRotation(float deltaTime, ModelComponent& modelComponent); void Update(float deltaTime, ModelComponent& modelComponent, UpdateResult& updateResult); void SpawnDrop(LOT dropLOT, Entity& entity); void ProcNormalAction(float deltaTime, ModelComponent& modelComponent, UpdateResult& updateResult); @@ -42,8 +46,8 @@ public: // 2 actions are required for strips to work bool HasMinimumActions() const { return m_Actions.size() >= 2; } - void OnChatMessageReceived(const std::string& sMessage); - void OnHit(); + void OnChatMessageReceived(const std::string& sMessage, const LWOOBJID sender); + void OnHit(const LWOOBJID attacker); private: // Indicates this Strip is waiting for an action to be taken upon it to progress to its actions bool m_WaitingForAction{ false }; @@ -51,6 +55,7 @@ private: // The amount of time this strip is paused for. Any interactions with this strip should be bounced if this is greater than 0. // Actions that do not use time do not use this (ex. positions). float m_PausedTime{ 0.0f }; + bool m_PausedFromOnTimer{ false }; // The index of the next action to be played. This should always be within range of [0, m_Actions.size()). size_t m_NextActionIndex{ 0 }; @@ -61,14 +66,32 @@ private: // The location of this strip on the UGBehaviorEditor UI StripUiPosition m_Position; - // The current actions remaining distance to the target + // The current actions remaining translation to the target along the model's local right (x), up (y) and forward (z) axes. // Only 1 of these vertexs' will be active at once for any given strip. - NiPoint3 m_InActionMove{}; + NiPoint3 m_InActionTranslation{}; // The position of the parent model on the previous frame NiPoint3 m_PreviousFramePosition{}; - NiPoint3 m_SavedVelocity{}; + // The signed target degrees of the current rotation action. Only 1 axis is active at once for any given strip. + NiPoint3 m_InActionRotation{}; + + // The signed degrees the current rotation action has progressed so far + float m_RotationProgress{ 0.0f }; + + // Whether this strip is waiting on a MoveBackToStart to arrive + bool m_MovingToStart{ false }; + + // The model's move interrupt count when this strip's current move or rotation started + uint32_t m_MoveInterruptCount{}; + + static constexpr float DEFAULT_SPEED = 3.0f; + static constexpr float MIN_SPEED = 0.1f; + + // Speed applied to moves and rotations started by this strip + float m_Speed{ DEFAULT_SPEED }; + + LWOOBJID m_StripInitiatorID{ LWOOBJID_EMPTY }; }; #endif //!__STRIP__H__ diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index e4c421bc8..07beab0f1 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1430,7 +1430,7 @@ void HandlePacket(Packet* packet) { std::string sMessage = GeneralUtils::UTF16ToWTF8(chatMessage.message); LOG("%s: %s", playerName.c_str(), sMessage.c_str()); ChatPackets::SendChatMessage(packet->systemAddress, chatMessage.chatChannel, playerName, user->GetLoggedInChar(), isMythran, chatMessage.message); - if (PropertyManagementComponent::Instance()) PropertyManagementComponent::Instance()->OnChatMessageReceived(sMessage); + if (PropertyManagementComponent::Instance()) PropertyManagementComponent::Instance()->OnChatMessageReceived(sMessage, lastChar->GetObjectID()); } break;