Files
DarkflameServer/dScripts/ai/LuaAI/LuaAIScript.cpp
Aaron Kimbrell 8a7768ae37 feat(ai): LuaAIScript runs the shared Lua AI on an entity
A script base whose original requires the shared Lua AI: StartLuaAI from
OnStartup with the Set table; proximity, hits, timers, deaths and
notifications go to the machine, arrivals come from the movement AI
finishing a GoTo or follow, and the tether is checked every frame. Moves,
skills, immunity and health go through the movement AI, skill and
destroyable components.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:50:36 -06:00

237 lines
8.4 KiB
C++

#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 "ProximityMonitorComponent.h"
#include "SkillComponent.h"
#include "eKillType.h"
#include <memory>
#include <random>
#include <unordered_map>
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<MovementAIComponent>();
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<MovementAIComponent>();
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<MovementAIComponent>();
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<LWOOBJID> GetProximityObjects(const std::string& name) const override {
const auto* const proximity = m_Self->GetComponent<ProximityMonitorComponent>();
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<DestroyableComponent>();
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<CDObjectsTable>()->GetByID(other->GetLOT()).type;
}
std::vector<uint32_t> GetSkills() const override {
std::vector<uint32_t> skills;
for (const auto& row : CDClientManager::GetTable<CDObjectSkillsTable>()->Get(m_Self->GetLOT())) skills.push_back(row.skillID);
return skills;
}
float GetSkillCooldown(const uint32_t skill) const override {
return CDClientManager::GetTable<CDSkillBehaviorTable>()->GetSkillByID(skill).cooldown;
}
void CastSkill(const uint32_t skill, const LWOOBJID optionalTarget) override {
auto* const skillComponent = m_Self->GetComponent<SkillComponent>();
if (skillComponent) skillComponent->CastSkill(skill, optionalTarget);
}
void SetImmunity(const bool immune) override {
auto* const destroyable = m_Self->GetComponent<DestroyableComponent>();
if (!destroyable) return;
destroyable->SetIsImmune(immune);
Game::entityManager->SerializeEntity(m_Self);
}
void RestoreHealth() override {
auto* const destroyable = m_Self->GetComponent<DestroyableComponent>();
if (!destroyable) return;
destroyable->SetHealth(static_cast<int32_t>(destroyable->GetMaxHealth()));
Game::entityManager->SerializeEntity(m_Self);
}
void SetMaxHealth(const int32_t health) override {
auto* const destroyable = m_Self->GetComponent<DestroyableComponent>();
if (!destroyable) return;
destroyable->SetMaxHealth(static_cast<float>(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<DestroyableComponent>();
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<int32_t>(min, max)(Game::randomEngine);
}
// 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<LWOOBJID, std::unique_ptr<Brain>> 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;
auto& brain = g_Brains[self->GetObjectID()];
brain = std::make_unique<Brain>(self, settings, 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::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<MovementAIComponent>();
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();
}