Files
AVA2/tests/ava2_render_3d_test.cpp

1658 lines
83 KiB
C++

// The checks call the code under test inside assert(); keep them in release builds.
#ifdef NDEBUG
#undef NDEBUG
#endif
#include "src/eter_render/Gr2ModelRenderer.h"
#include "src/eter_render/TerrainHeightmap.h"
#include "src/eter_render/MapObjectManager.h"
#include "src/eter_render/WaterManager.h"
#include "src/eter_render/OrbitCamera.h"
#include "src/eter_render/MinimapManager.h"
#include "src/eter_render/ActorInstance.h"
#include "src/eter_render/RaceData.h"
#include "src/eter_render/FloatingTextManager.h"
#include "src/eter_render/TargetManager.h"
#include "src/eter_render/TextTailManager.h"
#include "src/eter_sound/SoundManager.h"
#include "src/eter_effect/EffectManager.h"
#include "src/eter_effect/FlyingManager.h"
#include "src/eter_net/NetworkActorManager.h"
#include <SDL3/SDL.h>
#include <cassert>
#include <iostream>
#include <filesystem>
#include <map>
#include <set>
#include <fstream>
#include <chrono>
#include "test_rundir.h"
using ava2_test::kSkip;
using ava2_test::PackMaker;
int main(int argc, char** argv) {
if (!ava2_test::EnterTestRunDir()) return kSkip;
std::string model_path = "ymir work/pc/warrior/warrior_assasin1.gr2";
if (argc > 1) {
model_path = argv[1];
}
if (!std::filesystem::exists(model_path)) {
if (std::filesystem::exists("build/dev/" + model_path)) {
model_path = "build/dev/" + model_path;
} else if (std::filesystem::exists("../" + model_path)) {
model_path = "../" + model_path;
} else {
std::cerr << "SKIP: model file not found: " << model_path << std::endl;
return kSkip;
}
}
// The scene below loads cwd-relative client assets (merged `ymir work`, bgm, sound),
// like the Windows client root. Without them the asserts would only report the
// environment, so skip instead; when they are present every check runs.
for (const char* required : {"ymir work/zone/b/obj/b_general_obj_01_2.gr2",
"bgm/login_window.mp3",
"sound/ui/click.wav"}) {
if (!std::filesystem::exists(required)) {
std::cerr << "SKIP: client asset missing from working directory: " << required << std::endl;
return kSkip;
}
}
std::cout << "Loading 3D GR2 Model: " << model_path << std::endl;
auto model = ava2::Gr2ModelInstance::Load(model_path);
if (!model) {
std::cerr << "Failed to load GR2 model instance!" << std::endl;
return 1;
}
const auto& info = model->GetInfo();
std::cout << "Model Info: " << info.models.size() << " models, "
<< info.meshes.size() << " meshes, "
<< info.skeletons.size() << " skeletons." << std::endl;
if (!info.skeletons.empty()) {
std::cout << "Skeleton bones (" << info.skeletons[0].bones.size() << "): ";
for (const auto& b : info.skeletons[0].bones) {
if (b.name.find("Hand") != std::string::npos || b.name.find("equip") != std::string::npos || b.name.find("Head") != std::string::npos) {
std::cout << "[" << b.name << "] ";
}
}
std::cout << std::endl;
}
// Warrior toes point along native -Y, converted by GR2 to engine +Z.
// At yaw=0, both the mesh forward axis and locomotion must remain +Z.
float foot[16]{},toe[16]{};
assert(model->GetBoneWorldTransform("Bip01 L Foot",foot));
assert(model->GetBoneWorldTransform("Bip01 L Toe0",toe));
const float forwardX=toe[12]-foot[12], forwardZ=-(toe[13]-foot[13]);
assert(forwardZ>0);
ava2::ActorInstance facing;
facing.SetModel(model_path); facing.SetPosition(0,0,0); facing.SetSpeed(100);
facing.MoveInDirection(0,0.1f);
auto facingDraws=facing.BuildDrawCommands();
assert(!facingDraws.empty());
const auto& w=facingDraws[0].world;
const float worldForwardZ=forwardX*w[2]+(toe[13]-foot[13])*w[6]+(toe[14]-foot[14])*w[10];
assert(worldForwardZ*facing.GetZ()>0 && "rendered face must point toward movement");
facing.SetYaw(180.0f);
auto showcaseDraws=facing.BuildDrawCommands();
const auto& sw=showcaseDraws[0].world;
const float showcaseForwardZ=forwardX*sw[2]+(toe[13]-foot[13])*sw[6]+(toe[14]-foot[14])*sw[10];
assert(showcaseForwardZ*worldForwardZ<0 && facing.GetYaw()==180);
assert(!info.meshes.empty() && "GR2 model must contain at least one mesh");
std::size_t total_verts = 0;
std::size_t total_indices = 0;
for (const auto& mesh : info.meshes) {
total_verts += mesh.vertices.size();
total_indices += mesh.indices.size();
}
std::cout << "Total vertices: " << total_verts << ", Total indices: " << total_indices << std::endl;
assert(total_verts > 100 && "Warrior mesh must have substantial vertex count");
assert(total_indices > 300 && "Warrior mesh must have triangle indices");
// Build 3D draw commands with bind pose skinning
auto draws = model->BuildDrawCommands();
std::cout << "Generated " << draws.size() << " 3D draw commands." << std::endl;
for (size_t i = 0; i < draws.size(); ++i) {
std::cout << "Draw " << i << " texture0: '" << draws[i].texture0 << "'" << std::endl;
}
assert(!draws.empty() && "Must produce at least one 3D draw command");
{
// GPU draw caches keep skinned texture names; skin changes after the cache is built must apply.
auto skinned = ava2::Gr2ModelInstance::Load(model_path);assert(skinned);
const auto base = skinned->BuildDrawCommands(-1.0f, nullptr, true);assert(!base.empty());
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == base[0].texture0);
std::string upper = base[0].texture0;for (auto& c : upper) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
skinned->SetSkin(upper, "skin-test.dds");
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
skinned->ClearSkins();
assert(skinned->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == base[0].texture0);
auto fresh = ava2::Gr2ModelInstance::Load(model_path);assert(fresh);fresh->SetSkin(base[0].texture0, "skin-test.dds");
assert(fresh->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
assert(fresh->BuildDrawCommands(-1.0f, nullptr, true)[0].texture0 == "skin-test.dds");
}
// Setup 3D Scene Renderer
const int width = 1024;
const int height = 768;
ava2::Gr2SceneRenderer renderer(width, height);
// Setup Camera to look at the warrior model
// Warrior height is typically ~170-180 units in Metin2 space
renderer.SetCameraLookAt(
0.0f, 130.0f, -320.0f, // Eye
0.0f, 100.0f, 0.0f, // Target (chest height)
0.0f, 1.0f, 0.0f // Up
);
renderer.SetPerspective(45.0f, static_cast<float>(width) / static_cast<float>(height), 1.0f, 2000.0f);
SDL_Surface* surface = SDL_CreateSurface(width, height, SDL_PIXELFORMAT_ARGB8888);
assert(surface != nullptr && "Failed to create SDL surface for 3D rendering");
// Clear background to dark blue
uint32_t bg_color = 0xFF101826;
SDL_FillSurfaceRect(surface, nullptr, bg_color);
renderer.Clear(bg_color, 1.0f);
// Execute 3D rendering
renderer.RenderScene(surface, draws);
// Verify rasterized content
uint32_t* pixels = static_cast<uint32_t*>(surface->pixels);
int rendered_mesh_pixels = 0;
const auto& depth = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (depth[i] < 0.999f) {
rendered_mesh_pixels++;
}
}
std::cout << "Rasterized 3D Warrior model pixels: " << rendered_mesh_pixels
<< " out of " << (width * height) << std::endl;
// Save screenshot of base pose
const char* screenshot_path = "/tmp/test_3d_warrior.bmp";
if (SDL_SaveBMP(surface, screenshot_path)) {
std::cout << "Successfully saved 3D warrior render to: " << screenshot_path << std::endl;
}
// Test World Rotation (Yaw 35 degrees)
float world_rot[16];
ava2::MakeTransformMatrix(35.0f, 0.0f, 0.0f, 0.0f, 1.0f, world_rot);
auto rotated_draws = model->BuildDrawCommands(-1.0f, world_rot);
renderer.Clear(bg_color, 1.0f);
SDL_FillSurfaceRect(surface, nullptr, bg_color);
renderer.RenderScene(surface, rotated_draws);
int rotated_mesh_pixels = 0;
const auto& depth_rot = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (depth_rot[i] < 0.999f) rotated_mesh_pixels++;
}
std::cout << "Rasterized Rotated 3D Warrior model pixels: " << rotated_mesh_pixels << std::endl;
assert(rotated_mesh_pixels > 5000 && "Rotated mesh must produce valid silhouette");
const char* rot_screenshot = "/tmp/test_3d_warrior_rotated.bmp";
if (SDL_SaveBMP(surface, rot_screenshot)) {
std::cout << "Successfully saved rotated 3D warrior render to: " << rot_screenshot << std::endl;
}
// ── Test Bone Query (equip_right_hand and Bip01 Head) ──────────────────
float hand_matrix[16] = {};
bool has_hand = model->GetBoneWorldTransform("equip_right_hand", hand_matrix);
if (!has_hand) {
has_hand = model->GetBoneWorldTransform("Bip01 R Hand", hand_matrix);
}
std::cout << "GetBoneWorldTransform(right_hand): " << (has_hand ? "SUCCESS" : "FAILED") << std::endl;
assert(has_hand && "Must find hand bone on warrior skeleton");
std::cout << "Hand position: (" << hand_matrix[12] << ", " << hand_matrix[13] << ", " << hand_matrix[14] << ")" << std::endl;
// Bone effects / mount saddles must use the same native Z-up conversion as meshes.
{
ava2::ActorInstance actor;
assert(actor.SetModel(model_path));actor.SetScale(2);actor.SetPosition(11,22,33);actor.SetYaw(90);
std::string bone="equip_right_hand";
float native[16];
if (!model->GetBoneWorldTransform(bone,native,0)) { bone="Bip01 R Hand";assert(model->GetBoneWorldTransform(bone,native,0)); }
float x,y,z;assert(actor.GetBonePosition(bone,x,y,z));
assert(std::abs(x-(11-2*native[13]))<.01f);
assert(std::abs(y-(22+2*native[14]))<.01f);
assert(std::abs(z-(33-2*native[12]))<.01f);
}
// ── Test Weapon Attachment ─────────────────────────────────────────────
std::string weapon_path = "ymir work/item/weapon/set_11_sword.gr2";
if (!std::filesystem::exists(weapon_path) && std::filesystem::exists("../" + weapon_path)) {
weapon_path = "../" + weapon_path;
}
auto weapon = ava2::Gr2ModelInstance::Load(weapon_path);
if (weapon) {
std::cout << "Loaded weapon model: " << weapon_path << std::endl;
model->AttachModel("equip_right_hand", std::move(weapon));
auto equipped_draws = model->BuildDrawCommands();
const auto& wd = equipped_draws.back();
std::cout << "Weapon draw world translation: (" << wd.world[12] << ", " << wd.world[13] << ", " << wd.world[14] << ")" << std::endl;
float wx = wd.positions[0]*wd.world[0] + wd.positions[1]*wd.world[4] + wd.positions[2]*wd.world[8] + wd.world[12];
float wy = wd.positions[0]*wd.world[1] + wd.positions[1]*wd.world[5] + wd.positions[2]*wd.world[9] + wd.world[13];
float wz = wd.positions[0]*wd.world[2] + wd.positions[1]*wd.world[6] + wd.positions[2]*wd.world[10] + wd.world[14];
std::cout << "Weapon vertex 0 world pos: (" << wx << ", " << wy << ", " << wz << ")" << std::endl;
renderer.Clear(bg_color, 1.0f);
SDL_FillSurfaceRect(surface, nullptr, bg_color);
renderer.RenderScene(surface, equipped_draws);
int equipped_pixels = 0;
const auto& eq_depth = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (eq_depth[i] < 0.999f) equipped_pixels++;
}
std::cout << "Equipped warrior (with weapon) pixels: " << equipped_pixels << std::endl;
assert(equipped_pixels > rendered_mesh_pixels && "Weapon attachment must add visible pixels");
const char* wep_screenshot = "/tmp/test_3d_warrior_weapon.bmp";
if (SDL_SaveBMP(surface, wep_screenshot)) {
std::cout << "Successfully saved weapon attachment render to: " << wep_screenshot << std::endl;
}
}
// ── Test Hair Part Attachment ──────────────────────────────────────────
std::string hair_path = "ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2";
if (!std::filesystem::exists(hair_path) && std::filesystem::exists("../" + hair_path)) {
hair_path = "../" + hair_path;
}
auto hair = ava2::Gr2ModelInstance::Load(hair_path);
if (hair) {
std::cout << "Loaded hair part model: " << hair_path << std::endl;
model->AttachPart(std::move(hair));
auto full_draws = model->BuildDrawCommands();
std::cout << "Fully equipped draws count: " << full_draws.size() << std::endl;
renderer.Clear(bg_color, 1.0f);
SDL_FillSurfaceRect(surface, nullptr, bg_color);
renderer.RenderScene(surface, full_draws);
const char* full_screenshot = "/tmp/test_3d_warrior_fully_equipped.bmp";
if (SDL_SaveBMP(surface, full_screenshot)) {
std::cout << "Successfully saved fully equipped warrior render to: " << full_screenshot << std::endl;
}
}
// ── Test External Animation Loading & Pose Sampling ───────────────────
std::string anim_model_path = "ymir work/npc_mount/halloween_2018_cerberos/halloween_2018_cerberos.gr2";
std::string anim_file_path = "ymir work/npc_mount/halloween_2018_cerberos/wait.gr2";
if (!std::filesystem::exists(anim_model_path) && std::filesystem::exists("../" + anim_model_path)) {
anim_model_path = "../" + anim_model_path;
anim_file_path = "../" + anim_file_path;
}
auto anim_model = ava2::Gr2ModelInstance::Load(anim_model_path);
if (anim_model) {
bool anim_loaded = anim_model->LoadExternalAnimation(anim_file_path);
std::cout << "Loaded external animation: " << (anim_loaded ? "SUCCESS" : "FAILED") << std::endl;
assert(anim_loaded && "External animation file must load successfully");
float duration = anim_model->GetAnimationDuration();
std::cout << "Cerberos animation duration: " << duration << "s" << std::endl;
assert(duration > 0.1f && "Animation duration must be positive");
// Sample pose at t = 0.5s
auto anim_draws = anim_model->BuildDrawCommands(0.5f);
assert(!anim_draws.empty() && "Animated model must generate draw commands");
float cminX=1e9, cmaxX=-1e9, cminY=1e9, cmaxY=-1e9, cminZ=1e9, cmaxZ=-1e9;
for (const auto& d : anim_draws) {
for (size_t i = 0; i < d.positions.size(); i += 3) {
cminX = std::min(cminX, d.positions[i]); cmaxX = std::max(cmaxX, d.positions[i]);
cminY = std::min(cminY, d.positions[i+1]); cmaxY = std::max(cmaxY, d.positions[i+1]);
cminZ = std::min(cminZ, d.positions[i+2]); cmaxZ = std::max(cmaxZ, d.positions[i+2]);
}
}
std::cout << "Cerberos bounds: X[" << cminX << ".." << cmaxX << "] Y[" << cminY << ".." << cmaxY << "] Z[" << cminZ << ".." << cmaxZ << "]" << std::endl;
renderer.SetCameraLookAt(0.0f, 100.0f, -350.0f, 0.0f, 80.0f, 0.0f, 0.0f, 1.0f, 0.0f);
renderer.Clear(bg_color, 1.0f);
SDL_FillSurfaceRect(surface, nullptr, bg_color);
renderer.RenderScene(surface, anim_draws);
int anim_pixels = 0;
const auto& anim_depth = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (anim_depth[i] < 0.999f) anim_pixels++;
}
std::cout << "Rasterized Animated Cerberos pixels: " << anim_pixels << std::endl;
assert(anim_pixels > 5000 && "Animated model rendering must produce valid silhouette");
const char* anim_screenshot = "/tmp/test_3d_cerberos_anim.bmp";
if (SDL_SaveBMP(surface, anim_screenshot)) {
std::cout << "Successfully saved animated cerberos render to: " << anim_screenshot << std::endl;
}
}
// ── Test Terrain Heightmap & Outdoor Scene Rendering ────────────────────
std::cout << "\n── Testing Terrain Heightmap & Outdoor Scene Rendering ──" << std::endl;
ava2::TerrainHeightmap terrain;
std::string raw_path = PackMaker() + "/Maps/metin2_map_a1/001003/height.raw";
if (std::filesystem::exists(raw_path)) {
bool raw_ok = terrain.LoadRaw(raw_path, 0.5f, 50.0f);
std::cout << "Loaded Metin2 height.raw: " << (raw_ok ? "SUCCESS" : "FAILED") << std::endl;
assert(raw_ok && "Metin2 height.raw must load successfully");
std::string tile_path = PackMaker() + "/Maps/metin2_map_a1/001003/tile.raw";
if (std::filesystem::exists(tile_path)) {
bool tile_ok = terrain.LoadTileRaw(tile_path);
std::cout << "Loaded Metin2 tile.raw: " << (tile_ok ? "SUCCESS" : "FAILED") << std::endl;
assert(tile_ok && "Metin2 tile.raw must load successfully");
assert(terrain.HasTileMap());
}
} else {
terrain.GenerateProcedural(64, 64, 40.0f, 60.0f);
std::cout << "Generated procedural outdoor rolling hill terrain" << std::endl;
}
assert(terrain.GetWidth() >= 16 && terrain.GetHeight() >= 16);
float h_center = terrain.GetHeightAtWorld(0.0f, 0.0f);
std::cout << "Terrain height at center (0,0): " << h_center
<< ", min: " << terrain.GetMinHeight() << ", max: " << terrain.GetMaxHeight() << std::endl;
float normal[3];
terrain.GetNormalAtWorld(0.0f, 0.0f, normal);
std::cout << "Terrain normal at center: (" << normal[0] << ", " << normal[1] << ", " << normal[2] << ")" << std::endl;
assert(normal[1] > 0.1f && "Terrain normal Y component must point upwards");
// Build terrain 3D draw command (with tile-aware shading)
auto terrain_draw = terrain.BuildDrawCommand(nullptr, 2);
std::cout << "Terrain mesh vertices: " << (terrain_draw.positions.size() / 3)
<< ", indices: " << terrain_draw.indices.size() << std::endl;
assert(!terrain_draw.positions.empty() && !terrain_draw.indices.empty());
// ── Test MapObjectManager: Outdoor Buildings & Props ───────────────────
std::cout << "\n── Testing MapObjectManager (Buildings & Props) ──" << std::endl;
ava2::MapObjectManager obj_mgr;
std::string bldg_path = "ymir work/zone/b/obj/b_general_obj_01_2.gr2";
if (!std::filesystem::exists(bldg_path) && std::filesystem::exists("../" + bldg_path)) {
bldg_path = "../" + bldg_path;
}
bool added_bldg = obj_mgr.AddObject(bldg_path, 80.0f, h_center, -60.0f, 30.0f, 0.0f, 0.0f, 1.0f);
std::cout << "Added outdoor building instance: " << (added_bldg ? "SUCCESS" : "FAILED") << std::endl;
assert(added_bldg && "Building model must instantiate successfully");
{
const auto fixture = std::filesystem::temp_directory_path() / "ava2-native-area-test.txt";
{ std::ofstream f(fixture); f << "AreaDataFile\nStart Object000\n10 -20 30\n1\n0#0#90\n5\nEnd Object\n"; }
ava2::MapObjectManager native;
native.RegisterProperty(1, bldg_path);
assert(native.LoadAreaData(fixture.string(), 1, nullptr, true));
assert(native.GetObjectCount() == 1);
const auto& object = native.GetObjects().front();
assert(object.x == 10 && object.y == 35 && object.z == 20);
assert(object.yaw == 90 && object.pitch == 0 && object.roll == 0);
std::filesystem::remove(fixture);
}
// Test AreaData & Property scanning
std::string prop_dir = PackMaker() + "/property/property";
if (std::filesystem::exists(prop_dir)) {
obj_mgr.RegisterProperty(234517142, bldg_path);
assert(obj_mgr.GetPropertyCount() >= 1);
std::string areadata_path = PackMaker() + "/Maps/metin2_map_a1/001003/areadata.txt";
if (std::filesystem::exists(areadata_path)) {
obj_mgr.LoadAreaData(areadata_path, 0.05f);
std::cout << "Loaded objects from areadata.txt: " << obj_mgr.GetObjectCount() << std::endl;
}
}
auto obj_draws = obj_mgr.BuildDrawCommands();
std::cout << "Generated " << obj_draws.size() << " draw commands for map objects." << std::endl;
assert(!obj_draws.empty() && "Map objects must produce 3D draw commands");
auto objRepeat = obj_mgr.BuildDrawCommands();
assert(obj_draws.front().geometry && obj_draws.front().positions.empty());
assert(objRepeat.front().geometry == obj_draws.front().geometry);
ava2::MapObjectManager instanceObjects;
instanceObjects.AddObject(bldg_path,80.f,h_center,-60.f,30.f,0.f,0.f,1.f);
instanceObjects.AddObject(bldg_path,180.f,h_center,-60.f,60.f,0.f,0.f,1.f);
auto repeatedObjects=instanceObjects.BuildDrawCommands();
assert(!repeatedObjects.empty() && repeatedObjects.size()%2==0);
const auto groupSize=repeatedObjects.size()/2;
assert(repeatedObjects[0].geometry==repeatedObjects[groupSize].geometry);
assert(repeatedObjects[0].world[12]!=repeatedObjects[groupSize].world[12]);
assert(!obj_draws.front().Mesh().positions.empty());
// Spatial broad phase must match the original object-order traversal, including normals.
ava2::MapObjectManager collisionGrid;
for(int x=-5;x<=5;++x)for(int z=-5;z<=5;++z)
collisionGrid.AddObject(bldg_path,x*3000.f,h_center,z*3000.f,float((x+z)*13),0,0,1);
collisionGrid.AddObject(bldg_path,0,h_center,0,45,0,0,80); // oversized fallback candidate
auto linear=[&](float x,float z,float r,float& nx,float& nz,bool normal){
for(const auto& obj:collisionGrid.GetObjects()) {
if(!obj.has_collision)continue;
const float maxR=std::max(obj.obb.halfExtents[0],obj.obb.halfExtents[2])*1.5f+r;
float dx=x-obj.obb.centerX,dz=z-obj.obb.centerZ;
if(dx*dx+dz*dz>maxR*maxR)continue;
float penetration;
if(normal ? obj.obb.GetPenetrationAndNormal(x,z,r,nx,nz,penetration) : obj.obb.IntersectsCircle2D(x,z,r))return true;
}
return false;
};
for(int i=0;i<500;++i) {
float x=float((i*7919)%40000-20000),z=float((i*3571)%40000-20000),r=i%7==0 ? 5000.f : float(i%90+1);
float a=0,b=0,c=0,d=0;
assert(collisionGrid.CheckCollision(x,z,r)==linear(x,z,r,a,b,false));
bool expected=linear(x,z,r,a,b,true),actual=collisionGrid.CheckCollisionNormal(x,z,r,c,d);
assert(expected==actual);if(expected){assert(std::abs(a-c)<.001f && std::abs(b-d)<.001f);}
}
collisionGrid.CheckCollision(0,0,30);
assert(collisionGrid.GetLastCollisionCandidateCount()<collisionGrid.GetObjectCount()/4);
collisionGrid.ClearObjects();assert(!collisionGrid.CheckCollision(0,0,30));
collisionGrid.AddObject(bldg_path,0,h_center,0,0,0,0,1);
float nx=0,nz=0;assert(collisionGrid.CheckCollision(0,0,30)==linear(0,0,30,nx,nz,false));
// Place character standing on terrain at (0, h_center, 0)
std::vector<ava2::Render3DDraw> outdoor_scene_draws;
outdoor_scene_draws.push_back(std::move(terrain_draw));
for (auto& od : obj_draws) {
outdoor_scene_draws.push_back(std::move(od));
}
if (model) {
float char_world[16];
ava2::MakeTransformMatrix(0.0f, 0.0f, h_center, 0.0f, 0.8f, char_world);
auto char_draws = model->BuildDrawCommands(-1.0f, char_world);
for (auto& cd : char_draws) {
outdoor_scene_draws.push_back(std::move(cd));
}
}
// Setup 3D camera for outdoor perspective (third-person view looking at terrain + character)
renderer.SetCameraLookAt(
0.0f, h_center + 160.0f, -400.0f, // Eye position
0.0f, h_center + 60.0f, 0.0f, // Target position
0.0f, 1.0f, 0.0f // Up
);
renderer.SetPerspective(50.0f, static_cast<float>(width) / static_cast<float>(height), 1.0f, 4000.0f);
uint32_t sky_color = 0xFF355272; // Outdoor atmospheric sky blue
SDL_FillSurfaceRect(surface, nullptr, sky_color);
renderer.Clear(sky_color, 1.0f);
renderer.RenderScene(surface, outdoor_scene_draws);
int outdoor_pixels = 0;
const auto& outdoor_depth = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (outdoor_depth[i] < 0.999f) outdoor_pixels++;
}
std::cout << "Rasterized outdoor terrain + character scene pixels: " << outdoor_pixels
<< " (" << (float(outdoor_pixels) / float(width * height) * 100.0f) << "%)" << std::endl;
assert(outdoor_pixels > 50000 && "Outdoor terrain must cover substantial viewport pixels");
const char* outdoor_screenshot = "/tmp/test_3d_terrain_scene.bmp";
if (SDL_SaveBMP(surface, outdoor_screenshot)) {
std::cout << "Successfully saved outdoor terrain + character render to: " << outdoor_screenshot << std::endl;
}
// ── Test WaterManager & Fog Rendering ──────────────────────────────────
std::cout << "\n── Testing WaterManager & Depth Fog System ──" << std::endl;
ava2::WaterManager water_mgr;
std::string water_file = PackMaker() + "/Maps/metin2_map_a1/001003/water.wtr";
if (std::filesystem::exists(water_file)) {
bool water_loaded = water_mgr.LoadWater(water_file, 40.0f, 0.5f, 40.0f, -2560.0f, -2560.0f);
assert(water_loaded && "Failed to load water.wtr");
assert(water_mgr.HasWater() && "WaterManager must report water exists");
std::cout << "Loaded water.wtr successfully! Water face count: " << water_mgr.GetWaterFaceCount() << std::endl;
assert(water_mgr.GetWaterFaceCount() > 0 && "Water face count must be non-zero");
} else {
water_mgr.GenerateProceduralWater(25.0f, -2000.0f, 2000.0f, -2000.0f, 2000.0f, 60.0f);
std::cout << "Generated procedural water plane with faces: " << water_mgr.GetWaterFaceCount() << std::endl;
}
auto water_draw = water_mgr.BuildDrawCommand(0.5f);
assert(!water_draw.indices.empty() && "Water draw command must produce indices");
assert(!water_draw.positions.empty() && "Water draw command must produce positions");
outdoor_scene_draws.push_back(std::move(water_draw));
// Test Fog configuration
renderer.SetFog(true, 0xFF355272, 0.00035f, 200.0f, 3200.0f, true);
assert(renderer.IsFogEnabled() && "Renderer fog must be enabled");
assert(renderer.GetFogColor() == 0xFF355272 && "Renderer fog color mismatch");
SDL_FillSurfaceRect(surface, nullptr, sky_color);
renderer.Clear(sky_color, 1.0f);
renderer.RenderScene(surface, outdoor_scene_draws);
int water_fog_pixels = 0;
const auto& fog_depth = renderer.GetDepthBuffer();
for (int i = 0; i < width * height; ++i) {
if (fog_depth[i] < 0.999f) water_fog_pixels++;
}
std::cout << "Rasterized outdoor terrain + water + fog pixels: " << water_fog_pixels
<< " (" << (float(water_fog_pixels) / float(width * height) * 100.0f) << "%)" << std::endl;
assert(water_fog_pixels > 50000 && "Outdoor scene with water must cover substantial pixels");
const char* water_screenshot = "/tmp/test_3d_water_fog_scene.bmp";
if (SDL_SaveBMP(surface, water_screenshot)) {
std::cout << "Successfully saved water + fog scene render to: " << water_screenshot << std::endl;
}
// ── Test Monster & NPC GR2 Models ───────────────────────────────────────
std::cout << "\n── Testing Monster & NPC Models Loading ──" << std::endl;
const char* mob_npc_models[] = {
"ymir work/npc_mount/christmas_2017_sleddog/christmas_2017_sleddog.gr2",
"ymir work/monster/metinstone_02/metinstone_10.gr2",
"ymir work/npc/12zi_statue_rabbit_npc/12zi_statue_rabbit_npc.gr2"
};
int mob_loaded = 0;
for (const char* mob_p : mob_npc_models) {
std::string p = mob_p;
if (!std::filesystem::exists(p) && std::filesystem::exists("../" + p)) {
p = "../" + p;
}
auto mob_inst = ava2::Gr2ModelInstance::Load(p);
if (mob_inst) {
mob_loaded++;
auto d = mob_inst->BuildDrawCommands();
assert(!d.empty() && "Monster/NPC model must produce draw commands");
}
}
std::cout << "Successfully loaded and verified " << mob_loaded << "/3 monster/NPC models." << std::endl;
assert(mob_loaded == 3 && "All 3 monster/NPC models must load successfully");
// ── Test 8 Character Class / Form Models ────────────────────────────────
std::cout << "\n── Testing 8 Character Class Models Loading ──" << std::endl;
const char* race_models[] = {
"ymir work/pc/warrior/warrior_assasin1.gr2",
"ymir work/pc/assassin/assassin_halloween1_lod_01.gr2",
"ymir work/pc/sura/sura_soccer1_germany_lod_02.gr2",
"ymir work/pc/shaman/shaman_fencing1_germany_lod_02.gr2",
"ymir work/pc/plechito/summer2020_costume/warrior_w.gr2",
"ymir work/pc/plechito/summer2020_costume/assassin_m.gr2",
"ymir work/pc/plechito/summer2020_costume/sura_w.gr2",
"ymir work/pc/plechito/summer2020_costume/shaman_m.gr2"
};
int loaded_count = 0;
for (int r = 0; r < 8; ++r) {
std::string p = race_models[r];
if (!std::filesystem::exists(p) && std::filesystem::exists("../" + p)) {
p = "../" + p;
}
auto race_inst = ava2::Gr2ModelInstance::Load(p);
if (race_inst) {
loaded_count++;
auto d = race_inst->BuildDrawCommands();
assert(!d.empty() && "Race model must produce draw commands");
}
}
std::cout << "Successfully loaded and verified " << loaded_count << "/8 character class models." << std::endl;
assert(loaded_count == 8 && "All 8 character class models must load successfully");
// ── Test OrbitCamera (Third-Person Orbit Camera System) ─────────────────
std::cout << "\n── Testing OrbitCamera (Third-Person Camera System) ──" << std::endl;
ava2::OrbitCamera cam;
cam.SetTarget(50.0f, 20.0f, 100.0f);
cam.SetTargetHeight(85.0f);
assert(cam.GetTargetHeight() == 85.0f);
cam.SetDistance(500.0f);
assert(cam.GetDistance() == 500.0f);
cam.SetPitch(30.0f);
assert(cam.GetPitch() == 30.0f);
cam.SetYaw(45.0f);
assert(cam.GetYaw() == 45.0f);
// Test pitch clamping
cam.SetPitch(100.0f);
assert(cam.GetPitch() <= 85.0f);
cam.SetPitch(-20.0f);
assert(cam.GetPitch() >= 5.0f);
cam.SetPitch(30.0f);
// Test yaw wrapping
cam.SetYaw(400.0f);
assert(std::abs(cam.GetYaw() - 40.0f) < 0.01f);
cam.SetYaw(-30.0f);
assert(std::abs(cam.GetYaw() - 330.0f) < 0.01f);
cam.SetYaw(0.0f);
// Test distance clamping & Zoom
cam.SetDistance(3000.0f);
assert(cam.GetDistance() <= 2500.0f);
cam.SetDistance(50.0f);
assert(cam.GetDistance() >= 120.0f);
cam.SetDistance(400.0f);
cam.Zoom(2.0f, 50.0f); // Zoom in: 400 - 100 = 300
assert(cam.GetDistance() == 300.0f);
cam.Zoom(-1.0f, 50.0f); // Zoom out: 300 + 50 = 350
assert(cam.GetDistance() == 350.0f);
// Test mouse dragging
cam.BeginDrag(100, 100);
assert(cam.IsDragging());
cam.Drag(120, 80, 0.5f); // dx = +20 -> yaw += 10; dy = -20 -> pitch += 10
assert(cam.GetYaw() > 0.0f);
cam.EndDrag();
assert(!cam.IsDragging());
// Test eye position calculation and renderer application
float eyeX = 0.0f, eyeY = 0.0f, eyeZ = 0.0f;
cam.GetEye(eyeX, eyeY, eyeZ);
float tgtX = 0.0f, tgtY = 0.0f, tgtZ = 0.0f;
cam.GetLookTarget(tgtX, tgtY, tgtZ);
assert(tgtX == 50.0f && tgtY == 105.0f && tgtZ == 100.0f);
cam.ApplyToRenderer(renderer);
std::cout << "OrbitCamera tested and verified successfully!" << std::endl;
// ── Test MinimapManager (Radar Minimap System) ──────────────────────────
std::cout << "\n── Testing MinimapManager (Radar Minimap System) ──" << std::endl;
ava2::MinimapManager minimap;
std::string minimap_test_path = PackMaker() + "/Maps/metin2_map_a1/001003/minimap.dds";
if (std::filesystem::exists(minimap_test_path)) {
bool m_ok = minimap.LoadMinimap(minimap_test_path);
std::cout << "Loaded Metin2 minimap.dds: " << (m_ok ? "SUCCESS" : "FAILED")
<< " (" << minimap.GetTextureWidth() << "x" << minimap.GetTextureHeight() << ")" << std::endl;
assert(m_ok);
assert(minimap.HasTexture());
assert(minimap.GetTextureWidth() == 256 && minimap.GetTextureHeight() == 256);
} else {
minimap.GenerateProceduralMinimap(256, 256);
assert(minimap.HasTexture());
}
minimap.SetWorldBounds(-2600.0f, 2600.0f, -2600.0f, 2600.0f);
minimap.ClearBlips();
minimap.AddBlip(120.0f, -80.0f, ava2::MinimapBlipType::Monster);
minimap.AddBlip(-160.0f, 90.0f, ava2::MinimapBlipType::Monster);
minimap.AddBlip(60.0f, 140.0f, ava2::MinimapBlipType::NPC);
assert(minimap.GetBlipCount() == 3);
// Test radar rasterization onto surface
minimap.RenderRadar(surface, width - 180, 20, 160, 0.0f, 0.0f, 0.0f);
// Check that golden border pixel exists
uint32_t* radar_px = static_cast<uint32_t*>(surface->pixels);
int gold_pixels = 0;
for (int y = 20; y < 180; ++y) {
for (int x = width - 180; x < width - 20; ++x) {
uint32_t col = radar_px[y * (surface->pitch / 4) + x];
if (col == 0xFFC29B4A) gold_pixels++;
}
}
std::cout << "Radar golden frame pixels rendered: " << gold_pixels << std::endl;
assert(gold_pixels > 50 && "Minimap radar golden frame must be rasterized");
const char* radar_screenshot = "/tmp/test_3d_minimap_radar.bmp";
if (SDL_SaveBMP(surface, radar_screenshot)) {
std::cout << "Successfully saved minimap radar render to: " << radar_screenshot << std::endl;
}
// Parsed model resources are shared, while instance attachments and pose clocks are independent.
auto sharedA = ava2::Gr2ModelInstance::Load(model_path);
auto sharedB = ava2::Gr2ModelInstance::Load(model_path);
assert(sharedA && sharedB && &sharedA->GetFile() == &sharedB->GetFile());
const std::string cachedAnimation = "ymir work/pc/warrior/horse/wait.gr2";
assert(sharedA->LoadExternalAnimation(cachedAnimation));
assert(sharedB->LoadExternalAnimation(cachedAnimation));
assert(sharedA->GetImpl()->GetAnimationResource() == sharedB->GetImpl()->GetAnimationResource());
float cachedLeg[16], repeatLeg[16];
assert(sharedA->GetBoneWorldTransform("Bip01 L Calf", cachedLeg, .25f));
const auto countBefore = sharedA->GetImpl()->GetPoseEvaluationCount();
assert(sharedA->GetBoneWorldTransform("Bip01 L Calf", repeatLeg, .25f));
sharedA->BuildDrawCommands(.25f);
assert(sharedA->GetImpl()->GetPoseEvaluationCount() == countBefore);
std::vector<gr2::Mat4> referenceWorld, referenceSkin;
const auto* animationFile = sharedA->GetImpl()->GetAnimationResource();
const gr2::Mat4 identity{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
gr2::sample_pose(sharedA->GetInfo().skeletons[0], animationFile->file_info().animations[0], .25f,
referenceWorld, referenceSkin, &identity);
const auto& bones = sharedA->GetInfo().skeletons[0].bones;
for (size_t b=0;b<bones.size();++b) if (bones[b].name=="Bip01 L Calf")
for (int k=0;k<16;++k) assert(std::abs(cachedLeg[k]-referenceWorld[b][k])<.001f);
assert(sharedA->GetBoneWorldTransform("Bip01 L Calf", repeatLeg, .5f));
assert(sharedA->GetImpl()->GetPoseEvaluationCount() == countBefore+1);
assert(sharedA->LoadExternalAnimation("ymir work/pc/warrior/general/wait.gr2"));
assert(sharedA->GetBoneWorldTransform("Bip01 L Calf", repeatLeg, .5f));
assert(sharedA->GetImpl()->GetPoseEvaluationCount() == countBefore+2);
assert(sharedB->GetImpl()->GetPoseEvaluationCount() == 0);
// Replacing a resource at the same path must invalidate the parsed-file cache.
const auto reloadPath = std::filesystem::temp_directory_path()/"ava2_model_cache_reload.gr2";
std::filesystem::copy_file(model_path,reloadPath,std::filesystem::copy_options::overwrite_existing);
auto reloadA = ava2::Gr2ModelInstance::Load(reloadPath.string());
auto reloadB = ava2::Gr2ModelInstance::Load(reloadPath.string());
assert(reloadA && reloadB && &reloadA->GetFile()==&reloadB->GetFile());
std::filesystem::last_write_time(reloadPath,std::filesystem::last_write_time(reloadPath)+std::chrono::seconds(1));
auto reloadC = ava2::Gr2ModelInstance::Load(reloadPath.string());
assert(reloadC && &reloadA->GetFile()!=&reloadC->GetFile());
std::filesystem::remove(reloadPath);
// GPU streams retain raw vertices and weights; independently apply the palette
// and compare every vertex/normal against the established CPU skinning path.
auto checkGpuSkin=[](ava2::Gr2ModelInstance& instance,float time) {
auto cpu=instance.GetImpl()->BuildDrawCommands(time,nullptr,false);
auto gpu=instance.GetImpl()->BuildDrawCommands(time,nullptr,true);
assert(cpu.size()==gpu.size());
auto again=instance.GetImpl()->BuildDrawCommands(time+.1f,nullptr,true);
assert(again.size()==gpu.size());
// One palette per instance per frame: draws of a mesh/part share it instead of copying.
std::set<const void*> palettes;size_t skinned=0;
for(const auto& g:gpu)if(g.gpu_skinning){palettes.insert(g.palette.get());++skinned;}
assert(skinned<2 || palettes.size()<skinned);
for(size_t d=0;d<cpu.size();++d) {
const auto& g=gpu[d];assert(g.geometry && again[d].geometry==g.geometry);
assert(!g.gpu_skinning || g.palette);
const auto& mesh=*g.geometry;
assert(cpu[d].positions.size()==mesh.positions.size());
// Tri-groups share one geometry per mesh; each GPU draw covers its own index range.
assert(g.first_index+size_t(cpu[d].indices.size())<=mesh.indices.size() || g.index_count==0);
assert(std::equal(cpu[d].indices.begin(),cpu[d].indices.end(),mesh.indices.begin()+std::min<size_t>(g.first_index,mesh.indices.size())));
assert(g.index_count==UINT32_MAX ? cpu[d].indices.size()==mesh.indices.size() : cpu[d].indices.size()==g.index_count);
for(size_t v=0;v<mesh.positions.size()/3;++v) {
float p[3]{},n[3]{},total=0;
if(g.gpu_skinning)for(int b=0;b<4;++b) {
const auto bone=mesh.bone_indices[v*4+b];const float w=mesh.bone_weights[v*4+b];
if(w<=0 || size_t(bone)*16+15>=g.palette->size())continue;
const auto* m=g.palette->data()+bone*16;
for(int k=0;k<3;++k){p[k]+=(mesh.positions[v*3]*m[k]+mesh.positions[v*3+1]*m[k+4]+mesh.positions[v*3+2]*m[k+8]+m[k+12])*w;
n[k]+=(mesh.normals[v*3]*m[k]+mesh.normals[v*3+1]*m[k+4]+mesh.normals[v*3+2]*m[k+8])*w;}
total+=w;
}
for(int k=0;k<3;++k){if(total<=.0001f){p[k]=mesh.positions[v*3+k];n[k]=mesh.normals[v*3+k];}
assert(std::abs(p[k]-cpu[d].positions[v*3+k])<.001f);
assert(std::abs(n[k]-cpu[d].normals[v*3+k])<.001f);}
}
}
};
checkGpuSkin(*sharedA,.25f);
auto gpuPart=ava2::Gr2ModelInstance::Load(hair_path);
if(gpuPart)sharedA->AttachPart(std::move(gpuPart));
auto gpuWeapon=ava2::Gr2ModelInstance::Load(weapon_path);
if(gpuWeapon)sharedA->AttachModel("equip_right_hand",std::move(gpuWeapon));
checkGpuSkin(*sharedA,.5f);
// Mounted NPCs must animate in the registered horse mode, including after an armor rebuild.
ava2::RaceManager::Instance().LoadPlayerRaces();
ava2::ActorInstance rider;
assert(rider.SetRace(0));
assert(rider.SetModel(model_path));
assert(rider.PlayMotion(ava2::MotionType::Wait, true));
float standingLeg[16], ridingLeg[16];
assert(rider.GetModel()->GetBoneWorldTransform("Bip01 L Calf", standingLeg, 0.0f));
rider.SetMotionMode(9);
assert(rider.PlayMotion(ava2::MotionType::Wait, true));
assert(rider.GetModel()->GetBoneWorldTransform("Bip01 L Calf", ridingLeg, 0.0f));
float poseDifference = 0;
for (int i = 0; i < 16; ++i) poseDifference += std::abs(standingLeg[i] - ridingLeg[i]);
assert(poseDifference > 1.0f && "Riding must bend the legs rather than reuse standing pose");
assert(rider.SetRace(0));
assert(rider.SetModel(model_path));
assert(rider.PlayMotion(ava2::MotionType::Wait, true));
float rebuiltLeg[16];
assert(rider.GetModel()->GetBoneWorldTransform("Bip01 L Calf", rebuiltLeg, 0.0f));
for (int i = 0; i < 16; ++i) assert(std::abs(rebuiltLeg[i] - ridingLeg[i]) < 0.001f);
rider.SetMotionMode(1);
assert(rider.PlayMotion(ava2::MotionType::Wait, true));
assert(rider.GetModel()->GetBoneWorldTransform("Bip01 L Calf", rebuiltLeg, 0.0f));
for (int i = 0; i < 16; ++i) assert(std::abs(rebuiltLeg[i] - standingLeg[i]) < 0.001f);
// ── Test ActorInstance (Motion State Machine & Combat System) ─────────
std::cout << "\n── Testing ActorInstance (Motion State Machine & Combat) ──" << std::endl;
ava2::ActorInstance actor;
bool actor_loaded = actor.SetModel(model_path);
assert(actor_loaded && "ActorInstance must load base model");
bool wep_loaded = actor.SetWeapon(weapon_path);
assert(wep_loaded && "ActorInstance must attach weapon");
actor.RegisterMotion(ava2::MotionType::Wait, "ymir work/pc/warrior/skill/geomgyeong.gr2");
actor.RegisterMotion(ava2::MotionType::Run, "ymir work/pc/warrior/skill/geompung.gr2");
actor.RegisterMotion(ava2::MotionType::Walk, "ymir work/pc/warrior/skill/geompung.gr2");
actor.RegisterMotion(ava2::MotionType::Attack, "ymir work/pc/warrior/skill/samyeon.gr2");
actor.RegisterMotion(ava2::MotionType::ComboAttack1, "ymir work/pc/warrior/skill/samyeon.gr2");
actor.RegisterMotion(ava2::MotionType::ComboAttack2, "ymir work/pc/warrior/skill/palbang.gr2");
actor.RegisterMotion(ava2::MotionType::ComboAttack3, "ymir work/pc/warrior/skill/finish.gr2");
actor.RegisterMotion(ava2::MotionType::Damage, "ymir work/pc/warrior/skill/geomgyeong.gr2");
bool played_wait = actor.PlayMotion(ava2::MotionType::Wait, true);
assert(played_wait && "Must play Wait motion");
assert(actor.GetCurrentMotion() == ava2::MotionType::Wait);
assert(actor.GetMotionDuration() > 0.1f);
actor.Update(0.1f, &terrain);
assert(actor.GetAnimTime() > 0.05f);
actor.SetPosition(0,0,0);
ava2::Gr2SceneRenderer cullCamera;
cullCamera.SetCameraLookAt(0,200,-1000,0,100,0,0,1,0);
cullCamera.SetPerspective(45,1.0f,1,10000);
assert(actor.IsVisible(cullCamera.GetViewMatrix(),cullCamera.GetProjMatrix()));
actor.SetPosition(100000,0,0);
assert(!actor.IsVisible(cullCamera.GetViewMatrix(),cullCamera.GetProjMatrix()));
const auto poseBeforeCull = actor.GetModel()->GetImpl()->GetPoseEvaluationCount();
assert(!actor.IsVisible(cullCamera.GetViewMatrix(),cullCamera.GetProjMatrix()));
assert(actor.GetModel()->GetImpl()->GetPoseEvaluationCount()==poseBeforeCull);
// 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 && 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 && actor.GetLODLevel()==0);
assert(actor.GetDrawModel()->GetFilePath().find("_lod_03.gr2")!=std::string::npos);
assert(!actor.BuildDrawCommands().empty());
// The SetWeapon helper attachment (outside the part slots) follows the LOD instance.
{
auto weaponOnly = ava2::Gr2ModelInstance::Load(weapon_path);
assert(weaponOnly);
std::set<std::string> weaponTextures;
for (const auto& d : weaponOnly->BuildDrawCommands()) weaponTextures.insert(d.texture0);
auto drawsWeapon = [&]() {
for (const auto& d : actor.BuildDrawCommands()) if (weaponTextures.count(d.texture0)) return true;
return false;
};
assert(!weaponTextures.empty() && drawsWeapon() && "weapon must stay attached on the LOD instance");
actor.UpdateLODLevel(0,200,-300,0,0);
assert(actor.GetDrawModel()==actor.GetModel() && drawsWeapon());
actor.UpdateLODLevel(0,200,-4900,2000,0);
assert(actor.GetLODLevel()==0 && drawsWeapon());
}
float lodBone[16];
assert(actor.GetBoneWorldTransform("Bip01 Spine",lodBone));
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.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()-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
assert(actor.GetX() > 10.0f && "Actor must move in X direction");
assert(actor.GetCurrentMotion() == ava2::MotionType::Run);
actor.StopMoving();
assert(actor.GetCurrentMotion() == ava2::MotionType::Wait);
// Test combat combo attack
bool attacked = actor.Attack();
assert(attacked && "Must initiate attack combo");
assert(actor.IsAttacking());
assert(actor.GetCurrentMotion() == ava2::MotionType::ComboAttack1);
// Test attack range detection
ava2::ActorInstance target_dummy;
target_dummy.SetPosition(actor.GetX() + 50.0f, actor.GetY(), actor.GetZ());
actor.SetYaw(90.0f); // Facing target
assert(actor.IsTargetInAttackRange(target_dummy, 100.0f, 60.0f));
target_dummy.SetPosition(actor.GetX() - 50.0f, actor.GetY(), actor.GetZ()); // Behind
assert(!actor.IsTargetInAttackRange(target_dummy, 100.0f, 60.0f));
// Test target taking damage & knockback
target_dummy.SetMaxHP(500);
target_dummy.TakeDamage(150, -10.0f, 0.0f);
assert(target_dummy.GetHP() == 350);
target_dummy.Update(0.1f, &terrain);
// Test BuildDrawCommands
auto actor_draws = actor.BuildDrawCommands();
assert(!actor_draws.empty() && "ActorInstance must produce draw commands with animated weapon");
std::cout << "ActorInstance motion state machine and combat verified successfully!" << std::endl;
// ── Test FloatingTextManager (Combat Floating Numbers & Projection) ───
std::cout << "\n── Testing FloatingTextManager (Combat Text & Projection) ──" << std::endl;
ava2::FloatingTextManager ftm;
ftm.AddDamage(420, 0.0f, 100.0f, 0.0f, false, true);
ftm.AddDamage(840, 0.0f, 100.0f, 0.0f, true, true);
assert(ftm.GetCount() == 2);
ftm.Update(0.2f);
assert(ftm.GetCount() == 2);
float sx = 0.0f, sy = 0.0f;
bool projected = renderer.ProjectToScreen(0.0f, 100.0f, 0.0f, sx, sy);
assert(projected && "Gr2SceneRenderer::ProjectToScreen must project visible point");
assert(sx > 0.0f && sx < static_cast<float>(width));
assert(sy > 0.0f && sy < static_cast<float>(height));
std::cout << "3D to Screen projection test: (" << sx << ", " << sy << ")" << std::endl;
ftm.Update(2.0f); // Fast forward past lifetime
assert(ftm.GetCount() == 0 && "Floating texts must expire after lifetime");
std::cout << "FloatingTextManager verified successfully!" << std::endl;
// ── Test TextTailManager (40250 CPythonTextTail Overhead & Item Labels) ─
std::cout << "\n── Testing TextTailManager (Overhead Names, Titles, Levels, Items & Picking) ──" << std::endl;
auto& ttm = ava2::TextTailManager::Instance();
ttm.Clear();
assert(ttm.GetCharacterCount() == 0);
assert(ttm.GetItemCount() == 0);
// 1. Character TextTail registration
uint32_t charVid = 1001;
ttm.RegisterCharacterTextTail(12, charVid, 0xFFFFFFFF, 175.0f);
ttm.SetCharacterName(charVid, "WarriorKing");
ttm.AttachTitle(charVid, "Noble", 0xFFFFD700);
ttm.AttachLevel(charVid, "[Lv. 99]", 0xFF98FF33);
ttm.SetGuildName(charVid, "Olympus");
ttm.SetCharacterPosition(charVid, 0.0f, 0.0f, 0.0f);
assert(ttm.HasCharacter(charVid));
// 2. Chat bubble
ttm.RegisterChatTail(charVid, "Welcome to Metin2!");
assert(ttm.IsChatTextTail(charVid));
// 3. Item TextTail registration
uint32_t itemVid = 2001;
ttm.RegisterItemTextTail(itemVid, "Full Moon Sword +9", 50.0f, 0.0f, 50.0f, 180, "WarriorKing", true, 0xFFFFFFFF);
assert(ttm.HasItem(itemVid));
uint32_t itemVid2 = 2002;
ttm.RegisterItemTextTail(itemVid2, "Red Potion (L)", 50.0f, 0.0f, 50.0f, 0, "", false, 0xFFFF4040);
assert(ttm.HasItem(itemVid2));
// 4. Update projections & show texttails
ttm.ShowAllTextTail();
assert(ttm.GetShowingCharacterCount() == 1);
assert(ttm.GetShowingItemCount() == 2);
ttm.UpdateAllTextTail(0.0f, 0.0f, 0.0f, &renderer);
ttm.UpdateShowingTextTail(&renderer);
float ttx = 0.0f, tty = 0.0f, ttz = 0.0f;
bool hasPos = ttm.GetTextTailPosition(charVid, ttx, tty, ttz);
assert(hasPos && "Character texttail must have valid screen position");
std::cout << "Projected Character TextTail screen pos: (" << ttx << ", " << tty << ")" << std::endl;
// 5. Arrange texttails (overlap resolution)
auto item1 = ttm.GetItemTail(itemVid);
auto item2 = ttm.GetItemTail(itemVid2);
float origY2 = item2->y;
ttm.ArrangeTextTail();
// Since item1 and item2 were at same world pos, item2's y must be shifted down to prevent overlap!
assert(item2->y > origY2 && "Overlapping items must be arranged apart");
std::cout << "ArrangeTextTail resolved overlap: item1.y=" << item1->y << ", item2.y=" << item2->y << std::endl;
// 6. Mouse Picking
// Mouse clicked on item1's screen position
int pickVid = ttm.Pick(static_cast<int>(item1->x), static_cast<int>(item1->y));
assert(pickVid == static_cast<int>(itemVid) && "Mouse picking must hit item1");
assert(item1->isSelected && "Picked item must be marked as selected");
std::cout << "Mouse picking successfully picked item VID: " << pickVid << std::endl;
// 7. Chat timer update
ttm.Update(5.0f); // Fast forward past chat duration
assert(!ttm.IsChatTextTail(charVid) && "Chat bubble must expire after duration");
// 8. Hide and Clear
ttm.HideAllTextTail();
assert(ttm.GetShowingCharacterCount() == 0);
assert(ttm.GetShowingItemCount() == 0);
ttm.Clear();
assert(ttm.GetCharacterCount() == 0);
std::cout << "TextTailManager verified successfully!" << std::endl;
// ── Test ScreenToWorldRay & Terrain Picking (40250 GrpScreen & MapOutdoor) ─
std::cout << "\n── Testing ScreenToWorldRay & PickTerrain ──" << std::endl;
cam.SetTarget(0.0f, h_center, 0.0f);
cam.SetDistance(450.0f);
cam.SetPitch(25.0f);
cam.SetYaw(0.0f);
cam.ApplyToRenderer(renderer);
renderer.SetPerspective(50.0f, static_cast<float>(width) / static_cast<float>(height), 1.0f, 4000.0f);
float rayOrig[3] = {0}, rayDir[3] = {0};
bool rayOk = renderer.ScreenToWorldRay(width * 0.5f, height * 0.5f, rayOrig, rayDir);
assert(rayOk && "ScreenToWorldRay must succeed for screen center");
float rLen = std::sqrt(rayDir[0]*rayDir[0] + rayDir[1]*rayDir[1] + rayDir[2]*rayDir[2]);
assert(std::abs(rLen - 1.0f) < 1e-4f && "Ray direction must be normalized");
std::cout << "Unprojected ray: Orig(" << rayOrig[0] << ", " << rayOrig[1] << ", " << rayOrig[2]
<< ") Dir(" << rayDir[0] << ", " << rayDir[1] << ", " << rayDir[2] << ")" << std::endl;
float pickX = 0, pickY = 0, pickZ = 0;
bool pickOk = renderer.PickTerrain(width * 0.5f, height * 0.5f, terrain, pickX, pickY, pickZ);
std::cout << "PickTerrain at center: " << (pickOk ? "HIT" : "MISS")
<< " (" << pickX << ", " << pickY << ", " << pickZ << ")" << std::endl;
assert(pickOk && "Screen center ray must hit terrain in outdoor scene");
float groundH = terrain.GetHeightAtWorld(pickX, pickZ);
assert(std::abs(pickY - groundH) < 0.1f && "PickTerrain Y coordinate must match terrain heightmap");
// ── Test Click-to-Move & Destination Pathing ───────────────────────────
std::cout << "\n── Testing Click-to-Move & Destination Pathing ──" << std::endl;
actor.SetPosition(0.0f, h_center, 0.0f);
actor.PlayMotion(ava2::MotionType::Wait, true);
actor.SetMoveTarget(80.0f, 60.0f);
assert(actor.HasMoveTarget());
float tx = 0, tz = 0;
actor.GetMoveTarget(tx, tz);
assert(tx == 80.0f && tz == 60.0f);
actor.Update(0.1f, &terrain);
assert(actor.GetCurrentMotion() == ava2::MotionType::Run);
assert(actor.GetX() > 0.0f && actor.GetZ() > 0.0f && "Actor must move towards destination");
// Advance until destination reached
actor.Update(1.0f, &terrain);
assert(!actor.HasMoveTarget() && "Actor must clear move target upon arriving at destination");
assert(actor.GetCurrentMotion() == ava2::MotionType::Wait);
// ── Test Screen Space Capsule HitTestScreen ────────────────────────────
std::cout << "\n── Testing HitTestScreen ──" << std::endl;
actor.SetPosition(0.0f, h_center, 0.0f);
float ax = 0, ay = 0;
bool aProj = renderer.ProjectToScreen(0.0f, h_center, 0.0f, ax, ay);
assert(aProj);
assert(actor.HitTestScreen(ax, ay, renderer, 40.0f) && "Click at projected base must hit actor");
assert(!actor.HitTestScreen(ax + 200.0f, ay + 200.0f, renderer, 40.0f) && "Click far away must miss actor");
// ── Test TargetManager (Selection Ring Decal, TargetBoard, EFFECT_PICK)
std::cout << "\n── Testing TargetManager (Selection Ring & TargetBoard) ──" << std::endl;
ava2::TargetManager tm;
actor.SetVID(1001);
actor.SetName("WarriorHero");
actor.SetMaxHP(1200);
tm.SelectTarget(&actor);
assert(tm.HasTarget());
assert(tm.GetTarget() == &actor);
assert(tm.GetTargetVID() == 1001);
tm.AddGroundPickEffect(pickX, pickY, pickZ);
assert(tm.HasGroundPickEffect());
tm.Update(0.1f);
assert(tm.HasGroundPickEffect());
// Software renderer verification of TargetManager drawing routines
SDL_Renderer* sw_rnd = SDL_CreateSoftwareRenderer(surface);
assert(sw_rnd && "SDL_CreateSoftwareRenderer must succeed");
tm.Render(sw_rnd, renderer);
// Render floating text as well
ftm.AddDamage(350, 0.0f, h_center + 60.0f, 0.0f, true, true);
ftm.Render(sw_rnd, renderer);
// Render TextTailManager overhead nameplates & dropped items
ttm.RegisterCharacterTextTail(1, 1001, 0xFFFFFFFF, 175.0f);
ttm.SetCharacterName(1001, "WarriorHero");
ttm.AttachTitle(1001, "Noble", 0xFFFFD700);
ttm.AttachLevel(1001, "[Lv. 99]", 0xFF98FF33);
ttm.SetGuildName(1001, "Olympus");
ttm.SetCharacterPosition(1001, 0.0f, h_center, 0.0f);
ttm.RegisterChatTail(1001, "Metin2 TextTail System Online!");
ttm.RegisterItemTextTail(5001, "Full Moon Sword +9", 60.0f, h_center, 40.0f, 180, "WarriorHero", true);
ttm.RegisterItemTextTail(5002, "Red Potion (L)", 60.0f, h_center, 40.0f, 0, "", false, 0xFFFF3333);
ttm.ShowAllTextTail();
ttm.UpdateAllTextTail(0.0f, h_center, 0.0f, &renderer);
ttm.UpdateShowingTextTail(&renderer);
ttm.ArrangeTextTail();
ttm.SelectItemName(5001);
ttm.Render(sw_rnd, &renderer);
SDL_RenderPresent(sw_rnd);
const char* texttail_screenshot = "/tmp/test_3d_texttail_scene.bmp";
SDL_SaveBMP(surface, texttail_screenshot);
std::cout << "Successfully saved texttail + 3D scene render to: " << texttail_screenshot << std::endl;
SDL_DestroyRenderer(sw_rnd);
tm.ClearTarget();
assert(!tm.HasTarget() && "ClearTarget must clear selected actor");
std::cout << "TargetManager & Click-to-Move verified successfully!" << std::endl;
// ── Test PRTerrainLib: Quadtree, Frustum Culling, Attr Blocking & Multi-Texture Patch Shading ──
std::cout << "\n── Testing PRTerrainLib Quadtree, Frustum Culling & Attr Collision ──" << std::endl;
ava2::TerrainHeightmap pr_terrain;
std::string test_raw = "map/metin2_map_a1/001003/height.raw";
if (!std::filesystem::exists(test_raw)) {
test_raw = PackMaker() + "/Maps/metin2_map_a1/001003/height.raw";
}
std::string test_tile = "map/metin2_map_a1/001003/tile.raw";
if (!std::filesystem::exists(test_tile)) {
test_tile = PackMaker() + "/Maps/metin2_map_a1/001003/tile.raw";
}
std::string test_attr = "map/metin2_map_a1/001003/attr.atr";
if (!std::filesystem::exists(test_attr)) {
test_attr = PackMaker() + "/Maps/metin2_map_a1/001003/attr.atr";
}
std::string test_tset = "textureset/metin2_map1.txt";
if (!std::filesystem::exists(test_tset)) {
test_tset = PackMaker() + "/textureset/textureset/metin2_map1.txt";
}
if (std::filesystem::exists(test_raw)) {
bool raw_res = pr_terrain.LoadRaw(test_raw, 0.5f, 200.0f);
assert(raw_res && "PRTerrain LoadRaw must succeed");
std::cout << "Loaded official height.raw: " << pr_terrain.GetWidth() << "x" << pr_terrain.GetHeight() << std::endl;
}
if (std::filesystem::exists(test_tile)) {
bool tile_res = pr_terrain.LoadTileRaw(test_tile);
assert(tile_res && "PRTerrain LoadTileRaw must succeed");
std::cout << "Loaded official tile.raw: " << pr_terrain.GetTileWidth() << "x" << pr_terrain.GetTileHeight() << std::endl;
}
if (std::filesystem::exists(test_attr)) {
bool attr_res = pr_terrain.LoadAttr(test_attr);
assert(attr_res && "PRTerrain LoadAttr must succeed");
std::cout << "Loaded official attr.atr: " << pr_terrain.GetAttrWidth() << "x" << pr_terrain.GetAttrHeight() << std::endl;
assert(pr_terrain.GetAttrWidth() == 256 && pr_terrain.GetAttrHeight() == 256);
}
if (std::filesystem::exists(test_tset)) {
bool tset_res = pr_terrain.LoadTextureSet(test_tset);
assert(tset_res && "PRTerrain LoadTextureSet must succeed");
std::cout << "Loaded textureset: " << test_tset << std::endl;
}
// 1. Verify 8x8 Patch Quadtree
assert(pr_terrain.GetPatchCount() == 64 && "Terrain must have 64 (8x8) patches");
std::cout << "Verified 8x8 patches (count = " << pr_terrain.GetPatchCount() << ")" << std::endl;
// 2. Verify Frustum Culling with OrbitCamera
float pr_h_center = pr_terrain.GetHeightAtWorld(0.0f, 0.0f);
ava2::OrbitCamera qt_cam;
qt_cam.SetDistance(450.0f);
qt_cam.SetPitch(22.0f);
qt_cam.SetYaw(20.0f);
qt_cam.SetTargetHeight(95.0f);
qt_cam.SetTarget(0.0f, pr_h_center, 0.0f);
qt_cam.ApplyToRenderer(renderer);
renderer.SetPerspective(50.0f, static_cast<float>(width) / static_cast<float>(height), 1.0f, 8000.0f);
auto culled_draws = pr_terrain.BuildCulledDraws(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 8000.0f);
auto repeatedTerrain = pr_terrain.BuildCulledDraws(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 8000.0f);
assert(!culled_draws.empty() && culled_draws.size()==repeatedTerrain.size());
assert(culled_draws.front().geometry==repeatedTerrain.front().geometry);
assert(!culled_draws.front().Mesh().positions.empty());
const auto oldTerrainGeometry = culled_draws.front().geometry;
pr_terrain.SetWorldOrigin(pr_terrain.GetWorldMinX(),pr_terrain.GetWorldMinZ());
repeatedTerrain = pr_terrain.BuildCulledDraws(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 8000.0f);
assert(!repeatedTerrain.empty() && repeatedTerrain.front().geometry!=oldTerrainGeometry);
std::cout << "Quadtree Frustum Culling visible patch draws: " << culled_draws.size() << " / 64" << std::endl;
assert(!culled_draws.empty() && culled_draws.size() <= 64 && "Culled draws must be non-empty and <= 64");
// 3. Test Collision & Wall Sliding in ActorInstance
std::cout << "Testing ActorInstance collision and wall sliding against ATTR_BLOCK..." << std::endl;
ava2::ActorInstance col_actor;
col_actor.SetSpeed(300.0f);
col_actor.SetPosition(0.0f, pr_terrain.GetHeightAtWorld(0.0f, 0.0f), 0.0f);
float startX = col_actor.GetX();
float startZ = col_actor.GetZ();
col_actor.MoveInDirection(0.0f, 0.1f, &pr_terrain);
std::cout << "Actor moved from (" << startX << ", " << startZ << ") to (" << col_actor.GetX() << ", " << col_actor.GetZ() << ")" << std::endl;
// Test Attribute Query & Collision Blocking
int block_gx = -1, block_gy = -1;
for (int y = 5; y < pr_terrain.GetAttrHeight() - 5; ++y) {
for (int x = 5; x < pr_terrain.GetAttrWidth() - 5; ++x) {
if ((pr_terrain.GetAttrAtGrid(x, y) & ava2::TerrainAttr::ATTR_BLOCK) &&
!(pr_terrain.GetAttrAtGrid(x, y - 1) & ava2::TerrainAttr::ATTR_BLOCK)) {
block_gx = x;
block_gy = y;
break;
}
}
if (block_gx >= 0) break;
}
if (block_gx >= 0) {
std::cout << "Found ATTR_BLOCK boundary at grid (" << block_gx << ", " << block_gy << ")" << std::endl;
// attr.atr cells are half a height cell, starting at the block origin one height cell in.
const float attr_cell = pr_terrain.GetCellScale() * 0.5f;
float b_world_x = pr_terrain.GetWorldMinX() + pr_terrain.GetCellScale() + (static_cast<float>(block_gx) + 0.5f) * attr_cell;
float b_world_z = pr_terrain.GetWorldMinZ() + pr_terrain.GetCellScale() + (static_cast<float>(block_gy) + 0.5f) * attr_cell;
float walk_z = pr_terrain.GetWorldMinZ() + pr_terrain.GetCellScale() + (static_cast<float>(block_gy - 1) + 0.5f) * attr_cell;
assert(pr_terrain.IsAttrOn(b_world_x, b_world_z, ava2::TerrainAttr::ATTR_BLOCK));
assert(!pr_terrain.IsAttrOn(b_world_x, walk_z, ava2::TerrainAttr::ATTR_BLOCK));
// Place actor at walkable tile, attempting to walk directly north (+Z) into blocked tile
col_actor.SetPosition(b_world_x, pr_terrain.GetHeightAtWorld(b_world_x, walk_z), walk_z);
col_actor.MoveInDirection(0.0f, 0.5f, &pr_terrain); // Try to step into blocked cell
// Actor must NOT enter the blocked cell
assert(!pr_terrain.IsAttrOn(col_actor.GetX(), col_actor.GetZ(), ava2::TerrainAttr::ATTR_BLOCK) && "Actor must not penetrate blocked cell");
std::cout << "Actor collision blocking verified: Actor prevented from penetrating ATTR_BLOCK tile at (" << col_actor.GetX() << ", " << col_actor.GetZ() << ")" << std::endl;
}
// 4. Render Quadtree Multi-texture Terrain Scene
SDL_FillSurfaceRect(surface, nullptr, 0xFF7098B8);
renderer.Clear(0xFF7098B8, 1.0f);
renderer.SetFog(true, 0xFFB4C8E0, 0.00010f, 1500.0f, 7500.0f, false);
std::vector<ava2::Render3DDraw> quadtree_scene_draws;
for (auto&& d : culled_draws) {
quadtree_scene_draws.push_back(std::move(d));
}
ava2::MapObjectManager pr_bldgs;
std::string gate_path = "ymir work/zone/b/building/b1-034-stonedoor.gr2";
if (std::filesystem::exists(gate_path)) {
float gh = pr_terrain.GetHeightAtWorld(0.0f, 800.0f);
pr_bldgs.AddObject(gate_path, 0.0f, gh, 800.0f, 0.0f, 0.0f, 0.0f, 0.55f);
}
for (auto& bd : pr_bldgs.BuildDrawCommands()) {
quadtree_scene_draws.push_back(std::move(bd));
}
if (model) {
float char_world[16];
ava2::MakeTransformMatrix(20.0f + 180.0f, 0.0f, pr_h_center, 0.0f, 0.8f, char_world);
auto char_draws = model->BuildDrawCommands(-1.0f, char_world);
for (auto& cd : char_draws) {
quadtree_scene_draws.push_back(std::move(cd));
}
}
renderer.RenderScene(surface, quadtree_scene_draws);
// 5. Overlay 2D HUD / TextTails / Radar on top of quadtree scene
SDL_Renderer* qt_sw_rnd = SDL_CreateSoftwareRenderer(surface);
if (qt_sw_rnd) {
ttm.SetCharacterPosition(1001, 0.0f, pr_h_center, 0.0f);
ttm.UpdateAllTextTail(0.0f, pr_h_center, 0.0f, &renderer);
ttm.UpdateShowingTextTail(&renderer);
ttm.ArrangeTextTail();
ttm.Render(qt_sw_rnd, &renderer);
tm.Render(qt_sw_rnd, renderer, &pr_terrain);
SDL_RenderPresent(qt_sw_rnd);
SDL_DestroyRenderer(qt_sw_rnd);
}
const char* quadtree_screenshot = "/tmp/test_3d_terrain_quadtree.bmp";
SDL_SaveBMP(surface, quadtree_screenshot);
std::cout << "Successfully saved terrain quadtree render to: " << quadtree_screenshot << std::endl;
SDL_DestroySurface(surface);
// 6. Test Metin2 / MilesLib SoundManager Engine
std::cout << "Testing SoundManager Audio Engine (2D/3D SFX, BGM streaming, .mss parsing)..." << std::endl;
auto& snd = ava2::SoundManager::Instance();
bool snd_init = snd.Initialize();
assert(snd_init && "SoundManager::Initialize must succeed");
snd.SetSoundVolumeGrade(5);
assert(snd.GetSoundVolume() >= 0.99f);
snd.SetMusicVolumeGrade(4);
assert(snd.GetMusicVolume() > 0.0f);
snd.SetPosition(0.0f, pr_h_center, 0.0f);
// Test 2D sound effect playback (UI click)
snd.PlaySound2D("sound/ui/click.wav");
// Test 3D sound effect playback (Warrior Skill / Swing)
snd.PlaySound3D(50.0f, pr_h_center, 50.0f, "sound/common/swing/w_1h_c_1.wav");
// Test BGM music streaming via dr_mp3 decoder
snd.FadeInMusic("BGM/login_window.mp3", 0.05f);
snd.Update(0.1f);
assert(!snd.GetCurrentMusic().empty());
// Test Character Sound Script (.mss) parsing
std::vector<ava2::CharacterSoundEvent> mss_events;
bool mss_loaded = snd.LoadCharacterSoundScript("sound/pc/warrior/skill/samyeon.mss", mss_events);
if (!mss_loaded) {
mss_loaded = snd.LoadCharacterSoundScript(PackMaker() + "/Sound/sound/pc/warrior/skill/samyeon.mss", mss_events);
}
assert(mss_loaded && "Samyeon .mss script must be loaded");
assert(mss_events.size() == 2 && "Samyeon .mss must have exactly 2 sound events");
std::cout << "Verified Samyeon .mss events: [" << mss_events[0].time << "s -> " << mss_events[0].soundFile
<< "], [" << mss_events[1].time << "s -> " << mss_events[1].soundFile << "]" << std::endl;
snd.Update(0.5f);
std::cout << "SoundManager verified with " << snd.GetCachedSoundCount() << " cached audio assets." << std::endl;
// 7. Test Metin2 EffectLib & GameLib Particles & Flying Engine
std::cout << "Testing EffectLib & FlyingManager Particle and Missile Engine..." << std::endl;
auto& effMgr = ava2::EffectManager::Instance();
auto& flyMgr = ava2::FlyingManager::Instance();
// Test .mse loading: Palbang ground spin
uint32_t palbang_id = 0;
bool palbang_loaded = effMgr.RegisterEffect("ymir work/pc/warrior/effect/palbang_2_spin.mse", &palbang_id);
assert(palbang_loaded && "Palbang .mse must load successfully");
assert(palbang_id != 0 && "Palbang effect ID must be non-zero");
// Test .mse loading: Samyeon triple slash
uint32_t samyeon_id = 0;
bool samyeon_loaded = effMgr.RegisterEffect("ymir work/pc/warrior/effect/samyeon_d.mse", &samyeon_id);
assert(samyeon_loaded && "Samyeon .mse must load successfully");
// Test .mse loading: Aura of the sword (continuous weapon aura)
uint32_t geom_id = 0;
bool geom_loaded = effMgr.RegisterEffect("ymir work/pc/warrior/effect/geom_sword_loop.mse", &geom_id);
assert(geom_loaded && "Geom sword loop .mse must load successfully");
// Test creating instances
uint32_t palbang_inst = effMgr.CreateEffect(palbang_id, 0.0f, 100.0f, 0.0f);
assert(palbang_inst != 0 && "Effect instance creation must succeed");
assert(effMgr.IsAliveEffect(palbang_inst) && "Created effect must be alive");
// Test updating instance past StartTime (0.208s)
effMgr.Update(0.3f);
assert(effMgr.IsAliveEffect(palbang_inst));
// Test draw command generation for billboard particle quads
float dummyView[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float dummyProj[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float dummyCam[3] = {0.0f, 100.0f, -200.0f};
std::vector<ava2::Render3DDraw> effectDraws;
effMgr.BuildDrawCommands(dummyView, dummyProj, dummyCam, effectDraws);
assert(!effectDraws.empty() && "EffectManager must produce 3D draw commands for active particles");
assert(effectDraws[0].blend_mode == 1 && "Palbang spin effect must use Additive blend mode");
assert(effectDraws[0].lighting == false && "Particles must not have lighting enabled");
// Test FlyTrace weapon/projectile ribbon
ava2::FlyTrace trace;
trace.Create(0xFFFFAA00, 0.3f, 15.0f, false);
trace.UpdateNewPosition(0.0f, 100.0f, 0.0f, 0.0f);
trace.UpdateNewPosition(10.0f, 105.0f, 5.0f, 0.05f);
trace.UpdateNewPosition(25.0f, 110.0f, 15.0f, 0.10f);
assert(!trace.IsEmpty() && "FlyTrace must contain positions");
std::vector<ava2::Render3DDraw> traceDraws;
float traceProjection[16]={};traceProjection[0]=traceProjection[5]=0.001f;traceProjection[10]=0.0005f;traceProjection[14]=0.5f;traceProjection[15]=1;
trace.BuildDrawCommands(dummyView,traceProjection,0.12f,traceDraws);
assert(!traceDraws.empty() && "FlyTrace must generate ribbon quad draw commands");
assert(traceDraws[0].blend_mode == 1 && "FlyTrace must use Additive blend mode");
// Test .msf projectile loading and simulation
uint32_t geompung_msf_id = 0;
bool msf_loaded = flyMgr.RegisterFlyingData("ymir work/pc/warrior/effect/geompung.msf", &geompung_msf_id);
assert(msf_loaded && "Geompung .msf must load successfully");
float flyStart[3] = {0.0f, 100.0f, 0.0f};
float flyTarget[3] = {200.0f, 100.0f, 0.0f};
bool hitTriggered = false;
uint32_t flyInst = flyMgr.CreateFlyingInstance(geompung_msf_id, flyStart, flyTarget, [&](const float* hitPos) {
hitTriggered = true;
});
assert(flyInst != 0 && "FlyingInstance creation must succeed");
// Simulate flying until hit
for (int step = 0; step < 20 && !hitTriggered; ++step) {
flyMgr.Update(0.02f, step * 0.02f);
}
assert(hitTriggered && "Flying missile must hit target and trigger explosion callback");
std::cout << "EffectLib, Particle Billboard, FlyTrace and FlyingManager pipeline passed successfully!" << std::endl;
// 8. Test NetworkActorManager (CNetworkActorManager 1:1 Replica)
std::cout << "Testing NetworkActorManager (CNetworkActorManager 1:1 Replica)..." << std::endl;
auto& netActorMgr = ava2::NetworkActorManager::Instance();
netActorMgr.Clear();
netActorMgr.SetMainActorVID(1001);
// Append warrior player actor
ava2::SNetworkActorData mainActorData;
mainActorData.m_dwVID = 1001;
mainActorData.m_stName = "WarriorHero";
mainActorData.m_bType = 6; // PC
mainActorData.m_dwRace = 0; // Warrior
mainActorData.m_dwLevel = 99;
mainActorData.m_dwGuildID = 1;
mainActorData.m_stGuildName = "Antigravity";
mainActorData.m_sAlignment = 12500; // Chivalric
mainActorData.m_dwWeapon = 299;
mainActorData.m_dwHair = 1;
mainActorData.m_lCurX = 0;
mainActorData.m_lCurY = 0;
mainActorData.m_lCurZ = static_cast<int32_t>(pr_h_center);
mainActorData.m_fRot = 45.0f;
netActorMgr.AppendActor(mainActorData);
assert(netActorMgr.GetActorData(1001) != nullptr && "Main actor must exist in NetworkActorManager");
assert(netActorMgr.GetActorInstance(1001) != nullptr && "Main actor must have valid ActorInstance");
// Append surrounding mob (Plechi slime / frog)
ava2::SNetworkActorData mobData;
mobData.m_dwVID = 2001;
mobData.m_stName = "WildDog";
mobData.m_bType = 0; // Mob
mobData.m_dwRace = 102; // Plechi frog
mobData.m_dwLevel = 5;
mobData.m_lCurX = 150;
mobData.m_lCurY = 150;
mobData.m_lCurZ = static_cast<int32_t>(pr_h_center);
netActorMgr.AppendActor(mobData);
assert(netActorMgr.GetActorDict().size() == 2 && "Actor dict must contain 2 actors");
// Test MoveActor interpolation
ava2::SNetworkMoveActorData mv;
mv.m_dwVID = 2001;
mv.m_dwFunc = 1; // Move
mv.m_lPosX = 100;
mv.m_lPosY = 100;
mv.m_fRot = 180.0f;
netActorMgr.MoveActor(mv);
assert(netActorMgr.GetActorData(2001)->m_isMoving && "Mob must enter moving state");
// Update 0.1s
netActorMgr.Update(0.1f, &pr_terrain);
assert(netActorMgr.GetActorData(2001)->m_lCurX < 150 && "Mob must advance towards target");
// Test SyncActor
netActorMgr.SyncActor(2001, 80, 80);
assert(netActorMgr.GetActorData(2001)->m_lCurX == 80 && "SyncActor must set exact coordinate");
assert(!netActorMgr.GetActorData(2001)->m_isMoving && "SyncActor must finish moving");
// Test UpdateActor
ava2::SNetworkUpdateActorData upd;
upd.m_dwVID = 1001;
upd.m_dwWeapon = 299;
upd.m_sAlignment = -12500; // Cruel
netActorMgr.UpdateActor(upd);
assert(netActorMgr.GetActorData(1001)->m_sAlignment == -12500 && "Actor alignment must be updated");
std::cout << "NetworkActorManager verified with 2 active network actors." << std::endl;
// 9. Render Skill Particle Effects Showcase Scene
std::cout << "Rendering Skill Particle & Missile Effects Showcase Scene..." << std::endl;
SDL_Surface* eff_surf = SDL_CreateSurface(1024, 768, SDL_PIXELFORMAT_ARGB8888);
if (eff_surf) {
SDL_FillSurfaceRect(eff_surf, nullptr, 0xFFB4C8E0);
renderer.SetViewport(0, 0, 1024, 768);
renderer.Clear(0xFFB4C8E0, 1.0f);
renderer.SetFog(true, 0xFFB4C8E0, 0.00010f, 1800.0f, 7500.0f, false);
renderer.SetCameraLookAt(70.0f, pr_h_center + 140.0f, -240.0f, 30.0f, pr_h_center + 45.0f, 30.0f, 0.0f, 1.0f, 0.0f);
renderer.SetPerspective(48.0f, 1024.0f / 768.0f, 1.0f, 5000.0f);
std::vector<ava2::Render3DDraw> scene_draws;
// Terrain
auto terr_draws = pr_terrain.BuildCulledDraws(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 6000.0f);
for (auto& td : terr_draws) scene_draws.push_back(std::move(td));
// Buildings
for (auto& bd : pr_bldgs.BuildDrawCommands()) scene_draws.push_back(std::move(bd));
// Warrior character with weapon
if (model) {
float char_world[16];
ava2::MakeTransformMatrix(45.0f + 180.0f, 0.0f, pr_h_center, 0.0f, 0.8f, char_world);
auto char_draws = model->BuildDrawCommands(-1.0f, char_world);
for (auto& cd : char_draws) scene_draws.push_back(std::move(cd));
}
// Active particles: Palbang ground spin, Aura flame, and Hit Sparks
effMgr.DeleteAllInstances();
uint32_t eff_spin = effMgr.CreateEffect("ymir work/pc/warrior/effect/palbang_2_spin.mse", 0.0f, pr_h_center + 5.0f, 0.0f);
uint32_t eff_aura = effMgr.CreateEffect("ymir work/pc/warrior/effect/geom_sword_loop.mse", 15.0f, pr_h_center + 60.0f, 10.0f);
uint32_t eff_spark = effMgr.CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", 90.0f, pr_h_center + 45.0f, 50.0f);
effMgr.Update(0.35f);
float effCamPos[3] = {70.0f, pr_h_center + 140.0f, -240.0f};
effMgr.BuildDrawCommands(renderer.GetViewMatrix(), renderer.GetProjMatrix(), effCamPos, scene_draws);
// Sword blade ribbon trace
ava2::FlyTrace blade_trace;
blade_trace.Create(0xFFFFAA00, 0.4f, 18.0f, false);
blade_trace.UpdateNewPosition(-20.0f, pr_h_center + 50.0f, -10.0f, 0.0f);
blade_trace.UpdateNewPosition(0.0f, pr_h_center + 65.0f, 10.0f, 0.05f);
blade_trace.UpdateNewPosition(25.0f, pr_h_center + 60.0f, 25.0f, 0.10f);
blade_trace.UpdateNewPosition(50.0f, pr_h_center + 55.0f, 35.0f, 0.15f);
blade_trace.BuildDrawCommands(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 0.18f, scene_draws);
// Flying projectile ribbon trace
ava2::FlyTrace proj_trace;
proj_trace.Create(0xFF44CCFF, 0.5f, 12.0f, false);
proj_trace.UpdateNewPosition(15.0f, pr_h_center + 60.0f, 10.0f, 0.0f);
proj_trace.UpdateNewPosition(40.0f, pr_h_center + 55.0f, 25.0f, 0.06f);
proj_trace.UpdateNewPosition(65.0f, pr_h_center + 50.0f, 38.0f, 0.12f);
proj_trace.UpdateNewPosition(85.0f, pr_h_center + 46.0f, 48.0f, 0.18f);
proj_trace.BuildDrawCommands(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 0.20f, scene_draws);
renderer.RenderScene(eff_surf, scene_draws);
// Overlay TextTail and floating text
SDL_Renderer* eff_rnd = SDL_CreateSoftwareRenderer(eff_surf);
if (eff_rnd) {
ttm.SetCharacterPosition(1001, 0.0f, pr_h_center, 0.0f);
ttm.UpdateAllTextTail(0.0f, pr_h_center, 0.0f, &renderer);
ttm.UpdateShowingTextTail(&renderer);
ttm.ArrangeTextTail();
ttm.Render(eff_rnd, &renderer);
SDL_RenderPresent(eff_rnd);
SDL_DestroyRenderer(eff_rnd);
}
const char* eff_screenshot = "/tmp/test_3d_skill_effects.bmp";
SDL_SaveBMP(eff_surf, eff_screenshot);
std::cout << "Successfully saved skill effects render to: " << eff_screenshot << std::endl;
SDL_DestroySurface(eff_surf);
}
// 10. Render Stage 5: PhaseGame Network Actor Synchronization Showcase Scene
std::cout << "Rendering Stage 5 PhaseGame Network Actors & Synchronized World Scene..." << std::endl;
SDL_Surface* net_surf = SDL_CreateSurface(1024, 768, SDL_PIXELFORMAT_ARGB8888);
if (net_surf) {
SDL_FillSurfaceRect(net_surf, nullptr, 0xFFB4C8E0);
renderer.SetViewport(0, 0, 1024, 768);
renderer.Clear(0xFFB4C8E0, 1.0f);
renderer.SetFog(true, 0xFFB4C8E0, 0.00010f, 1800.0f, 7500.0f, false);
renderer.SetCameraLookAt(50.0f, pr_h_center + 130.0f, -230.0f, 10.0f, pr_h_center + 45.0f, 25.0f, 0.0f, 1.0f, 0.0f);
renderer.SetPerspective(48.0f, 1024.0f / 768.0f, 1.0f, 5000.0f);
std::vector<ava2::Render3DDraw> scene_draws;
// Terrain
auto terr_draws = pr_terrain.BuildCulledDraws(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 6000.0f);
for (auto& td : terr_draws) scene_draws.push_back(std::move(td));
// Buildings
for (auto& bd : pr_bldgs.BuildDrawCommands()) scene_draws.push_back(std::move(bd));
// Add 3rd Network Actor: Sura Mage (VID 1002)
ava2::SNetworkActorData suraData;
suraData.m_dwVID = 1002;
suraData.m_stName = "SuraMage";
suraData.m_bType = 6; // PC
suraData.m_dwRace = 2; // Sura
suraData.m_dwLevel = 75;
suraData.m_dwGuildID = 2;
suraData.m_stGuildName = "ShinsooEmpire";
suraData.m_sAlignment = 8000; // Noble
suraData.m_lCurX = -75;
suraData.m_lCurY = 35;
suraData.m_lCurZ = static_cast<int32_t>(pr_h_center);
suraData.m_fRot = 120.0f;
netActorMgr.AppendActor(suraData);
// Network ActorManager 3D draws for all actors (Main Warrior, WildDog, SuraMage)
auto net_draws = netActorMgr.BuildDrawCommands(0.2f);
for (auto& nd : net_draws) scene_draws.push_back(std::move(nd));
// Warrior character fallback if model was directly loaded
if (model) {
float char_world[16];
ava2::MakeTransformMatrix(45.0f + 180.0f, 0.0f, pr_h_center, 0.0f, 0.8f, char_world);
auto char_draws = model->BuildDrawCommands(-1.0f, char_world);
for (auto& cd : char_draws) scene_draws.push_back(std::move(cd));
}
// Sword blade slash ribbon from Warrior attack
ava2::FlyTrace blade_trace;
blade_trace.Create(0xFFFFAA00, 0.4f, 18.0f, false);
blade_trace.UpdateNewPosition(-10.0f, pr_h_center + 45.0f, -5.0f, 0.0f);
blade_trace.UpdateNewPosition(15.0f, pr_h_center + 60.0f, 15.0f, 0.06f);
blade_trace.UpdateNewPosition(45.0f, pr_h_center + 55.0f, 35.0f, 0.12f);
blade_trace.BuildDrawCommands(renderer.GetViewMatrix(), renderer.GetProjMatrix(), 0.15f, scene_draws);
// Hit spark particle effect at mob location
uint32_t net_spark = effMgr.CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", 80.0f, pr_h_center + 40.0f, 80.0f);
(void)net_spark;
effMgr.Update(0.2f);
float netCamPos[3] = {50.0f, pr_h_center + 130.0f, -230.0f};
effMgr.BuildDrawCommands(renderer.GetViewMatrix(), renderer.GetProjMatrix(), netCamPos, scene_draws);
renderer.RenderScene(net_surf, scene_draws);
// 2D Overlay: TextTail & Floating Damage Numbers
SDL_Renderer* net_rnd = SDL_CreateSoftwareRenderer(net_surf);
if (net_rnd) {
ttm.RegisterChatTail(1001, "[PhaseGame] Protocol 1:1 Synced!");
ttm.RegisterItemTextTail(7777, "Full Moon Sword +9", 35.0f, pr_h_center, -45.0f, 180, "Antigravity", true);
ttm.RegisterItemTextTail(7778, "Blessing Scroll", 55.0f, pr_h_center, -30.0f, 0, "", false, 0xFFFFCC33);
ttm.ShowAllTextTail();
ttm.SetCharacterPosition(1001, 0.0f, pr_h_center, 0.0f);
ttm.SetCharacterPosition(1002, -75.0f, pr_h_center, 35.0f);
ttm.SetCharacterPosition(2001, 80.0f, pr_h_center, 80.0f);
ttm.UpdateAllTextTail(0.0f, pr_h_center, 0.0f, &renderer);
ttm.UpdateShowingTextTail(&renderer);
ttm.ArrangeTextTail();
ttm.SelectItemName(7777);
ttm.Render(net_rnd, &renderer);
// Floating combat damage numbers
ftm.Clear();
ftm.AddDamage(2450, 80.0f, pr_h_center + 70.0f, 80.0f, true, true); // Critical hit on mob
ftm.AddDamage(320, -75.0f, pr_h_center + 85.0f, 35.0f, false, false); // Normal damage on sura
ftm.Render(net_rnd, renderer);
SDL_RenderPresent(net_rnd);
SDL_DestroyRenderer(net_rnd);
}
const char* net_screenshot = "/tmp/test_3d_network_phasegame.bmp";
SDL_SaveBMP(net_surf, net_screenshot);
std::cout << "Successfully saved PhaseGame network scene render to: " << net_screenshot << std::endl;
SDL_DestroySurface(net_surf);
}
std::cout << "AVA2 3D GR2 Model, Water, Fog, PRTerrain Quadtree, Attr Blocking, Combat, Picking, Targeting, Audio & Effects Pipeline passed successfully!" << std::endl;
return 0;
}