From bfd42bd7769b7a70c60dca351acbe4c4c3ad43d5 Mon Sep 17 00:00:00 2001 From: shenlei Date: Mon, 12 Oct 2026 17:56:41 +0900 Subject: [PATCH] Swap actor body to _lod_ meshes by camera distance Port CGrannyLODController level selection: _lod_01.._03 are queued {lod_03, lod_02, lod_01, main}, loaded lazily, and chosen from the camera-target/camera distance bands (actors) or the building factor. Parts, skins and the current motion follow the drawn instance. Shipped LODs that drop an attaching bone in use (lion2_lod_02/03 lose "saddle", shaman_miyeom_lod_* lose equip_left/right) stay on PART_MAIN, and bone queries fall back to PART_MAIN for bones a LOD lacks. Weapon item LODs are not ported. Co-Authored-By: Claude Opus 5.5 --- src/eter_render/ActorInstance.cpp | 132 ++++++++++++++++++++++++++---- src/eter_render/ActorInstance.h | 20 ++++- tests/ava2_render_3d_test.cpp | 37 +++++++-- 3 files changed, 167 insertions(+), 22 deletions(-) diff --git a/src/eter_render/ActorInstance.cpp b/src/eter_render/ActorInstance.cpp index 929af39b..bb1b8b40 100644 --- a/src/eter_render/ActorInstance.cpp +++ b/src/eter_render/ActorInstance.cpp @@ -52,32 +52,102 @@ void ActorInstance::SetMainModel(std::shared_ptr model, const auto it = m_motionPaths.find(m_currentMotion); if (it != m_motionPaths.end()) { std::string resolved = ResolvePath(it->second); - if (m_model->LoadExternalAnimation(resolved)) + 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. +// 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()) { - m_model->AttachPart(slot.model); + target->AttachPart(slot.model); continue; } - m_model->AttachModel(slot.bone, slot.model); + target->AttachModel(slot.bone, slot.model); if (part == RaceData::PART_SASH) { - m_model->SetAttachmentAnimated(slot.bone, true); - if (m_hasSashScale) m_model->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]); + target->SetAttachmentAnimated(slot.bone, true); + if (m_hasSashScale) target->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]); } } } +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; + } + 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(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) { @@ -94,6 +164,8 @@ bool ActorInstance::SetRace(uint32_t race) { 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). @@ -127,17 +199,21 @@ void ActorInstance::SetShape(uint32_t shape, float specular) { const std::string& file = pkShape->model.empty() ? raceData->GetBaseModelFileName() : pkShape->model; // The _lod_01.._03 LOD things are not ported: LOD 0 always draws. 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 : pkShape->skins) model->SetSkin(skin.srcFileName, skin.dstFileName); + 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); } @@ -211,11 +287,22 @@ void ActorInstance::ResetLodModel() { 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; - std::error_code error; - m_hasLodModel = std::filesystem::is_regular_file(ResolvePath((hasExtension ? m_modelPath.substr(0, dot) : m_modelPath) + "_lod_01.gr2"), error); + 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 @@ -233,6 +320,7 @@ bool ActorInstance::SetModel(const std::string& modelPath) { m_model = Gr2ModelInstance::Load(resolved); if (!m_model) return false; m_modelPath = modelPath; + m_mainSkins.clear(); ResetLodModel(); return true; } @@ -297,10 +385,12 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) { 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 || @@ -608,7 +698,7 @@ std::vector ActorInstance::BuildDrawCommands(const float* worldOve 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 = m_model->BuildDrawCommands(PoseTime(), worldOverride ? worldOverride : world); + auto draws = DrawModel()->BuildDrawCommands(PoseTime(), worldOverride ? worldOverride : world); // Shining system (ENABLE_SHINING_SYSTEM): weapon aura / glow if (m_weaponShining > 0) { @@ -686,24 +776,36 @@ std::vector ActorInstance::BuildDrawCommands(const float* worldOve 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 factor = std::clamp(m_lodDistance - std::sqrt(dx * dx + dy * dy + dz * dz), 0.0f, m_lodDistance); + 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((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(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(m_lodLocalTime * 120.0f); const uint32_t step = 120 / m_lodAniFps; - if (m_poseTimeValid && m_poseModel == m_model.get() && m_animTime >= m_poseAnimTime + 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 = m_model.get(); + m_poseModel = DrawModel(); m_poseTimeValid = step > 1; // full rate: always draw the current time } @@ -750,7 +852,9 @@ bool ActorInstance::HitTestScreen(float clickX, float clickY, const Gr2SceneRend bool ActorInstance::GetBoneWorldTransform(const std::string& boneName, float* outWorld16) const { if (!m_model || !outWorld16) return false; float localBone[16]; - if (!m_model->GetBoneWorldTransform(boneName, localBone, PoseTime())) { + // 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 diff --git a/src/eter_render/ActorInstance.h b/src/eter_render/ActorInstance.h index 7209b8b5..b1d81ece 100644 --- a/src/eter_render/ActorInstance.h +++ b/src/eter_render/ActorInstance.h @@ -214,6 +214,10 @@ public: // _lod_ models far from the camera sample their pose at a reduced animation FPS (Y-up world). void UpdateLODLevel(float eyeX, float eyeY, float eyeZ, float targetX, float targetZ); uint32_t GetLODAniFPS() const { return m_lodAniFps; } + // Index into the CGrannyLODController queue {_lod_N .. _lod_01, main}; the last entry is the main model. + uint32_t GetLODLevel() const { return m_lodLevel; } + uint32_t GetLODCount() const { return uint32_t(m_lodPaths.size()) + 1; } + Gr2ModelInstance* GetDrawModel() { return DrawModel(); } Gr2ModelInstance* GetModel() { return m_model.get(); } const std::string& GetModelPath() const { return m_modelPath; } @@ -223,6 +227,10 @@ private: std::shared_ptr LoadPartModel(const std::string& path) const; void SetMainModel(std::shared_ptr model, const std::string& path); void ResetLodModel(); + Gr2ModelInstance* DrawModel() const; + void SetLodLevel(uint32_t level); + bool LodHasAttachBones(const Gr2ModelInstance& lod) const; + void SyncLodMotion(); void AttachWeaponPart(uint32_t part, const SPartItem& item); void RebindParts(); @@ -246,8 +254,18 @@ private: mutable const Gr2ModelInstance* m_boundsModel = nullptr; mutable float m_boundsRadius = 500.f; std::string m_modelPath; - // LOD animation rate (CGrannyLODController); the meshes of _lod_01.._03 are still not ported. + // CGrannyLODController: _lod_01.._03 instances (queue order, coarsest first), animation rate. float PoseTime() const { return m_poseTimeValid ? m_poseAnimTime : m_animTime; } + struct SLodModel { + std::shared_ptr model; + std::string motionFile; // external animation currently loaded on this instance + bool motionLoop = true; + }; + std::vector m_lodPaths; // queue order: _lod_N first + std::vector m_lodModels; // loaded on first use, same order as m_lodPaths + uint32_t m_lodLevel = 0; // == m_lodPaths.size(): main model + std::vector> m_mainSkins; // shape skins, applied to every LOD + std::string m_motionFile; // resolved animation on m_model bool m_hasLodModel = false; float m_lodDistance = 5000.0f; // LODDISTANCE_ACTOR, LODDISTANCE_BUILDING for size >= 500 float m_lodLocalTime = 0.0f; diff --git a/tests/ava2_render_3d_test.cpp b/tests/ava2_render_3d_test.cpp index c7c84366..5cc7641c 100644 --- a/tests/ava2_render_3d_test.cpp +++ b/tests/ava2_render_3d_test.cpp @@ -829,31 +829,54 @@ int main(int argc, char** argv) { assert(!actor.IsVisible(cullCamera.GetViewMatrix(),cullCamera.GetProjMatrix())); assert(actor.GetModel()->GetImpl()->GetPoseEvaluationCount()==poseBeforeCull); - // CGrannyLODController: warrior_assasin1 has _lod_ models, so far from the camera it animates at - // ANIFPS_MIN (pose re-sampled every 4/120 s) and near the camera target at full rate. + // CGrannyLODController: warrior_assasin1 has _lod_01.._03, queued {lod_03, lod_02, lod_01, main}. + // Far from the camera it draws the coarsest LOD at ANIFPS_MIN (pose re-sampled every 4/120 s); + // near the camera target it draws the main model at full rate. actor.SetPosition(0,0,0); + assert(actor.GetLODCount()==4); actor.UpdateLODLevel(0,200,-300,0,0); - assert(actor.GetLODAniFPS()==120); + assert(actor.GetLODAniFPS()==120 && actor.GetLODLevel()==3 && actor.GetDrawModel()==actor.GetModel()); + actor.UpdateLODLevel(0,200,-1000,2000,0); + assert(actor.GetLODLevel()==2 && actor.GetDrawModel()->GetFilePath().find("_lod_01.gr2")!=std::string::npos); + actor.UpdateLODLevel(0,200,-2000,2000,0); + assert(actor.GetLODLevel()==1 && actor.GetDrawModel()->GetFilePath().find("_lod_02.gr2")!=std::string::npos); actor.UpdateLODLevel(0,200,-4900,2000,0); - assert(actor.GetLODAniFPS()==30); + assert(actor.GetLODAniFPS()==30 && actor.GetLODLevel()==0); + assert(actor.GetDrawModel()->GetFilePath().find("_lod_03.gr2")!=std::string::npos); + assert(!actor.BuildDrawCommands().empty()); float lodBone[16]; assert(actor.GetBoneWorldTransform("Bip01 Spine",lodBone)); - const auto poseBeforeLod=actor.GetModel()->GetImpl()->GetPoseEvaluationCount(); + const auto poseBeforeLod=actor.GetDrawModel()->GetImpl()->GetPoseEvaluationCount(); for(int frame=0;frame<24;++frame){ actor.Update(1.0f/60.0f,&terrain); actor.UpdateLODLevel(0,200,-4900,2000,0); assert(actor.GetBoneWorldTransform("Bip01 Spine",lodBone)); } - const auto farEvaluations=actor.GetModel()->GetImpl()->GetPoseEvaluationCount()-poseBeforeLod; + const auto farEvaluations=actor.GetDrawModel()->GetImpl()->GetPoseEvaluationCount()-poseBeforeLod; assert(farEvaluations>=10 && farEvaluations<=14 && "30 FPS animation over 0.4 s"); + actor.UpdateLODLevel(0,200,-300,0,0); + assert(actor.GetDrawModel()==actor.GetModel()); + const auto poseNear=actor.GetModel()->GetImpl()->GetPoseEvaluationCount(); for(int frame=0;frame<24;++frame){ actor.Update(1.0f/60.0f,&terrain); actor.UpdateLODLevel(0,200,-300,0,0); assert(actor.GetBoneWorldTransform("Bip01 Spine",lodBone)); } - assert(actor.GetModel()->GetImpl()->GetPoseEvaluationCount()-poseBeforeLod-farEvaluations==24); + assert(actor.GetModel()->GetImpl()->GetPoseEvaluationCount()-poseNear==24); assert(actor.IsVisible(nullptr,nullptr)); + // lion2_lod_02/03 dropped the "saddle" bone the rider attaches to: those levels stay on PART_MAIN. + { + ava2::ActorInstance mount; + assert(mount.SetModel("ymir work/npc/lion_2/lion2.gr2") && mount.GetLODCount()==4); + mount.UpdateLODLevel(0,200,-1000,2000,0); + assert(mount.GetLODLevel()==2 && mount.GetDrawModel()!=mount.GetModel()); + mount.UpdateLODLevel(0,200,-4900,2000,0); + assert(mount.GetLODLevel()==3 && mount.GetDrawModel()==mount.GetModel()); + float saddle[16]; + assert(mount.GetBoneWorldTransform("saddle",saddle)); + } + // Test movement driving actor.SetPosition(0.0f, 0.0f, 0.0f); actor.MoveInDirection(90.0f, 0.2f, &terrain); // Move East