Initialize shared Metin2 SDK with rendering optimizations and tests

This commit is contained in:
shen
2026-10-11 17:52:55 -07:00
commit 86759bb726
147 changed files with 27272 additions and 0 deletions
+764
View File
@@ -0,0 +1,764 @@
#include <gr2_render/gr2_render.h>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <filesystem>
#include <list>
#include <mutex>
namespace gr2_render {
namespace {
// Share immutable parsed assets, never mutable animation/attachment instances.
// Bound strong retention by entry count and source bytes; live instances keep ownership.
std::shared_ptr<const gr2::File> LoadCachedFile(const std::string& path, gr2::LoadError* err) {
struct Entry { std::string key; uintmax_t bytes; std::filesystem::file_time_type stamp;
std::shared_ptr<const gr2::File> file; };
static std::list<Entry> cache;
static std::mutex mutex;
std::error_code ec;
auto canonical = std::filesystem::weakly_canonical(path, ec);
if (ec) return {};
auto stamp = std::filesystem::last_write_time(canonical, ec);
if (ec) return {};
auto bytes = std::filesystem::file_size(canonical, ec);
if (ec) return {};
const auto key = canonical.string();
std::lock_guard lock(mutex);
for (auto it = cache.begin(); it != cache.end(); ++it) {
if (it->key != key) continue;
if (it->stamp == stamp && it->bytes == bytes) {
auto file = it->file; cache.splice(cache.begin(), cache, it); return file;
}
cache.erase(it); break;
}
auto parsed = gr2::File::load_path(key, err);
if (!parsed) return {};
auto file = std::make_shared<const gr2::File>(std::move(*parsed));
cache.push_front({key, bytes, stamp, file});
uintmax_t total = 0; for (const auto& entry : cache) total += entry.bytes;
while (cache.size() > 64 || (total > 128u*1024u*1024u && cache.size() > 1)) {
total -= cache.back().bytes; cache.pop_back();
}
return file;
}
Gr2MeshDraw ShareGpuMesh(Gr2MeshDraw source) {
Gr2MeshDraw command=source;
command.positions={};command.normals={};command.uv0={};command.diffuse={};command.indices={};
command.bone_indices={};command.bone_weights={};
source.bone_matrices={};
command.geometry=std::make_shared<const Gr2MeshDraw>(std::move(source));
return command;
}
void UpdateGpuDraws(std::vector<Gr2MeshDraw>& draws,const float* world,const std::vector<gr2::Mat4>& palette) {
for(auto& draw:draws){std::copy_n(world,16,draw.world);draw.bone_matrices.clear();
if(draw.gpu_skinning)for(const auto& matrix:palette)draw.bone_matrices.insert(draw.bone_matrices.end(),matrix.begin(),matrix.end());
}
}
inline void MultiplyMat4(const float* a, const float* b, float* out) {
float r[16];
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
r[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] +
a[i * 4 + 1] * b[1 * 4 + j] +
a[i * 4 + 2] * b[2 * 4 + j] +
a[i * 4 + 3] * b[3 * 4 + j];
}
}
for (int k = 0; k < 16; ++k) out[k] = r[k];
}
// Basis change from Granny (Z-up, Y-forward) to Engine (Y-up, Z-forward): (x, y, z) -> (x, z, -y)
const float R_GRANNY_TO_ENGINE[16] = {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
std::string SkinKey(std::string path) {
for (auto& c : path) {
if (c == '\\') c = '/';
else if (static_cast<unsigned char>(c) < 128) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return path;
}
} // namespace
std::unique_ptr<Gr2ModelInstance> Gr2ModelInstance::Load(const std::string& filepath) {
gr2::LoadError err;
auto file_opt = LoadCachedFile(filepath, &err);
if (!file_opt) {
std::cerr << "Gr2ModelInstance::Load failed: [" << err.stage << "] " << err.message << " for " << filepath << std::endl;
return nullptr;
}
auto instance = std::make_unique<Gr2ModelInstance>();
instance->m_file = file_opt;
instance->m_filepath = filepath;
return instance;
}
std::unique_ptr<Gr2ModelInstance> Gr2ModelInstance::LoadFromMemory(const uint8_t* data, size_t size, const std::string& name) {
if (!data || size == 0) return nullptr;
gr2::LoadError err;
auto file_opt = gr2::File::load(data, size, &err);
if (!file_opt) {
std::cerr << "Gr2ModelInstance::LoadFromMemory failed: [" << err.stage << "] " << err.message << std::endl;
return nullptr;
}
auto instance = std::make_unique<Gr2ModelInstance>();
instance->m_file = std::make_shared<const gr2::File>(std::move(*file_opt));
instance->m_filepath = name;
return instance;
}
bool Gr2ModelInstance::LoadExternalAnimation(const std::string& anim_filepath) {
gr2::LoadError err;
auto file_opt = LoadCachedFile(anim_filepath, &err);
if (!file_opt) {
std::cerr << "Gr2ModelInstance::LoadExternalAnimation failed: [" << err.stage << "] " << err.message << " for " << anim_filepath << std::endl;
return false;
}
if (file_opt->file_info().animations.empty()) {
std::cerr << "Gr2ModelInstance::LoadExternalAnimation: no animations in " << anim_filepath << std::endl;
return false;
}
m_anim_file = file_opt;
m_poseValid = false;
m_anim_filepath = anim_filepath;
return true;
}
bool Gr2ModelInstance::LoadExternalAnimationFromMemory(const uint8_t* data, size_t size) {
if (!data || size == 0) return false;
gr2::LoadError err;
auto file_opt = gr2::File::load(data, size, &err);
if (!file_opt) {
std::cerr << "Gr2ModelInstance::LoadExternalAnimationFromMemory failed: [" << err.stage << "] " << err.message << std::endl;
return false;
}
if (file_opt->file_info().animations.empty()) {
std::cerr << "Gr2ModelInstance::LoadExternalAnimationFromMemory: no animations in buffer" << std::endl;
return false;
}
m_anim_file = std::make_shared<const gr2::File>(std::move(*file_opt));
m_poseValid = false;
m_anim_filepath = "memory";
return true;
}
float Gr2ModelInstance::GetAnimationDuration() const {
if (m_anim_file && !m_anim_file->file_info().animations.empty()) {
return m_anim_file->file_info().animations[0].duration;
}
if (m_file && !m_file->file_info().animations.empty()) {
return m_file->file_info().animations[0].duration;
}
return 0.0f;
}
void Gr2ModelInstance::EvaluatePose(float time) const {
if (!m_file || m_file->file_info().skeletons.empty()) return;
const auto& sk = m_file->file_info().skeletons[0];
const gr2::Animation* anim = nullptr;
if (m_anim_file && !m_anim_file->file_info().animations.empty()) anim = &m_anim_file->file_info().animations[0];
else if (!m_file->file_info().animations.empty()) anim = &m_file->file_info().animations[0];
const float keyTime = time >= 0 && anim ? time : -1;
if (m_poseValid && keyTime == m_poseTime && anim == m_poseAnimation) return;
if (anim != m_poseAnimation || !m_poseValid) {
m_trackBones.clear();
if (anim) {
std::unordered_map<std::string, int> bones;
for (size_t i=0; i<sk.bones.size(); ++i) bones.emplace(sk.bones[i].name, int(i));
for (const auto& track : anim->tracks) {
auto it=bones.find(track.bone_name);
m_trackBones.push_back(it==bones.end() ? -1 : it->second);
}
}
}
m_localPose.resize(sk.bones.size());
for (size_t i=0; i<sk.bones.size(); ++i) m_localPose[i]=sk.bones[i].local_transform;
if (keyTime >= 0) {
anim->sample_local(time, m_trackPose);
for (size_t i=0; i<m_trackPose.size() && i<m_trackBones.size(); ++i)
if (m_trackBones[i]>=0) m_localPose[m_trackBones[i]]=m_trackPose[i];
}
m_worldPose.resize(sk.bones.size()); m_skinPose.resize(sk.bones.size());
const gr2::Mat4 identity{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
for (size_t i=0; i<sk.bones.size(); ++i) {
const int parent=sk.bones[i].parent;
const auto& root=keyTime >= 0 ? identity : sk.initial_placement;
const auto& parentWorld=parent<0 || size_t(parent)>=i ? root : m_worldPose[parent];
MultiplyMat4(m_localPose[i].data(), parentWorld.data(), m_worldPose[i].data());
MultiplyMat4(sk.bones[i].inverse_world.data(), m_worldPose[i].data(), m_skinPose[i].data());
}
m_poseAnimation=anim; m_poseTime=keyTime; m_poseValid=true; ++m_poseEvaluations;
}
bool Gr2ModelInstance::GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time) const {
if (!m_file || m_file->file_info().skeletons.empty() || !out_matrix) return false;
const auto& sk = m_file->file_info().skeletons[0];
int target_bone = -1;
for (size_t i = 0; i < sk.bones.size(); ++i) {
if (sk.bones[i].name == bone_name) {
target_bone = static_cast<int>(i);
break;
}
}
if (target_bone < 0) return false;
EvaluatePose(animation_time);
const auto& world_pose = m_worldPose;
if (target_bone >= 0 && target_bone < static_cast<int>(world_pose.size())) {
std::copy(world_pose[target_bone].data(), world_pose[target_bone].data() + 16, out_matrix);
return true;
}
return false;
}
void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix) {
if (!attachment) return;
for (auto& existing : m_attached_models) {
if (existing.bone_name == bone_name) {
existing.model = attachment;
if (offset_matrix) {
std::copy(offset_matrix, offset_matrix + 16, existing.offset);
} else {
for (int i = 0; i < 16; ++i) existing.offset[i] = (i % 5 == 0) ? 1.0f : 0.0f;
}
return;
}
}
AttachedModel am;
am.bone_name = bone_name;
am.model = attachment;
if (offset_matrix) {
std::copy(offset_matrix, offset_matrix + 16, am.offset);
} else {
for (int i = 0; i < 16; ++i) am.offset[i] = (i % 5 == 0) ? 1.0f : 0.0f;
}
m_attached_models.push_back(std::move(am));
}
void Gr2ModelInstance::AttachPart(std::shared_ptr<Gr2ModelInstance> part) {
if (part) m_attached_parts.push_back(part);
}
void Gr2ModelInstance::DetachAll() {
m_attached_models.clear();
m_attached_parts.clear();
}
void Gr2ModelInstance::DetachModel(const std::string& bone_name) {
m_attached_models.erase(std::remove_if(m_attached_models.begin(), m_attached_models.end(),
[&](const AttachedModel& am) { return am.bone_name == bone_name; }), m_attached_models.end());
}
void Gr2ModelInstance::DetachPart(const std::shared_ptr<Gr2ModelInstance>& part) {
m_attached_parts.erase(std::remove(m_attached_parts.begin(), m_attached_parts.end(), part), m_attached_parts.end());
}
void Gr2ModelInstance::SetAttachmentAnimated(const std::string& bone_name, bool animated) {
for (auto& am : m_attached_models) {
if (am.bone_name == bone_name) am.animated = animated;
}
}
void Gr2ModelInstance::SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz) {
for (auto& am : m_attached_models) {
if (am.bone_name != bone_name) continue;
am.scaled = true;
am.scale[0] = sx; am.scale[1] = sy; am.scale[2] = sz;
}
}
void Gr2ModelInstance::SetSkin(const std::string& src_file_name, const std::string& dst_file_name) {
m_skins[SkinKey(src_file_name)] = dst_file_name;
}
void Gr2ModelInstance::ApplySkins(std::vector<Gr2MeshDraw>& draws, size_t first) const {
if (m_skins.empty()) return;
for (size_t i = first; i < draws.size(); ++i) {
auto it = m_skins.find(SkinKey(draws[i].texture0));
if (it != m_skins.end()) draws[i].texture0 = it->second;
}
}
std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const std::vector<gr2::Mat4>& skin_matrices,
const float* world_matrix,
const gr2::Skeleton* parent_skeleton, bool hardwareSkinning) {
std::vector<Gr2MeshDraw> draws;
if (!m_file) return draws;
const auto& info = m_file->file_info();
bool has_skin = !skin_matrices.empty();
std::vector<gr2::Mat4> part_skin_matrices = skin_matrices;
// Map this model's skeleton bones to parent skeleton bones by name if a parent skeleton is provided
std::vector<int> part_to_parent_bone_map;
if (parent_skeleton && !info.skeletons.empty()) {
const auto& my_skel = info.skeletons[0];
std::vector<gr2::Mat4> parent_bind_world, parent_bind_skin;
gr2::bind_pose(*parent_skeleton, parent_bind_world, parent_bind_skin);
part_to_parent_bone_map.resize(my_skel.bones.size(), -1);
for (size_t b = 0; b < my_skel.bones.size(); ++b) {
const std::string& bname = my_skel.bones[b].name;
for (size_t pb = 0; pb < parent_skeleton->bones.size(); ++pb) {
if (parent_skeleton->bones[pb].name == bname) {
part_to_parent_bone_map[b] = static_cast<int>(pb);
// A shared animation pose does not imply shared inverse bind matrices.
// Recover the parent's animated world pose, then skin with THIS part's
// inverse bind pose (hair exports can have a different rest skeleton).
if (pb < skin_matrices.size()) {
gr2::Mat4 animated_world;
MultiplyMat4(parent_bind_world[pb].data(), skin_matrices[pb].data(), animated_world.data());
MultiplyMat4(my_skel.bones[b].inverse_world.data(), animated_world.data(), part_skin_matrices[pb].data());
}
break;
}
}
}
}
hardwareSkinning = hardwareSkinning && part_skin_matrices.size()<=128;
float cachedWorld[16];
if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld);
else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld);
if(m_gpuPartParent!=parent_skeleton || m_gpuPartPaletteSize!=part_skin_matrices.size()){m_gpuParts.clear();m_gpuPartParent=parent_skeleton;m_gpuPartPaletteSize=part_skin_matrices.size();}
if(hardwareSkinning && !m_gpuParts.empty()) {
draws=m_gpuParts;UpdateGpuDraws(draws,cachedWorld,part_skin_matrices);
} else {
for (const auto& mesh : info.meshes) {
std::vector<float> skinned_positions;
std::vector<float> skinned_normals;
std::vector<float> uvs;
std::vector<uint8_t> bone_indices;
std::vector<float> bone_weights;
skinned_positions.reserve(mesh.vertices.size() * 3);
skinned_normals.reserve(mesh.vertices.size() * 3);
uvs.reserve(mesh.vertices.size() * 2);
bone_indices.reserve(mesh.vertices.size() * 4);
bone_weights.reserve(mesh.vertices.size() * 4);
// Precompute mapped bone bindings for this mesh
std::vector<int> effective_bone_bindings(mesh.bone_bindings.size());
for (size_t i = 0; i < mesh.bone_bindings.size(); ++i) {
int raw_bone = mesh.bone_bindings[i];
if (!part_to_parent_bone_map.empty() && raw_bone >= 0 && raw_bone < static_cast<int>(part_to_parent_bone_map.size())) {
effective_bone_bindings[i] = part_to_parent_bone_map[raw_bone];
} else {
effective_bone_bindings[i] = raw_bone;
}
}
bool is_rigid_single_bone = (mesh.bone_bindings.size() == 1);
int single_bone_target = is_rigid_single_bone ? effective_bone_bindings[0] : -1;
for (const auto& v : mesh.vertices) {
float px = 0.0f, py = 0.0f, pz = 0.0f;
float nx = 0.0f, ny = 0.0f, nz = 0.0f;
float total_w = 0.0f;
if (has_skin) {
if (is_rigid_single_bone && v.bone_weight[0] == 0) {
// Rigid mesh attached 100% to a single bone (e.g. warrior face, hair, helmet)
if (single_bone_target >= 0 && single_bone_target < static_cast<int>(skin_matrices.size())) {
const auto& M = part_skin_matrices[single_bone_target];
px = v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12];
py = v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13];
pz = v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14];
nx = v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8];
ny = v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9];
nz = v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10];
total_w = 1.0f;
bone_indices.push_back(static_cast<uint8_t>(single_bone_target));
bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0);
bone_weights.push_back(1.0f);
bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f);
}
} else if (v.bone_weight[0] > 0) {
float w0 = v.bone_weight[0] / 255.0f;
float w1 = v.bone_weight[1] / 255.0f;
float w2 = v.bone_weight[2] / 255.0f;
float w3 = v.bone_weight[3] / 255.0f;
for (int b = 0; b < 4; ++b) {
if (v.bone_weight[b] == 0) continue;
float w = v.bone_weight[b] / 255.0f;
int local_slot = v.bone_index[b];
int sk_bone = (local_slot < static_cast<int>(effective_bone_bindings.size())) ? effective_bone_bindings[local_slot] : local_slot;
if (sk_bone >= 0 && sk_bone < static_cast<int>(skin_matrices.size())) {
if(hardwareSkinning){total_w+=w;continue;}
const auto& M = part_skin_matrices[sk_bone];
px += (v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12]) * w;
py += (v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13]) * w;
pz += (v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]) * w;
nx += (v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8]) * w;
ny += (v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9]) * w;
nz += (v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10]) * w;
total_w += w;
}
}
int b0 = v.bone_index[0] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[0]] : v.bone_index[0];
int b1 = v.bone_index[1] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[1]] : v.bone_index[1];
int b2 = v.bone_index[2] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[2]] : v.bone_index[2];
int b3 = v.bone_index[3] < effective_bone_bindings.size() ? effective_bone_bindings[v.bone_index[3]] : v.bone_index[3];
bone_indices.push_back(hardwareSkinning && (b0<0 || size_t(b0)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b0));
bone_indices.push_back(hardwareSkinning && (b1<0 || size_t(b1)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b1));
bone_indices.push_back(hardwareSkinning && (b2<0 || size_t(b2)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b2));
bone_indices.push_back(hardwareSkinning && (b3<0 || size_t(b3)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b3));
bone_weights.push_back(w0); bone_weights.push_back(w1); bone_weights.push_back(w2); bone_weights.push_back(w3);
}
}
if (total_w < 1e-4f) {
px = v.pos[0]; py = v.pos[1]; pz = v.pos[2];
nx = v.normal[0]; ny = v.normal[1]; nz = v.normal[2];
if (bone_indices.size() < (skinned_positions.size() / 3 + 1) * 4) {
bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0);
bone_weights.push_back(hardwareSkinning ? 0.f : 1.f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f);
}
}
if(hardwareSkinning){px=v.pos[0];py=v.pos[1];pz=v.pos[2];nx=v.normal[0];ny=v.normal[1];nz=v.normal[2];}
skinned_positions.push_back(px);
skinned_positions.push_back(py);
skinned_positions.push_back(pz);
skinned_normals.push_back(nx);
skinned_normals.push_back(ny);
skinned_normals.push_back(nz);
uvs.push_back(v.uv0[0]);
uvs.push_back(v.uv0[1]);
}
float effective_world[16];
if (world_matrix) {
MultiplyMat4(R_GRANNY_TO_ENGINE, world_matrix, effective_world);
} else {
std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world);
}
// Pack skin matrices for GPU skinning
std::vector<float> bone_mats_flat;
bone_mats_flat.reserve(skin_matrices.size() * 16);
for (const auto& sm : part_skin_matrices) {
for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]);
}
if (mesh.tri_groups.empty()) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.positions = skinned_positions;
draw.normals = skinned_normals;
draw.uv0 = uvs;
draw.indices = mesh.indices;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
if (!mesh.material_textures.empty())
draw.texture0 = mesh.material_textures[0];
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
} else {
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.positions = skinned_positions;
draw.normals = skinned_normals;
draw.uv0 = uvs;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
if (start_idx + count_idx <= mesh.indices.size()) {
draw.indices.assign(mesh.indices.begin() + start_idx,
mesh.indices.begin() + start_idx + count_idx);
}
if (group.material_index >= 0 && group.material_index < static_cast<int>(mesh.material_textures.size())) {
draw.texture0 = mesh.material_textures[group.material_index];
}
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
}
}
}
if(hardwareSkinning) {
for(auto& draw:draws){draw.gpu_skinning=!part_skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));}
m_gpuParts=draws;
}
}
ApplySkins(draws, 0);
return draws;
}
std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_time, const float* world_matrix, bool hardwareSkinning) {
std::vector<Gr2MeshDraw> draws;
if (!m_file) return draws;
const auto& info = m_file->file_info();
EvaluatePose(animation_time);
const auto& world_pose = m_worldPose;
const auto& skin_matrices = m_skinPose;
bool has_skeleton = !info.skeletons.empty();
// 1. Build main model draw commands
hardwareSkinning = hardwareSkinning && skin_matrices.size()<=128;
float cachedWorld[16];
if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld);
else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld);
if(hardwareSkinning && !m_gpuMain.empty()) {
draws=m_gpuMain;UpdateGpuDraws(draws,cachedWorld,skin_matrices);
} else {
for (const auto& mesh : info.meshes) {
std::vector<float> skinned_positions;
std::vector<float> skinned_normals;
std::vector<float> uvs;
std::vector<uint8_t> bone_indices;
std::vector<float> bone_weights;
skinned_positions.reserve(mesh.vertices.size() * 3);
skinned_normals.reserve(mesh.vertices.size() * 3);
uvs.reserve(mesh.vertices.size() * 2);
bone_indices.reserve(mesh.vertices.size() * 4);
bone_weights.reserve(mesh.vertices.size() * 4);
for (const auto& v : mesh.vertices) {
float px = 0.0f, py = 0.0f, pz = 0.0f;
float nx = 0.0f, ny = 0.0f, nz = 0.0f;
float total_w = 0.0f;
if (has_skeleton && !skin_matrices.empty() && (v.bone_weight[0] > 0)) {
float w0 = v.bone_weight[0] / 255.0f;
float w1 = v.bone_weight[1] / 255.0f;
float w2 = v.bone_weight[2] / 255.0f;
float w3 = v.bone_weight[3] / 255.0f;
for (int b = 0; b < 4; ++b) {
if (v.bone_weight[b] == 0) continue;
float w = v.bone_weight[b] / 255.0f;
int local_slot = v.bone_index[b];
int sk_bone = (local_slot < static_cast<int>(mesh.bone_bindings.size())) ? mesh.bone_bindings[local_slot] : local_slot;
if (sk_bone >= 0 && sk_bone < static_cast<int>(skin_matrices.size())) {
if(hardwareSkinning){total_w+=w;continue;}
const auto& M = skin_matrices[sk_bone];
px += (v.pos[0] * M[0] + v.pos[1] * M[4] + v.pos[2] * M[8] + M[12]) * w;
py += (v.pos[0] * M[1] + v.pos[1] * M[5] + v.pos[2] * M[9] + M[13]) * w;
pz += (v.pos[0] * M[2] + v.pos[1] * M[6] + v.pos[2] * M[10] + M[14]) * w;
nx += (v.normal[0] * M[0] + v.normal[1] * M[4] + v.normal[2] * M[8]) * w;
ny += (v.normal[0] * M[1] + v.normal[1] * M[5] + v.normal[2] * M[9]) * w;
nz += (v.normal[0] * M[2] + v.normal[1] * M[6] + v.normal[2] * M[10]) * w;
total_w += w;
}
}
int b0 = v.bone_index[0] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[0]] : v.bone_index[0];
int b1 = v.bone_index[1] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[1]] : v.bone_index[1];
int b2 = v.bone_index[2] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[2]] : v.bone_index[2];
int b3 = v.bone_index[3] < mesh.bone_bindings.size() ? mesh.bone_bindings[v.bone_index[3]] : v.bone_index[3];
bone_indices.push_back(hardwareSkinning && (b0<0 || size_t(b0)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b0));
bone_indices.push_back(hardwareSkinning && (b1<0 || size_t(b1)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b1));
bone_indices.push_back(hardwareSkinning && (b2<0 || size_t(b2)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b2));
bone_indices.push_back(hardwareSkinning && (b3<0 || size_t(b3)>=skin_matrices.size()) ? uint8_t(255) : static_cast<uint8_t>(b3));
bone_weights.push_back(w0); bone_weights.push_back(w1); bone_weights.push_back(w2); bone_weights.push_back(w3);
}
if (total_w < 1e-4f) {
px = v.pos[0]; py = v.pos[1]; pz = v.pos[2];
nx = v.normal[0]; ny = v.normal[1]; nz = v.normal[2];
if (bone_indices.size() < (skinned_positions.size() / 3 + 1) * 4) {
bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0); bone_indices.push_back(0);
bone_weights.push_back(hardwareSkinning ? 0.f : 1.f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f); bone_weights.push_back(0.0f);
}
}
if(hardwareSkinning){px=v.pos[0];py=v.pos[1];pz=v.pos[2];nx=v.normal[0];ny=v.normal[1];nz=v.normal[2];}
skinned_positions.push_back(px);
skinned_positions.push_back(py);
skinned_positions.push_back(pz);
skinned_normals.push_back(nx);
skinned_normals.push_back(ny);
skinned_normals.push_back(nz);
uvs.push_back(v.uv0[0]);
uvs.push_back(v.uv0[1]);
}
float effective_world[16];
if (world_matrix) {
MultiplyMat4(R_GRANNY_TO_ENGINE, world_matrix, effective_world);
} else {
std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world);
}
std::vector<float> bone_mats_flat;
bone_mats_flat.reserve(skin_matrices.size() * 16);
for (const auto& sm : skin_matrices) {
for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]);
}
if (mesh.tri_groups.empty()) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.positions = skinned_positions;
draw.normals = skinned_normals;
draw.uv0 = uvs;
draw.indices = mesh.indices;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
if (!mesh.material_textures.empty())
draw.texture0 = mesh.material_textures[0];
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
} else {
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.positions = skinned_positions;
draw.normals = skinned_normals;
draw.uv0 = uvs;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
if (start_idx + count_idx <= mesh.indices.size()) {
draw.indices.assign(mesh.indices.begin() + start_idx,
mesh.indices.begin() + start_idx + count_idx);
}
if (group.material_index >= 0 && group.material_index < static_cast<int>(mesh.material_textures.size())) {
draw.texture0 = mesh.material_textures[group.material_index];
}
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
}
}
}
if(hardwareSkinning) {
for(auto& draw:draws){draw.gpu_skinning=!skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));}
m_gpuMain=draws;
}
}
ApplySkins(draws, 0);
// 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices
for (const auto& part : m_attached_parts) {
if (!part) continue;
auto part_draws = part->BuildDrawCommandsWithPalette(skin_matrices, world_matrix, has_skeleton ? &info.skeletons[0] : nullptr, hardwareSkinning);
for (auto& pd : part_draws) {
draws.push_back(std::move(pd));
}
}
// 3. Build attached bone models (e.g. weapon in right hand, shield in left hand)
if (has_skeleton && !world_pose.empty()) {
const auto& sk = info.skeletons[0];
for (const auto& am : m_attached_models) {
if (!am.model) continue;
int bone_idx = -1;
for (size_t b = 0; b < sk.bones.size(); ++b) {
if (sk.bones[b].name == am.bone_name) {
bone_idx = static_cast<int>(b);
break;
}
}
if (bone_idx < 0) continue;
const auto& B = world_pose[bone_idx];
float attached_local[16];
MultiplyMat4(am.offset, B.data(), attached_local);
if (am.scaled) {
const float S[16] = {am.scale[0], 0, 0, 0, 0, am.scale[1], 0, 0, 0, 0, am.scale[2], 0, 0, 0, 0, 1};
MultiplyMat4(attached_local, S, attached_local);
}
float attached_engine[16];
MultiplyMat4(attached_local, R_GRANNY_TO_ENGINE, attached_engine);
float final_world[16];
if (world_matrix) {
MultiplyMat4(attached_engine, world_matrix, final_world);
} else {
std::copy(attached_engine, attached_engine + 16, final_world);
}
float attach_time = -1.0f;
if (am.animated && animation_time >= 0.0f) {
float duration = am.model->GetAnimationDuration();
attach_time = duration > 0.0f ? std::fmod(animation_time, duration) : 0.0f;
}
auto attach_draws = am.model->BuildDrawCommands(attach_time, nullptr, hardwareSkinning);
for (auto& ad : attach_draws) {
std::copy(final_world, final_world + 16, ad.world);
draws.push_back(std::move(ad));
}
}
}
return draws;
}
bool Gr2ModelInstance::GetLocalBounds(float& minX, float& minY, float& minZ, float& maxX, float& maxY, float& maxZ) const {
if (!m_file) return false;
const auto& info = m_file->file_info();
if (info.meshes.empty()) return false;
minX = 1e9f; minY = 1e9f; minZ = 1e9f;
maxX = -1e9f; maxY = -1e9f; maxZ = -1e9f;
bool found = false;
for (const auto& mesh : info.meshes) {
for (const auto& v : mesh.vertices) {
float ex = v.pos[0];
float ey = v.pos[2];
float ez = -v.pos[1];
minX = std::min(minX, ex);
minY = std::min(minY, ey);
minZ = std::min(minZ, ez);
maxX = std::max(maxX, ex);
maxY = std::max(maxY, ey);
maxZ = std::max(maxZ, ez);
found = true;
}
}
return found;
}
} // namespace gr2_render