#include "LuaAIScript.h" #include "Entity.h" #include "EntityManager.h" #include "Game.h" #include "GameMessages.h" #include "EffectsMessages.h" #include "CDClientManager.h" #include "CDObjectsTable.h" #include "CDObjectSkillsTable.h" #include "CDSkillBehaviorTable.h" #include "DestroyableComponent.h" #include "MovementAIComponent.h" #include "RenderComponent.h" #include "ZoneFile.h" #include "ProximityMonitorComponent.h" #include "SkillComponent.h" #include "eKillType.h" #include #include #include namespace { // The script API calls of the shared Lua, on a DLU entity class EntityHost final : public LuaAI::Host { public: explicit EntityHost(Entity* self) : m_Self(self) {} NiPoint3 GetPosition() const override { return m_Self->GetPosition(); } NiQuaternion GetRotation() const override { return m_Self->GetRotation(); } void SetRotation(const NiQuaternion& rotation) override { m_Self->SetRotation(rotation); Game::entityManager->SerializeEntity(m_Self); } void GoTo(const NiPoint3& target, const float speed) override { auto* const movement = m_Self->GetComponent(); if (!movement) return; // A GoTo ends any follow movement->FollowTarget(LWOOBJID_EMPTY, 0.0f, speed, false); movement->SetHaltDistance(0.0f); movement->SetMaxSpeed(speed); movement->SetCurrentSpeed(speed); movement->SetDestination(target); moving = true; } void FollowTarget(const LWOOBJID target, const float radius, const float speed, const bool keepFollowing) override { auto* const movement = m_Self->GetComponent(); if (!movement) return; movement->FollowTarget(target, radius, speed, keepFollowing); moving = true; } void FaceTarget(const LWOOBJID target) override { const auto* const other = Game::entityManager->GetEntity(target); if (!other) return; SetRotation(QuatUtils::LookAt(m_Self->GetPosition(), other->GetPosition())); } void StopPathing() override { auto* const movement = m_Self->GetComponent(); if (movement) movement->Stop(); moving = false; } void AddTimer(const std::string& name, const float time) override { m_Self->AddTimer(name, std::max(time, 0.0f)); } void CancelTimer(const std::string& name) override { m_Self->CancelTimer(name); } void SetProximityRadius(const float radius, const std::string& name) override { m_Self->SetProximityRadius(radius, name); } std::vector GetProximityObjects(const std::string& name) const override { const auto* const proximity = m_Self->GetComponent(); if (!proximity) return {}; const auto& objects = proximity->GetProximityObjects(name); return { objects.begin(), objects.end() }; } bool Exists(const LWOOBJID object) const override { return Game::entityManager->GetEntity(object) != nullptr; } bool IsDead(const LWOOBJID object) const override { const auto* const other = Game::entityManager->GetEntity(object); return !other || other->GetIsDead(); } bool IsSelfDead() const override { return m_Self->GetIsDead(); } bool IsEnemy(const LWOOBJID object) const override { const auto* const destroyable = m_Self->GetComponent(); const auto* const other = Game::entityManager->GetEntity(object); return destroyable && other && destroyable->IsEnemy(other); } std::string GetObjectType(const LWOOBJID object) const override { const auto* const other = Game::entityManager->GetEntity(object); if (!other) return ""; return CDClientManager::GetTable()->GetByID(other->GetLOT()).type; } std::vector GetSkills() const override { std::vector skills; for (const auto& row : CDClientManager::GetTable()->Get(m_Self->GetLOT())) skills.push_back(row.skillID); return skills; } float GetSkillCooldown(const uint32_t skill) const override { return CDClientManager::GetTable()->GetSkillByID(skill).cooldown; } void CastSkill(const uint32_t skill, const LWOOBJID optionalTarget) override { auto* const skillComponent = m_Self->GetComponent(); if (skillComponent) skillComponent->CastSkill(skill, optionalTarget); } void SetImmunity(const bool immune) override { auto* const destroyable = m_Self->GetComponent(); if (!destroyable) return; destroyable->SetIsImmune(immune); Game::entityManager->SerializeEntity(m_Self); } void RestoreHealth() override { auto* const destroyable = m_Self->GetComponent(); if (!destroyable) return; destroyable->SetHealth(static_cast(destroyable->GetMaxHealth())); Game::entityManager->SerializeEntity(m_Self); } void SetMaxHealth(const int32_t health) override { auto* const destroyable = m_Self->GetComponent(); if (!destroyable) return; destroyable->SetMaxHealth(static_cast(health)); destroyable->SetHealth(health); Game::entityManager->SerializeEntity(m_Self); } void PlayEmote(const std::u16string& effectType) override { GameMessages::PlayFXEffect effect(m_Self->GetObjectID(), -1, effectType, ""); effect.priority = 1.5f; effect.Send(UNASSIGNED_SYSTEM_ADDRESS); } void DieSilently() override { auto* const destroyable = m_Self->GetComponent(); if (destroyable) destroyable->Smash(m_Self->GetObjectID(), eKillType::SILENT); } int32_t Random(const int32_t min, const int32_t max) override { return std::uniform_int_distribution(min, max)(Game::randomEngine); } void FollowWaypoints(const std::string& path, const uint32_t start) override { auto* const movement = m_Self->GetComponent(); if (movement && !path.empty()) movement->SetPath(path, start); } // MovementAIComponent goes on along the path by itself void ContinueWaypoints() override {} float GetAnimationTime(const std::u16string& animation) const override { return RenderComponent::GetAnimationTime(m_Self, animation); } // MovementAIComponent runs the waypoint commands itself, so the waypoints this binding reports have no actions void RunWaypointAction(const std::string& name, const std::string&, std::optional) override { LOG_DEBUG("Lua AI waypoint action %s on %llu is run by the movement AI", name.c_str(), m_Self->GetObjectID()); } LWOOBJID GetObjectID() const override { return m_Self->GetObjectID(); } // SetName (game message 72) has no DLU message yet, and names otherwise come from the locale void SetName(const std::u16string& name) override { LOG_DEBUG("Lua AI SetName %s on %llu is not sent", GeneralUtils::UTF16ToWTF8(name).c_str(), m_Self->GetObjectID()); } bool BelongsToFaction(const LWOOBJID object, const int32_t faction) const override { const auto* const other = Game::entityManager->GetEntity(object); const auto* const destroyable = other ? other->GetComponent() : nullptr; return destroyable && destroyable->HasFaction(faction); } bool GetPointInLine(const LWOOBJID object) const override { const auto* const other = Game::entityManager->GetEntity(object); return other && other->GetVar(u"PointInLine"); } void SetPointInLine(const LWOOBJID object, const bool pointInLine) override { auto* const other = object == m_Self->GetObjectID() ? m_Self : Game::entityManager->GetEntity(object); if (other) other->SetVar(u"PointInLine", pointInLine); } bool IsFollowingDone(const LWOOBJID object) const override { const auto* const other = Game::entityManager->GetEntity(object); return other && other->GetVarAsString(u"Imfollowing") == "done"; } void SetImFollowing() override { m_Self->SetVar(u"Imfollowing", u"true"); } void CustomStateEnter() override { auto* const script = dynamic_cast(m_Self->GetScript()); if (script) script->OnTemplateCustomStateEnter(m_Self); } void CustomStateArrived() override { auto* const script = dynamic_cast(m_Self->GetScript()); if (script) script->OnTemplateCustomStateArrived(m_Self); } // A GoTo or FollowTarget is under way: the arrival is the first frame its movement is done bool moving = false; private: Entity* m_Self; }; struct Brain { Brain(Entity* self, const LuaAI::Settings& settings, const bool managed) : host(self), machine(host, settings), managed(managed) {} EntityHost host; LuaAI::Machine machine; // Made for an entity the entity manager holds, so it goes once that one is gone bool managed; }; std::unordered_map> g_Brains; Brain* GetBrain(const Entity* self) { const auto it = g_Brains.find(self->GetObjectID()); return it == g_Brains.end() ? nullptr : it->second.get(); } }; LuaAI::Machine* LuaAIScript::GetMachine(const Entity* self) { auto* const brain = GetBrain(self); return brain ? &brain->machine : nullptr; } void LuaAIScript::StartLuaAI(Entity* self, const LuaAI::Settings& settings) { // The machines of entities that have since gone std::erase_if(g_Brains, [](const auto& entry) { return entry.second->managed && !Game::entityManager->GetEntity(entry.first); }); const bool managed = Game::entityManager->GetEntity(self->GetObjectID()) == self; // The object's own path config, next to the Set table auto withConfig = settings; withConfig.attachedPath = self->GetVarAsString(u"attached_path"); withConfig.hasGroupID = !self->GetVarAsString(u"groupID").empty(); auto& brain = g_Brains[self->GetObjectID()]; brain = std::make_unique(self, withConfig, managed); brain->machine.Start(); } void LuaAIScript::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { auto* const brain = GetBrain(self); if (brain && entering && status == "ENTER") brain->machine.OnProximityEnter(entering->GetObjectID(), name); } void LuaAIScript::OnHit(Entity* self, Entity* attacker) { auto* const brain = GetBrain(self); if (brain && attacker) brain->machine.OnHit(attacker->GetObjectID()); } void LuaAIScript::OnTimerDone(Entity* self, std::string timerName) { auto* const brain = GetBrain(self); if (brain && brain->machine.OnStateTimerDone(timerName)) return; OnLuaTimerDone(self, timerName); } void LuaAIScript::OnLuaTimerDone(Entity* self, const std::string& timerName) { auto* const brain = GetBrain(self); if (brain) brain->machine.OnTimerDone(timerName); } void LuaAIScript::OnDie(Entity* self, Entity* killer) { auto* const brain = GetBrain(self); if (brain) brain->machine.OnDeath(); OnLuaDie(self, killer); } void LuaAIScript::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { auto* const brain = GetBrain(self); if (brain) brain->machine.OnNotifyObject(name); } void LuaAIScript::OnWaypointReached(Entity* self, const uint32_t waypointIndex) { auto* const brain = GetBrain(self); if (!brain) return; const auto* const movement = self->GetComponent(); const auto* const path = movement ? movement->GetPath() : nullptr; LuaAI::Arrived msg{}; msg.wayPoint = waypointIndex; if (path) { msg.pathName = path->pathName; // Loop and bounce paths have no end msg.isLastPoint = path->pathBehavior == PathBehavior::Once && waypointIndex + 1 >= path->pathWaypoints.size(); } // The end of the path is this arrival, not another one once the movement is done brain->host.moving = false; brain->machine.OnArrived(msg); } void LuaAIScript::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { auto* const brain = GetBrain(self); if (brain) brain->machine.OnFireEvent(args); } void LuaAIScript::OnUpdate(Entity* self) { auto* const brain = GetBrain(self); if (!brain) return; // onArrived: the GoTo or follow came to a stop (not a knockback stopping it) const auto* const movement = self->GetComponent(); if (movement && !movement->IsKnockedBack()) { const bool done = movement->AtFinalWaypoint(); if (brain->host.moving && done) { brain->host.moving = false; brain->machine.OnArrived(); } else if (!done) { brain->host.moving = true; } } brain->machine.Update(); }