Files
AVA2/src/eter_render/ActorInstance.cpp
T
shenleiandClaude Opus 5.5 c556795ecf Keep SetWeapon/AttachPart helper attachments across rebinds
Helper attachments made outside the part slots were attached to
PART_MAIN only and dropped whenever the parts were rebound (LOD level
change, shape change, slot update). They are now recorded on the actor,
attached to the drawn instance and re-attached after the slots. A slot
taking the same bone drops the helper (last writer wins, as before);
SetRace/SetModel clear them. LODs missing a helper's bone stay on
PART_MAIN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:18:14 +09:00

993 lines
38 KiB
C++

#include "ActorInstance.h"
#include "MapObjectManager.h"
#include "CRenderTarget.h"
#include "RaceData.h"
#include "src/eter_resource/ResourceManager.h"
#include <filesystem>
#include <cmath>
#include <algorithm>
#include <iostream>
namespace ava2 {
constexpr float DEG_TO_RAD = 3.14159265358979323846f / 180.0f;
constexpr float RAD_TO_DEG = 180.0f / 3.14159265358979323846f;
ActorInstance::ActorInstance() = default;
std::string ActorInstance::ResolvePath(const std::string& path) const {
std::string clean = path;
if (clean.rfind("d:/", 0) == 0 || clean.rfind("D:/", 0) == 0) {
clean = clean.substr(3);
}
if (std::filesystem::exists(clean)) return clean;
if (std::filesystem::exists("build/dev/" + clean)) return "build/dev/" + clean;
if (std::filesystem::exists("../" + clean)) return "../" + clean;
// Pack paths ("d:/ymir work/...", mixed case) go through the CResourceManager candidates.
std::error_code error;
for (const auto& candidate : CResourceManager::GetCandidatePaths(CResourceManager::NormalizePath(path.c_str())))
if (std::filesystem::is_regular_file(candidate, error)) return candidate;
return clean;
}
std::shared_ptr<Gr2ModelInstance> ActorInstance::LoadPartModel(const std::string& path) const {
if (path.empty()) return nullptr;
std::string resolved = ResolvePath(path);
std::error_code error;
if (!std::filesystem::is_regular_file(resolved, error)) {
std::cerr << "ActorInstance: model not found: " << path << std::endl;
return nullptr;
}
return std::shared_ptr<Gr2ModelInstance>(Gr2ModelInstance::Load(resolved));
}
void ActorInstance::SetMainModel(std::shared_ptr<Gr2ModelInstance> model, const std::string& path) {
m_boundsModel = nullptr;
m_model = std::move(model);
m_modelPath = m_model ? path : std::string();
ResetLodModel();
RebindParts();
// A new PART_MAIN instance restarts the current motion on it.
if (m_model) {
auto it = m_motionPaths.find(m_currentMotion);
if (it != m_motionPaths.end()) {
std::string resolved = ResolvePath(it->second);
if (m_model->LoadExternalAnimation(resolved)) {
m_motionFile = resolved;
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
}
}
}
}
// Re-attaches the part slots to PART_MAIN: hair deforms with the main skeleton, the others follow
// their attaching bone; PART_SASH also takes the ENABLE_OBJ_SCALLING scale matrix. Parts follow the
// current LOD instance (pSkelController->m_pCurrentModelInstance / AttachModelInstance).
void ActorInstance::RebindParts() {
if (!m_model) return;
m_model->DetachAll();
for (auto& lod : m_lodModels)
if (lod.model) lod.model->DetachAll();
Gr2ModelInstance* target = DrawModel();
for (uint32_t part = 1; part < kPartCount; ++part) {
const auto& slot = m_parts[part];
if (!slot.model) continue;
if (slot.bone.empty()) {
target->AttachPart(slot.model);
continue;
}
target->AttachModel(slot.bone, slot.model);
if (part == RaceData::PART_SASH) {
target->SetAttachmentAnimated(slot.bone, true);
if (m_hasSashScale) target->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]);
}
}
for (const auto& extra : m_extraAttachments) {
if (extra.bone.empty()) target->AttachPart(extra.model);
else target->AttachModel(extra.bone, extra.model);
}
}
void ActorInstance::DropExtraAttachment(const std::string& bone) {
if (bone.empty()) return;
m_extraAttachments.erase(std::remove_if(m_extraAttachments.begin(), m_extraAttachments.end(),
[&](const SExtraAttachment& e) { return e.bone == bone; }),
m_extraAttachments.end());
}
Gr2ModelInstance* ActorInstance::DrawModel() const {
if (m_lodLevel < m_lodModels.size() && m_lodModels[m_lodLevel].model) return m_lodModels[m_lodLevel].model.get();
return m_model.get();
}
static bool HasBone(const Gr2ModelInstance& model, const std::string& name) {
const auto& skeletons = model.GetInfo().skeletons;
if (skeletons.empty()) return false;
for (const auto& bone : skeletons[0].bones)
if (bone.name == name) return true;
return false;
}
// Some shipped LODs drop attaching bones (lion2_lod_02/03 lose "saddle", shaman_miyeom_lod_* lose
// equip_left/right). Drawing those would detach the rider or a part, so such a level falls back to
// PART_MAIN.
bool ActorInstance::LodHasAttachBones(const Gr2ModelInstance& lod) const {
for (uint32_t part = 1; part < kPartCount; ++part) {
const auto& slot = m_parts[part];
if (slot.model && !slot.bone.empty() && !HasBone(lod, slot.bone)) return false;
}
for (const auto& extra : m_extraAttachments)
if (!extra.bone.empty() && !HasBone(lod, extra.bone)) return false;
static const std::string kSaddle = "saddle";
return !HasBone(*m_model, kSaddle) || HasBone(lod, kSaddle);
}
// CGrannyLODController::SetLODLevel + SetCurrentModelInstance.
void ActorInstance::SetLodLevel(uint32_t level) {
level = std::min<uint32_t>(level, uint32_t(m_lodPaths.size()));
if (level < m_lodPaths.size()) {
if (m_lodModels.size() != m_lodPaths.size()) m_lodModels.resize(m_lodPaths.size());
auto& lod = m_lodModels[level];
if (!lod.model) {
lod.model = LoadPartModel(m_lodPaths[level]);
if (!lod.model) { // unreadable LOD: keep drawing the current instance
m_lodPaths.resize(level);
m_lodModels.resize(level);
return;
}
for (const auto& skin : m_mainSkins) lod.model->SetSkin(skin.first, skin.second);
}
if (!LodHasAttachBones(*lod.model)) level = uint32_t(m_lodPaths.size());
}
if (level == m_lodLevel) return;
m_lodLevel = level;
RebindParts();
SyncLodMotion();
}
// CGrannyLODController::SetMotionPointer applies the motion to every LOD instance; only the drawn
// one is kept in step here.
void ActorInstance::SyncLodMotion() {
if (m_lodLevel >= m_lodModels.size() || !m_lodModels[m_lodLevel].model) return;
auto& lod = m_lodModels[m_lodLevel];
bool loaded = false;
if (lod.motionFile != m_motionFile && !m_motionFile.empty() && lod.model->LoadExternalAnimation(m_motionFile)) {
lod.motionFile = m_motionFile;
loaded = true;
}
if (loaded || lod.motionLoop != m_loopMotion) {
lod.motionLoop = m_loopMotion;
lod.model->SetAnimationLoop(m_loopMotion, m_loopMotion);
}
}
bool ActorInstance::SetRace(uint32_t race) {
RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(race);
if (!raceData) {
m_race = 0;
m_raceData = nullptr;
return false;
}
m_race = race;
m_raceData = raceData;
// memset(m_adwPartItemID) + CGraphicThingInstance::Clear(): every part model is dropped.
std::fill(std::begin(m_partItemID), std::end(m_partItemID), 0u);
for (auto& slot : m_parts) slot = SPartSlot{};
m_extraAttachments.clear();
m_model.reset();
m_modelPath.clear();
m_shapeFile.clear();
m_mainSkins.clear();
ResetLodModel();
// SetMotionIndex(eRace): the race's GENERAL motion set (motlist.txt for NPC races, the
// chrmgr.RegisterMotionData calls for races built from Python).
m_motionPaths.clear();
m_motionQueue.clear();
{
static const RaceData::EMotion kNames[] = {
RaceData::NAME_WAIT, RaceData::NAME_WALK, RaceData::NAME_RUN, RaceData::NAME_CHANGE_WEAPON,
RaceData::NAME_DAMAGE, RaceData::NAME_DEAD, RaceData::NAME_NORMAL_ATTACK,
RaceData::NAME_COMBO_ATTACK_1, RaceData::NAME_COMBO_ATTACK_2, RaceData::NAME_COMBO_ATTACK_3,
};
for (auto name : kNames) {
const auto* motions = raceData->GetMotions(name);
if (!motions || motions->empty()) continue;
// The percent-weighted random pick of CActorInstance is not ported: the first entry plays.
std::string gr2 = ReadMotionFileName(motions->front().fileName);
if (!gr2.empty()) RegisterMotion(static_cast<MotionType>(name), gr2);
}
}
return true;
}
void ActorInstance::SetShape(uint32_t shape, float specular) {
(void)specular; // SMaterialData specular / sphere map: not rendered by the port yet.
m_shape = shape;
RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(m_race);
if (!raceData) return;
const RaceData::Shape* pkShape = raceData->FindShape(shape);
if (pkShape) {
const std::string& file = pkShape->model.empty() ? raceData->GetBaseModelFileName() : pkShape->model;
auto model = LoadPartModel(file);
m_mainSkins.clear();
for (const auto& skin : pkShape->skins) m_mainSkins.emplace_back(skin.srcFileName, skin.dstFileName);
if (model) {
for (const auto& skin : m_mainSkins) model->SetSkin(skin.first, skin.second);
}
m_shapeFile = file;
SetMainModel(std::move(model), file);
} else if (raceData->IsTree()) {
// __CreateTree (SpeedTree actors) is not ported.
m_mainSkins.clear();
m_shapeFile.clear();
SetMainModel(nullptr, std::string());
} else {
const std::string& file = raceData->GetBaseModelFileName();
m_mainSkins.clear();
m_shapeFile = file;
SetMainModel(LoadPartModel(file), file);
}
}
void ActorInstance::SetHair(uint32_t hair) {
m_hair = hair;
RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(m_race);
if (!raceData) return;
const RaceData::Shape* pkHair = raceData->FindHair(hair);
if (!pkHair) return; // the previous hair instance stays
if (!pkHair->model.empty()) {
m_parts[RaceData::PART_HAIR].model = LoadPartModel(pkHair->model);
m_parts[RaceData::PART_HAIR].file = pkHair->model;
m_parts[RaceData::PART_HAIR].bone.clear();
}
if (auto& model = m_parts[RaceData::PART_HAIR].model)
for (const auto& skin : pkHair->skins) model->SetSkin(skin.srcFileName, skin.dstFileName);
RebindParts();
}
void ActorInstance::AttachWeaponPart(uint32_t part, const SPartItem& item) {
std::string bone;
if (!m_raceData || !m_raceData->GetAttachingBoneName(part, &bone)) return;
// PART_WEAPON_LEFT registers GetSubModelThing(), which is the same model file.
m_parts[part].model = LoadPartModel(item.model);
m_parts[part].file = item.model;
m_parts[part].bone = bone;
DropExtraAttachment(bone);
// USE_WEAPON_SPECULAR sphere map and CWeaponTrace are not ported.
}
void ActorInstance::AttachWeapon(uint32_t itemIndex, const SPartItem* item, bool isMountingHorse) {
enum { WEAPON_DAGGER = 1, WEAPON_BOW = 2, WEAPON_FAN = 5 };
m_partItemID[RaceData::PART_WEAPON] = itemIndex;
if (!item) {
m_parts[RaceData::PART_WEAPON] = SPartSlot{};
m_parts[RaceData::PART_WEAPON_LEFT] = SPartSlot{};
RebindParts();
return;
}
const uint32_t type = item->weaponType;
const bool dual = type == WEAPON_DAGGER || (type == WEAPON_FAN && isMountingHorse);
// __IsRightHandWeapon / __IsLeftHandWeapon. A slot that is not re-attached keeps its old model
// (e.g. a dagger's left blade stays after switching to a sword), as on Windows.
if (dual || type != WEAPON_BOW) AttachWeaponPart(RaceData::PART_WEAPON, *item);
if (dual || type == WEAPON_BOW) AttachWeaponPart(RaceData::PART_WEAPON_LEFT, *item);
RebindParts();
}
void ActorInstance::AttachSash(const SPartItem* item, float specular) {
(void)specular; // sphere-map specular not rendered.
if (!item) {
m_parts[RaceData::PART_SASH] = SPartSlot{};
} else {
m_parts[RaceData::PART_SASH].model = LoadPartModel(item->model);
m_parts[RaceData::PART_SASH].file = item->model;
m_parts[RaceData::PART_SASH].bone = "Bip01 Spine2";
DropExtraAttachment(m_parts[RaceData::PART_SASH].bone);
}
RebindParts();
}
void ActorInstance::SetSashScale(float sx, float sy, float sz) {
m_hasSashScale = true;
m_sashScale[0] = sx; m_sashScale[1] = sy; m_sashScale[2] = sz;
RebindParts();
}
void ActorInstance::ResetLodModel() {
// CActorInstance registers NoExtension(model) + "_lod_01.gr2" when it exists; only then does
// CGrannyLODController::UpdateLODLevel lower the animation FPS (m_que_pkModelInst.size() > 1).
m_hasLodModel = false;
m_lodAniFps = 120;
m_poseTimeValid = false;
m_lodPaths.clear();
m_lodModels.clear();
m_lodLevel = 0;
if (!m_model) return;
const size_t dot = m_modelPath.find_last_of('.');
const bool hasExtension = dot != std::string::npos && m_modelPath.find_first_of("/\\", dot) == std::string::npos;
const std::string stem = hasExtension ? m_modelPath.substr(0, dot) : m_modelPath;
// _lod_01.._03 until the first missing file; push_front keeps the main model last.
for (int index = 1; index <= 3; ++index) {
const std::string lod = stem + "_lod_0" + std::to_string(index) + ".gr2";
std::error_code error;
if (!std::filesystem::is_regular_file(ResolvePath(lod), error)) break;
m_lodPaths.insert(m_lodPaths.begin(), lod);
}
m_lodLevel = uint32_t(m_lodPaths.size());
m_hasLodModel = !m_lodPaths.empty();
// CGrannyLODController::AddModel: models of 500 units or more use the building LOD distance.
float loX, loY, loZ, hiX, hiY, hiZ;
m_lodDistance = 5000.0f; // LODDISTANCE_ACTOR
if (m_model->GetLocalBounds(loX, loY, loZ, hiX, hiY, hiZ) && std::max({hiX - loX, hiY - loY, hiZ - loZ}) >= 500.0f)
m_lodDistance = 25000.0f; // LODDISTANCE_BUILDING
}
bool ActorInstance::SetModel(const std::string& modelPath) {
std::string resolved = ResolvePath(modelPath);
if (!std::filesystem::exists(resolved)) {
std::cerr << "ActorInstance::SetModel file not found: " << modelPath << std::endl;
return false;
}
m_boundsModel = nullptr;
m_model = Gr2ModelInstance::Load(resolved);
if (!m_model) return false;
m_modelPath = modelPath;
m_mainSkins.clear();
m_extraAttachments.clear(); // a fresh instance carries none of the old attachments
ResetLodModel();
return true;
}
bool ActorInstance::SetWeapon(const std::string& weaponPath, const std::string& boneName) {
if (!m_model) return false;
std::string resolved = ResolvePath(weaponPath);
if (!std::filesystem::exists(resolved)) return false;
auto weaponModel = Gr2ModelInstance::Load(resolved);
if (!weaponModel) {
std::string fallback = ResolvePath("ymir work/item/weapon/set_11_sword.gr2");
if (std::filesystem::exists(fallback)) {
weaponModel = Gr2ModelInstance::Load(fallback);
}
}
if (!weaponModel) return false;
std::shared_ptr<Gr2ModelInstance> weapon(std::move(weaponModel));
DropExtraAttachment(boneName);
m_extraAttachments.push_back({boneName, weapon});
DrawModel()->AttachModel(boneName, std::move(weapon));
return true;
}
bool ActorInstance::AttachPart(const std::string& partPath) {
if (!m_model) return false;
std::string resolved = ResolvePath(partPath);
if (!std::filesystem::exists(resolved)) return false;
auto partModel = Gr2ModelInstance::Load(resolved);
if (!partModel) return false;
std::shared_ptr<Gr2ModelInstance> part(std::move(partModel));
m_extraAttachments.push_back({std::string(), part});
DrawModel()->AttachPart(std::move(part));
return true;
}
void ActorInstance::RegisterMotion(MotionType type, const std::string& motionGr2Path) {
m_motionPaths[type] = motionGr2Path;
}
bool ActorInstance::PlayMotion(MotionType type, bool loop) {
if (!m_model) return false;
auto it = m_motionPaths.find(type);
if (it == m_motionPaths.end()) {
// Fallback: If combo attack not found, try generic attack
if (type == MotionType::ComboAttack1 || type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3) {
it = m_motionPaths.find(MotionType::Attack);
}
}
std::string motionPath;
// Resolve the active mode at playback time; SetRace/armor rebuilds must not
// silently replace riding motions with GENERAL standing/walking motions.
if (m_raceData && m_motionMode != 1) {
uint16_t actualMode = uint16_t(m_motionMode);
if (m_raceData->GetMotionKey(actualMode, uint16_t(type), &actualMode)) {
const auto* entries = m_raceData->GetMotions(actualMode, uint32_t(type));
if (entries && !entries->empty()) motionPath = ReadMotionFileName(entries->front().fileName);
}
}
if (motionPath.empty()) {
if (it == m_motionPaths.end()) return false;
motionPath = it->second;
}
std::string resolved = ResolvePath(motionPath);
if (!std::filesystem::exists(resolved)) return false;
bool loaded = m_model->LoadExternalAnimation(resolved);
if (!loaded) return false;
m_currentMotion = type;
m_motionFile = resolved;
m_animTime = 0.0f;
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
m_loopMotion = loop;
m_model->SetAnimationLoop(loop, loop);
SyncLodMotion();
if (type == MotionType::Attack || type == MotionType::ComboAttack1 ||
type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3 ||
type == MotionType::Skill1 || type == MotionType::Skill2 ||
type == MotionType::Skill3 || type == MotionType::Skill4 ||
type == MotionType::Skill5) {
m_isAttacking = true;
} else {
m_isAttacking = false;
}
return true;
}
bool ActorInstance::PlayMotionIndex(uint32_t index, bool loop) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
const auto* motions = m_raceData->GetMotions(keyMode, index);
if (!motions || motions->empty()) return false;
const std::string gr2 = ReadMotionFileName(motions->front().fileName);
if (gr2.empty()) return false;
RegisterMotion(static_cast<MotionType>(index), gr2);
return PlayMotion(static_cast<MotionType>(index), loop);
}
bool ActorInstance::SetLoopMotionIndex(uint32_t index) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
m_motionQueue.clear(); // __ClearMotion
return PlayMotionIndex(index, true);
}
bool ActorInstance::InterceptMotionIndex(uint32_t index, bool loop) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
m_motionQueue.clear(); // __ClearMotion
return PlayMotionIndex(index, loop);
}
bool ActorInstance::PushMotionIndex(uint32_t index, bool loop) {
uint16_t keyMode;
if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false;
m_motionQueue.emplace_back(index, loop);
return true;
}
bool ActorInstance::IsMotionFinished() const {
if (m_loopMotion) return false;
return m_animTime >= m_motionDuration;
}
void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
float rad = moveYaw * DEG_TO_RAD;
m_yaw = moveYaw;
float dx = std::sin(rad) * m_moveSpeed * dt;
float dz = std::cos(rad) * m_moveSpeed * dt;
auto isBlocked = [&](float testX, float testZ) -> bool {
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(testX, testZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) {
return true;
}
if (mapObjects && mapObjects->CheckCollision(testX, testZ, 30.0f)) {
return true;
}
return false;
};
float nextX = m_posX + dx;
float nextZ = m_posZ + dz;
if (!isBlocked(nextX, nextZ)) {
m_posX = nextX;
m_posZ = nextZ;
} else {
// Wall sliding: attempt to slide along X axis only
if (!isBlocked(nextX, m_posZ)) {
m_posX = nextX;
} else if (!isBlocked(m_posX, nextZ)) {
// Attempt to slide along Z axis only
m_posZ = nextZ;
} else {
// Check building collision normal for sliding: v' = v - (v . n) * n
float nx = 0.0f, nz = 0.0f;
if (mapObjects && mapObjects->CheckCollisionNormal(nextX, nextZ, 30.0f, nx, nz)) {
float dot = dx * nx + dz * nz;
float slideX = dx - dot * nx;
float slideZ = dz - dot * nz;
if (!isBlocked(m_posX + slideX, m_posZ + slideZ)) {
m_posX += slideX;
m_posZ += slideZ;
}
} else if (m_hasMoveTarget) {
ClearMoveTarget();
StopMoving();
}
}
}
if (terrain) {
m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
}
if (!m_isAttacking && m_currentMotion != MotionType::Run) {
PlayMotion(MotionType::Run, true);
}
}
void ActorInstance::StopMoving() {
if (!m_isAttacking && m_currentMotion == MotionType::Run) {
PlayMotion(MotionType::Wait, true);
}
}
void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
// 0. Click-to-Move destination pathing (aligned with 40250 CPythonPlayer)
if (m_hasMoveTarget && !m_isAttacking && m_curHP > 0) {
float dx = m_targetX - m_posX;
float dz = m_targetZ - m_posZ;
float dist = std::sqrt(dx * dx + dz * dz);
float step = m_moveSpeed * dt;
if (dist <= 15.0f || dist <= step) {
bool blocked = false;
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(m_targetX, m_targetZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) blocked = true;
if (mapObjects && mapObjects->CheckCollision(m_targetX, m_targetZ, 30.0f)) blocked = true;
if (!blocked) {
m_posX = m_targetX;
m_posZ = m_targetZ;
}
if (terrain) m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
StopMoving();
m_hasMoveTarget = false;
} else {
float moveYaw = std::atan2(dx, dz) * RAD_TO_DEG;
MoveInDirection(moveYaw, dt, terrain, mapObjects);
}
}
// Apply knockback impulse
if (std::abs(m_knockbackVx) > 0.01f || std::abs(m_knockbackVz) > 0.01f) {
float nextX = m_posX + m_knockbackVx * dt;
float nextZ = m_posZ + m_knockbackVz * dt;
if (!terrain || !terrain->HasAttrMap() || !terrain->IsAttrOn(nextX, nextZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) {
m_posX = nextX;
m_posZ = nextZ;
} else {
m_knockbackVx = 0.0f;
m_knockbackVz = 0.0f;
}
m_knockbackVx *= std::max(0.0f, 1.0f - 8.0f * dt);
m_knockbackVz *= std::max(0.0f, 1.0f - 8.0f * dt);
}
// Clamp Y to terrain height
if (terrain) {
m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
}
// Update active buffs
for (auto it = m_buffs.begin(); it != m_buffs.end(); ) {
it->second -= dt;
if (it->second <= 0.0f) {
if (it->first == "berserk") {
m_moveSpeed = 350.0f;
}
it = m_buffs.erase(it);
} else {
++it;
}
}
// Advance animation time
m_animTime += dt;
m_lodLocalTime += dt; // CGrannyModelInstance::UpdateLocalTime
if (!m_motionQueue.empty() && m_animTime >= m_motionDuration) {
// ReservingMotionProcess: the next pushed motion takes over when the current one ends.
const auto next = m_motionQueue.front();
m_motionQueue.pop_front();
PlayMotionIndex(next.first, next.second);
} else if (m_loopMotion) {
if (m_motionDuration > 0.001f && m_animTime >= m_motionDuration) {
m_animTime = std::fmod(m_animTime, m_motionDuration);
}
} else {
if (m_animTime >= m_motionDuration) {
m_isAttacking = false;
// On one-shot finish (e.g. attack or hit), return to wait or dead
if (m_curHP <= 0) {
// Keep dead pose or freeze at end of dead motion
m_animTime = m_motionDuration - 0.01f;
} else {
PlayMotion(MotionType::Wait, true);
}
}
}
}
bool ActorInstance::Attack() {
if (m_curHP <= 0) return false;
if (!m_isAttacking) {
m_comboIndex = 1;
if (!PlayMotion(MotionType::ComboAttack1, false)) {
PlayMotion(MotionType::Attack, false);
}
return true;
} else if (m_animTime > m_motionDuration * 0.35f) {
// Advance combo chain
m_comboIndex = (m_comboIndex % 3) + 1;
MotionType next = MotionType::ComboAttack1;
if (m_comboIndex == 2) next = MotionType::ComboAttack2;
else if (m_comboIndex == 3) next = MotionType::ComboAttack3;
if (!PlayMotion(next, false)) {
PlayMotion(MotionType::Attack, false);
}
return true;
}
return false;
}
bool ActorInstance::CastSkill(MotionType skillMotion) {
if (m_curHP <= 0) return false;
ClearMoveTarget();
StopMoving();
m_isAttacking = true;
m_animTime = 0.0f;
return PlayMotion(skillMotion, false);
}
void ActorInstance::SetBuff(const std::string& buffName, float duration) {
m_buffs[buffName] = duration;
if (buffName == "berserk") {
m_moveSpeed = 440.0f;
}
}
bool ActorInstance::HasBuff(const std::string& buffName) const {
auto it = m_buffs.find(buffName);
return it != m_buffs.end() && it->second > 0.0f;
}
float ActorInstance::GetBuffRemaining(const std::string& buffName) const {
auto it = m_buffs.find(buffName);
return (it != m_buffs.end()) ? it->second : 0.0f;
}
float ActorInstance::GetAttackMultiplier() const {
float mult = 1.0f;
if (HasBuff("berserk")) mult += 0.40f;
return mult;
}
int ActorInstance::GetBonusAttackDamage() const {
int bonus = 0;
if (HasBuff("aura")) bonus += 120;
return bonus;
}
void ActorInstance::Die() {
m_curHP = 0;
StopMoving();
PlayMotion(MotionType::Dead, false);
}
void ActorInstance::TakeDamage(int damage, float knockbackDirX, float knockbackDirZ) {
m_curHP = std::max(0, m_curHP - damage);
if (m_curHP <= 0) {
if (!PlayMotion(MotionType::Dead, false)) {
PlayMotion(MotionType::Damage, false);
}
} else {
PlayMotion(MotionType::Damage, false);
}
float len = std::sqrt(knockbackDirX * knockbackDirX + knockbackDirZ * knockbackDirZ);
if (len > 0.001f) {
m_knockbackVx = (knockbackDirX / len) * 260.0f;
m_knockbackVz = (knockbackDirZ / len) * 260.0f;
}
}
void ActorInstance::GetHeadPosition(float& hX, float& hY, float& hZ) const {
hX = m_posX;
hY = m_posY + (m_heightOffset + m_modelYOffset) * m_scale;
hZ = m_posZ;
}
bool ActorInstance::IsTargetInAttackRange(const ActorInstance& target, float maxRange, float maxAngleDeg) const {
float dx = target.GetX() - m_posX;
float dz = target.GetZ() - m_posZ;
float dist = std::sqrt(dx * dx + dz * dz);
if (dist > maxRange) return false;
float dirAngle = std::atan2(dx, dz) * RAD_TO_DEG;
float diff = std::abs(std::fmod(dirAngle - m_yaw + 540.0f, 360.0f) - 180.0f);
return diff <= maxAngleDeg;
}
std::vector<Render3DDraw> ActorInstance::BuildDrawCommands(const float* worldOverride) {
if (!m_model) return {};
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);
// Shining system (ENABLE_SHINING_SYSTEM): weapon aura / glow
if (m_weaponShining > 0) {
float hx = 0, hy = 0, hz = 0;
if (GetBonePosition("equip_right_hand", hx, hy, hz) || GetBonePosition("Bip01 R Hand", hx, hy, hz)) {
Render3DDraw sDraw;
sDraw.alpha_blend = true;
sDraw.blend_mode = 1; // Additive
sDraw.z_write = false;
sDraw.lighting = false;
float sz = 20.0f + m_weaponShining * 4.0f;
sDraw.positions = {
hx - sz, hy - sz, hz,
hx + sz, hy - sz, hz,
hx + sz, hy + sz, hz,
hx - sz, hy + sz, hz
};
sDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
sDraw.indices = {0, 1, 2, 0, 2, 3};
sDraw.texture0 = !m_weaponShiningPath.empty() ? m_weaponShiningPath : "ymir work/effect/shiningsystem/shining00.dds";
for (int k = 0; k < 16; ++k) sDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(sDraw));
}
}
// Shining system: armor body glow
if (m_armorShining > 0) {
float ax = m_posX, ay = m_posY + 100.0f * m_scale, az = m_posZ;
Render3DDraw aDraw;
aDraw.alpha_blend = true;
aDraw.blend_mode = 1; // Additive
aDraw.z_write = false;
aDraw.lighting = false;
float sz = 35.0f + m_armorShining * 6.0f;
aDraw.positions = {
ax - sz, ay - sz, az,
ax + sz, ay - sz, az,
ax + sz, ay + sz, az,
ax - sz, ay + sz, az
};
aDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
aDraw.indices = {0, 1, 2, 0, 2, 3};
aDraw.texture0 = !m_armorShiningPath.empty() ? m_armorShiningPath : "ymir work/effect/shiningsystem/shining01.dds";
for (int k = 0; k < 16; ++k) aDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(aDraw));
}
// Shining system: acce wing glow
if (m_acceShining > 0) {
float wx = 0, wy = 0, wz = 0;
if (GetBonePosition("Bip01 Spine2", wx, wy, wz) || GetBonePosition("Bip01 Spine1", wx, wy, wz)) {
Render3DDraw wDraw;
wDraw.alpha_blend = true;
wDraw.blend_mode = 1; // Additive
wDraw.z_write = false;
wDraw.lighting = false;
float sz = 45.0f + m_acceShining * 7.0f;
wDraw.positions = {
wx - sz, wy - sz, wz,
wx + sz, wy - sz, wz,
wx + sz, wy + sz, wz,
wx - sz, wy + sz, wz
};
wDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
wDraw.indices = {0, 1, 2, 0, 2, 3};
wDraw.texture0 = !m_acceShiningPath.empty() ? m_acceShiningPath : "ymir work/effect/shiningsystem/shining_wing.dds";
for (int k = 0; k < 16; ++k) wDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(wDraw));
}
}
return draws;
}
void ActorInstance::UpdateLODLevel(float eyeX, float eyeY, float eyeZ, float targetX, float targetZ) {
// CGrannyLODController::UpdateLODLevel; the distance from the camera target ignores height.
m_lodAniFps = 120;
const uint32_t count = GetLODCount();
uint32_t level = count - 1; // m_que_pkModelInst.back(): the main model
if (m_hasLodModel) {
const float centerX = targetX - m_posX, centerZ = targetZ - m_posZ;
if (std::sqrt(centerX * centerX + centerZ * centerZ) > 500.0f) { // LOD_APPLY_MIN
const float dx = eyeX - m_posX, dy = eyeY - m_posY, dz = eyeZ - m_posZ;
const float camera = std::sqrt(dx * dx + dy * dy + dz * dz);
const float factor = std::clamp(m_lodDistance - camera, 0.0f, m_lodDistance);
m_lodAniFps = static_cast<uint32_t>((120 - 30) * factor / m_lodDistance + 30) / 10 * 10; // ANIFPS_MAX/MIN
uint8_t lodLevel = uint8_t(factor / (m_lodDistance / float(count)));
if (m_lodDistance <= 5000.0f) {
const uint32_t band = camera < 500.0f ? 0 : camera < 1500.0f ? 1 : camera < 2500.0f ? 2 : 3;
// BYTE arithmetic as in the original: band == count wraps to 255, which SetLODLevel
// clamps back to the main model (e.g. a single _lod_01 beyond 1500 units).
lodLevel = uint8_t(count - std::min(band, count) - 1);
}
level = std::min<uint32_t>(count - 1, lodLevel);
}
}
SetLodLevel(level);
// CGrannyModelInstance::Update: hold the pose until the next ANIFPS_STEP frame. A restarted or
// switched motion (time going back, new model) re-samples at once instead of mixing clips.
const uint32_t frame = static_cast<uint32_t>(m_lodLocalTime * 120.0f);
const uint32_t step = 120 / m_lodAniFps;
if (m_poseTimeValid && m_poseModel == DrawModel() && m_animTime >= m_poseAnimTime
&& frame > step && frame / step == m_oldUpdateFrame / step)
return;
m_oldUpdateFrame = frame;
m_poseAnimTime = m_animTime;
m_poseModel = DrawModel();
m_poseTimeValid = step > 1; // full rate: always draw the current time
}
bool ActorInstance::IsVisible(const float* view, const float* proj) const {
if (!view || !proj || !m_model) return true;
if (m_boundsModel != m_model.get()) {
float loX,loY,loZ,hiX,hiY,hiZ;
m_boundsRadius = 500.f;
if (m_model->GetLocalBounds(loX,loY,loZ,hiX,hiY,hiZ)) {
const float x=std::max(std::abs(loX),std::abs(hiX));
const float y=std::max(std::abs(loY),std::abs(hiY));
const float z=std::max(std::abs(loZ),std::abs(hiZ));
m_boundsRadius = std::sqrt(x*x+y*y+z*z)*2.f + 300.f;
}
m_boundsModel=m_model.get();
}
const float r=m_boundsRadius*std::abs(m_scale);
const float y=m_posY+m_modelYOffset*m_scale;
const float lo[3]={m_posX-r,y-r,m_posZ-r};
const float hi[3]={m_posX+r,y+r,m_posZ+r};
return IsBoundsVisible(lo,hi,view,proj);
}
bool ActorInstance::HitTestScreen(float clickX, float clickY, const Gr2SceneRenderer& renderer, float tolerancePx) const {
if (m_curHP <= 0) return false;
float bx = 0.0f, by = 0.0f, hx = 0.0f, hy = 0.0f;
if (!renderer.ProjectToScreen(m_posX, m_posY, m_posZ, bx, by)) return false;
float topY = m_posY + m_heightOffset * m_scale;
if (!renderer.ProjectToScreen(m_posX, topY, m_posZ, hx, hy)) return false;
float segX = hx - bx;
float segY = hy - by;
float segLenSq = segX * segX + segY * segY;
float t = 0.0f;
if (segLenSq > 1e-4f) {
t = std::clamp(((clickX - bx) * segX + (clickY - by) * segY) / segLenSq, 0.0f, 1.0f);
}
float projX = bx + t * segX;
float projY = by + t * segY;
float dist = std::sqrt((clickX - projX) * (clickX - projX) + (clickY - projY) * (clickY - projY));
return dist <= tolerancePx;
}
bool ActorInstance::GetBoneWorldTransform(const std::string& boneName, float* outWorld16) const {
if (!m_model || !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;
}
float actorWorld[16];
MakeTransformMatrix(m_yaw, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, actorWorld);
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 += localBone[r * 4 + k] * actorWorld[k * 4 + c];
}
outWorld16[r * 4 + c] = sum;
}
}
return true;
}
bool ActorInstance::GetBonePosition(const std::string& boneName, float& outX, float& outY, float& outZ) const {
float mat[16];
if (GetBoneWorldTransform(boneName, mat)) {
outX = mat[12];
outY = mat[13];
outZ = mat[14];
return true;
}
return false;
}
bool ActorInstance::SetPolymorph(uint32_t mobVnum) {
std::string mobModel = CRenderTarget::ResolveNpcModel(mobVnum);
if (mobModel.empty() || !std::filesystem::exists(ResolvePath(mobModel))) {
return false;
}
if (!m_isPolymorph) {
m_origModelPath = m_modelPath;
m_origScale = m_scale;
m_origModelYOffset = m_modelYOffset;
m_origMotions = m_motionPaths;
}
if (!SetModel(mobModel)) return false;
std::filesystem::path p(ResolvePath(mobModel));
std::string parentDir = p.parent_path().string() + "/";
m_motionPaths.clear();
auto tryRegister = [&](MotionType mt, const std::string& name) {
std::string cand = parentDir + name;
if (std::filesystem::exists(cand)) {
RegisterMotion(mt, cand);
}
};
tryRegister(MotionType::Wait, "00.gr2");
tryRegister(MotionType::Walk, "02.gr2");
tryRegister(MotionType::Run, "03.gr2");
tryRegister(MotionType::Attack, "20.gr2");
tryRegister(MotionType::ComboAttack1, "20.gr2");
tryRegister(MotionType::ComboAttack2, "20_1.gr2");
tryRegister(MotionType::Damage, "30.gr2");
tryRegister(MotionType::Dead, "31.gr2");
PlayMotion(MotionType::Wait, true);
m_isPolymorph = true;
m_polymorphVnum = mobVnum;
return true;
}
void ActorInstance::ClearPolymorph() {
if (!m_isPolymorph) return;
if (!m_origModelPath.empty()) {
SetModel(m_origModelPath);
}
m_scale = m_origScale;
m_modelYOffset = m_origModelYOffset;
m_motionPaths = m_origMotions;
PlayMotion(MotionType::Wait, true);
m_isPolymorph = false;
m_polymorphVnum = 0;
}
void ActorInstance::SetWeaponShining(int grade, const std::string& effectPath) {
m_weaponShining = grade;
m_weaponShiningPath = effectPath;
}
void ActorInstance::SetArmorShining(int grade, const std::string& effectPath) {
m_armorShining = grade;
m_armorShiningPath = effectPath;
}
void ActorInstance::SetAcceShining(int grade, const std::string& effectPath) {
m_acceShining = grade;
m_acceShiningPath = effectPath;
}
void ActorInstance::ClearShining() {
m_weaponShining = 0;
m_weaponShiningPath.clear();
m_armorShining = 0;
m_armorShiningPath.clear();
m_acceShining = 0;
m_acceShiningPath.clear();
}
} // namespace ava2