Preview radar drew at the fixed PC spot; it now follows the uiminimap window (CPythonMiniMap::GetScreenPosition) and its open state. On Android the top safe inset came from the hidden status bar's gesture zone; Ava2Surface takes the top only from the cutout and visible bars. The preview keyboard-hint header is skipped in touch mode, and --game-script also runs with --preview-data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2773 lines
165 KiB
C++
2773 lines
165 KiB
C++
#include <SDL3/SDL.h>
|
|
#include "app/app_loop.h"
|
|
#include "eter_render/Gr2ModelRenderer.h"
|
|
#include "eter_render/TerrainHeightmap.h"
|
|
#include "eter_render/MapObjectManager.h"
|
|
#include "eter_render/WaterManager.h"
|
|
#include "eter_render/OrbitCamera.h"
|
|
#include "eter_render/MinimapManager.h"
|
|
#include "eter_render/ActorInstance.h"
|
|
#include "eter_render/FloatingTextManager.h"
|
|
#include "eter_render/TargetManager.h"
|
|
#include "eter_sound/SoundManager.h"
|
|
#include "eter_effect/EffectManager.h"
|
|
#include "eter_effect/FlyingManager.h"
|
|
#include "eter_render/TextTailManager.h"
|
|
#include "eter_net/NetworkActorManager.h"
|
|
#include "eter_net/PythonNetworkStream.h"
|
|
#include "eter_net/Packet.h"
|
|
#include "eter_render/EnvironmentData.h"
|
|
#include "eter_render/SkyBox.h"
|
|
#include "eter_render/SpeedTreeForest.h"
|
|
#include "eter_image/MarkManager.h"
|
|
#ifdef AVA2_HAS_PYTHON
|
|
#include "python_runtime.h"
|
|
#include "python_net.h"
|
|
#include "python_app.h"
|
|
#include "python_event_manager.h"
|
|
#include "python_system.h"
|
|
#include "python_background.h"
|
|
#include "python_minimap.h"
|
|
#include "eter_base/Random.h"
|
|
#include <ctime>
|
|
#include <random>
|
|
#include "python_gameplay_modules.h"
|
|
#include "eter_image/GrpDevice.h"
|
|
#include "eter_ui/PythonWindowManager.h"
|
|
#include "python_ime.h"
|
|
#include "player_settings.h"
|
|
#include "eter_render/RaceData.h"
|
|
#include "app/input/touch_router.h"
|
|
#include "python_touch.h"
|
|
#endif
|
|
#include "app/platform/platform.h"
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <chrono>
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#include <filesystem>
|
|
#include <iostream>
|
|
#include <memory>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <thread>
|
|
|
|
namespace {
|
|
struct Field { const char* label;std::string value;std::size_t max;bool secret=false; };
|
|
void text(SDL_Renderer* renderer,float x,float y,const std::string& value,float scale=2) {
|
|
SDL_SetRenderScale(renderer,scale,scale);SDL_RenderDebugText(renderer,x/scale,y/scale,value.c_str());SDL_SetRenderScale(renderer,1,1);
|
|
}
|
|
void rectangle(SDL_Renderer* renderer,float x,float y,float width,float height,int r,int g,int b) {
|
|
SDL_SetRenderDrawColor(renderer,r,g,b,255);SDL_FRect rect{x,y,width,height};SDL_RenderFillRect(renderer,&rect);
|
|
}
|
|
void erase_last(std::string& value) {
|
|
if(value.empty()) return;auto index=value.size()-1;
|
|
while(index && (static_cast<unsigned char>(value[index])&0xc0)==0x80) --index;
|
|
value.erase(index);
|
|
}
|
|
int port(const std::string& value) {
|
|
std::size_t used=0;int number=std::stoi(value,&used);
|
|
if(used!=value.size() || number<1 || number>65535) throw std::invalid_argument("Port must be between 1 and 65535");return number;
|
|
}
|
|
|
|
ava2::Render3DDraw BuildGroundShadowDraw(float x, float y, float z, float radius, const ava2::TerrainHeightmap* terrain) {
|
|
ava2::Render3DDraw draw;
|
|
draw.z_enable = true;
|
|
draw.z_write = false;
|
|
draw.cull_mode = 1; // 1: None
|
|
draw.alpha_blend = true;
|
|
draw.blend_mode = 0; // Alpha
|
|
draw.alpha_test = false;
|
|
draw.lighting = false;
|
|
draw.fog = false;
|
|
|
|
constexpr int SEGMENTS = 16;
|
|
static const auto ring = [] {
|
|
std::array<std::array<float, 2>, SEGMENTS> r{};
|
|
for (int i = 0; i < SEGMENTS; ++i) {
|
|
float angle = (2.0f * 3.14159265358979323846f * static_cast<float>(i)) / static_cast<float>(SEGMENTS);
|
|
r[i] = {std::cos(angle), std::sin(angle)};
|
|
}
|
|
return r;
|
|
}();
|
|
draw.positions.reserve((SEGMENTS + 1) * 3);
|
|
draw.normals.reserve((SEGMENTS + 1) * 3);
|
|
draw.uv0.reserve((SEGMENTS + 1) * 2);
|
|
draw.diffuse.reserve(SEGMENTS + 1);
|
|
draw.indices.reserve(SEGMENTS * 3);
|
|
float center_y = terrain ? (terrain->GetHeightAtWorld(x, z) + 2.0f) : (y + 2.0f);
|
|
|
|
// Center vertex (index 0)
|
|
draw.positions.push_back(x);
|
|
draw.positions.push_back(center_y);
|
|
draw.positions.push_back(z);
|
|
draw.normals.push_back(0.0f);
|
|
draw.normals.push_back(1.0f);
|
|
draw.normals.push_back(0.0f);
|
|
draw.uv0.push_back(0.5f);
|
|
draw.uv0.push_back(0.5f);
|
|
draw.diffuse.push_back(0x90000000); // semi-transparent black center
|
|
|
|
for (int i = 0; i < SEGMENTS; ++i) {
|
|
const float c = ring[i][0], s = ring[i][1];
|
|
float px = x + c * radius;
|
|
float pz = z + s * radius;
|
|
float py = terrain ? (terrain->GetHeightAtWorld(px, pz) + 2.0f) : (y + 2.0f);
|
|
|
|
draw.positions.push_back(px);
|
|
draw.positions.push_back(py);
|
|
draw.positions.push_back(pz);
|
|
draw.normals.push_back(0.0f);
|
|
draw.normals.push_back(1.0f);
|
|
draw.normals.push_back(0.0f);
|
|
draw.uv0.push_back(0.5f + 0.5f * c);
|
|
draw.uv0.push_back(0.5f + 0.5f * s);
|
|
draw.diffuse.push_back(0x00000000); // fully transparent edge
|
|
}
|
|
|
|
// Triangle fan from center
|
|
for (int i = 0; i < SEGMENTS; ++i) {
|
|
int next_idx = 1 + ((i + 1) % SEGMENTS);
|
|
draw.indices.push_back(0);
|
|
draw.indices.push_back(1 + i);
|
|
draw.indices.push_back(next_idx);
|
|
}
|
|
|
|
return draw;
|
|
}
|
|
|
|
int SDLKeyToDIK(SDL_Keycode key) {
|
|
if (key >= SDLK_A && key <= SDLK_Z) {
|
|
static const int lut[26] = {
|
|
30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38, 50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44
|
|
};
|
|
return lut[key - SDLK_A];
|
|
}
|
|
if (key >= SDLK_0 && key <= SDLK_9) {
|
|
if (key == SDLK_0) return 11;
|
|
return 2 + (key - SDLK_1);
|
|
}
|
|
switch (key) {
|
|
case SDLK_ESCAPE: return 1;
|
|
case SDLK_RETURN: case SDLK_KP_ENTER: return 28;
|
|
case SDLK_SPACE: return 57;
|
|
case SDLK_TAB: return 15;
|
|
case SDLK_BACKSPACE: return 14;
|
|
case SDLK_LSHIFT: case SDLK_RSHIFT: return 42;
|
|
case SDLK_LCTRL: case SDLK_RCTRL: return 29;
|
|
case SDLK_LALT: case SDLK_RALT: return 56;
|
|
case SDLK_UP: return 200;
|
|
case SDLK_LEFT: return 203;
|
|
case SDLK_RIGHT: return 205;
|
|
case SDLK_DOWN: return 208;
|
|
case SDLK_F1: return 59;
|
|
case SDLK_F2: return 60;
|
|
case SDLK_F3: return 61;
|
|
case SDLK_F4: return 62;
|
|
case SDLK_F5: return 63;
|
|
case SDLK_F6: return 64;
|
|
case SDLK_F7: return 65;
|
|
case SDLK_F8: return 66;
|
|
case SDLK_F9: return 67;
|
|
case SDLK_F10: return 68;
|
|
case SDLK_F11: return 87;
|
|
case SDLK_F12: return 88;
|
|
default: return 0;
|
|
}
|
|
}
|
|
} // namespace
|
|
|
|
struct ava2::app::AppLoop::Frame {
|
|
struct promise_type {
|
|
int result = 0;
|
|
Frame get_return_object() { return {std::coroutine_handle<promise_type>::from_promise(*this)}; }
|
|
std::suspend_always initial_suspend() noexcept { return {}; }
|
|
std::suspend_always final_suspend() noexcept { return {}; }
|
|
std::suspend_always yield_value(int) noexcept { return {}; }
|
|
void return_value(int code) noexcept { result = code; }
|
|
void unhandled_exception() noexcept {
|
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unhandled exception in the client loop");
|
|
result = 1;
|
|
}
|
|
};
|
|
std::coroutine_handle<promise_type> handle;
|
|
};
|
|
|
|
namespace {
|
|
// The client: start-up, then one loop turn per frame (suspended at the top of each), then
|
|
// teardown. Formerly main(); app_loop.h explains the coroutine.
|
|
ava2::app::AppLoop::Frame RunClient(ava2::app::AppLoop* loop, int argc, char** argv) {
|
|
if (std::string error; !ava2::platform::EnterClientDataDirectory(&error)) {
|
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", error.c_str());
|
|
co_return 1;
|
|
}
|
|
try {
|
|
int frame_limit = 0, auto_slot = -1, fps_cap = -1, game_frames = 1, rendered_game_frames = 0;
|
|
#ifdef __ANDROID__
|
|
float render_scale = 0.75f;
|
|
#else
|
|
float render_scale = 1.0f;
|
|
#endif
|
|
bool auto_connect = false, until_loading = false, until_select = false, until_game = false;
|
|
bool use_gpu_raster = true, preview_data = false, touch_flag = false;
|
|
std::string stdlib, script_root, view_script, screenshot, game_script, frame_profile;
|
|
std::string phone_spec, safe_spec;
|
|
int ui_height = 0;
|
|
bool game_script_executed = false;
|
|
std::string start_phase = "login";
|
|
std::array<Field,6> fields{{{"Auth host","127.0.0.1",255},{"Auth port","",5},{"Game host","127.0.0.1",255},{"Game port","",5},{"Account","",30},{"Password","",16,true}}};
|
|
|
|
for (int i = 1; i < argc; ++i) {
|
|
std::string arg = argv[i];
|
|
auto next = [&]() -> std::string {
|
|
if (i + 1 >= argc) throw std::invalid_argument("Missing value for " + arg);
|
|
return argv[++i];
|
|
};
|
|
if (arg == "--frames") { frame_limit = std::stoi(next()); if (frame_limit < 1) throw std::invalid_argument("frames must be positive"); }
|
|
else if (arg == "--fps-cap") { fps_cap = std::max(0, std::stoi(next())); }
|
|
else if (arg == "--render-scale") { render_scale = std::stof(next()); }
|
|
else if (arg == "--stdlib") stdlib = next();
|
|
else if (arg == "--python-root") script_root = next();
|
|
else if (arg == "--login-ui") view_script = next();
|
|
else if (arg == "--screenshot") screenshot = next();
|
|
else if (arg == "--game-script") game_script = next();
|
|
else if (arg == "--frame-profile") frame_profile = next();
|
|
else if (arg == "--phase") start_phase = next();
|
|
else if (arg == "--auth-host") fields[0].value = next();
|
|
else if (arg == "--auth-port") fields[1].value = next();
|
|
else if (arg == "--game-host") fields[2].value = next();
|
|
else if (arg == "--game-port") fields[3].value = next();
|
|
else if (arg == "--account") fields[4].value = next();
|
|
else if (arg == "--auto-connect") auto_connect = true;
|
|
else if (arg == "--auto-select") { auto_slot = std::stoi(next()); if (auto_slot < 0 || auto_slot > 4) throw std::invalid_argument("invalid auto-select slot"); }
|
|
else if (arg == "--until-loading") until_loading = true;
|
|
else if (arg == "--until-select") until_select = true;
|
|
else if (arg == "--until-game") until_game = true;
|
|
else if (arg == "--game-frames") game_frames = std::max(1, std::stoi(next()));
|
|
else if (arg == "--preview-data") preview_data = true;
|
|
else if (arg == "--software-raster") use_gpu_raster = false;
|
|
else if (arg == "--touch") touch_flag = true;
|
|
else if (arg == "--phone") { phone_spec = next(); touch_flag = true; }
|
|
else if (arg == "--ui-height") ui_height = std::stoi(next());
|
|
else if (arg == "--safe-insets") safe_spec = next();
|
|
else throw std::invalid_argument("Usage: ava2_client [--frames N] [--fps-cap N] [--render-scale 0.25..1] [--stdlib ZIP --python-root DIR] [--login-ui SCRIPT | --phase login|select|create|loading|game] [--auth-host HOST --auth-port PORT --game-host HOST --game-port PORT --account ACCOUNT] [--auto-connect] [--auto-select 0..4] [--until-select|--until-loading|--until-game] [--game-script FILE.py] [--software-raster] [--touch] [--phone WxH[@density]] [--ui-height N] [--safe-insets L,T,R,B] [--screenshot FILE.bmp]");
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// Before the Python runtime starts: app.ENABLE_MOBILE_HUD follows the touch mode.
|
|
if (const char* env = std::getenv("AVA2_TOUCH"); touch_flag || (env && std::strcmp(env, "0") != 0))
|
|
ava2::input::SetTouchMode(true);
|
|
#else
|
|
(void)touch_flag;
|
|
#endif
|
|
if (fps_cap < 0) {
|
|
if (const char* env = std::getenv("MT_FPS_CAP")) fps_cap = std::max(0, std::atoi(env));
|
|
else if (const char* env = std::getenv("AVA2_FPS_CAP")) fps_cap = std::max(0, std::atoi(env));
|
|
}
|
|
if (fps_cap < 0) {
|
|
#ifdef SDL_PLATFORM_IOS
|
|
// UIKit calls SDL_AppIterate once per display refresh; a software cap would block it.
|
|
fps_cap = 0;
|
|
#else
|
|
fps_cap = (frame_limit > 0) ? 0 : 60;
|
|
#endif
|
|
}
|
|
|
|
if (const char* env = std::getenv("MT_RENDER_SCALE")) render_scale = std::stof(env);
|
|
else if (const char* env = std::getenv("AVA2_RENDER_SCALE")) render_scale = std::stof(env);
|
|
render_scale = std::clamp(render_scale, 0.25f, 1.0f);
|
|
|
|
// Auto-discover resource directories if not explicitly supplied
|
|
if (stdlib.empty()) {
|
|
if (std::filesystem::exists("python27.zip")) stdlib = "python27.zip";
|
|
else if (std::filesystem::exists("build/dev/python27.zip")) stdlib = "build/dev/python27.zip";
|
|
else {
|
|
auto res = std::filesystem::path(SDL_GetBasePath()) / "../Resources/python27.zip";
|
|
if (std::filesystem::exists(res)) stdlib = res.string();
|
|
}
|
|
}
|
|
if (script_root.empty()) {
|
|
if (std::filesystem::exists("upstream/python-root")) script_root = "upstream/python-root";
|
|
else if (std::filesystem::exists("root")) script_root = "root";
|
|
else if (auto res = std::filesystem::path(SDL_GetBasePath()) / "../Resources/root"; std::filesystem::exists(res))
|
|
script_root = res.string();
|
|
// A flattened client root (scripts beside the assets), e.g. the Android data directory.
|
|
else if (std::filesystem::exists("game.py") && std::filesystem::exists("uiscript")) script_root = ".";
|
|
}
|
|
#if defined(__ANDROID__) || defined(SDL_PLATFORM_IOS)
|
|
if (stdlib.empty() || script_root.empty()) {
|
|
#ifdef __ANDROID__
|
|
const char* push = "android/push_assets.py";
|
|
#else
|
|
const char* push = "ios/push_assets.py";
|
|
#endif
|
|
const std::string message = "Game data not found in " + std::filesystem::current_path().string()
|
|
+ ".\nPush it with " + push + ".";
|
|
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "AVA2", message.c_str(), nullptr);
|
|
throw std::runtime_error(message);
|
|
}
|
|
#endif
|
|
|
|
bool original_phase_mode = view_script.empty();
|
|
#ifdef AVA2_HAS_PYTHON
|
|
ava2::PythonNetworkStream::Instance().SetClientFilename(std::filesystem::path(argv[0]).filename().string());
|
|
#endif
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (const std::string config = ava2::platform::ConfigDirectory(); !config.empty())
|
|
ava2::CPythonSystem::SetConfigDirectory(config);
|
|
std::unique_ptr<ava2::PythonRuntime> python;
|
|
if (!stdlib.empty() || !script_root.empty()) {
|
|
python = std::make_unique<ava2::PythonRuntime>(stdlib, script_root);
|
|
python->execute("import colorInfo, musicInfo\nassert colorInfo.CHR_NAME_RGB_METIN == (101,230,230)\n");
|
|
if (!view_script.empty()) {
|
|
python->load_login_view(view_script);
|
|
}
|
|
SDL_Log("AVA2 Python 2 runtime initialized");
|
|
}
|
|
#else
|
|
if (!stdlib.empty() || !script_root.empty() || !view_script.empty())
|
|
throw std::runtime_error("Python runtime disabled at build time");
|
|
#endif
|
|
|
|
// Allow native auto-connect without --login-ui
|
|
// if ((auto_connect || auto_slot >= 0) && view_script.empty())
|
|
// throw std::invalid_argument("Login automation with credentials requires --login-ui");
|
|
|
|
if (auto_connect) {
|
|
const char* password = std::getenv("AVA2_PASSWORD");
|
|
if (!password) throw std::invalid_argument("AVA2_PASSWORD required for --auto-connect");
|
|
fields[5].value = password;
|
|
#ifndef _WIN32
|
|
unsetenv("AVA2_PASSWORD");
|
|
#endif
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// WinMain: srandom(time(NULL) + DWORD(GetCurrentProcess())) for EterBase random_range.
|
|
eter::srandom(uint32_t(std::time(nullptr)) + std::random_device{}());
|
|
#endif
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// Touch mode: fingers go through the touch router instead of SDL's touch-to-mouse emulation.
|
|
// On desktop (--touch) the mouse emulates one finger.
|
|
const bool touch_mode = ava2::input::IsTouchMode();
|
|
if (touch_mode) {
|
|
SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
|
|
SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "1");
|
|
}
|
|
#endif
|
|
ava2::platform::Lifecycle::SetHints();
|
|
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw std::runtime_error(SDL_GetError());
|
|
struct Quit { ~Quit(){ SDL_Quit(); } } quit;
|
|
ava2::platform::Lifecycle lifecycle;
|
|
lifecycle.Install();
|
|
struct Unwatch { ava2::platform::Lifecycle& l; ~Unwatch(){ l.Uninstall(); } } unwatch{lifecycle};
|
|
|
|
std::unique_ptr<SDL_GPUDevice, decltype(&SDL_DestroyGPUDevice)> gpu(
|
|
SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL, std::getenv("AVA2_GPU_DEBUG") != nullptr, nullptr),
|
|
SDL_DestroyGPUDevice
|
|
);
|
|
if (!gpu) throw std::runtime_error(SDL_GetError());
|
|
|
|
// CPythonApplication::Create sizes the device from metin2.cfg (ava2::CPythonSystem::GetWidth/GetHeight).
|
|
int screen_width = 1280, screen_height = 720;
|
|
// Phones and tablets (or --phone on desktop): the logical UI size follows the screen instead
|
|
// of letterboxing metin2.cfg's size (platform::ChooseMobileLogicalSize).
|
|
bool mobile_ui = false;
|
|
float phone_w = 0.0f, phone_h = 0.0f, phone_density = 1.0f;
|
|
#if defined(SDL_PLATFORM_ANDROID) || defined(SDL_PLATFORM_IOS)
|
|
// The game is landscape-only. Without this hint SDL requests FULL_USER for a resizable window
|
|
// on Android, overriding the manifest's sensorLandscape (the HUD then letterboxes in portrait).
|
|
SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight");
|
|
mobile_ui = ava2::platform::QueryDisplay(&phone_w, &phone_h, &phone_density);
|
|
#endif
|
|
if (!phone_spec.empty()) {
|
|
if (!ava2::platform::ParsePhoneSpec(phone_spec, &phone_w, &phone_h, &phone_density))
|
|
throw std::invalid_argument("--phone expects WxH or WxH@density");
|
|
mobile_ui = true;
|
|
}
|
|
if (ui_height <= 0) {
|
|
if (const char* env = std::getenv("AVA2_UI_HEIGHT")) ui_height = std::atoi(env);
|
|
}
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python) {
|
|
if (mobile_ui) {
|
|
const auto size = ava2::platform::ChooseMobileLogicalSize(phone_w, phone_h, phone_density, ui_height);
|
|
ava2::CPythonSystem::Instance().SetDisplaySizeOverride(uint32_t(size.width), uint32_t(size.height));
|
|
SDL_Log("Mobile UI: screen %.0fx%.0f density %.2f -> logical %dx%d",
|
|
phone_w, phone_h, phone_density, size.width, size.height);
|
|
}
|
|
screen_width = int(ava2::CPythonSystem::Instance().GetWidth());
|
|
screen_height = int(ava2::CPythonSystem::Instance().GetHeight());
|
|
}
|
|
#endif
|
|
SDL_WindowFlags window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY;
|
|
#if defined(SDL_PLATFORM_ANDROID) || defined(SDL_PLATFORM_IOS)
|
|
// Immersive: hide the status and navigation bars, which otherwise draw over the HUD.
|
|
window_flags |= SDL_WINDOW_FULLSCREEN;
|
|
#endif
|
|
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> window(
|
|
SDL_CreateWindow("AVA2 — Metin2 Client", screen_width, screen_height, window_flags),
|
|
SDL_DestroyWindow
|
|
);
|
|
if (!window) throw std::runtime_error(SDL_GetError());
|
|
|
|
std::unique_ptr<SDL_Renderer, decltype(&SDL_DestroyRenderer)> renderer(
|
|
SDL_CreateGPURenderer(gpu.get(), window.get()),
|
|
SDL_DestroyRenderer
|
|
);
|
|
if (!renderer) throw std::runtime_error(SDL_GetError());
|
|
|
|
SDL_SetRenderLogicalPresentation(renderer.get(), screen_width, screen_height, SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
|
// One pacing source: software caps must not also wait on the display refresh.
|
|
SDL_SetRenderVSync(renderer.get(), fps_cap > 0 ? 0 : 1);
|
|
// Desktop: text input stays on for the whole session, as on Windows. Phones would keep the
|
|
// on-screen keyboard covering the game, so the frame loop toggles it with edit focus instead.
|
|
[[maybe_unused]] const bool screen_keyboard = SDL_HasScreenKeyboardSupport();
|
|
if (!screen_keyboard) SDL_StartTextInput(window.get());
|
|
float dpi_scale = SDL_GetWindowPixelDensity(window.get());
|
|
SDL_Log("AVA2 host started: platform=%s GPU=%s Retina_DPI=%.2fx FPS_Cap=%d RenderScale=%.2f",
|
|
SDL_GetPlatform(), SDL_GetGPUDeviceDriver(gpu.get()), dpi_scale, fps_cap, render_scale);
|
|
|
|
bool running = true, requested = false, entered = false;
|
|
int frames = 0, focus = 4;
|
|
float game_clock = 0.0f; // seconds of game time (sum of dt); deterministic under --frames
|
|
std::string local_error, last_phase;
|
|
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
CGraphicDevice graphicDevice;
|
|
graphicDevice.Init(renderer.get());
|
|
UI::CWindowManager* wm = python ? python->window_manager() : nullptr;
|
|
if (wm) {
|
|
wm->SetScreenSize(screen_width, screen_height);
|
|
wm->SetResolution(screen_width, screen_height);
|
|
}
|
|
if (python) ava2::CPythonSystem::Instance().GetDisplaySettings();
|
|
|
|
// Preview data must be explicitly requested; never shadow authenticated roster.
|
|
if (preview_data) {
|
|
// Setup mock character data for character selection (4 slots, different races)
|
|
ava2::Character c0;
|
|
c0.id = 1001;
|
|
c0.name = "WarriorHero";
|
|
c0.job = 0; // RACE_WARRIOR_M
|
|
c0.level = 75;
|
|
c0.strength = 90;
|
|
c0.dexterity = 40;
|
|
c0.health = 90;
|
|
c0.intelligence = 20;
|
|
c0.main_part = 11299; // Black Steel Armor
|
|
c0.play_minutes = 3600;
|
|
ava2::set_mock_character(0, c0);
|
|
|
|
ava2::Character c1;
|
|
c1.id = 1002;
|
|
c1.name = "ShadowBlade";
|
|
c1.job = 1; // RACE_ASSASSIN_W
|
|
c1.level = 72;
|
|
c1.strength = 30;
|
|
c1.dexterity = 90;
|
|
c1.health = 70;
|
|
c1.intelligence = 20;
|
|
c1.main_part = 11499; // Ninja Suit
|
|
c1.play_minutes = 2400;
|
|
ava2::set_mock_character(1, c1);
|
|
|
|
ava2::Character c2;
|
|
c2.id = 1003;
|
|
c2.name = "DarkLord";
|
|
c2.job = 2; // RACE_SURA_M
|
|
c2.level = 70;
|
|
c2.strength = 60;
|
|
c2.dexterity = 30;
|
|
c2.health = 80;
|
|
c2.intelligence = 90;
|
|
c2.main_part = 11699; // Sura Plate
|
|
c2.play_minutes = 1800;
|
|
ava2::set_mock_character(2, c2);
|
|
|
|
ava2::Character c3;
|
|
c3.id = 1004;
|
|
c3.name = "MysticHealer";
|
|
c3.job = 3; // RACE_SHAMAN_W
|
|
c3.level = 68;
|
|
c3.strength = 20;
|
|
c3.dexterity = 30;
|
|
c3.health = 60;
|
|
c3.intelligence = 95;
|
|
c3.main_part = 11899; // Shaman Dress
|
|
c3.play_minutes = 1200;
|
|
ava2::set_mock_character(3, c3);
|
|
|
|
ava2::set_mock_empire(1);
|
|
if (python) {
|
|
PyRun_SimpleString("try:\n import constInfo\n constInfo.ACCOUNT_NAME = 'WarriorHero'\nexcept: pass\n");
|
|
}
|
|
}
|
|
|
|
// Initialize 3D Character Renderer (modeled after 40250)
|
|
std::unique_ptr<ava2::Gr2ModelInstance> model3d;
|
|
std::string model3d_path = "ymir work/pc/warrior/warrior_assasin1.gr2";
|
|
if (!std::filesystem::exists(model3d_path)) {
|
|
if (std::filesystem::exists("assets/loose/" + model3d_path)) model3d_path = "assets/loose/" + model3d_path;
|
|
else if (std::filesystem::exists("build/dev/" + model3d_path)) model3d_path = "build/dev/" + model3d_path;
|
|
else if (std::filesystem::exists("../" + model3d_path)) model3d_path = "../" + model3d_path;
|
|
}
|
|
if (std::filesystem::exists(model3d_path)) {
|
|
model3d = ava2::Gr2ModelInstance::Load(model3d_path);
|
|
if (model3d) {
|
|
SDL_Log("Loaded 3D Character Model for preview: %s", model3d_path.c_str());
|
|
std::string weapon_path = "ymir work/item/weapon/set_11_sword.gr2";
|
|
if (!std::filesystem::exists(weapon_path)) {
|
|
if (std::filesystem::exists("assets/loose/" + weapon_path)) weapon_path = "assets/loose/" + weapon_path;
|
|
else if (std::filesystem::exists("build/dev/" + weapon_path)) weapon_path = "build/dev/" + weapon_path;
|
|
else if (std::filesystem::exists("../" + weapon_path)) weapon_path = "../" + weapon_path;
|
|
}
|
|
if (std::filesystem::exists(weapon_path)) {
|
|
auto weapon = ava2::Gr2ModelInstance::Load(weapon_path);
|
|
if (weapon) {
|
|
model3d->AttachModel("equip_right_hand", std::move(weapon));
|
|
SDL_Log("Attached 3D Weapon: %s", weapon_path.c_str());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const int view3d_w = std::max(320, static_cast<int>(std::round(screen_width * render_scale)));
|
|
const int view3d_h = std::max(180, static_cast<int>(std::round(screen_height * render_scale)));
|
|
std::unique_ptr<ava2::Gr2SceneRenderer> renderer3d;
|
|
std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)> surface3d(nullptr, SDL_DestroySurface);
|
|
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> texture3d(nullptr, SDL_DestroyTexture);
|
|
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> gpu_scene_texture(nullptr, SDL_DestroyTexture);
|
|
std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)> minimap_surface(nullptr, SDL_DestroySurface);
|
|
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> minimap_texture(nullptr, SDL_DestroyTexture);
|
|
std::array<float, 9> minimap_last_radar{};bool minimap_radar_valid = false; // redraw only when inputs move
|
|
|
|
ava2::TerrainHeightmap outdoor_terrain;
|
|
std::string raw_path = "map/metin2_map_a1/001003/height.raw";
|
|
if (!std::filesystem::exists(raw_path)) {
|
|
raw_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/height.raw";
|
|
}
|
|
if (std::filesystem::exists(raw_path)) {
|
|
outdoor_terrain.LoadRaw(raw_path, 0.5f, 200.0f);
|
|
SDL_Log("Loaded outdoor height.raw: %d x %d", outdoor_terrain.GetWidth(), outdoor_terrain.GetHeight());
|
|
std::string tile_path = "map/metin2_map_a1/001003/tile.raw";
|
|
if (!std::filesystem::exists(tile_path)) {
|
|
tile_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/tile.raw";
|
|
}
|
|
if (std::filesystem::exists(tile_path)) {
|
|
outdoor_terrain.LoadTileRaw(tile_path);
|
|
SDL_Log("Loaded outdoor tile.raw for multi-terrain shading: %d x %d", outdoor_terrain.GetTileWidth(), outdoor_terrain.GetTileHeight());
|
|
}
|
|
|
|
std::string attr_path = "map/metin2_map_a1/001003/attr.atr";
|
|
if (!std::filesystem::exists(attr_path)) {
|
|
attr_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/attr.atr";
|
|
}
|
|
if (std::filesystem::exists(attr_path)) {
|
|
outdoor_terrain.LoadAttr(attr_path);
|
|
SDL_Log("Loaded outdoor attr.atr: %d x %d", outdoor_terrain.GetAttrWidth(), outdoor_terrain.GetAttrHeight());
|
|
}
|
|
|
|
std::string tset_path = "textureset/metin2_map1.txt";
|
|
if (!std::filesystem::exists(tset_path)) {
|
|
tset_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/textureset/metin2_map1.txt";
|
|
}
|
|
if (std::filesystem::exists(tset_path)) {
|
|
outdoor_terrain.LoadTextureSet(tset_path);
|
|
SDL_Log("Loaded outdoor textureset: %s (%zu textures)", tset_path.c_str(), outdoor_terrain.GetTextureSet().size());
|
|
}
|
|
} else {
|
|
outdoor_terrain.GenerateProcedural(64, 64, 200.0f, 60.0f);
|
|
SDL_Log("Generated procedural outdoor terrain");
|
|
}
|
|
float player_world_y = 0.0f;
|
|
float player_world_x = 0.0f, player_world_z = 0.0f, player_world_yaw = 0.0f;
|
|
|
|
// Initialize SkyBox and Environment Engine (modeled after 40250 CSkyBox & SEnvironmentData)
|
|
ava2::SkyBox outdoor_skybox;
|
|
ava2::EnvironmentData current_env;
|
|
if (!current_env.LoadFromFile("c1.msenv") && !current_env.LoadFromFile("b1.msenv")) {
|
|
current_env = ava2::EnvironmentData::CreateDayPreset();
|
|
}
|
|
outdoor_skybox.SetEnvironment(current_env);
|
|
SDL_Log("Loaded outdoor environment: %s (fog near=%.1f far=%.1f)",
|
|
current_env.name.c_str(), current_env.fog.near_dist, current_env.fog.far_dist);
|
|
|
|
// Initialize Outdoor Map Objects & Buildings (scenic Metin2 world dressing)
|
|
ava2::MapObjectManager map_objects;
|
|
|
|
// 1. Distant Monumental Stone City Gate Arch framing the valley road
|
|
std::string gate_path = "ymir work/zone/b/building/b1-034-stonedoor.gr2";
|
|
if (std::filesystem::exists(gate_path)) {
|
|
float gh = outdoor_terrain.GetHeightAtWorld(0.0f, 1100.0f);
|
|
map_objects.AddObject(gate_path, 0.0f, gh, 1100.0f, 0.0f, 0.0f, 0.0f, 0.55f);
|
|
}
|
|
|
|
// 2. Village House on the left distant hill
|
|
std::string house_path = "ymir work/zone/b/building/b1-001-house3.gr2";
|
|
if (std::filesystem::exists(house_path)) {
|
|
float hh = outdoor_terrain.GetHeightAtWorld(-650.0f, 800.0f);
|
|
map_objects.AddObject(house_path, -650.0f, hh, 800.0f, -45.0f, 0.0f, 0.0f, 0.75f);
|
|
}
|
|
|
|
// 3. Outpost / Guard Pavilion on the right distant hill
|
|
std::string bldg_path = "ymir work/zone/b/obj/b_general_obj_01_2.gr2";
|
|
if (std::filesystem::exists(bldg_path)) {
|
|
float bh = outdoor_terrain.GetHeightAtWorld(650.0f, 750.0f);
|
|
map_objects.AddObject(bldg_path, 650.0f, bh, 750.0f, 45.0f, 0.0f, 0.0f, 0.70f);
|
|
}
|
|
|
|
// 4. Craggy Boulders & Field Rocks (framing the perimeter)
|
|
std::string rock1_path = "ymir work/zone/b/obj/general_obj_stone01.gr2";
|
|
if (std::filesystem::exists(rock1_path)) {
|
|
float rh1 = outdoor_terrain.GetHeightAtWorld(-620.0f, 600.0f);
|
|
map_objects.AddObject(rock1_path, -620.0f, rh1, 600.0f, 30.0f, 0.0f, 0.0f, 0.95f);
|
|
}
|
|
std::string rock2_path = "ymir work/zone/b/obj/general_obj_stone04.gr2";
|
|
if (std::filesystem::exists(rock2_path)) {
|
|
float rh2 = outdoor_terrain.GetHeightAtWorld(380.0f, 260.0f);
|
|
map_objects.AddObject(rock2_path, 380.0f, rh2, 260.0f, -20.0f, 0.0f, 0.0f, 0.85f);
|
|
}
|
|
|
|
// 5. Village Wooden Barrels & Crates along the roadside
|
|
std::string barrel_path = "ymir work/zone/b/obj/ob-b1-005-woodbarrel.gr2";
|
|
if (std::filesystem::exists(barrel_path)) {
|
|
float bar_h = outdoor_terrain.GetHeightAtWorld(370.0f, 170.0f);
|
|
map_objects.AddObject(barrel_path, 370.0f, bar_h, 170.0f, 15.0f, 0.0f, 0.0f, 0.90f);
|
|
}
|
|
std::string box_path = "ymir work/zone/b/obj/general_obj_woodbox.gr2";
|
|
if (std::filesystem::exists(box_path)) {
|
|
float box_h = outdoor_terrain.GetHeightAtWorld(400.0f, 190.0f);
|
|
map_objects.AddObject(box_path, 400.0f, box_h, 190.0f, -25.0f, 0.0f, 0.0f, 0.90f);
|
|
}
|
|
|
|
// Initialize SpeedTree Forest & Vegetation Engine (modeled after 40250 CSpeedTreeForest)
|
|
ava2::SpeedTreeForest outdoor_forest;
|
|
std::string prop_dir = "property/property";
|
|
if (!std::filesystem::exists(prop_dir)) prop_dir = "property";
|
|
if (!std::filesystem::exists(prop_dir)) prop_dir = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/property/property";
|
|
outdoor_forest.ScanPropertyDirectory(prop_dir);
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{101, "Oak", "ymir work/palnts_2/all/ot/treewillowoakfreesu.spt", 900.0f, 0.0f});
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{102, "Pine", "ymir work/palnts_2/all/ot/treescotchpineforest.spt", 1000.0f, 0.0f});
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{103, "Beech", "ymir work/zone/b/tree/1/beech_rt.spt", 850.0f, 0.0f});
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{104, "WildGrass", "ymir work/plants/grass.spt", 40.0f, 0.0f});
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{105, "Bush", "ymir work/plants/plant_bush.spt", 65.0f, 0.0f});
|
|
outdoor_forest.RegisterPropertyData(ava2::SpeedTreeProperty{106, "Flower", "ymir work/plants/flower.spt", 35.0f, 0.0f});
|
|
|
|
// Populate world with trees and vegetation along valleys and roads
|
|
struct TreePlacement { float x, z; uint32_t crc; float yaw, scale; };
|
|
std::vector<TreePlacement> tree_placements = {
|
|
{-180.0f, 290.0f, 101, 25.0f, 1.00f}, // Majestic oak mid-left
|
|
{ 210.0f, 310.0f, 102, -30.0f, 1.05f}, // Scotch pine mid-right
|
|
{ -60.0f, 440.0f, 103, 45.0f, 0.95f}, // Beech center-back
|
|
{ 120.0f, 420.0f, 101, -60.0f, 0.95f}, // Willow oak center-right
|
|
{ -60.0f, 120.0f, 104, 0.0f, 1.00f}, // Wild grass groundcover
|
|
{ 80.0f, 130.0f, 104, 35.0f, 1.00f}, // Wild grass groundcover
|
|
{-130.0f, 180.0f, 104, 20.0f, 1.00f}, // Wild grass cluster
|
|
{-140.0f, 210.0f, 105, 15.0f, 1.00f}, // Bush near trees
|
|
{ 160.0f, 220.0f, 105, -25.0f, 1.00f}, // Bush near dog
|
|
{ -40.0f, 95.0f, 106, 50.0f, 1.00f}, // Wild flowers foreground
|
|
{ 55.0f, 100.0f, 106, -20.0f, 1.00f}, // Wild flowers foreground
|
|
{-480.0f, 650.0f, 101, 15.0f, 1.05f}, // Distant hill oaks
|
|
{ 520.0f, 720.0f, 102, -35.0f, 1.15f}, // Distant hill pines
|
|
{-320.0f, 520.0f, 101, 45.0f, 1.00f}, // Valley trees
|
|
{ 430.0f, 480.0f, 103, -50.0f, 0.90f} // Valley beeches
|
|
};
|
|
for (const auto& tp : tree_placements) {
|
|
float th = outdoor_terrain.GetHeightAtWorld(tp.x, tp.z);
|
|
outdoor_forest.CreateInstance(tp.x, th, tp.z, tp.crc, tp.yaw, tp.scale);
|
|
}
|
|
SDL_Log("Populated outdoor forest: %zu tree & vegetation instances", outdoor_forest.GetInstanceCount());
|
|
|
|
// Initialize Outdoor Water (water.wtr / procedural water mesh)
|
|
ava2::WaterManager outdoor_water;
|
|
std::string water_path = "map/metin2_map_a1/001003/water.wtr";
|
|
if (!std::filesystem::exists(water_path)) {
|
|
water_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/water.wtr";
|
|
}
|
|
if (std::filesystem::exists(water_path)) {
|
|
outdoor_water.LoadWater(water_path, outdoor_terrain.GetCellScale(), 0.5f, 200.0f,
|
|
outdoor_terrain.GetWorldMinX(), outdoor_terrain.GetWorldMinZ());
|
|
SDL_Log("Loaded outdoor water.wtr: %zu water faces", outdoor_water.GetWaterFaceCount());
|
|
} else {
|
|
outdoor_water.GenerateProceduralWater(25.0f, outdoor_terrain.GetWorldMinX(), outdoor_terrain.GetWorldMaxX(),
|
|
outdoor_terrain.GetWorldMinZ(), outdoor_terrain.GetWorldMaxZ(), 80.0f);
|
|
SDL_Log("Generated procedural outdoor water plane");
|
|
}
|
|
|
|
// Initialize Third-Person Orbit Camera (40250 CCamera)
|
|
ava2::OrbitCamera orbit_camera;
|
|
orbit_camera.SetDistance(1200.0f);
|
|
orbit_camera.SetPitch(30.0f);
|
|
orbit_camera.SetYaw(0.0f);
|
|
orbit_camera.SetTargetHeight(120.0f);
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// Touch router sink: fingers become wndMgr mouse events, the joystick and attack key of the
|
|
// original player module, and orbit camera drags / pinches.
|
|
struct HostTouchSink final : ava2::input::TouchSink {
|
|
UI::CWindowManager* wm = nullptr;
|
|
ava2::OrbitCamera* camera = nullptr;
|
|
bool release_pending = false; // world tap: button goes up on the next frame
|
|
float release_x = 0.0f, release_y = 0.0f;
|
|
|
|
bool IsUiAt(float x, float y) override {
|
|
if (!wm) return false;
|
|
auto* window = wm->PickWindow(long(x), long(y));
|
|
return window && !ava2::IsPlayerGameWindow(window->GetHandler());
|
|
}
|
|
void UiMouseMove(float x, float y) override { if (wm) wm->RunMouseMove(long(x), long(y)); }
|
|
void UiMouseDown(float x, float y) override { if (wm) wm->RunMouseLeftButtonDown(long(x), long(y)); }
|
|
void UiMouseUp(float x, float y) override { if (wm) ava2::TouchUiMouseUp(*wm, long(x), long(y)); }
|
|
void UiDoubleClick(float x, float y) override { if (wm) wm->RunMouseLeftButtonDoubleClick(long(x), long(y)); }
|
|
bool UiLongPress(float x, float y) override { return wm && ava2::TouchUiLongPress(*wm, long(x), long(y)); }
|
|
void WorldTap(float x, float y) override {
|
|
if (!wm) return;
|
|
// GameWindow.OnMouseLeftButtonDown sets player.SetMouseState; holding it for one
|
|
// game update picks the target or ground under the finger like a mouse click.
|
|
FlushRelease();
|
|
wm->RunMouseMove(long(x), long(y));
|
|
wm->RunMouseLeftButtonDown(long(x), long(y));
|
|
release_pending = true;
|
|
release_x = x;
|
|
release_y = y;
|
|
}
|
|
void FlushRelease() {
|
|
if (!release_pending || !wm) return;
|
|
release_pending = false;
|
|
wm->RunMouseLeftButtonUp(long(release_x), long(release_y));
|
|
}
|
|
void Joystick(bool active, float x, float y) override { ava2::SetPlayerJoystick(active, x, y); }
|
|
void Attack(bool pressed) override { ava2::SetPlayerAttackKey(pressed); }
|
|
void CameraRotate(float dx, float dy) override {
|
|
camera->SetYaw(camera->GetYaw() + dx * 0.25f);
|
|
camera->SetPitch(camera->GetPitch() - dy * 0.25f);
|
|
}
|
|
void CameraZoom(float ratio) override { camera->SetDistance(camera->GetDistance() / ratio); }
|
|
} touch_sink;
|
|
touch_sink.wm = wm;
|
|
touch_sink.camera = &orbit_camera;
|
|
auto& touch_router = ava2::input::GetTouchRouter();
|
|
// --safe-insets L,T,R,B simulates a notch / gesture bar on desktop.
|
|
auto query_safe = [&]() {
|
|
ava2::platform::SafeInsets safe;
|
|
if (!safe_spec.empty() &&
|
|
std::sscanf(safe_spec.c_str(), "%f,%f,%f,%f", &safe.left, &safe.top, &safe.right, &safe.bottom) == 4)
|
|
return safe;
|
|
return ava2::platform::QuerySafeInsets(window.get(), renderer.get());
|
|
};
|
|
if (touch_mode) {
|
|
touch_router.SetSink(&touch_sink);
|
|
const auto safe = query_safe();
|
|
touch_router.SetLayout(ava2::input::TouchLayout::ForScreen(float(screen_width), float(screen_height),
|
|
safe.left, safe.top, safe.right, safe.bottom));
|
|
SDL_Log("Safe area insets: %.0f %.0f %.0f %.0f", safe.left, safe.top, safe.right, safe.bottom);
|
|
}
|
|
// Finger position in UI pixels (SDL gives it normalized to the window).
|
|
auto finger_point = [&](const SDL_TouchFingerEvent& finger, float& x, float& y) {
|
|
int ww = 0, wh = 0;
|
|
SDL_GetWindowSize(window.get(), &ww, &wh);
|
|
SDL_RenderCoordinatesFromWindow(renderer.get(), finger.x * float(ww), finger.y * float(wh), &x, &y);
|
|
};
|
|
#endif
|
|
|
|
// Initialize Minimap Radar System
|
|
ava2::MinimapManager minimap_mgr;
|
|
bool minimap_preview_opened = false;
|
|
minimap_mgr.SetWorldBounds(outdoor_terrain.GetWorldMinX(), outdoor_terrain.GetWorldMaxX(),
|
|
outdoor_terrain.GetWorldMinZ(), outdoor_terrain.GetWorldMaxZ());
|
|
std::string minimap_path = "map/metin2_map_a1/001003/minimap.dds";
|
|
if (!std::filesystem::exists(minimap_path)) {
|
|
minimap_path = "/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/minimap.dds";
|
|
}
|
|
if (std::filesystem::exists(minimap_path)) {
|
|
minimap_mgr.LoadMinimap(minimap_path);
|
|
SDL_Log("Loaded outdoor minimap.dds: %d x %d", minimap_mgr.GetTextureWidth(), minimap_mgr.GetTextureHeight());
|
|
} else {
|
|
minimap_mgr.GenerateProceduralMinimap(256, 256);
|
|
SDL_Log("Generated procedural minimap texture");
|
|
}
|
|
|
|
if (model3d) {
|
|
renderer3d = std::make_unique<ava2::Gr2SceneRenderer>(view3d_w, view3d_h);
|
|
renderer3d->SetLogicalSize(screen_width, screen_height);
|
|
if (use_gpu_raster) {renderer3d->SetGPUDevice(gpu.get());ava2::Gr2ModelInstance::SetHardwareSkinningEnabled(std::getenv("AVA2_CPU_SKINNING")==nullptr);}
|
|
renderer3d->SetCameraLookAt(0.0f, 130.0f, -320.0f, 0.0f, 100.0f, 0.0f, 0.0f, 1.0f, 0.0f);
|
|
renderer3d->SetPerspective(45.0f, static_cast<float>(view3d_w) / static_cast<float>(view3d_h), 1.0f, 4000.0f);
|
|
surface3d.reset(SDL_CreateSurface(view3d_w, view3d_h, SDL_PIXELFORMAT_ARGB8888));
|
|
texture3d.reset(SDL_CreateTexture(renderer.get(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, view3d_w, view3d_h));
|
|
if (texture3d) {
|
|
SDL_SetTextureBlendMode(texture3d.get(), SDL_BLENDMODE_BLEND);
|
|
SDL_SetTextureScaleMode(texture3d.get(), SDL_SCALEMODE_LINEAR);
|
|
}
|
|
if (use_gpu_raster && render_scale < 0.999f) {
|
|
gpu_scene_texture.reset(SDL_CreateTexture(renderer.get(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, view3d_w, view3d_h));
|
|
if (gpu_scene_texture) {
|
|
SDL_SetTextureScaleMode(gpu_scene_texture.get(), SDL_SCALEMODE_LINEAR);
|
|
}
|
|
}
|
|
ava2::TextTailManager::Instance().SetCurrentRenderer(renderer.get());
|
|
ava2::TextTailManager::Instance().SetCurrentSceneRenderer(renderer3d.get());
|
|
}
|
|
|
|
// Initialize ActorInstances for Game World (modeled after 40250 CInstanceBase / CActorInstance)
|
|
ava2::ActorInstance player_actor;
|
|
if (std::filesystem::exists(model3d_path)) {
|
|
player_actor.SetModel(model3d_path);
|
|
std::string weapon_path = "ymir work/item/weapon/set_11_sword.gr2";
|
|
player_actor.SetWeapon(weapon_path, "equip_right_hand");
|
|
std::string hair_path = "ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2";
|
|
player_actor.AttachPart(hair_path);
|
|
player_actor.SetScale(0.85f);
|
|
player_actor.SetSpeed(340.0f);
|
|
player_actor.SetVID(1);
|
|
player_actor.SetName("WarriorHero");
|
|
player_actor.SetMaxHP(1500);
|
|
player_actor.SetWeaponShining(9); // +9 Weapon Shining System
|
|
|
|
// Register warrior motions (general or skill fallbacks)
|
|
player_actor.RegisterMotion(ava2::MotionType::Wait, "ymir work/pc/warrior/general/wait.gr2");
|
|
if (!player_actor.PlayMotion(ava2::MotionType::Wait, true)) {
|
|
player_actor.RegisterMotion(ava2::MotionType::Wait, "ymir work/pc/warrior/skill/geomgyeong.gr2");
|
|
player_actor.PlayMotion(ava2::MotionType::Wait, true);
|
|
}
|
|
player_actor.RegisterMotion(ava2::MotionType::Run, "ymir work/pc/warrior/general/run.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Walk, "ymir work/pc/warrior/general/walk.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Attack, "ymir work/pc/warrior/skill/samyeon.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::ComboAttack1, "ymir work/pc/warrior/skill/samyeon.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::ComboAttack2, "ymir work/pc/warrior/skill/palbang.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::ComboAttack3, "ymir work/pc/warrior/skill/finish.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Skill1, "ymir work/pc/warrior/skill/samyeon.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Skill2, "ymir work/pc/warrior/skill/palbang.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Skill3, "ymir work/pc/warrior/skill/jeongwi.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Skill4, "ymir work/pc/warrior/skill/geomgyeong.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Skill5, "ymir work/pc/warrior/skill/gitu.gr2");
|
|
player_actor.RegisterMotion(ava2::MotionType::Damage, "ymir work/pc/warrior/general/damage.gr2");
|
|
|
|
float p_h = outdoor_terrain.GetHeightAtWorld(0.0f, 0.0f);
|
|
player_actor.SetPosition(0.0f, p_h, 0.0f);
|
|
player_actor.SetYaw(0.0f);
|
|
}
|
|
|
|
// Initialize Stand-in Preview Monsters (only active when --preview-data is explicitly specified)
|
|
ava2::ActorInstance mob_dog;
|
|
ava2::ActorInstance mob_metin;
|
|
if (preview_data) {
|
|
std::string dog_path = "ymir work/monster/stray_dog/stray_dog.gr2";
|
|
if (!std::filesystem::exists(dog_path) && std::filesystem::exists("../" + dog_path)) dog_path = "../" + dog_path;
|
|
if (mob_dog.SetModel(dog_path)) {
|
|
mob_dog.SetVID(201);
|
|
mob_dog.SetScale(0.95f);
|
|
mob_dog.SetName("Wild Dog (Lv.1)");
|
|
mob_dog.SetMaxHP(600);
|
|
mob_dog.SetHeightOffset(85.0f);
|
|
mob_dog.SetModelYOffset(0.0f);
|
|
mob_dog.RegisterMotion(ava2::MotionType::Wait, "ymir work/monster/stray_dog/00.gr2");
|
|
mob_dog.PlayMotion(ava2::MotionType::Wait, true);
|
|
mob_dog.RegisterMotion(ava2::MotionType::Walk, "ymir work/monster/stray_dog/02.gr2");
|
|
mob_dog.RegisterMotion(ava2::MotionType::Run, "ymir work/monster/stray_dog/03.gr2");
|
|
mob_dog.RegisterMotion(ava2::MotionType::Attack, "ymir work/monster/stray_dog/20.gr2");
|
|
mob_dog.RegisterMotion(ava2::MotionType::Damage, "ymir work/monster/stray_dog/30.gr2");
|
|
mob_dog.RegisterMotion(ava2::MotionType::Dead, "ymir work/monster/stray_dog/31.gr2");
|
|
float dog_h = outdoor_terrain.GetHeightAtWorld(130.0f, 160.0f);
|
|
mob_dog.SetPosition(130.0f, dog_h, 160.0f);
|
|
mob_dog.SetYaw(38.7f); // Facing towards player at (0, 0)
|
|
}
|
|
|
|
std::string metin_path = "ymir work/monster/metinstone/metinstone_01.gr2";
|
|
if (!std::filesystem::exists(metin_path) && std::filesystem::exists("../" + metin_path)) metin_path = "../" + metin_path;
|
|
if (mob_metin.SetModel(metin_path)) {
|
|
mob_metin.SetVID(301);
|
|
mob_metin.SetScale(1.25f);
|
|
mob_metin.SetName("Metin of Sorrow (Lv.5)");
|
|
mob_metin.SetMaxHP(2000);
|
|
mob_metin.SetHeightOffset(135.0f);
|
|
mob_metin.SetModelYOffset(0.0f);
|
|
mob_metin.RegisterMotion(ava2::MotionType::Wait, "ymir work/monster/metinstone/metinstone_loop.gr2");
|
|
mob_metin.PlayMotion(ava2::MotionType::Wait, true);
|
|
mob_metin.RegisterMotion(ava2::MotionType::Damage, "ymir work/monster/metinstone/metinstone_blow.gr2");
|
|
float metin_h = outdoor_terrain.GetHeightAtWorld(-320.0f, 220.0f);
|
|
mob_metin.SetPosition(-320.0f, metin_h, 220.0f);
|
|
mob_metin.SetYaw(115.0f);
|
|
}
|
|
}
|
|
|
|
// Floating Combat Text Manager (modeled after 40250 CPythonTextTail)
|
|
ava2::FloatingTextManager floating_text_mgr;
|
|
|
|
// Target Manager (modeled after 40250 CPythonPlayer TargetBoard & EFFECT_PICK)
|
|
ava2::TargetManager target_mgr;
|
|
|
|
// Initialize Audio Engine (MilesLib / CSoundManager)
|
|
ava2::SoundManager::Instance().Initialize();
|
|
|
|
auto switch_phase = [&](const std::string& phase) {
|
|
if (!python) return;
|
|
try {
|
|
if (phase == "login") {
|
|
python->execute("stream.SetLoginPhase()\n");
|
|
ava2::SoundManager::Instance().FadeInMusic("BGM/login_window.mp3", 0.05f);
|
|
} else if (phase == "select") {
|
|
python->execute("stream.SetSelectCharacterPhase()\n");
|
|
ava2::SoundManager::Instance().FadeInMusic("BGM/characterselect.mp3", 0.05f);
|
|
} else if (phase == "create") {
|
|
python->execute("stream.SetCharacterSlot(1)\nstream.SetCreateCharacterPhase()\n");
|
|
} else if (phase == "loading") {
|
|
python->execute("stream.SetLoadingPhase()\n");
|
|
} else if (phase == "game") {
|
|
python->execute(
|
|
"import localeInfo\nlocaleInfo.LoadLocaleData()\nstream.SetGamePhase()\n"
|
|
"if stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'Open'):\n"
|
|
" stream.curPhaseWindow.Open()\n"
|
|
"import chr\n"
|
|
"chr.Destroy()\n"
|
|
);
|
|
ava2::SoundManager::Instance().FadeInMusic("BGM/enter_the_east.mp3", 0.05f);
|
|
|
|
// Start GamePhase in PythonNetworkStream
|
|
ava2::PythonNetworkStream::Instance().StartGame();
|
|
|
|
// Initialize GuildMarkManager (Guild Mark Atlas 512x512)
|
|
auto& markMgr = ava2::GuildMarkManager::Instance();
|
|
markMgr.SetMarkPathPrefix("10");
|
|
markMgr.LoadMarkIndex();
|
|
markMgr.AddMarkIDByGuildID(1001, 160); // WarriorHero's Antigravity crest
|
|
markMgr.AddMarkIDByGuildID(2, 162); // SuraMage's ShinsooEmpire crest
|
|
markMgr.SaveMarkIndex();
|
|
|
|
// Initialize TextTailManager for official overhead display
|
|
auto& ttm = ava2::TextTailManager::Instance();
|
|
ttm.Clear();
|
|
ttm.RegisterCharacterTextTail(1001, 1001, 0xFFFFFFFF, 175.0f);
|
|
ttm.SetCharacterName(1001, "WarriorHero");
|
|
ttm.AttachLevel(1001, "[Lv. 99]", 0xFF98FF33);
|
|
ttm.AttachTitle(1001, "Noble", 0xFFFFD700);
|
|
ttm.SetGuildName(1001, "Antigravity", 1001);
|
|
ttm.SetCharacterPosition(1001, player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
|
|
// Register Wild Dog & Metin TextTails
|
|
ttm.RegisterCharacterTextTail(0, 201, 0xFFFF4444, 95.0f);
|
|
ttm.SetCharacterName(201, "Wild Dog");
|
|
ttm.AttachLevel(201, "[Lv. 1]", 0xFFFF7777);
|
|
ttm.SetCharacterPosition(201, mob_dog.GetX(), mob_dog.GetY(), mob_dog.GetZ());
|
|
|
|
ttm.RegisterCharacterTextTail(0, 301, 0xFF44EEEE, 140.0f);
|
|
ttm.SetCharacterName(301, "Metin of Sorrow");
|
|
ttm.AttachLevel(301, "[Lv. 5]", 0xFF66FFFF);
|
|
ttm.SetCharacterPosition(301, mob_metin.GetX(), mob_metin.GetY(), mob_metin.GetZ());
|
|
|
|
// Register Offline Shop booth texttail
|
|
float shop_y = outdoor_terrain.GetHeightAtWorld(105.0f, 65.0f) + 20.0f;
|
|
ttm.RegisterInfoTail(7001, "[Offline Shop] Hero's Rare Emporium");
|
|
ttm.SetCharacterPosition(7001, 105.0f, shop_y, 65.0f);
|
|
|
|
// Register dropped items on ground
|
|
float item1_y = outdoor_terrain.GetHeightAtWorld(45.0f, 35.0f);
|
|
ttm.RegisterItemTextTail(5001, "Full Moon Sword +9", 45.0f, item1_y, 35.0f, 180, "WarriorHero", true);
|
|
float item2_y = outdoor_terrain.GetHeightAtWorld(65.0f, 25.0f);
|
|
ttm.RegisterItemTextTail(5002, "Red Potion (L)", 65.0f, item2_y, 25.0f, 0, "", false, 0xFFFF3333);
|
|
|
|
// Initialize NetworkActorManager
|
|
auto& netActorMgr = ava2::NetworkActorManager::Instance();
|
|
netActorMgr.Clear();
|
|
netActorMgr.SetMainActorVID(1001);
|
|
|
|
// Add ally network actor SuraMage (VID 1002) with Guild Mark
|
|
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>(outdoor_terrain.GetHeightAtWorld(-75.0f, 35.0f));
|
|
suraData.m_fRot = 120.0f;
|
|
netActorMgr.AppendActor(suraData);
|
|
|
|
ttm.RegisterCharacterTextTail(2, 1002, 0xFFFFFFFF, 175.0f);
|
|
ttm.SetCharacterName(1002, "SuraMage");
|
|
ttm.AttachLevel(1002, "[Lv. 75]", 0xFF98FF33);
|
|
ttm.AttachTitle(1002, "Noble", 0xFFFFD700);
|
|
ttm.SetGuildName(1002, "ShinsooEmpire", 2);
|
|
ttm.SetCharacterPosition(1002, -75.0f, outdoor_terrain.GetHeightAtWorld(-75.0f, 35.0f), 35.0f);
|
|
|
|
ttm.ShowAllTextTail();
|
|
|
|
floating_text_mgr.Clear();
|
|
floating_text_mgr.AddText("COMBAT ZONE ACTIVE [Ranking #1 | Score: 3250]", 0.0f, player_actor.GetY() + 230.0f, 0.0f, 0xFFFFCC00, 2.0f, 15.0f);
|
|
}
|
|
last_phase = phase;
|
|
SDL_Log("Active Phase: %s", phase.c_str());
|
|
} catch (const std::exception& e) {
|
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to switch phase to %s: %s", phase.c_str(), e.what());
|
|
}
|
|
};
|
|
|
|
uint32_t sword_aura_effect_id = 0;
|
|
ava2::FlyTrace player_weapon_trace;
|
|
player_weapon_trace.Create(0xFFFFAA33, 0.25f, 12.0f, false);
|
|
|
|
std::unordered_map<int, float> skill_last_cast;
|
|
auto cast_skill = [&](int quickSlot, int skillIndex) {
|
|
if (last_phase != "game") return;
|
|
if (player_actor.IsDead()) return;
|
|
|
|
float curTime = SDL_GetTicks() / 1000.0f;
|
|
float cd = 12.0f;
|
|
if (skillIndex == 1) cd = 12.0f; // Samyeon
|
|
else if (skillIndex == 2) cd = 15.0f; // Palbang
|
|
else if (skillIndex == 3) cd = 25.0f; // Berserk
|
|
else if (skillIndex == 4) cd = 30.0f; // Aura
|
|
else if (skillIndex == 5) cd = 10.0f; // Dash
|
|
|
|
auto it = skill_last_cast.find(skillIndex);
|
|
if (it != skill_last_cast.end() && curTime - it->second < cd) {
|
|
float remaining = cd - (curTime - it->second);
|
|
float px, py, pz;
|
|
player_actor.GetHeadPosition(px, py, pz);
|
|
char buf[64];
|
|
std::snprintf(buf, sizeof(buf), "Skill Recharging! (%.1fs)", remaining);
|
|
floating_text_mgr.AddText(buf, px, py + 25.0f, pz, 0xFFFF5555, 1.3f, 1.5f);
|
|
return;
|
|
}
|
|
|
|
skill_last_cast[skillIndex] = curTime;
|
|
|
|
ava2::SetSkillCoolTime(skillIndex, cd);
|
|
|
|
// Trigger cooltime on taskbar slot in Python and WindowManager
|
|
if (python) {
|
|
std::string pyCmd =
|
|
"if 'stream' in globals() and stream.curPhaseWindow:\n"
|
|
" wnd = stream.curPhaseWindow\n"
|
|
" tb = getattr(wnd, 'wndTaskBar', None)\n"
|
|
" if not tb and hasattr(wnd, 'interface'): tb = getattr(wnd.interface, 'wndTaskBar', None)\n"
|
|
" if tb:\n"
|
|
" if hasattr(tb, 'OnUseSkill'): tb.OnUseSkill(" + std::to_string(skillIndex) + ", " + std::to_string(cd) + ")\n"
|
|
" if hasattr(tb, 'quickslot'):\n"
|
|
" for qw in tb.quickslot:\n"
|
|
" qw.SetSlotCoolTime(" + std::to_string(quickSlot) + ", " + std::to_string(cd) + ")\n";
|
|
python->execute(pyCmd);
|
|
}
|
|
|
|
float px, py, pz;
|
|
player_actor.GetHeadPosition(px, py, pz);
|
|
|
|
if (skillIndex == 1) { // 三连击 Samyeon (Triple Slash)
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/samyeon_s.wav");
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/samyeon_v.wav");
|
|
player_actor.CastSkill(ava2::MotionType::Skill1);
|
|
if (target_mgr.HasTarget()) {
|
|
auto* tgt = target_mgr.GetTarget();
|
|
float dx = tgt->GetX() - player_actor.GetX();
|
|
float dz = tgt->GetZ() - player_actor.GetZ();
|
|
player_actor.SetYaw(std::atan2(dx, dz) * (180.0f / 3.14159265f));
|
|
}
|
|
|
|
// Official Warrior Triple Slash effect
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/samyeon_d.mse", player_actor.GetX(), player_actor.GetY(), player_actor.GetZ(), player_actor.GetYaw());
|
|
|
|
floating_text_mgr.AddText("TRIPLE SLASH!", px, py + 35.0f, pz, 0xFFFFAA00, 1.6f, 2.5f);
|
|
std::vector<ava2::ActorInstance*> targets = { &mob_dog, &mob_metin };
|
|
for (auto* t : targets) {
|
|
if (!t->IsDead() && player_actor.IsTargetInAttackRange(*t, 220.0f, 85.0f)) {
|
|
float hx, hy, hz;
|
|
t->GetHeadPosition(hx, hy, hz);
|
|
int baseDmg = static_cast<int>((180 + (std::rand() % 60) + player_actor.GetBonusAttackDamage()) * player_actor.GetAttackMultiplier());
|
|
int dmg1 = baseDmg;
|
|
int dmg2 = static_cast<int>(baseDmg * 1.15f);
|
|
int dmg3 = static_cast<int>(baseDmg * 1.35f);
|
|
float kx = t->GetX() - player_actor.GetX();
|
|
float kz = t->GetZ() - player_actor.GetZ();
|
|
t->TakeDamage(dmg1 + dmg2 + dmg3, kx * 0.8f, kz * 0.8f);
|
|
floating_text_mgr.AddDamage(dmg1, hx, hy + 20.0f, hz, false, true);
|
|
floating_text_mgr.AddDamage(dmg2, hx, hy + 45.0f, hz, false, true);
|
|
floating_text_mgr.AddDamage(dmg3, hx, hy + 70.0f, hz, true, true);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", hx, hy + 20.0f, hz);
|
|
if (t == &mob_dog) {
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/damage_1.wav");
|
|
if (t->IsDead()) ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/dead_1.wav");
|
|
} else if (t == &mob_metin) {
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/metinstone/metinstone_crash.wav");
|
|
}
|
|
SDL_Log("Player cast Triple Slash on %s for %d total damage! (HP: %d/%d)", t->GetName().c_str(), dmg1+dmg2+dmg3, t->GetHP(), t->GetMaxHP());
|
|
}
|
|
}
|
|
} else if (skillIndex == 2) { // 八方风雨 Palbang (Sword Spin)
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/palbang.wav");
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/palbang_v.wav");
|
|
player_actor.CastSkill(ava2::MotionType::Skill2);
|
|
|
|
// Official Warrior Whirlwind ground spin effect
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/palbang_2_spin.mse", player_actor.GetX(), player_actor.GetY() + 5.0f, player_actor.GetZ());
|
|
|
|
floating_text_mgr.AddText("SWORD SPIN!", px, py + 35.0f, pz, 0xFFFFCC00, 1.8f, 2.5f);
|
|
std::vector<ava2::ActorInstance*> targets = { &mob_dog, &mob_metin };
|
|
for (auto* t : targets) {
|
|
float dx = t->GetX() - player_actor.GetX();
|
|
float dz = t->GetZ() - player_actor.GetZ();
|
|
float dist = std::sqrt(dx * dx + dz * dz);
|
|
if (!t->IsDead() && dist <= 280.0f) {
|
|
float hx, hy, hz;
|
|
t->GetHeadPosition(hx, hy, hz);
|
|
int dmg = static_cast<int>((320 + (std::rand() % 80) + player_actor.GetBonusAttackDamage()) * player_actor.GetAttackMultiplier());
|
|
t->TakeDamage(dmg, dx * 1.5f, dz * 1.5f);
|
|
floating_text_mgr.AddDamage(dmg, hx, hy + 25.0f, hz, true, true);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/spark.mse", hx, hy + 20.0f, hz);
|
|
if (t == &mob_dog) {
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/damage_1.wav");
|
|
if (t->IsDead()) ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/dead_1.wav");
|
|
} else if (t == &mob_metin) {
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/metinstone/metinstone_crash.wav");
|
|
}
|
|
SDL_Log("Player cast Sword Spin on %s for %d dmg! (HP: %d/%d)", t->GetName().c_str(), dmg, t->GetHP(), t->GetMaxHP());
|
|
}
|
|
}
|
|
} else if (skillIndex == 3) { // 狂战士 Jeongwi (Berserk)
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/jeongwi.wav");
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/jeongwi_v.wav");
|
|
player_actor.CastSkill(ava2::MotionType::Skill3);
|
|
player_actor.SetBuff("berserk", 30.0f);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/jeongwi.mse", player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
floating_text_mgr.AddText("BERSERK ACTIVATED! (ATK +40%, SPD +25%)", px, py + 40.0f, pz, 0xFFFF4444, 1.7f, 3.5f);
|
|
SDL_Log("Player activated Berserk buff!");
|
|
} else if (skillIndex == 4) { // 剑气 Geomgyeong (Aura of the Sword)
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/geomgyeong.wav");
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/geomgyeong_v.wav");
|
|
player_actor.CastSkill(ava2::MotionType::Skill4);
|
|
player_actor.SetBuff("aura", 35.0f);
|
|
|
|
// Ground explosion burst
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/geom_4_badak.mse", player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
|
|
// Continuous weapon aura
|
|
if (sword_aura_effect_id != 0) {
|
|
ava2::EffectManager::Instance().DestroyEffectInstance(sword_aura_effect_id);
|
|
}
|
|
sword_aura_effect_id = ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/geom_sword_loop.mse", player_actor.GetX(), player_actor.GetY() + 60.0f, player_actor.GetZ());
|
|
|
|
floating_text_mgr.AddText("AURA OF THE SWORD! (DMG +120)", px, py + 40.0f, pz, 0xFF44FFFF, 1.7f, 3.5f);
|
|
SDL_Log("Player activated Aura of the Sword buff!");
|
|
} else if (skillIndex == 5) { // 剑风 / 冲锋 (Geompung / Dash)
|
|
if (target_mgr.HasTarget()) {
|
|
auto* tgt = target_mgr.GetTarget();
|
|
float dx = tgt->GetX() - player_actor.GetX();
|
|
float dz = tgt->GetZ() - player_actor.GetZ();
|
|
player_actor.SetYaw(std::atan2(dx, dz) * (180.0f / 3.14159265f));
|
|
player_actor.CastSkill(ava2::MotionType::Skill5);
|
|
|
|
// Launch flying projectile
|
|
float startPos[3] = {player_actor.GetX(), player_actor.GetY() + 60.0f, player_actor.GetZ()};
|
|
float tgtPos[3] = {tgt->GetX(), tgt->GetY() + 40.0f, tgt->GetZ()};
|
|
ava2::FlyingManager::Instance().CreateFlyingInstance(
|
|
"ymir work/pc/warrior/effect/geompung.msf", startPos, tgtPos,
|
|
[tgt, &floating_text_mgr](const float* hitPos) {
|
|
int dmg = static_cast<int>((450 + (std::rand() % 120)) * 1.25f);
|
|
tgt->TakeDamage(dmg, 0.0f, 0.0f);
|
|
floating_text_mgr.AddDamage(dmg, hitPos[0], hitPos[1] + 25.0f, hitPos[2], true, true);
|
|
floating_text_mgr.AddText("SWORD BLAST!", hitPos[0], hitPos[1] + 50.0f, hitPos[2], 0xFF00FFFF, 1.8f, 2.5f);
|
|
ava2::SoundManager::Instance().PlaySound3D(hitPos[0], hitPos[1], hitPos[2], "sound/pc/warrior/skill/geompung.wav");
|
|
}
|
|
);
|
|
floating_text_mgr.AddText("SWORD STRIKE!", px, py + 35.0f, pz, 0xFF00DDFF, 1.6f, 2.0f);
|
|
} else {
|
|
ava2::SoundManager::Instance().PlaySound3D(px, py, pz, "sound/pc/warrior/skill/tanhwan.wav");
|
|
player_actor.CastSkill(ava2::MotionType::Skill5);
|
|
float rad = player_actor.GetYaw() * (3.14159265f / 180.0f);
|
|
float fx = std::sin(rad) * 160.0f;
|
|
float fz = std::cos(rad) * 160.0f;
|
|
float nx = player_actor.GetX() + fx;
|
|
float nz = player_actor.GetZ() + fz;
|
|
player_actor.SetPosition(nx, outdoor_terrain.GetHeightAtWorld(nx, nz), nz);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/tanhwan.mse", player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
floating_text_mgr.AddText("DASH!", px, py + 35.0f, pz, 0xFFFFFF00, 1.5f, 2.0f);
|
|
}
|
|
}
|
|
};
|
|
ava2::SetPlayerSkillCastCallback(cast_skill);
|
|
|
|
auto handle_item_use = [&](int window, int slot) {
|
|
std::string weaponModel;
|
|
std::string msg;
|
|
if (ava2::UsePlayerItem(window, slot, weaponModel, msg)) {
|
|
if (!weaponModel.empty()) {
|
|
player_actor.SetWeapon(weaponModel, "equip_right_hand");
|
|
}
|
|
if (!msg.empty()) {
|
|
floating_text_mgr.AddText(msg, player_actor.GetX(), player_actor.GetY() + 180.0f, player_actor.GetZ(), 0xFF50FF50, 1.8f, 2.5f);
|
|
}
|
|
if (python) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" stream.curPhaseWindow.interface.RefreshInventory()\n"
|
|
);
|
|
}
|
|
}
|
|
};
|
|
ava2::SetItemUsePacketCallback(handle_item_use);
|
|
|
|
auto handle_item_move = [&](int srcWindow, int srcSlot, int dstWindow, int dstSlot, int count) {
|
|
std::string weaponModel;
|
|
if (ava2::MovePlayerItem(srcWindow, srcSlot, dstWindow, dstSlot, count, weaponModel)) {
|
|
if (!weaponModel.empty()) {
|
|
player_actor.SetWeapon(weaponModel, "equip_right_hand");
|
|
}
|
|
if (python) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" stream.curPhaseWindow.interface.RefreshInventory()\n"
|
|
);
|
|
}
|
|
}
|
|
};
|
|
ava2::SetItemMovePacketCallback(handle_item_move);
|
|
|
|
if (original_phase_mode && python) {
|
|
ava2::LoadPlayerSettings();
|
|
python->execute("import introLoading\nintroLoading.__main__()\n");
|
|
if (std::filesystem::exists("npclist.txt"))
|
|
ava2::RaceManager::Instance().LoadGameNPC("npclist.txt");
|
|
else if (std::filesystem::exists("upstream/python-root/npclist.txt"))
|
|
ava2::RaceManager::Instance().LoadGameNPC("upstream/python-root/npclist.txt");
|
|
else if (std::filesystem::exists("locale/en/npclist.txt"))
|
|
ava2::RaceManager::Instance().LoadGameNPC("locale/en/npclist.txt");
|
|
else
|
|
ava2::RaceManager::Instance().LoadGameNPC("npclist.txt");
|
|
ava2::RaceManager::Instance().LoadPlayerRaces();
|
|
|
|
python->execute(
|
|
"import networkModule, game, net, constInfo, app\n"
|
|
// Match prototype.RunApp before the first character is constructed.
|
|
"app.SetHairColorEnable(constInfo.HAIR_COLOR_ENABLE)\n"
|
|
"app.SetArmorSpecularEnable(constInfo.ARMOR_SPECULAR_ENABLE)\n"
|
|
"app.SetWeaponSpecularEnable(constInfo.WEAPON_SPECULAR_ENABLE)\n"
|
|
"stream = networkModule.MainStream()\n"
|
|
"stream.Create()\n"
|
|
);
|
|
if (until_game && !auto_connect) {
|
|
start_phase = "game";
|
|
} else if (until_loading && !auto_connect) {
|
|
start_phase = "loading";
|
|
} else if (until_select && !auto_connect) {
|
|
start_phase = "select";
|
|
}
|
|
switch_phase(start_phase);
|
|
}
|
|
|
|
auto connect = [&] {
|
|
try {
|
|
python->connect_view(fields[2].value, port(fields[3].value), fields[0].value, port(fields[1].value), fields[4].value, fields[5].value);
|
|
std::fill(fields[5].value.begin(), fields[5].value.end(), 0);
|
|
fields[5].value.clear();
|
|
local_error.clear();
|
|
} catch (const std::exception& e) { local_error = e.what(); }
|
|
};
|
|
auto enter = [&] {
|
|
try {
|
|
python->view_action("Enter");
|
|
local_error.clear();
|
|
} catch (const std::exception& e) { local_error = e.what(); }
|
|
};
|
|
#endif
|
|
|
|
bool key_move_fwd = false;
|
|
bool key_move_back = false;
|
|
bool key_turn_left = false;
|
|
bool key_turn_right = false;
|
|
bool chat_input_active = false;
|
|
std::string chat_input_buffer;
|
|
auto prev_frame_time = std::chrono::steady_clock::now();
|
|
|
|
auto cap_period = fps_cap > 0 ? std::chrono::nanoseconds(1'000'000'000LL / fps_cap)
|
|
: std::chrono::nanoseconds(0);
|
|
auto next_frame_at = std::chrono::steady_clock::now() + cap_period;
|
|
|
|
std::ofstream profileOutput;
|
|
if (!frame_profile.empty()) {
|
|
profileOutput.open(frame_profile);
|
|
if (!profileOutput) throw std::runtime_error("Cannot write --frame-profile");
|
|
profileOutput << "phase,frame,interval_ms,active_ms,build_ms,raster_ms,present_ms\n";
|
|
}
|
|
auto profilePreviousEnd = std::chrono::steady_clock::now();
|
|
for (;;) {
|
|
// app_loop: wait for the next SDL_AppIterate (or classic loop turn).
|
|
co_yield frames;
|
|
if (!running || loop->QuitRequested() || (frame_limit && frames >= frame_limit)) break;
|
|
const auto profileFrameStart = std::chrono::steady_clock::now();
|
|
double profileBuildMs = 0.0, profileRasterMs = 0.0;
|
|
const auto profileActiveStart = std::chrono::steady_clock::now();
|
|
#ifdef AVA2_HAS_PYTHON
|
|
ava2::LoginViewSnapshot snapshot;
|
|
if (python && !view_script.empty()) {
|
|
python->pump_network();
|
|
// CheckPacket unknown header / "quit" server command: Windows PostQuitMessage(0)
|
|
if (ava2::PythonNetworkStream::Instance().IsQuitRequested()) running = false;
|
|
snapshot = python->view_snapshot();
|
|
}
|
|
#endif
|
|
ava2::TerrainHeightmap* active_terrain = &outdoor_terrain;
|
|
ava2::MapObjectManager* active_map_objects = &map_objects;
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (ava2::CPythonBackground::Instance().IsMapReady()) {
|
|
if (ava2::CPythonBackground::Instance().GetTerrain()) {
|
|
active_terrain = ava2::CPythonBackground::Instance().GetTerrain();
|
|
}
|
|
if (ava2::CPythonBackground::Instance().GetMapObjects()) {
|
|
active_map_objects = ava2::CPythonBackground::Instance().GetMapObjects();
|
|
}
|
|
}
|
|
#endif
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// On-screen keyboards appear only while an edit line captures text (ime.EnableCaptureInput
|
|
// from the original ui.py), the in-game chat is open or the dev login view is editing.
|
|
if (screen_keyboard) {
|
|
const bool want = ava2::IME_IsCaptureInput() || chat_input_active
|
|
|| (!view_script.empty() && snapshot.phase == "login");
|
|
if (want != SDL_TextInputActive(window.get()))
|
|
want ? SDL_StartTextInput(window.get()) : SDL_StopTextInput(window.get());
|
|
}
|
|
#endif
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (touch_mode) {
|
|
touch_sink.FlushRelease();
|
|
touch_router.SetWorldEnabled(last_phase == "game");
|
|
touch_router.Update(SDL_GetTicks());
|
|
}
|
|
#endif
|
|
SDL_Event event;
|
|
while (loop->PollEvent(&event)) {
|
|
if (event.type == SDL_EVENT_QUIT) running = false;
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (touch_mode && (event.type == SDL_EVENT_WINDOW_SAFE_AREA_CHANGED || event.type == SDL_EVENT_WINDOW_RESIZED)) {
|
|
// Rotating 180 degrees moves the notch to the other side. The router gets the default
|
|
// layout for the new insets; MobileHUD sees touch.GetSafeArea() change, lays itself out
|
|
// again and re-registers its attack button.
|
|
const auto safe = query_safe();
|
|
const auto old = touch_router.GetLayout();
|
|
if (safe.left != old.safe_left || safe.top != old.safe_top ||
|
|
safe.right != old.safe_right || safe.bottom != old.safe_bottom) {
|
|
touch_router.SetLayout(ava2::input::TouchLayout::ForScreen(float(screen_width), float(screen_height),
|
|
safe.left, safe.top, safe.right, safe.bottom));
|
|
SDL_Log("Safe area insets: %.0f %.0f %.0f %.0f", safe.left, safe.top, safe.right, safe.bottom);
|
|
}
|
|
}
|
|
if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {
|
|
ava2::CancelPlayerMovement(); orbit_camera.EndDrag();
|
|
key_move_fwd = key_move_back = key_turn_left = key_turn_right = false;
|
|
ava2::ReleaseAllKeys();
|
|
if (touch_mode) touch_router.CancelAll();
|
|
}
|
|
if (touch_mode) {
|
|
float tx = 0.0f, ty = 0.0f;
|
|
const std::uint64_t tms = event.common.timestamp / 1000000;
|
|
switch (event.type) {
|
|
case SDL_EVENT_FINGER_DOWN:
|
|
finger_point(event.tfinger, tx, ty);
|
|
touch_router.FingerDown(event.tfinger.fingerID, tx, ty, tms);
|
|
break;
|
|
case SDL_EVENT_FINGER_MOTION:
|
|
finger_point(event.tfinger, tx, ty);
|
|
touch_router.FingerMove(event.tfinger.fingerID, tx, ty, tms);
|
|
break;
|
|
case SDL_EVENT_FINGER_UP:
|
|
finger_point(event.tfinger, tx, ty);
|
|
touch_router.FingerUp(event.tfinger.fingerID, tx, ty, tms);
|
|
break;
|
|
case SDL_EVENT_FINGER_CANCELED:
|
|
touch_router.CancelAll();
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
// In touch mode the window manager only sees fingers; desktop mouse input arrives
|
|
// a second time as the emulated finger.
|
|
const bool touch_owns_mouse = touch_mode &&
|
|
(event.type == SDL_EVENT_MOUSE_MOTION || event.type == SDL_EVENT_MOUSE_BUTTON_DOWN ||
|
|
event.type == SDL_EVENT_MOUSE_BUTTON_UP);
|
|
if (wm && !touch_owns_mouse) {
|
|
if (event.type == SDL_EVENT_MOUSE_MOTION) {
|
|
float mx, my;
|
|
SDL_RenderCoordinatesFromWindow(renderer.get(), event.motion.x, event.motion.y, &mx, &my);
|
|
wm->RunMouseMove(static_cast<long>(mx), static_cast<long>(my));
|
|
if (orbit_camera.IsDragging()) {
|
|
orbit_camera.Drag(static_cast<int>(mx), static_cast<int>(my));
|
|
}
|
|
} else if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
|
|
float bx, by;
|
|
SDL_RenderCoordinatesFromWindow(renderer.get(), event.button.x, event.button.y, &bx, &by);
|
|
if (event.button.button == SDL_BUTTON_LEFT) {
|
|
wm->RunMouseLeftButtonDown(static_cast<long>(bx), static_cast<long>(by));
|
|
// PythonApplicationEvent.cpp OnMouseLeftButtonDoubleClick: down, then double click.
|
|
if (event.button.clicks >= 2)
|
|
wm->RunMouseLeftButtonDoubleClick(static_cast<long>(bx), static_cast<long>(by));
|
|
if (last_phase == "game" && renderer3d) {
|
|
// Ignore clicks on the minimap radar at top-right
|
|
bool is_minimap_area = (bx >= static_cast<float>(screen_width) - 135.0f && by <= 140.0f);
|
|
if (!is_minimap_area) {
|
|
// 1. Mouse picking on dropped items via TextTail
|
|
auto& ttm = ava2::TextTailManager::Instance();
|
|
int pickedItemVID = ttm.Pick(static_cast<int>(bx), static_cast<int>(by));
|
|
if (pickedItemVID > 0) {
|
|
auto tail = ttm.GetItemTail(static_cast<uint32_t>(pickedItemVID));
|
|
if (tail) {
|
|
float ix = tail->worldX;
|
|
float iz = tail->worldZ;
|
|
float dx = ix - player_actor.GetX();
|
|
float dz = iz - player_actor.GetZ();
|
|
float dist = std::sqrt(dx * dx + dz * dz);
|
|
if (dist <= 180.0f) {
|
|
ava2::SoundManager::Instance().PlaySound2D("sound/ui/pickup.wav");
|
|
ava2::PythonNetworkStream::Instance().SendItemPickUpPacket(static_cast<uint32_t>(pickedItemVID));
|
|
floating_text_mgr.AddText("Picked up item!", player_actor.GetX(), player_actor.GetY() + 180.0f, player_actor.GetZ(), 0xFFFFD700, 1.6f, 2.0f);
|
|
ttm.DeleteItemTextTail(static_cast<uint32_t>(pickedItemVID));
|
|
} else {
|
|
player_actor.SetMoveTarget(ix, iz);
|
|
target_mgr.AddGroundPickEffect(ix, tail->worldY, iz);
|
|
}
|
|
}
|
|
} else {
|
|
ava2::ActorInstance* clicked_actor = nullptr;
|
|
if (!mob_dog.IsDead() && mob_dog.HitTestScreen(bx, by, *renderer3d)) {
|
|
clicked_actor = &mob_dog;
|
|
} else if (!mob_metin.IsDead() && mob_metin.HitTestScreen(bx, by, *renderer3d)) {
|
|
clicked_actor = &mob_metin;
|
|
}
|
|
|
|
if (clicked_actor) {
|
|
target_mgr.SelectTarget(clicked_actor);
|
|
float dx = clicked_actor->GetX() - player_actor.GetX();
|
|
float dz = clicked_actor->GetZ() - player_actor.GetZ();
|
|
float dist = std::sqrt(dx * dx + dz * dz);
|
|
float target_yaw = std::atan2(dx, dz) * (180.0f / 3.14159265f);
|
|
player_actor.SetYaw(target_yaw);
|
|
|
|
if (dist <= 160.0f) {
|
|
// Within melee range: stop and attack directly
|
|
player_actor.ClearMoveTarget();
|
|
player_actor.StopMoving();
|
|
if (player_actor.Attack()) {
|
|
int baseDmg = 150 + (std::rand() % 75) + player_actor.GetBonusAttackDamage();
|
|
int dmg = static_cast<int>(baseDmg * player_actor.GetAttackMultiplier());
|
|
bool isCrit = ((std::rand() % 4) == 0);
|
|
if (isCrit) dmg = static_cast<int>(dmg * 1.8f);
|
|
float kx = (dist > 1.0f) ? (dx / dist) * 120.0f : 0.0f;
|
|
float kz = (dist > 1.0f) ? (dz / dist) * 120.0f : 0.0f;
|
|
clicked_actor->TakeDamage(dmg, kx, kz);
|
|
float hx, hy, hz;
|
|
clicked_actor->GetHeadPosition(hx, hy, hz);
|
|
floating_text_mgr.AddDamage(dmg, hx, hy + 20.0f, hz, isCrit, true);
|
|
SDL_Log("Player attacked targeted %s for %d dmg! (HP: %d/%d)", clicked_actor->GetName().c_str(), dmg, clicked_actor->GetHP(), clicked_actor->GetMaxHP());
|
|
}
|
|
} else {
|
|
// Outside melee range: set move target to chase towards target
|
|
float approach_dist = dist - 100.0f;
|
|
float app_x = player_actor.GetX() + (dx / dist) * approach_dist;
|
|
float app_z = player_actor.GetZ() + (dz / dist) * approach_dist;
|
|
player_actor.SetMoveTarget(app_x, app_z);
|
|
}
|
|
} else {
|
|
// Pick terrain
|
|
float pickX = 0.0f, pickY = 0.0f, pickZ = 0.0f;
|
|
if (renderer3d->PickTerrain(bx, by, *active_terrain, pickX, pickY, pickZ)) {
|
|
player_actor.SetMoveTarget(pickX, pickZ);
|
|
target_mgr.AddGroundPickEffect(pickX, pickY, pickZ);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else if (event.button.button == SDL_BUTTON_RIGHT) {
|
|
wm->RunMouseRightButtonDown(static_cast<long>(bx), static_cast<long>(by));
|
|
if (preview_data || ava2::IsPlayerCameraDragging())
|
|
orbit_camera.BeginDrag(static_cast<int>(bx), static_cast<int>(by));
|
|
}
|
|
} else if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {
|
|
float bx, by;
|
|
SDL_RenderCoordinatesFromWindow(renderer.get(), event.button.x, event.button.y, &bx, &by);
|
|
if (event.button.button == SDL_BUTTON_LEFT)
|
|
wm->RunMouseLeftButtonUp(static_cast<long>(bx), static_cast<long>(by));
|
|
else if (event.button.button == SDL_BUTTON_RIGHT) {
|
|
wm->RunMouseRightButtonUp(static_cast<long>(bx), static_cast<long>(by));
|
|
if (orbit_camera.IsDragging()) {
|
|
orbit_camera.EndDrag();
|
|
}
|
|
}
|
|
} else if (event.type == SDL_EVENT_MOUSE_WHEEL) {
|
|
if (last_phase == "game" && !wm->RunMouseWheelEvent(long(event.wheel.y * 120))) {
|
|
orbit_camera.Zoom(event.wheel.y);
|
|
}
|
|
} else if (event.type == SDL_EVENT_KEY_DOWN) {
|
|
if (original_phase_mode) {
|
|
if (last_phase != "game") {
|
|
if (event.key.key == SDLK_F1) switch_phase("login");
|
|
else if (event.key.key == SDLK_F2) switch_phase("select");
|
|
else if (event.key.key == SDLK_F3) switch_phase("create");
|
|
else if (event.key.key == SDLK_F4) switch_phase("loading");
|
|
else if (event.key.key == SDLK_F5) switch_phase("game");
|
|
}
|
|
|
|
if (last_phase == "select") {
|
|
if (event.key.key >= SDLK_1 && event.key.key <= SDLK_4) {
|
|
int slot = static_cast<int>(event.key.key - SDLK_1);
|
|
python->execute("if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'SelectSlot'): stream.curPhaseWindow.SelectSlot(" + std::to_string(slot) + ")\n");
|
|
} else if (event.key.key == SDLK_LEFT) {
|
|
python->execute("if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'ChangeSlot'): stream.curPhaseWindow.ChangeSlot(stream.curPhaseWindow.slot - 1)\n");
|
|
} else if (event.key.key == SDLK_RIGHT) {
|
|
python->execute("if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'ChangeSlot'): stream.curPhaseWindow.ChangeSlot(stream.curPhaseWindow.slot + 1)\n");
|
|
} else if (event.key.key == SDLK_C) {
|
|
switch_phase("create");
|
|
} else if (event.key.key == SDLK_RETURN) {
|
|
python->execute("if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'StartGame'): stream.curPhaseWindow.StartGame()\n");
|
|
}
|
|
} else if (last_phase == "create") {
|
|
if (event.key.key >= SDLK_1 && event.key.key <= SDLK_4) {
|
|
int slot = static_cast<int>(event.key.key - SDLK_1);
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow:\n"
|
|
" if hasattr(stream.curPhaseWindow, '_CreateCharacterWindow__SelectSlot'): stream.curPhaseWindow._CreateCharacterWindow__SelectSlot(" + std::to_string(slot) + ")\n"
|
|
" elif hasattr(stream.curPhaseWindow, 'SelectSlot'): stream.curPhaseWindow.SelectSlot(" + std::to_string(slot) + ")\n"
|
|
);
|
|
} else if (event.key.key == SDLK_G || event.key.key == SDLK_TAB) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, '_CreateCharacterWindow__SelectGender'):\n"
|
|
" stream.curPhaseWindow._CreateCharacterWindow__SelectGender(1 if stream.curPhaseWindow.gender == 0 else 0)\n"
|
|
);
|
|
} else if (event.key.key == SDLK_S) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, '_CreateCharacterWindow__SelectShape'):\n"
|
|
" cur = stream.curPhaseWindow.shapeList[stream.curPhaseWindow.gender][stream.curPhaseWindow.slot]\n"
|
|
" stream.curPhaseWindow._CreateCharacterWindow__SelectShape(1 if cur == 0 else 0)\n"
|
|
);
|
|
} else if (event.key.key == SDLK_BACKSPACE) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'editCharacterName'):\n"
|
|
" t = stream.curPhaseWindow.editCharacterName.GetText()\n"
|
|
" if len(t) > 0: stream.curPhaseWindow.editCharacterName.SetText(t[:-1])\n"
|
|
);
|
|
} else if (event.key.key == SDLK_RETURN) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'CreateCharacter'):\n"
|
|
" stream.curPhaseWindow.CreateCharacter()\n"
|
|
);
|
|
} else if (event.key.key == SDLK_ESCAPE) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'CancelCreate'):\n"
|
|
" stream.curPhaseWindow.CancelCreate()\n"
|
|
);
|
|
}
|
|
} else if (last_phase == "login") {
|
|
if (event.key.key == SDLK_TAB) {
|
|
wm->RunIMETabEvent();
|
|
} else if (event.key.key == SDLK_BACKSPACE) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
ava2::IME_OnBackspace();
|
|
}
|
|
} else if (event.key.key == SDLK_DELETE) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEKeyDown(0x2E); // VK_DELETE
|
|
}
|
|
} else if (event.key.key == SDLK_LEFT) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEKeyDown(0x25); // VK_LEFT
|
|
}
|
|
} else if (event.key.key == SDLK_RIGHT) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEKeyDown(0x27); // VK_RIGHT
|
|
}
|
|
} else if (event.key.key == SDLK_HOME) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEKeyDown(0x24); // VK_HOME
|
|
}
|
|
} else if (event.key.key == SDLK_END) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEKeyDown(0x23); // VK_END
|
|
}
|
|
} else if (event.key.key == SDLK_RETURN || event.key.key == SDLK_KP_ENTER) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
wm->RunIMEReturnEvent();
|
|
} else {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow:\n"
|
|
" w = stream.curPhaseWindow\n"
|
|
" if hasattr(w, 'serverBoard') and w.serverBoard.IsShow():\n"
|
|
" w._LoginWindow__OnClickSelectServerButton()\n"
|
|
" elif hasattr(w, 'loginBoard') and w.loginBoard.IsShow():\n"
|
|
" w._LoginWindow__OnClickLoginButton()\n"
|
|
);
|
|
}
|
|
} else if (event.key.key == SDLK_ESCAPE) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'OnPressExitKey'):\n"
|
|
" stream.curPhaseWindow.OnPressExitKey()\n"
|
|
);
|
|
}
|
|
} else if (last_phase == "game" && preview_data) {
|
|
if (event.key.key == SDLK_RETURN || event.key.key == SDLK_KP_ENTER) {
|
|
if (chat_input_active) {
|
|
if (!chat_input_buffer.empty()) {
|
|
ava2::PythonNetworkStream::Instance().SendChatPacket(chat_input_buffer);
|
|
auto& ttm = ava2::TextTailManager::Instance();
|
|
ttm.RegisterChatTail(1001, chat_input_buffer);
|
|
float px, py, pz;
|
|
player_actor.GetHeadPosition(px, py, pz);
|
|
floating_text_mgr.AddText(chat_input_buffer, px, py + 40.0f, pz, 0xFFFFFFFF, 1.6f, 3.5f);
|
|
chat_input_buffer.clear();
|
|
}
|
|
chat_input_active = false;
|
|
} else {
|
|
chat_input_active = true;
|
|
chat_input_buffer.clear();
|
|
}
|
|
} else if (chat_input_active) {
|
|
if (event.key.key == SDLK_BACKSPACE) {
|
|
erase_last(chat_input_buffer);
|
|
} else if (event.key.key == SDLK_ESCAPE) {
|
|
chat_input_active = false;
|
|
chat_input_buffer.clear();
|
|
}
|
|
} else {
|
|
if (event.key.key == SDLK_W || event.key.key == SDLK_UP) {
|
|
key_move_fwd = true;
|
|
player_actor.ClearMoveTarget();
|
|
} else if (event.key.key == SDLK_S || event.key.key == SDLK_DOWN) {
|
|
key_move_back = true;
|
|
player_actor.ClearMoveTarget();
|
|
} else if (event.key.key == SDLK_A || event.key.key == SDLK_LEFT) {
|
|
key_turn_left = true;
|
|
player_actor.ClearMoveTarget();
|
|
} else if (event.key.key == SDLK_D || event.key.key == SDLK_RIGHT) {
|
|
key_turn_right = true;
|
|
player_actor.ClearMoveTarget();
|
|
} else if (event.key.key == SDLK_I) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" stream.curPhaseWindow.interface.ToggleInventoryWindow()\n"
|
|
);
|
|
} else if (event.key.key == SDLK_1) {
|
|
cast_skill(0, 1);
|
|
} else if (event.key.key == SDLK_2) {
|
|
cast_skill(1, 2);
|
|
} else if (event.key.key == SDLK_3) {
|
|
cast_skill(2, 3);
|
|
} else if (event.key.key == SDLK_4) {
|
|
cast_skill(3, 4);
|
|
} else if (event.key.key == SDLK_5 || event.key.key == SDLK_F1) {
|
|
cast_skill(4, 5);
|
|
} else if (event.key.key == SDLK_F7) {
|
|
static int env_cycle = 0;
|
|
env_cycle = (env_cycle + 1) % 5;
|
|
if (env_cycle == 0) {
|
|
if (!current_env.LoadFromFile("c1.msenv")) current_env = ava2::EnvironmentData::CreateDayPreset();
|
|
} else if (env_cycle == 1) {
|
|
current_env = ava2::EnvironmentData::CreateSunsetPreset();
|
|
} else if (env_cycle == 2) {
|
|
current_env = ava2::EnvironmentData::CreateNightPreset();
|
|
} else if (env_cycle == 3) {
|
|
current_env = ava2::EnvironmentData::CreateSnowPreset();
|
|
} else if (env_cycle == 4) {
|
|
if (!current_env.LoadFromFile("bayblacksand.msenv")) current_env = ava2::EnvironmentData::CreateDayPreset();
|
|
}
|
|
outdoor_skybox.SetEnvironment(current_env);
|
|
SDL_Log("Switched environment to: %s (fog near=%.1f far=%.1f)",
|
|
current_env.name.c_str(), current_env.fog.near_dist, current_env.fog.far_dist);
|
|
} else if (event.key.key == SDLK_SPACE) {
|
|
// If a target is locked, automatically orient towards it before swinging
|
|
if (target_mgr.HasTarget()) {
|
|
auto* tgt = target_mgr.GetTarget();
|
|
float dx = tgt->GetX() - player_actor.GetX();
|
|
float dz = tgt->GetZ() - player_actor.GetZ();
|
|
float target_yaw = std::atan2(dx, dz) * (180.0f / 3.14159265f);
|
|
player_actor.SetYaw(target_yaw);
|
|
}
|
|
if (player_actor.Attack()) {
|
|
ava2::SoundManager::Instance().PlaySound3D(player_actor.GetX(), player_actor.GetY(), player_actor.GetZ(), "sound/common/swing/w_1h_c_1.wav");
|
|
if (preview_data) {
|
|
// Melee combat hit detection in forward cone against stand-in preview monsters
|
|
if (!mob_dog.IsDead() && player_actor.IsTargetInAttackRange(mob_dog, 180.0f, 85.0f)) {
|
|
int baseDmg = 150 + (std::rand() % 75) + player_actor.GetBonusAttackDamage();
|
|
int dmg = static_cast<int>(baseDmg * player_actor.GetAttackMultiplier());
|
|
bool isCrit = ((std::rand() % 4) == 0);
|
|
if (isCrit) dmg = static_cast<int>(dmg * 1.8f);
|
|
float kx = mob_dog.GetX() - player_actor.GetX();
|
|
float kz = mob_dog.GetZ() - player_actor.GetZ();
|
|
mob_dog.TakeDamage(dmg, kx, kz);
|
|
float hx, hy, hz;
|
|
mob_dog.GetHeadPosition(hx, hy, hz);
|
|
floating_text_mgr.AddDamage(dmg, hx, hy + 20.0f, hz, isCrit, true);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/gihyeol_spark.mse", hx, hy + 20.0f, hz);
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/damage_1.wav");
|
|
if (mob_dog.IsDead()) ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/stray_dog/dead_1.wav");
|
|
SDL_Log("Player hit Wild Dog for %d dmg! (HP: %d/%d)", dmg, mob_dog.GetHP(), mob_dog.GetMaxHP());
|
|
}
|
|
if (!mob_metin.IsDead() && player_actor.IsTargetInAttackRange(mob_metin, 230.0f, 90.0f)) {
|
|
int baseDmg = 130 + (std::rand() % 50) + player_actor.GetBonusAttackDamage();
|
|
int dmg = static_cast<int>(baseDmg * player_actor.GetAttackMultiplier());
|
|
bool isCrit = ((std::rand() % 5) == 0);
|
|
if (isCrit) dmg = static_cast<int>(dmg * 1.8f);
|
|
mob_metin.TakeDamage(dmg, 0.0f, 0.0f);
|
|
float hx, hy, hz;
|
|
mob_metin.GetHeadPosition(hx, hy, hz);
|
|
floating_text_mgr.AddDamage(dmg, hx, hy + 30.0f, hz, isCrit, true);
|
|
ava2::EffectManager::Instance().CreateEffect("ymir work/pc/warrior/effect/spark.mse", hx, hy + 30.0f, hz);
|
|
ava2::SoundManager::Instance().PlaySound3D(hx, hy, hz, "sound/monster/metinstone/metinstone_crash.wav");
|
|
SDL_Log("Player hit Metin Stone for %d dmg! (HP: %d/%d)", dmg, mob_metin.GetHP(), mob_metin.GetMaxHP());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (event.key.key == SDLK_ESCAPE) {
|
|
if (last_phase == "game" && target_mgr.HasTarget()) {
|
|
target_mgr.ClearTarget();
|
|
} else {
|
|
wm->RunPressEscapeKey();
|
|
}
|
|
}
|
|
if (preview_data && event.key.key == SDLK_F9) {
|
|
use_gpu_raster = !use_gpu_raster;
|
|
ava2::Gr2ModelInstance::SetHardwareSkinningEnabled(use_gpu_raster && std::getenv("AVA2_CPU_SKINNING")==nullptr);
|
|
SDL_Log("3D Rasterizer toggled: %s", use_gpu_raster ? "GPU Hardware Accelerated (Metal)" : "CPU Software Rasterizer");
|
|
}
|
|
int dik = SDLKeyToDIK(event.key.key);
|
|
if (dik) ava2::SetKeyPressed(dik, true);
|
|
if (dik) wm->RunKeyDown(dik);
|
|
} else if (event.type == SDL_EVENT_KEY_UP) {
|
|
if (original_phase_mode && last_phase == "game") {
|
|
if (event.key.key == SDLK_W || event.key.key == SDLK_UP) key_move_fwd = false;
|
|
else if (event.key.key == SDLK_S || event.key.key == SDLK_DOWN) key_move_back = false;
|
|
else if (event.key.key == SDLK_A || event.key.key == SDLK_LEFT) key_turn_left = false;
|
|
else if (event.key.key == SDLK_D || event.key.key == SDLK_RIGHT) key_turn_right = false;
|
|
}
|
|
int dik = SDLKeyToDIK(event.key.key);
|
|
if (dik) ava2::SetKeyPressed(dik, false);
|
|
if (dik) wm->RunKeyUp(dik);
|
|
} else if (event.type == SDL_EVENT_TEXT_INPUT && original_phase_mode && python) {
|
|
if (ava2::IME_IsCaptureInput()) {
|
|
ava2::IME_InsertText(event.text.text);
|
|
} else if (last_phase == "create") {
|
|
std::string text_in = event.text.text;
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'editCharacterName'):\n"
|
|
" t = stream.curPhaseWindow.editCharacterName.GetText() + '" + text_in + "'\n"
|
|
" if len(t) <= 12: stream.curPhaseWindow.editCharacterName.SetText(t)\n"
|
|
);
|
|
} else if (last_phase == "game" && chat_input_active) {
|
|
std::string text_in = event.text.text;
|
|
if (chat_input_buffer.size() + text_in.size() <= 64) {
|
|
chat_input_buffer += text_in;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!python || view_script.empty()) continue;
|
|
bool editable = snapshot.phase == "login";
|
|
if (event.type == SDL_EVENT_TEXT_INPUT && editable) {
|
|
auto& field = fields[focus]; std::string add = event.text.text;
|
|
if (field.value.size() + add.size() <= field.max) field.value += add;
|
|
}
|
|
if (event.type == SDL_EVENT_KEY_DOWN) {
|
|
if (event.key.key == SDLK_ESCAPE) { python->view_action("Cancel"); local_error.clear(); }
|
|
else if (event.key.key == SDLK_TAB && editable) focus = (focus + (event.key.mod & SDL_KMOD_SHIFT ? 5 : 1)) % 6;
|
|
else if (event.key.key == SDLK_BACKSPACE && editable) erase_last(fields[focus].value);
|
|
else if (event.key.key == SDLK_RETURN) { if (editable) connect(); else if (snapshot.phase == "select") enter(); }
|
|
else if (event.key.key >= SDLK_1 && event.key.key <= SDLK_5 && snapshot.phase == "select") {
|
|
try { python->view_action("Choose", int(event.key.key - SDLK_1)); local_error.clear(); } catch (const std::exception& e) { local_error = e.what(); }
|
|
}
|
|
}
|
|
if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN && event.button.button == SDL_BUTTON_LEFT) {
|
|
float x, y; SDL_RenderCoordinatesFromWindow(renderer.get(), event.button.x, event.button.y, &x, &y);
|
|
if (editable && y >= 166 && y < 526 && x >= 48 && x < 630) focus = std::clamp(int((y - 166) / 60), 0, 5);
|
|
if (editable && y >= 554 && y < 606 && x >= 48 && x < 270) connect();
|
|
if (y >= 554 && y < 606 && x >= 292 && x < 490) { python->view_action("Cancel"); local_error.clear(); }
|
|
if (snapshot.phase == "select" && y >= 174 && y < 524 && x >= 680 && x < 1220) {
|
|
try { python->view_action("Choose", int((y - 174) / 70)); local_error.clear(); } catch (const std::exception& e) { local_error = e.what(); }
|
|
}
|
|
if (snapshot.phase == "select" && y >= 554 && y < 606 && x >= 680 && x < 950) enter();
|
|
}
|
|
#endif
|
|
}
|
|
|
|
// platform/ lifecycle: save and go quiet in the background, keep the connection.
|
|
switch (lifecycle.Poll()) {
|
|
case ava2::platform::Lifecycle::Change::EnterBackground:
|
|
SDL_Log("Entering background");
|
|
#ifdef AVA2_HAS_PYTHON
|
|
ava2::CancelPlayerMovement(); orbit_camera.EndDrag();
|
|
key_move_fwd = key_move_back = key_turn_left = key_turn_right = false;
|
|
ava2::ReleaseAllKeys();
|
|
if (touch_mode) touch_router.CancelAll();
|
|
// The OS may kill a background app without another event.
|
|
if (python) {
|
|
ava2::CPythonSystem::Instance().SaveConfig();
|
|
ava2::CPythonSystem::Instance().SaveInterfaceStatus();
|
|
}
|
|
#endif
|
|
ava2::SoundManager::Instance().SetPaused(true);
|
|
break;
|
|
case ava2::platform::Lifecycle::Change::EnterForeground:
|
|
SDL_Log("Entering foreground");
|
|
ava2::SoundManager::Instance().SetPaused(false);
|
|
// The first foreground frame must not see the whole pause as one frame.
|
|
prev_frame_time = std::chrono::steady_clock::now();
|
|
break;
|
|
default: break;
|
|
}
|
|
if (lifecycle.TakeLowMemory()) SDL_Log("Low memory warning");
|
|
if (lifecycle.IsTerminating()) running = false;
|
|
if (lifecycle.IsBackground() && running) {
|
|
// No rendering (the surface is gone on Android) and no game update; the network keeps
|
|
// its keepalive and the queue drained. SDL itself waits up to 100 ms per poll on Android.
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python) {
|
|
if (!view_script.empty()) python->pump_network();
|
|
ava2::PythonNetworkStream::Instance().ProcessRecvData();
|
|
ava2::pump_python_net();
|
|
if (ava2::PythonNetworkStream::Instance().IsQuitRequested()) running = false;
|
|
}
|
|
#endif
|
|
#ifndef __ANDROID__
|
|
SDL_Delay(50);
|
|
#endif
|
|
continue;
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python && !view_script.empty()) {
|
|
if (auto_connect && !requested) { requested = true; connect(); if (!local_error.empty()) throw std::runtime_error(local_error); }
|
|
snapshot = python->view_snapshot();
|
|
if (auto_slot >= 0 && snapshot.phase == "select" && !entered) { python->view_action("Choose", auto_slot); python->view_action("Enter"); entered = true; }
|
|
snapshot = python->view_snapshot();
|
|
if (snapshot.phase != last_phase) { SDL_Log("UI phase: %s", snapshot.phase.c_str()); last_phase = snapshot.phase; }
|
|
}
|
|
#endif
|
|
|
|
// Native auto-connect support
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python && original_phase_mode && auto_connect && !requested && frames > 10) {
|
|
requested = true;
|
|
auto* globals = PyModule_GetDict(PyImport_AddModule("__main__"));
|
|
auto* account = PyString_FromString(fields[4].value.c_str());
|
|
auto* password = PyString_FromString(fields[5].value.c_str());
|
|
PyDict_SetItemString(globals, "__ava2_account", account);
|
|
PyDict_SetItemString(globals, "__ava2_password", password);
|
|
Py_DECREF(account); Py_DECREF(password);
|
|
python->execute(
|
|
"try:\n"
|
|
" w = stream.curPhaseWindow\n"
|
|
" if hasattr(w, 'serverBoard') and w.serverBoard.IsShow():\n"
|
|
" w._LoginWindow__OnClickSelectServerButton()\n"
|
|
" w.idEditLine.SetText(__ava2_account)\n"
|
|
" w.pwdEditLine.SetText(__ava2_password)\n"
|
|
" w.Connect(__ava2_account, __ava2_password)\n"
|
|
"finally:\n"
|
|
" del __ava2_account, __ava2_password\n");
|
|
fields[5].value.clear();
|
|
}
|
|
#endif
|
|
|
|
// Synchronize real phase from stream.curPhaseWindow
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python && original_phase_mode) {
|
|
std::string current_py_phase;
|
|
PyObject* main_mod = PyImport_AddModule("__main__");
|
|
if (main_mod) {
|
|
PyObject* dict = PyModule_GetDict(main_mod);
|
|
PyObject* py_stream = dict ? PyDict_GetItemString(dict, "stream") : nullptr;
|
|
if (py_stream) {
|
|
PyObject* cur_win = PyObject_GetAttrString(py_stream, "curPhaseWindow");
|
|
if (cur_win && cur_win != Py_None) {
|
|
PyObject* cls = PyObject_GetAttrString(cur_win, "__class__");
|
|
if (cls) {
|
|
PyObject* name = PyObject_GetAttrString(cls, "__name__");
|
|
if (name) {
|
|
const char* cname = PyString_AsString(name);
|
|
if (cname) {
|
|
if (std::strcmp(cname, "LoginWindow") == 0) current_py_phase = "login";
|
|
else if (std::strcmp(cname, "SelectCharacterWindow") == 0) current_py_phase = "select";
|
|
else if (std::strcmp(cname, "CreateCharacterWindow") == 0) current_py_phase = "create";
|
|
else if (std::strcmp(cname, "LoadingWindow") == 0) current_py_phase = "loading";
|
|
else if (std::strcmp(cname, "GameWindow") == 0) current_py_phase = "game";
|
|
}
|
|
Py_DECREF(name);
|
|
}
|
|
Py_DECREF(cls);
|
|
}
|
|
Py_DECREF(cur_win);
|
|
} else if (cur_win) {
|
|
Py_DECREF(cur_win);
|
|
}
|
|
}
|
|
}
|
|
if (!current_py_phase.empty() && current_py_phase != last_phase) {
|
|
if (current_py_phase == "game") {
|
|
orbit_camera.SetDistance(1550.0f);
|
|
orbit_camera.SetPitch(27.0f);
|
|
}
|
|
last_phase = current_py_phase;
|
|
SDL_Log("Phase synchronized: %s", last_phase.c_str());
|
|
}
|
|
if (original_phase_mode && auto_slot >= 0 && last_phase == "select" && !entered) {
|
|
python->execute("if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'SelectSlot'):\n"
|
|
" stream.curPhaseWindow.SelectSlot(" + std::to_string(auto_slot) + ")\n"
|
|
" stream.curPhaseWindow.StartGame()\n");
|
|
entered = true;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
auto cur_time = std::chrono::steady_clock::now();
|
|
float dt = std::chrono::duration<float>(cur_time - prev_frame_time).count();
|
|
prev_frame_time = cur_time;
|
|
if (frame_limit > 0) dt = 0.033f;
|
|
else dt = std::clamp(dt, 0.001f, 0.25f);
|
|
game_clock += dt;
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python) {
|
|
ava2::SetGameFrameDelta(dt);
|
|
ava2::pump_python_net();
|
|
}
|
|
#endif
|
|
|
|
if (last_phase == "game" && preview_data) {
|
|
// Continuous rotation
|
|
if (key_turn_left) {
|
|
player_actor.SetYaw(player_actor.GetYaw() - 140.0f * dt);
|
|
}
|
|
if (key_turn_right) {
|
|
player_actor.SetYaw(player_actor.GetYaw() + 140.0f * dt);
|
|
}
|
|
|
|
// Continuous movement (Wait <-> Run state machine)
|
|
if (!player_actor.IsAttacking()) {
|
|
if (key_move_fwd) {
|
|
player_actor.MoveInDirection(player_actor.GetYaw(), dt, active_terrain, active_map_objects);
|
|
} else if (key_move_back) {
|
|
player_actor.MoveInDirection(player_actor.GetYaw() + 180.0f, dt, active_terrain, active_map_objects);
|
|
} else if (!player_actor.HasMoveTarget()) {
|
|
player_actor.StopMoving();
|
|
}
|
|
}
|
|
|
|
// If moving towards target and reached melee range, auto attack
|
|
if (target_mgr.HasTarget() && player_actor.HasMoveTarget()) {
|
|
auto* tgt = target_mgr.GetTarget();
|
|
float dx = tgt->GetX() - player_actor.GetX();
|
|
float dz = tgt->GetZ() - player_actor.GetZ();
|
|
float dist = std::sqrt(dx * dx + dz * dz);
|
|
if (dist <= 160.0f) {
|
|
player_actor.ClearMoveTarget();
|
|
player_actor.StopMoving();
|
|
float target_yaw = std::atan2(dx, dz) * (180.0f / 3.14159265f);
|
|
player_actor.SetYaw(target_yaw);
|
|
if (player_actor.Attack()) {
|
|
int baseDmg = 150 + (std::rand() % 75) + player_actor.GetBonusAttackDamage();
|
|
int dmg = static_cast<int>(baseDmg * player_actor.GetAttackMultiplier());
|
|
bool isCrit = ((std::rand() % 4) == 0);
|
|
if (isCrit) dmg = static_cast<int>(dmg * 1.8f);
|
|
float kx = (dist > 1.0f) ? (dx / dist) * 120.0f : 0.0f;
|
|
float kz = (dist > 1.0f) ? (dz / dist) * 120.0f : 0.0f;
|
|
tgt->TakeDamage(dmg, kx, kz);
|
|
float hx, hy, hz;
|
|
tgt->GetHeadPosition(hx, hy, hz);
|
|
floating_text_mgr.AddDamage(dmg, hx, hy + 20.0f, hz, isCrit, true);
|
|
SDL_Log("Player arrived and hit %s for %d dmg!", tgt->GetName().c_str(), dmg);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Synchronize network position on movement
|
|
if (key_move_fwd || key_move_back || key_turn_left || key_turn_right || player_actor.HasMoveTarget()) {
|
|
if (python) {
|
|
int ix = static_cast<int>(player_actor.GetX() * 100.0f);
|
|
int iz = static_cast<int>(player_actor.GetZ() * 100.0f);
|
|
python->execute(
|
|
"import net\n"
|
|
"net.SendCharacterMovePacket(1, 0, " + std::to_string(player_actor.GetYaw()) + ", "
|
|
+ std::to_string(ix) + ", " + std::to_string(iz) + ")\n"
|
|
);
|
|
}
|
|
}
|
|
|
|
// Automated headless/screenshot verification: target selection, pick ripple, skill cast towards dog
|
|
if (frame_limit > 0 && frames == 1) {
|
|
target_mgr.SelectTarget(&mob_dog);
|
|
}
|
|
if (frame_limit > 0 && frames == 2) {
|
|
// Activate Aura of the Sword buff & trigger cooldown on slot 3
|
|
cast_skill(3, 4);
|
|
}
|
|
if (frame_limit > 0 && frames == 3) {
|
|
// Send chat message via PythonNetworkStream and display overhead speech bubble
|
|
std::string autoChat = "[Stage 6] Client Runtime & Network Online!";
|
|
ava2::PythonNetworkStream::Instance().SendChatPacket(autoChat);
|
|
ava2::TextTailManager::Instance().RegisterChatTail(1001, autoChat);
|
|
|
|
// Toggle inventory window open and refresh item slots
|
|
if (python) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" stream.curPhaseWindow.interface.ToggleInventoryWindow()\n"
|
|
" if hasattr(stream.curPhaseWindow.interface, 'RefreshInventory'):\n"
|
|
" stream.curPhaseWindow.interface.RefreshInventory()\n"
|
|
);
|
|
}
|
|
}
|
|
if (frame_limit > 0 && frames == 4) {
|
|
// Right-click slot 0 (Nymph Sword+9) to equip it!
|
|
if (python) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" if hasattr(stream.curPhaseWindow.interface, 'wndInventory') and stream.curPhaseWindow.interface.wndInventory:\n"
|
|
" stream.curPhaseWindow.interface.wndInventory.UseItemSlot(0)\n"
|
|
);
|
|
}
|
|
}
|
|
if (frame_limit > 0 && frames == 5) {
|
|
// Mouse hover over equipped weapon slot 184 to display detailed tooltip
|
|
if (python) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" if hasattr(stream.curPhaseWindow.interface, 'wndInventory') and stream.curPhaseWindow.interface.wndInventory:\n"
|
|
" stream.curPhaseWindow.interface.wndInventory.ShowToolTip(184)\n"
|
|
);
|
|
}
|
|
}
|
|
int hit_frame = (frame_limit > 20) ? (frame_limit - 14) : 10;
|
|
if (frame_limit > 0 && frames == hit_frame) {
|
|
target_mgr.SelectTarget(&mob_dog);
|
|
float dx = mob_dog.GetX() - player_actor.GetX();
|
|
float dz = mob_dog.GetZ() - player_actor.GetZ();
|
|
float target_yaw = std::atan2(dx, dz) * (180.0f / 3.14159265f);
|
|
player_actor.SetYaw(target_yaw);
|
|
cast_skill(0, 1); // Cast Triple Slash on slot 0
|
|
}
|
|
|
|
// Update actor instances, floating combat text, and target decals
|
|
player_actor.Update(dt, active_terrain, active_map_objects);
|
|
if (preview_data) {
|
|
mob_dog.Update(dt, active_terrain);
|
|
mob_metin.Update(dt, active_terrain);
|
|
}
|
|
floating_text_mgr.Update(dt);
|
|
target_mgr.Update(dt);
|
|
ava2::SoundManager::Instance().SetPosition(player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
ava2::SoundManager::Instance().Update(dt);
|
|
ava2::EffectManager::Instance().Update(dt);
|
|
ava2::FlyingManager::Instance().Update(dt, game_clock);
|
|
|
|
// Drive PythonNetworkStream and NetworkActorManager
|
|
ava2::PythonNetworkStream::Instance().ProcessRecvData();
|
|
ava2::pump_python_net();
|
|
ava2::NetworkActorManager::Instance().Update(dt, active_terrain);
|
|
|
|
// Update TextTail overhead positions
|
|
auto& ttm = ava2::TextTailManager::Instance();
|
|
ttm.SetCharacterPosition(1001, player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
if (preview_data) {
|
|
if (!mob_dog.IsDead()) ttm.SetCharacterPosition(201, mob_dog.GetX(), mob_dog.GetY(), mob_dog.GetZ());
|
|
else ttm.DeleteCharacterTextTail(201);
|
|
if (!mob_metin.IsDead()) ttm.SetCharacterPosition(301, mob_metin.GetX(), mob_metin.GetY(), mob_metin.GetZ());
|
|
else ttm.DeleteCharacterTextTail(301);
|
|
}
|
|
|
|
|
|
if (sword_aura_effect_id != 0) {
|
|
if (!player_actor.HasBuff("aura")) {
|
|
ava2::EffectManager::Instance().DestroyEffectInstance(sword_aura_effect_id);
|
|
sword_aura_effect_id = 0;
|
|
} else {
|
|
float bx, by, bz;
|
|
if (player_actor.GetBonePosition("equip_right_hand", bx, by, bz)) {
|
|
ava2::EffectManager::Instance().SetEffectInstancePosition(sword_aura_effect_id, bx, by, bz);
|
|
} else {
|
|
ava2::EffectManager::Instance().SetEffectInstancePosition(sword_aura_effect_id, player_actor.GetX(), player_actor.GetY() + 60.0f, player_actor.GetZ());
|
|
}
|
|
}
|
|
}
|
|
|
|
if (player_actor.IsAttacking()) {
|
|
float bx, by, bz;
|
|
if (player_actor.GetBonePosition("equip_right_hand", bx, by, bz)) {
|
|
player_weapon_trace.UpdateNewPosition(bx, by, bz, game_clock);
|
|
}
|
|
}
|
|
|
|
player_world_y = player_actor.GetY();
|
|
player_world_x = player_actor.GetX();
|
|
player_world_z = player_actor.GetZ();
|
|
player_world_yaw = player_actor.GetYaw();
|
|
#ifdef AVA2_HAS_PYTHON
|
|
ava2::SetMainCharacterPosition(player_actor.GetX(), player_actor.GetY(), player_actor.GetZ());
|
|
#endif
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// One-shot integration verification against the real GameWindow (also with --preview-data).
|
|
if (last_phase == "game" && python && !game_script.empty() && !game_script_executed && rendered_game_frames >= 3) {
|
|
FILE* script = std::fopen(game_script.c_str(), "rb");
|
|
if (!script) throw std::runtime_error("Cannot open --game-script");
|
|
std::string code;
|
|
char chunk[4096];
|
|
while (size_t size = std::fread(chunk, 1, sizeof(chunk), script)) code.append(chunk, size);
|
|
const bool failed = std::ferror(script);
|
|
std::fclose(script);
|
|
if (failed) throw std::runtime_error("Cannot read --game-script");
|
|
python->execute(code);
|
|
game_script_executed = true;
|
|
}
|
|
if (last_phase == "game" && !preview_data) {
|
|
int rotateInput=0,pitchInput=0,zoomInput=0;
|
|
ava2::GetCameraInput(rotateInput,pitchInput,zoomInput);
|
|
orbit_camera.SetYaw(orbit_camera.GetYaw()+rotateInput*60.0f*dt);
|
|
orbit_camera.SetPitch(orbit_camera.GetPitch()+pitchInput*45.0f*dt);
|
|
if (zoomInput) orbit_camera.SetDistance(orbit_camera.GetDistance()*std::exp(zoomInput*dt));
|
|
// Network/loading callbacks can replace the map during this frame.
|
|
// Resolve owners again after pumping packets instead of retaining freed terrain.
|
|
active_terrain = ava2::CPythonBackground::Instance().GetTerrain();
|
|
active_map_objects = ava2::CPythonBackground::Instance().GetMapObjects();
|
|
if (const auto* environment = ava2::CPythonBackground::Instance().GetCurrentEnvironmentData())
|
|
current_env = *environment;
|
|
ava2::GetMainCharacterPosition(player_world_x, player_world_z, player_world_y);
|
|
if (active_terrain) player_world_y = active_terrain->GetHeightAtWorld(player_world_x, player_world_z);
|
|
auto* main = ava2::NetworkActorManager::Instance().GetMainInstance();
|
|
if (main && main->m_pActorInstance) {
|
|
auto& actor = *main->m_pActorInstance;
|
|
// An add packet can arrive between updates with Z=0. Place it on the map
|
|
// before camera collision checks, rather than shrinking the camera underground.
|
|
if (active_terrain) actor.SetPosition(actor.GetX(), active_terrain->GetHeightAtWorld(actor.GetX(), actor.GetZ()), actor.GetZ());
|
|
// Original GameWindow routes input through player.SetSingleDIKKeyState
|
|
// and SetMouseState. Apply it to the server-owned actor, not the preview.
|
|
static bool wasKeyboardMoving = false;
|
|
static bool wasMoving = false;
|
|
static uint32_t lastMoveSent = 0;
|
|
float moveYaw = 0.0f;
|
|
// Auto hunt (mobile step 6) steers and presses attack like a player would.
|
|
ava2::ProcessAutoHunt();
|
|
// Attack input first (NEW_Attack ends walking); no movement while an attack plays.
|
|
if (ava2::ProcessPlayerAttack(orbit_camera.GetYaw(), dt, wasMoving)) wasMoving = false;
|
|
const bool attacking = ava2::IsPlayerAttacking();
|
|
if (attacking) actor.ClearMoveTarget();
|
|
const bool keyboardMoving = actor.CanAct() && !attacking && ava2::GetPlayerMovementYaw(orbit_camera.GetYaw(), moveYaw);
|
|
actor.SetSpeed(340.0f * float(main->m_dwMovSpd) / 100.0f);
|
|
if (keyboardMoving) {
|
|
actor.ClearMoveTarget();
|
|
actor.MoveInDirection(moveYaw, dt, active_terrain, active_map_objects);
|
|
} else {
|
|
if (wasKeyboardMoving) actor.StopMoving();
|
|
if (actor.CanAct() && !attacking && ava2::IsPlayerMouseMoving() && renderer3d && active_terrain) {
|
|
long mouseX=0, mouseY=0;
|
|
UI::CWindowManager::Instance().GetMousePosition(mouseX,mouseY);
|
|
float pickX=0,pickY=0,pickZ=0;
|
|
if (renderer3d->PickTerrain(float(mouseX),float(mouseY),*active_terrain,pickX,pickY,pickZ))
|
|
actor.SetMoveTarget(pickX,pickZ);
|
|
}
|
|
}
|
|
if (!actor.CanAct()) { actor.ClearMoveTarget(); actor.StopMoving(); }
|
|
const bool moving = keyboardMoving || actor.HasMoveTarget();
|
|
const uint32_t now = ava2::GetServerMSec();
|
|
if ((moving && (!wasMoving || now-lastMoveSent>=100)) || (!moving && wasMoving)) {
|
|
ava2::PythonNetworkStream::Instance().SendCharacterMovePacket(moving?1:0,0,
|
|
uint8_t(std::fmod(actor.GetYaw()+360.0f,360.0f)/5.0f),
|
|
int32_t(actor.GetX()),int32_t(actor.GetZ()),now);
|
|
lastMoveSent = now;
|
|
}
|
|
wasKeyboardMoving = keyboardMoving; wasMoving = moving;
|
|
main->m_lCurX=int32_t(actor.GetX()); main->m_lCurY=int32_t(actor.GetZ()); main->m_lCurZ=int32_t(actor.GetY());
|
|
ava2::TextTailManager::Instance().SetCharacterPosition(main->m_dwVID,actor.GetX(),actor.GetY(),actor.GetZ());
|
|
player_world_x = actor.GetX();
|
|
player_world_y = actor.GetY();
|
|
player_world_z = actor.GetZ();
|
|
player_world_yaw = actor.GetYaw();
|
|
ava2::SetMainCharacterPosition(player_world_x, player_world_z, player_world_y);
|
|
ava2::SoundManager::Instance().SetPosition(player_world_x, player_world_y, player_world_z);
|
|
}
|
|
}
|
|
#endif
|
|
|
|
if (last_phase == "game") {
|
|
uint32_t clear_col = current_env.fog.GetColorUint();
|
|
uint8_t cr = (clear_col >> 16) & 0xFF;
|
|
uint8_t cg = (clear_col >> 8) & 0xFF;
|
|
uint8_t cb = (clear_col) & 0xFF;
|
|
SDL_SetRenderDrawColor(renderer.get(), cr, cg, cb, 255);
|
|
} else {
|
|
SDL_SetRenderDrawColor(renderer.get(), 16, 20, 30, 255);
|
|
}
|
|
SDL_RenderClear(renderer.get());
|
|
|
|
// 3D Model & Terrain Rendering (Python-driven characters + outdoor terrain + fallback)
|
|
if (renderer3d && surface3d && texture3d) {
|
|
#ifdef AVA2_HAS_PYTHON
|
|
auto draws = (last_phase == "game") ? std::vector<ava2::Render3DDraw>{} : (original_phase_mode ? std::vector<ava2::Render3DDraw>{} : ava2::GetAllActiveChrDraws());
|
|
#else
|
|
std::vector<ava2::Render3DDraw> draws;
|
|
#endif
|
|
// Draw count is stable frame to frame; reserve last frame's peak up front.
|
|
static size_t draw_reserve = 0;
|
|
draws.reserve(draw_reserve);
|
|
// Cached map-object commands go by pointer; flattened in order right before rendering.
|
|
static std::vector<ava2::Render3DDrawRef> draw_refs;
|
|
static std::vector<const ava2::Render3DDraw*> draw_list;
|
|
draw_refs.clear();
|
|
const auto profileBuildStart = std::chrono::steady_clock::now();
|
|
if (last_phase == "game") {
|
|
// Update outdoor SkyBox, Clouds UV scrolling & dynamic environment
|
|
outdoor_skybox.Update(dt);
|
|
outdoor_forest.UpdateSystem(0.033f);
|
|
|
|
// Atmospheric Environment Fog (modeled after 40250 CMapOutdoor & .msenv)
|
|
uint32_t fog_color_u = current_env.fog.GetColorUint();
|
|
renderer3d->SetFog(current_env.fog.enable, fog_color_u, 0.00010f, current_env.fog.near_dist, current_env.fog.far_dist, false);
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
float requestedDistance,requestedPitch,requestedYaw,requestedHeight;
|
|
if (!preview_data && ava2::ConsumeCameraSetting(requestedDistance,requestedPitch,requestedYaw,requestedHeight)) {
|
|
orbit_camera.SetDistance(requestedDistance);orbit_camera.SetPitch(requestedPitch);
|
|
orbit_camera.SetYaw(requestedYaw);orbit_camera.SetTargetHeight(requestedHeight);
|
|
}
|
|
#endif
|
|
// Third-person orbit camera following player (40250 CCamera)
|
|
orbit_camera.SetTarget(player_world_x, player_world_y, player_world_z);
|
|
orbit_camera.UpdateWithTerrain(active_terrain);
|
|
|
|
orbit_camera.ApplyToRenderer(*renderer3d);
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (!preview_data) ava2::UpdateCameraFromHost(orbit_camera.GetDistance(),orbit_camera.GetPitch(),orbit_camera.GetYaw(),orbit_camera.GetTargetHeight());
|
|
#endif
|
|
|
|
float fov = 50.0f;
|
|
#ifdef AVA2_HAS_PYTHON
|
|
float sys_fov = ava2::CPythonSystem::Instance().GetFOVLevel();
|
|
if (sys_fov > 10.0f) {
|
|
fov = sys_fov;
|
|
}
|
|
float far_clip = std::max(12000.0f, ava2::CPythonBackground::Instance().GetFarClip());
|
|
#else
|
|
float far_clip = 6000.0f;
|
|
#endif
|
|
renderer3d->SetPerspective(fov, static_cast<float>(view3d_w) / static_cast<float>(view3d_h), 1.0f, far_clip);
|
|
|
|
auto& ttm = ava2::TextTailManager::Instance();
|
|
ttm.UpdateAllTextTail(player_world_x, player_world_y, player_world_z, renderer3d.get());
|
|
ttm.UpdateShowingTextTail(renderer3d.get());
|
|
ttm.ArrangeTextTail();
|
|
|
|
float eyeX = 0.0f, eyeY = 0.0f, eyeZ = 0.0f;
|
|
renderer3d->GetEyePosition(eyeX, eyeY, eyeZ);
|
|
if (until_game && (rendered_game_frames == 0 || rendered_game_frames + 1 == game_frames)) {
|
|
SDL_Log("World camera target=(%.0f,%.0f,%.0f) eye=(%.0f,%.0f,%.0f) distance=%.0f terrain=(%.0f,%.0f)",
|
|
player_world_x, player_world_y, player_world_z, eyeX, eyeY, eyeZ,
|
|
orbit_camera.GetDistance(), active_terrain->GetWorldMinX(), active_terrain->GetWorldMinZ());
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
bool bg_rendered = false;
|
|
if (ava2::CPythonBackground::Instance().IsMapReady()) {
|
|
ava2::CPythonBackground::Instance().Update(player_world_x, player_world_y, player_world_z);
|
|
float camPos[3] = {eyeX, eyeY, eyeZ};
|
|
ava2::CPythonBackground::Instance().BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), camPos, draws, &draw_refs);
|
|
bg_rendered = true;
|
|
}
|
|
if (!bg_rendered)
|
|
#endif
|
|
{
|
|
// 1. SkyDome, Scrolling Clouds, and Sun Flare (drawn first with depth-write disabled)
|
|
auto sky_draws = outdoor_skybox.BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), eyeX, eyeY, eyeZ);
|
|
for (auto& sd : sky_draws) {
|
|
draws.push_back(std::move(sd));
|
|
}
|
|
|
|
// 2. Game phase: render outdoor terrain with quadtree culling & multi-texture patches
|
|
const float terrain_light_dir[3] = {current_env.dir_light.direction[0], current_env.dir_light.direction[1], current_env.dir_light.direction[2]};
|
|
const float terrain_light_ambient[3] = {std::max(0.35f, current_env.dir_light.bg_ambient[0]),
|
|
std::max(0.35f, current_env.dir_light.bg_ambient[1]), std::max(0.38f, current_env.dir_light.bg_ambient[2])};
|
|
const size_t terrain_ref_count = draw_refs.size();
|
|
outdoor_terrain.AppendCulledDrawRefs(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), 8000.0f, draws.size(), draw_refs,
|
|
terrain_light_dir, terrain_light_ambient);
|
|
if (draw_refs.size() == terrain_ref_count) {
|
|
auto td = outdoor_terrain.BuildDrawCommand(nullptr, 2);
|
|
td.light_direction[0] = current_env.dir_light.direction[0];
|
|
td.light_direction[1] = current_env.dir_light.direction[1];
|
|
td.light_direction[2] = current_env.dir_light.direction[2];
|
|
td.light_ambient[0] = std::max(0.35f, current_env.dir_light.bg_ambient[0]);
|
|
td.light_ambient[1] = std::max(0.35f, current_env.dir_light.bg_ambient[1]);
|
|
td.light_ambient[2] = std::max(0.38f, current_env.dir_light.bg_ambient[2]);
|
|
draws.push_back(std::move(td));
|
|
}
|
|
|
|
// Add water surface (translucent, animated)
|
|
if (outdoor_water.HasWater()) {
|
|
auto water_draw = outdoor_water.BuildDrawCommand(game_clock);
|
|
draws.push_back(std::move(water_draw));
|
|
}
|
|
|
|
map_objects.AppendDrawRefs(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), draws.size(), draw_refs);
|
|
|
|
// Add outdoor forest trees, pines, and vegetation (SpeedTree Engine)
|
|
auto tree_draws = outdoor_forest.BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), eyeX, eyeY, eyeZ, 6000.0f);
|
|
for (auto& td : tree_draws) {
|
|
td.light_direction[0] = current_env.dir_light.direction[0];
|
|
td.light_direction[1] = current_env.dir_light.direction[1];
|
|
td.light_direction[2] = current_env.dir_light.direction[2];
|
|
td.light_ambient[0] = std::max(0.35f, current_env.dir_light.bg_ambient[0]);
|
|
td.light_ambient[1] = std::max(0.35f, current_env.dir_light.bg_ambient[1]);
|
|
td.light_ambient[2] = std::max(0.38f, current_env.dir_light.bg_ambient[2]);
|
|
draws.push_back(std::move(td));
|
|
}
|
|
}
|
|
|
|
// Soft circular ground shadows
|
|
bool enable_shadows = true;
|
|
#ifdef AVA2_HAS_PYTHON
|
|
enable_shadows = ava2::CPythonSystem::Instance().IsShadow();
|
|
#endif
|
|
if (enable_shadows) {
|
|
const ava2::TerrainHeightmap* shadow_terrain = (last_phase == "select" || last_phase == "create") ? nullptr : active_terrain;
|
|
if (preview_data) draws.push_back(BuildGroundShadowDraw(player_actor.GetX(), player_actor.GetY(), player_actor.GetZ(), 45.0f, shadow_terrain));
|
|
if (preview_data) {
|
|
if (!mob_dog.IsDead()) {
|
|
draws.push_back(BuildGroundShadowDraw(mob_dog.GetX(), mob_dog.GetY(), mob_dog.GetZ(), 35.0f, shadow_terrain));
|
|
}
|
|
if (!mob_metin.IsDead()) {
|
|
draws.push_back(BuildGroundShadowDraw(mob_metin.GetX(), mob_metin.GetY(), mob_metin.GetZ(), 65.0f, shadow_terrain));
|
|
}
|
|
}
|
|
for (const auto& [vid, actorData] : ava2::NetworkActorManager::Instance().GetActorDict()) {
|
|
// Same frustum test the actor's own draws use; its bounds cover the shadow.
|
|
if (actorData.m_pActorInstance && !actorData.m_isHidden &&
|
|
actorData.m_pActorInstance->IsVisible(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix())) {
|
|
draws.push_back(BuildGroundShadowDraw(
|
|
actorData.m_pActorInstance->GetX(),
|
|
actorData.m_pActorInstance->GetY(),
|
|
actorData.m_pActorInstance->GetZ(),
|
|
45.0f,
|
|
shadow_terrain
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Add animated player actor
|
|
auto char_draws = preview_data ? player_actor.BuildDrawCommands() : std::vector<ava2::Render3DDraw>{};
|
|
auto dog_draws = preview_data ? mob_dog.BuildDrawCommands() : std::vector<ava2::Render3DDraw>{};
|
|
auto metin_draws = preview_data ? mob_metin.BuildDrawCommands() : std::vector<ava2::Render3DDraw>{};
|
|
ava2::NetworkActorManager::Instance().UpdateLODLevel(eyeX, eyeY, eyeZ, player_world_x, player_world_z);
|
|
auto net_draws = ava2::NetworkActorManager::Instance().BuildDrawCommands(game_clock, renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix());
|
|
if (until_game && rendered_game_frames == 20) {
|
|
for (const auto& entry : ava2::NetworkActorManager::Instance().GetActorDict()) {
|
|
const auto& npc=entry.second;
|
|
if (npc.m_dwVirtualNumber >= 61000 && npc.m_dwVirtualNumber <= 61007 && npc.m_pActorInstance)
|
|
SDL_Log("NPC appearance source=%u race=%u armor=%u model=%s", npc.m_dwVirtualNumber, npc.m_dwRace, npc.m_dwArmor, npc.m_pActorInstance->GetShapeModelFile().c_str());
|
|
}
|
|
}
|
|
|
|
auto apply_char_lighting = [&](std::vector<ava2::Render3DDraw>& dlist) {
|
|
for (auto& cd : dlist) {
|
|
cd.light_direction[0] = current_env.dir_light.direction[0];
|
|
cd.light_direction[1] = current_env.dir_light.direction[1];
|
|
cd.light_direction[2] = current_env.dir_light.direction[2];
|
|
cd.light_ambient[0] = std::max(0.55f, current_env.dir_light.chr_ambient[0]);
|
|
cd.light_ambient[1] = std::max(0.55f, current_env.dir_light.chr_ambient[1]);
|
|
cd.light_ambient[2] = std::max(0.58f, current_env.dir_light.chr_ambient[2]);
|
|
cd.light_diffuse[0] = current_env.dir_light.chr_diffuse[0];
|
|
cd.light_diffuse[1] = current_env.dir_light.chr_diffuse[1];
|
|
cd.light_diffuse[2] = current_env.dir_light.chr_diffuse[2];
|
|
cd.material_ambient[0] = 0.85f;
|
|
cd.material_ambient[1] = 0.85f;
|
|
cd.material_ambient[2] = 0.85f;
|
|
cd.material_emissive[0] = 0.05f;
|
|
cd.material_emissive[1] = 0.05f;
|
|
cd.material_emissive[2] = 0.05f;
|
|
}
|
|
};
|
|
apply_char_lighting(char_draws);
|
|
for (auto& cd : char_draws) draws.push_back(std::move(cd));
|
|
|
|
if (preview_data) {
|
|
if (!mob_dog.IsDead()) {
|
|
apply_char_lighting(dog_draws);
|
|
for (auto& dd : dog_draws) draws.push_back(std::move(dd));
|
|
}
|
|
if (!mob_metin.IsDead()) {
|
|
apply_char_lighting(metin_draws);
|
|
for (auto& md : metin_draws) draws.push_back(std::move(md));
|
|
}
|
|
}
|
|
|
|
apply_char_lighting(net_draws);
|
|
draws.insert(draws.end(), std::make_move_iterator(net_draws.begin()), std::make_move_iterator(net_draws.end()));
|
|
|
|
// Add Particle effects, projectiles, and weapon ribbon trails
|
|
float camPos[3] = {eyeX, eyeY, eyeZ};
|
|
ava2::EffectManager::Instance().BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), camPos, draws);
|
|
ava2::FlyingManager::Instance().BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), game_clock, draws);
|
|
if (!player_weapon_trace.IsEmpty()) {
|
|
player_weapon_trace.BuildDrawCommands(renderer3d->GetViewMatrix(), renderer3d->GetProjMatrix(), game_clock, draws);
|
|
}
|
|
} else {
|
|
renderer3d->SetFog(false);
|
|
if (!original_phase_mode) {
|
|
// Select / Create showcase camera
|
|
renderer3d->SetCameraLookAt(0.0f, 130.0f, -320.0f, 0.0f, 100.0f, 0.0f, 0.0f, 1.0f, 0.0f);
|
|
renderer3d->SetPerspective(45.0f, static_cast<float>(view3d_w) / static_cast<float>(view3d_h), 1.0f, 2000.0f);
|
|
|
|
if (draws.empty() && model3d) {
|
|
float angle = static_cast<float>(frames) * 1.5f;
|
|
float world[16];
|
|
ava2::MakeTransformMatrix(angle, 0.0f, 0.0f, 0.0f, 1.0f, world);
|
|
draws = model3d->BuildDrawCommands(-1.0f, world);
|
|
}
|
|
}
|
|
}
|
|
|
|
profileBuildMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-profileBuildStart).count();
|
|
draw_reserve = std::max(draw_reserve, draws.size());
|
|
ava2::FlattenDraws(draws, draw_refs, draw_list);
|
|
if (!draw_list.empty()) {
|
|
const auto profileRasterStart = std::chrono::steady_clock::now();
|
|
uint32_t clear_col = (last_phase == "game") ? current_env.fog.GetColorUint() : 0x00000000;
|
|
if (use_gpu_raster) {
|
|
// High Performance Hardware-Accelerated GPU Pipeline (Metal / Vulkan via SDL_RenderGeometry)
|
|
// Only the SDL geometry fallback rasterizes at screen coordinates and needs the
|
|
// scaled intermediate; the hardware pipeline upscales its colour target in one blit.
|
|
const bool scaled_target = gpu_scene_texture && !renderer3d->HasHardwarePipeline();
|
|
if (scaled_target) {
|
|
SDL_SetRenderTarget(renderer.get(), gpu_scene_texture.get());
|
|
SDL_SetRenderDrawColor(renderer.get(), (clear_col >> 16) & 0xFF, (clear_col >> 8) & 0xFF, clear_col & 0xFF, (clear_col >> 24) & 0xFF);
|
|
SDL_RenderClear(renderer.get());
|
|
}
|
|
|
|
renderer3d->RenderSceneGPU(renderer.get(), draw_list);
|
|
|
|
if (scaled_target) {
|
|
SDL_SetRenderTarget(renderer.get(), nullptr);
|
|
SDL_FRect dst = { 0.0f, 0.0f, static_cast<float>(screen_width), static_cast<float>(screen_height) };
|
|
SDL_RenderTexture(renderer.get(), gpu_scene_texture.get(), nullptr, &dst);
|
|
}
|
|
} else {
|
|
// CPU Software Rasterizer (Fallback & Headless verification)
|
|
SDL_FillSurfaceRect(surface3d.get(), nullptr, clear_col);
|
|
renderer3d->Clear(clear_col, 1.0f);
|
|
renderer3d->RenderScene(surface3d.get(), draw_list);
|
|
|
|
SDL_UpdateTexture(texture3d.get(), nullptr, surface3d->pixels, surface3d->pitch);
|
|
SDL_FRect dst = { 0.0f, 0.0f, static_cast<float>(screen_width), static_cast<float>(screen_height) };
|
|
SDL_RenderTexture(renderer.get(), texture3d.get(), nullptr, &dst);
|
|
}
|
|
|
|
profileRasterMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-profileRasterStart).count();
|
|
// Render Minimap Radar HUD in game phase (modeled after 40250 CPythonMiniMap)
|
|
if (last_phase == "game" && preview_data) {
|
|
minimap_mgr.ClearBlips();
|
|
if (preview_data) {
|
|
if (!mob_dog.IsDead()) {
|
|
minimap_mgr.AddBlip(mob_dog.GetX(), mob_dog.GetZ(), ava2::MinimapBlipType::Monster);
|
|
}
|
|
if (!mob_metin.IsDead()) {
|
|
minimap_mgr.AddBlip(mob_metin.GetX(), mob_metin.GetZ(), ava2::MinimapBlipType::Monster);
|
|
}
|
|
}
|
|
minimap_mgr.AddBlip(60.0f, 140.0f, ava2::MinimapBlipType::NPC); // NPC
|
|
|
|
if (!minimap_surface) {
|
|
minimap_surface.reset(SDL_CreateSurface(128, 128, SDL_PIXELFORMAT_ARGB8888));
|
|
minimap_texture.reset(SDL_CreateTexture(renderer.get(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 128, 128));
|
|
minimap_radar_valid = false;
|
|
if (minimap_texture) {
|
|
SDL_SetTextureBlendMode(minimap_texture.get(), SDL_BLENDMODE_BLEND);
|
|
}
|
|
}
|
|
if (minimap_surface && minimap_texture) {
|
|
// Redraw/upload only when the radar inputs move; a standing player re-presents the texture.
|
|
const std::array<float, 9> radar{player_world_x, player_world_z, player_world_yaw,
|
|
mob_dog.GetX(), mob_dog.GetZ(), mob_dog.IsDead() ? 1.f : 0.f,
|
|
mob_metin.GetX(), mob_metin.GetZ(), mob_metin.IsDead() ? 1.f : 0.f};
|
|
if (!minimap_radar_valid || radar != minimap_last_radar) {
|
|
SDL_FillSurfaceRect(minimap_surface.get(), nullptr, 0x00000000);
|
|
minimap_mgr.RenderRadar(minimap_surface.get(), 0, 0, 128, player_world_x, player_world_z, player_world_yaw);
|
|
SDL_UpdateTexture(minimap_texture.get(), nullptr, minimap_surface->pixels, minimap_surface->pitch);
|
|
minimap_last_radar = radar;minimap_radar_valid = true;
|
|
}
|
|
// Inside the uiminimap.MiniMap frame (the mobile HUD moves it), at the
|
|
// offset its OnRender passes to miniMap.Render; hidden with the minimap.
|
|
SDL_FRect dst = { static_cast<float>(screen_width - 132), 5.0f, 128.0f, 128.0f };
|
|
bool radar_shown = true;
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (python) {
|
|
auto& mini_map = ava2::CPythonMiniMap::Instance();
|
|
float sx = 0.0f, sy = 0.0f;
|
|
mini_map.GetScreenPosition(&sx, &sy);
|
|
if (sx != 0.0f || sy != 0.0f) {
|
|
dst.x = sx; dst.y = sy;
|
|
// No map loads in preview, so MiniMap.AtlasInfo never opens the minimap;
|
|
// open it once so its close/open buttons drive the radar.
|
|
if (!minimap_preview_opened) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow and hasattr(stream.curPhaseWindow, 'interface'):\n"
|
|
" stream.curPhaseWindow.interface.wndMiniMap.ShowMiniMap()\n");
|
|
minimap_preview_opened = true;
|
|
}
|
|
radar_shown = mini_map.CanShow();
|
|
}
|
|
}
|
|
#endif
|
|
if (radar_shown) SDL_RenderTexture(renderer.get(), minimap_texture.get(), nullptr, &dst);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
graphicDevice.BeginScene(false);
|
|
if (wm) {
|
|
// CTimer::GetElapsedMilliecond for the event sets updated by this frame's windows.
|
|
ava2::CPythonEventManager::Instance().SetElapsedMillisecond(long(dt * 1000.0f));
|
|
wm->Update();
|
|
wm->Render();
|
|
}
|
|
if (python && original_phase_mode) {
|
|
python->execute(
|
|
"if 'stream' in globals() and stream.curPhaseWindow:\n"
|
|
" if hasattr(stream.curPhaseWindow, 'OnUpdate'): stream.curPhaseWindow.OnUpdate()\n"
|
|
" if hasattr(stream.curPhaseWindow, 'OnRender'): stream.curPhaseWindow.OnRender()\n"
|
|
);
|
|
}
|
|
if (python && wm) {
|
|
// CPythonApplication OnMouseUpdate/OnMouseRender: the attached icon over the UI.
|
|
long mouse_x = 0, mouse_y = 0;
|
|
wm->GetMousePosition(mouse_x, mouse_y);
|
|
ava2::RunMouseHandler(mouse_x, mouse_y);
|
|
}
|
|
graphicDevice.EndScene(false);
|
|
|
|
if (last_phase == "game" && renderer3d && preview_data) {
|
|
target_mgr.Render(renderer.get(), *renderer3d, active_terrain);
|
|
ava2::TextTailManager::Instance().ShowAllTextTail();
|
|
ava2::TextTailManager::Instance().Render(renderer.get(), renderer3d.get());
|
|
floating_text_mgr.Render(renderer.get(), *renderer3d);
|
|
|
|
if (chat_input_active) {
|
|
rectangle(renderer.get(), 18, 660, 480, 34, 12, 18, 28);
|
|
SDL_SetRenderDrawColor(renderer.get(), 255, 230, 100, 255);
|
|
std::string disp = "Chat: " + chat_input_buffer + "_";
|
|
text(renderer.get(), 26, 668, disp, 1.4f);
|
|
}
|
|
}
|
|
|
|
if (original_phase_mode && preview_data && !touch_mode) {
|
|
// Informative header for interactive mode (keyboard hints; the mobile HUD owns the top row)
|
|
SDL_SetRenderDrawColor(renderer.get(), 200, 220, 240, 200);
|
|
std::string hud;
|
|
if (last_phase == "select") {
|
|
hud = "AVA2 [select] — 1-4: Select Slot | C/Enter: Create Character | F1-F5: Phases";
|
|
} else if (last_phase == "create") {
|
|
hud = "AVA2 [create] — 1-4: Class | G/Tab: Gender | S: Shape | Type: Name | Enter: Submit | Esc: Back";
|
|
} else if (last_phase == "game") {
|
|
hud = "AVA2 [game] HP: " + std::to_string(player_actor.GetHP()) + "/" + std::to_string(player_actor.GetMaxHP())
|
|
+ " | LClick: Pick/Target/Move | Space: Combo | 1-5: Skills | Enter: Chat | Esc: Clear";
|
|
} else {
|
|
hud = "AVA2 Metin2 Client [" + last_phase + "] — F1: Login | F2: Select | F3: Create | F4: Loading | F5: Game";
|
|
}
|
|
text(renderer.get(), 16, 12, hud, 1.2f);
|
|
} else if (!view_script.empty()) {
|
|
SDL_SetRenderDrawColor(renderer.get(), 235, 240, 246, 255); text(renderer.get(), 48, 40, "AVA2 / CROSS-PLATFORM CLIENT", 3);
|
|
SDL_SetRenderDrawColor(renderer.get(), 143, 158, 176, 255); text(renderer.get(), 48, 86, "Login integration / original artwork and 3D character preview pending", 1.5f);
|
|
SDL_SetRenderDrawColor(renderer.get(), 116, 210, 196, 255); text(renderer.get(), 48, 126, snapshot.message, 1.5f);
|
|
for (int i = 0; i < 6; ++i) {
|
|
rectangle(renderer.get(), 48, 166 + i * 60, 582, 50, i == focus ? 35 : 22, i == focus ? 56 : 32, i == focus ? 73 : 45);
|
|
SDL_SetRenderDrawColor(renderer.get(), 162, 177, 195, 255); text(renderer.get(), 62, 174 + i * 60, fields[i].label, 1.5f);
|
|
SDL_SetRenderDrawColor(renderer.get(), 245, 245, 245, 255); auto display = fields[i].secret ? std::string(fields[i].value.size(), '*') : fields[i].value;
|
|
if (display.size() > 33) display = display.substr(0, 30) + "...";
|
|
text(renderer.get(), 236, 184 + i * 60, display, 1.5f);
|
|
}
|
|
for (std::size_t i = 0; i < snapshot.slots.size(); ++i) {
|
|
const auto& slot = snapshot.slots[i]; bool selected = snapshot.selected == int(i);
|
|
rectangle(renderer.get(), 680, 174 + i * 70, 540, 60, selected ? 31 : 20, selected ? 76 : 31, selected ? 84 : 43);
|
|
SDL_SetRenderDrawColor(renderer.get(), slot.id ? 235 : 110, slot.id ? 240 : 125, slot.id ? 246 : 140, 255);
|
|
text(renderer.get(), 696, 186 + i * 70, std::to_string(i + 1) + " " + (slot.id ? slot.name : "Empty slot"), 2);
|
|
if (slot.id) { SDL_SetRenderDrawColor(renderer.get(), 158, 180, 199, 255); text(renderer.get(), 738, 216 + i * 70, "Level " + std::to_string(slot.level) + " Race " + std::to_string(slot.job), 1.5f); }
|
|
}
|
|
rectangle(renderer.get(), 48, 554, 222, 52, 26, 92, 93);
|
|
rectangle(renderer.get(), 292, 554, 198, 52, 38, 47, 60);
|
|
rectangle(renderer.get(), 680, 554, 270, 52, 26, 92, 93);
|
|
SDL_SetRenderDrawColor(renderer.get(), 245, 245, 245, 255);
|
|
text(renderer.get(), 72, 574, "CONNECT", 2);
|
|
text(renderer.get(), 316, 574, "CANCEL", 2);
|
|
text(renderer.get(), 704, 574, "ENTER CHARACTER", 2);
|
|
SDL_SetRenderDrawColor(renderer.get(), 143, 158, 176, 255);
|
|
text(renderer.get(), 48, 632, "Tab: next field Enter: connect/enter Esc: cancel 1-5: choose slot", 1.5f);
|
|
if (!local_error.empty()) { SDL_SetRenderDrawColor(renderer.get(), 245, 128, 128, 255); text(renderer.get(), 48, 665, local_error, 1.5f); }
|
|
}
|
|
#endif
|
|
|
|
bool finished = frame_limit && (frames + 1 == frame_limit);
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if (view_script.empty()) {
|
|
if (until_loading && last_phase == "loading") finished = true;
|
|
if (until_select && last_phase == "select") finished = true;
|
|
if (last_phase == "game") {
|
|
++rendered_game_frames;
|
|
if (until_game && rendered_game_frames >= game_frames) finished = true;
|
|
}
|
|
} else {
|
|
if (until_loading && snapshot.phase == "loading") finished = true;
|
|
if (until_select && snapshot.phase == "select") finished = true;
|
|
if (until_game && snapshot.phase == "game") finished = true;
|
|
}
|
|
if ((until_loading || until_select || until_game) && std::chrono::steady_clock::now() > deadline)
|
|
throw std::runtime_error("automated UI run timed out");
|
|
#endif
|
|
if (finished && !screenshot.empty()) {
|
|
std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)> surface(
|
|
SDL_RenderReadPixels(renderer.get(), nullptr),
|
|
SDL_DestroySurface
|
|
);
|
|
if (!surface || !SDL_SaveBMP(surface.get(), screenshot.c_str()))
|
|
throw std::runtime_error(SDL_GetError());
|
|
}
|
|
|
|
// Pace presentation, not the start of drawing: a varying scene cost
|
|
// must not turn a steady 60 Hz update loop into uneven visible frames.
|
|
const auto profilePacingStart = std::chrono::steady_clock::now();
|
|
if (cap_period.count() > 0) {
|
|
const auto now = std::chrono::steady_clock::now();
|
|
if (next_frame_at > now) {
|
|
SDL_DelayPrecise(std::chrono::duration_cast<std::chrono::nanoseconds>(next_frame_at-now).count());
|
|
} else if (now-next_frame_at > cap_period) {
|
|
next_frame_at = now;
|
|
}
|
|
next_frame_at += cap_period;
|
|
}
|
|
const auto profilePresentStart = std::chrono::steady_clock::now();
|
|
if (!SDL_RenderPresent(renderer.get())) throw std::runtime_error(SDL_GetError());
|
|
if (until_game && last_phase == "game" && rendered_game_frames % 20 == 0)
|
|
SDL_Log("Frame profile total=%.2f build=%.2f raster=%.2f active=%.2f present=%.2f ms",
|
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-profileFrameStart).count(), profileBuildMs, profileRasterMs,
|
|
std::chrono::duration<double, std::milli>(profilePacingStart-profileActiveStart+std::chrono::steady_clock::now()-profilePresentStart).count(),
|
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now()-profilePresentStart).count());
|
|
if(!frame_profile.empty() && last_phase=="game" && rendered_game_frames%120==0 && renderer3d) {
|
|
SDL_Log("Resource profile decoded=%zu gpuTextures=%zu decodes=%zu uploads=%zu",renderer3d->GetDecodedTextureBytes(),renderer3d->GetHardwareTextureBytes(),renderer3d->GetTextureDecodeCount(),renderer3d->GetHardwareTextureUploadCount());
|
|
if(active_map_objects)SDL_Log("Collision profile candidates=%zu objects=%zu",active_map_objects->GetLastCollisionCandidateCount(),active_map_objects->GetObjectCount());
|
|
#ifdef AVA2_HAS_PYTHON
|
|
if(python)SDL_Log("Python code profile entries=%zu bytes=%zu compilations=%zu",python->compiled_code_count(),python->compiled_code_bytes(),python->compilation_count());
|
|
#endif
|
|
}
|
|
const auto profileEnd = std::chrono::steady_clock::now();
|
|
if (profileOutput) profileOutput << last_phase << ',' << rendered_game_frames << ','
|
|
<< std::chrono::duration<double,std::milli>(profileEnd-profilePreviousEnd).count() << ','
|
|
<< std::chrono::duration<double,std::milli>(profilePacingStart-profileActiveStart+profileEnd-profilePresentStart).count() << ','
|
|
<< profileBuildMs << ',' << profileRasterMs << ','
|
|
<< std::chrono::duration<double,std::milli>(profileEnd-profilePresentStart).count() << '\n';
|
|
profilePreviousEnd = profileEnd;
|
|
++frames;
|
|
if (finished) running = false;
|
|
}
|
|
|
|
#ifdef AVA2_HAS_PYTHON
|
|
// CPythonApplication::Destroy: SaveConfig, then SaveInterfaceStatus while Python is alive.
|
|
if (python) {
|
|
ava2::CPythonSystem::Instance().SaveConfig();
|
|
ava2::CPythonSystem::Instance().SaveInterfaceStatus();
|
|
// Release UI/minimap image resources while their SDL renderer is still alive.
|
|
python.reset();
|
|
}
|
|
graphicDevice.Init(nullptr);
|
|
#endif
|
|
ava2::SoundManager::Instance().Destroy();
|
|
SDL_StopTextInput(window.get());
|
|
SDL_WaitForGPUIdle(gpu.get());
|
|
co_return 0;
|
|
} catch (const std::exception& e) {
|
|
std::cerr << e.what() << '\n';
|
|
#ifdef __ANDROID__
|
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", e.what()); // stderr is not captured on Android
|
|
#endif
|
|
co_return 1;
|
|
}
|
|
}
|
|
} // namespace
|
|
|
|
namespace ava2::app {
|
|
namespace {
|
|
using Promise = AppLoop::Frame::promise_type;
|
|
Promise& PromiseOf(std::coroutine_handle<> frame) {
|
|
return std::coroutine_handle<Promise>::from_address(frame.address()).promise();
|
|
}
|
|
} // namespace
|
|
|
|
AppLoop::~AppLoop() {
|
|
if (m_frame) m_frame.destroy();
|
|
}
|
|
|
|
bool AppLoop::Start(int argc, char** argv, bool queuedEvents) {
|
|
m_queuedEvents = queuedEvents;
|
|
m_frame = RunClient(this, argc, argv).handle;
|
|
return Resume();
|
|
}
|
|
|
|
bool AppLoop::Iterate() {
|
|
return Resume();
|
|
}
|
|
|
|
bool AppLoop::Resume() {
|
|
if (!m_frame || m_frame.done()) return false;
|
|
// SDL may call back in while the frame runs (e.g. an event watch during a live resize).
|
|
if (m_inFrame) return true;
|
|
m_inFrame = true;
|
|
m_frame.resume();
|
|
m_inFrame = false;
|
|
if (!m_frame.done()) return true;
|
|
m_exitCode = PromiseOf(m_frame).result;
|
|
return false;
|
|
}
|
|
|
|
void AppLoop::QueueEvent(const SDL_Event& event) {
|
|
// Nothing reads the queue while the app is suspended in the background; keep the newest.
|
|
constexpr std::size_t kMaxQueued = 4096;
|
|
if (m_events.size() >= kMaxQueued) m_events.pop_front();
|
|
m_events.push_back(event);
|
|
}
|
|
|
|
bool AppLoop::PollEvent(SDL_Event* event) {
|
|
if (!m_queuedEvents) return SDL_PollEvent(event);
|
|
if (m_events.empty()) return false;
|
|
*event = m_events.front();
|
|
m_events.pop_front();
|
|
return true;
|
|
}
|
|
|
|
int AppLoop::Finish() {
|
|
if (m_frame && !m_frame.done() && !m_inFrame) {
|
|
// Leaves the loop at the top of the next turn and runs the teardown.
|
|
m_quit = true;
|
|
Resume();
|
|
}
|
|
if (m_frame && m_frame.done()) {
|
|
m_exitCode = PromiseOf(m_frame).result;
|
|
m_frame.destroy();
|
|
m_frame = nullptr;
|
|
}
|
|
return m_exitCode;
|
|
}
|
|
|
|
int AppLoop::Run(int argc, char** argv) {
|
|
if (Start(argc, argv, false))
|
|
while (Iterate()) {}
|
|
return Finish();
|
|
}
|
|
|
|
} // namespace ava2::app
|