game_engine.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  1. #include "game_engine.h"
  2. #include "../controllers/action_vfx.h"
  3. #include "../controllers/command_controller.h"
  4. #include "../models/audio_system_proxy.h"
  5. #include "../models/cursor_manager.h"
  6. #include "../models/hover_tracker.h"
  7. #include "AudioEventHandler.h"
  8. #include "app/models/cursor_mode.h"
  9. #include "app/utils/engine_view_helpers.h"
  10. #include "app/utils/movement_utils.h"
  11. #include "app/utils/selection_utils.h"
  12. #include "core/system.h"
  13. #include "game/audio/AudioSystem.h"
  14. #include "game/units/spawn_type.h"
  15. #include "game/units/troop_type.h"
  16. #include <QBuffer>
  17. #include <QCoreApplication>
  18. #include <QCursor>
  19. #include <QDebug>
  20. #include <QImage>
  21. #include <QOpenGLContext>
  22. #include <QQuickWindow>
  23. #include <QSize>
  24. #include <QVariant>
  25. #include <memory>
  26. #include <optional>
  27. #include <qbuffer.h>
  28. #include <qcoreapplication.h>
  29. #include <qdir.h>
  30. #include <qevent.h>
  31. #include <qglobal.h>
  32. #include <qimage.h>
  33. #include <qjsonobject.h>
  34. #include <qnamespace.h>
  35. #include <qobject.h>
  36. #include <qobjectdefs.h>
  37. #include <qpoint.h>
  38. #include <qsize.h>
  39. #include <qstringliteral.h>
  40. #include <qstringview.h>
  41. #include <qtmetamacros.h>
  42. #include <qvectornd.h>
  43. #include "../models/selected_units_model.h"
  44. #include "game/core/component.h"
  45. #include "game/core/event_manager.h"
  46. #include "game/core/world.h"
  47. #include "game/game_config.h"
  48. #include "game/map/environment.h"
  49. #include "game/map/level_loader.h"
  50. #include "game/map/map_catalog.h"
  51. #include "game/map/map_loader.h"
  52. #include "game/map/map_transformer.h"
  53. #include "game/map/skirmish_loader.h"
  54. #include "game/map/terrain_service.h"
  55. #include "game/map/visibility_service.h"
  56. #include "game/map/world_bootstrap.h"
  57. #include "game/systems/ai_system.h"
  58. #include "game/systems/arrow_system.h"
  59. #include "game/systems/building_collision_registry.h"
  60. #include "game/systems/camera_service.h"
  61. #include "game/systems/capture_system.h"
  62. #include "game/systems/cleanup_system.h"
  63. #include "game/systems/combat_system.h"
  64. #include "game/systems/command_service.h"
  65. #include "game/systems/formation_planner.h"
  66. #include "game/systems/game_state_serializer.h"
  67. #include "game/systems/global_stats_registry.h"
  68. #include "game/systems/movement_system.h"
  69. #include "game/systems/nation_registry.h"
  70. #include "game/systems/owner_registry.h"
  71. #include "game/systems/patrol_system.h"
  72. #include "game/systems/picking_service.h"
  73. #include "game/systems/production_service.h"
  74. #include "game/systems/production_system.h"
  75. #include "game/systems/save_load_service.h"
  76. #include "game/systems/selection_system.h"
  77. #include "game/systems/terrain_alignment_system.h"
  78. #include "game/systems/troop_count_registry.h"
  79. #include "game/systems/victory_service.h"
  80. #include "game/units/factory.h"
  81. #include "game/units/troop_config.h"
  82. #include "render/geom/arrow.h"
  83. #include "render/geom/patrol_flags.h"
  84. #include "render/gl/bootstrap.h"
  85. #include "render/gl/camera.h"
  86. #include "render/ground/biome_renderer.h"
  87. #include "render/ground/bridge_renderer.h"
  88. #include "render/ground/firecamp_renderer.h"
  89. #include "render/ground/fog_renderer.h"
  90. #include "render/ground/ground_renderer.h"
  91. #include "render/ground/pine_renderer.h"
  92. #include "render/ground/plant_renderer.h"
  93. #include "render/ground/river_renderer.h"
  94. #include "render/ground/riverbank_renderer.h"
  95. #include "render/ground/stone_renderer.h"
  96. #include "render/ground/terrain_renderer.h"
  97. #include "render/scene_renderer.h"
  98. #include <QDir>
  99. #include <QFile>
  100. #include <QJsonArray>
  101. #include <QJsonDocument>
  102. #include <QJsonObject>
  103. #include <QSet>
  104. #include <algorithm>
  105. #include <cmath>
  106. #include <utility>
  107. #include <vector>
  108. GameEngine::GameEngine(QObject *parent)
  109. : QObject(parent),
  110. m_selectedUnitsModel(new SelectedUnitsModel(this, this)) {
  111. Game::Systems::NationRegistry::instance().initializeDefaults();
  112. Game::Systems::TroopCountRegistry::instance().initialize();
  113. Game::Systems::GlobalStatsRegistry::instance().initialize();
  114. m_world = std::make_unique<Engine::Core::World>();
  115. m_renderer = std::make_unique<Render::GL::Renderer>();
  116. m_camera = std::make_unique<Render::GL::Camera>();
  117. m_ground = std::make_unique<Render::GL::GroundRenderer>();
  118. m_terrain = std::make_unique<Render::GL::TerrainRenderer>();
  119. m_biome = std::make_unique<Render::GL::BiomeRenderer>();
  120. m_river = std::make_unique<Render::GL::RiverRenderer>();
  121. m_riverbank = std::make_unique<Render::GL::RiverbankRenderer>();
  122. m_bridge = std::make_unique<Render::GL::BridgeRenderer>();
  123. m_fog = std::make_unique<Render::GL::FogRenderer>();
  124. m_stone = std::make_unique<Render::GL::StoneRenderer>();
  125. m_plant = std::make_unique<Render::GL::PlantRenderer>();
  126. m_pine = std::make_unique<Render::GL::PineRenderer>();
  127. m_firecamp = std::make_unique<Render::GL::FireCampRenderer>();
  128. m_passes = {m_ground.get(), m_terrain.get(), m_river.get(),
  129. m_riverbank.get(), m_bridge.get(), m_biome.get(),
  130. m_stone.get(), m_plant.get(), m_pine.get(),
  131. m_firecamp.get(), m_fog.get()};
  132. std::unique_ptr<Engine::Core::System> arrow_sys =
  133. std::make_unique<Game::Systems::ArrowSystem>();
  134. m_world->addSystem(std::move(arrow_sys));
  135. m_world->addSystem(std::make_unique<Game::Systems::MovementSystem>());
  136. m_world->addSystem(std::make_unique<Game::Systems::PatrolSystem>());
  137. m_world->addSystem(std::make_unique<Game::Systems::CombatSystem>());
  138. m_world->addSystem(std::make_unique<Game::Systems::CaptureSystem>());
  139. m_world->addSystem(std::make_unique<Game::Systems::AISystem>());
  140. m_world->addSystem(std::make_unique<Game::Systems::ProductionSystem>());
  141. m_world->addSystem(std::make_unique<Game::Systems::TerrainAlignmentSystem>());
  142. m_world->addSystem(std::make_unique<Game::Systems::CleanupSystem>());
  143. {
  144. std::unique_ptr<Engine::Core::System> sel_sys =
  145. std::make_unique<Game::Systems::SelectionSystem>();
  146. m_world->addSystem(std::move(sel_sys));
  147. }
  148. m_pickingService = std::make_unique<Game::Systems::PickingService>();
  149. m_victoryService = std::make_unique<Game::Systems::VictoryService>();
  150. m_saveLoadService = std::make_unique<Game::Systems::SaveLoadService>();
  151. m_cameraService = std::make_unique<Game::Systems::CameraService>();
  152. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  153. m_selectionController = std::make_unique<Game::Systems::SelectionController>(
  154. m_world.get(), selection_system, m_pickingService.get());
  155. m_commandController = std::make_unique<App::Controllers::CommandController>(
  156. m_world.get(), selection_system, m_pickingService.get());
  157. m_cursorManager = std::make_unique<CursorManager>();
  158. m_hoverTracker = std::make_unique<HoverTracker>(m_pickingService.get());
  159. m_mapCatalog = std::make_unique<Game::Map::MapCatalog>(this);
  160. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::mapLoaded, this,
  161. [this](const QVariantMap &mapData) {
  162. m_availableMaps.append(mapData);
  163. emit availableMapsChanged();
  164. });
  165. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::loadingChanged, this,
  166. [this](bool loading) {
  167. m_mapsLoading = loading;
  168. emit mapsLoadingChanged();
  169. });
  170. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::allMapsLoaded, this,
  171. [this]() { emit availableMapsChanged(); });
  172. if (AudioSystem::getInstance().initialize()) {
  173. qInfo() << "AudioSystem initialized successfully";
  174. loadAudioResources();
  175. } else {
  176. qWarning() << "Failed to initialize AudioSystem";
  177. }
  178. m_audio_systemProxy = std::make_unique<App::Models::AudioSystemProxy>(this);
  179. m_audioEventHandler =
  180. std::make_unique<Game::Audio::AudioEventHandler>(m_world.get());
  181. if (m_audioEventHandler->initialize()) {
  182. qInfo() << "AudioEventHandler initialized successfully";
  183. m_audioEventHandler->loadUnitVoiceMapping("archer", "archer_voice");
  184. m_audioEventHandler->loadUnitVoiceMapping("knight", "knight_voice");
  185. m_audioEventHandler->loadUnitVoiceMapping("spearman", "spearman_voice");
  186. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::PEACEFUL,
  187. "music_peaceful");
  188. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::TENSE,
  189. "music_tense");
  190. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::COMBAT,
  191. "music_combat");
  192. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::VICTORY,
  193. "music_victory");
  194. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::DEFEAT,
  195. "music_defeat");
  196. qInfo() << "Audio mappings configured";
  197. } else {
  198. qWarning() << "Failed to initialize AudioEventHandler";
  199. }
  200. connect(m_cursorManager.get(), &CursorManager::modeChanged, this,
  201. &GameEngine::cursorModeChanged);
  202. connect(m_cursorManager.get(), &CursorManager::globalCursorChanged, this,
  203. &GameEngine::globalCursorChanged);
  204. connect(m_selectionController.get(),
  205. &Game::Systems::SelectionController::selectionChanged, this,
  206. &GameEngine::selectedUnitsChanged);
  207. connect(m_selectionController.get(),
  208. &Game::Systems::SelectionController::selectionChanged, this,
  209. &GameEngine::syncSelectionFlags);
  210. connect(m_selectionController.get(),
  211. &Game::Systems::SelectionController::selectionModelRefreshRequested,
  212. this, &GameEngine::selectedUnitsDataChanged);
  213. connect(m_commandController.get(),
  214. &App::Controllers::CommandController::attack_targetSelected,
  215. [this]() {
  216. if (auto *sel_sys =
  217. m_world->getSystem<Game::Systems::SelectionSystem>()) {
  218. const auto &sel = sel_sys->getSelectedUnits();
  219. if (!sel.empty()) {
  220. auto *cam = m_camera.get();
  221. auto *picking = m_pickingService.get();
  222. if ((cam != nullptr) && (picking != nullptr)) {
  223. Engine::Core::EntityID const target_id =
  224. picking->pickUnitFirst(0.0F, 0.0F, *m_world, *cam,
  225. m_viewport.width,
  226. m_viewport.height, 0);
  227. if (target_id != 0) {
  228. App::Controllers::ActionVFX::spawnAttackArrow(m_world.get(),
  229. target_id);
  230. }
  231. }
  232. }
  233. }
  234. });
  235. connect(m_commandController.get(),
  236. &App::Controllers::CommandController::troopLimitReached, [this]() {
  237. setError("Maximum troop limit reached. Cannot produce more units.");
  238. });
  239. connect(this, SIGNAL(selectedUnitsChanged()), m_selectedUnitsModel,
  240. SLOT(refresh()));
  241. connect(this, SIGNAL(selectedUnitsDataChanged()), m_selectedUnitsModel,
  242. SLOT(refresh()));
  243. emit selectedUnitsChanged();
  244. m_unitDiedSubscription =
  245. Engine::Core::ScopedEventSubscription<Engine::Core::UnitDiedEvent>(
  246. [this](const Engine::Core::UnitDiedEvent &e) {
  247. onUnitDied(e);
  248. if (e.owner_id != m_runtime.localOwnerId) {
  249. int const individuals_per_unit =
  250. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  251. e.spawn_type);
  252. m_enemyTroopsDefeated += individuals_per_unit;
  253. emit enemyTroopsDefeatedChanged();
  254. }
  255. });
  256. m_unitSpawnedSubscription =
  257. Engine::Core::ScopedEventSubscription<Engine::Core::UnitSpawnedEvent>(
  258. [this](const Engine::Core::UnitSpawnedEvent &e) {
  259. onUnitSpawned(e);
  260. });
  261. }
  262. GameEngine::~GameEngine() {
  263. if (m_audioEventHandler) {
  264. m_audioEventHandler->shutdown();
  265. }
  266. AudioSystem::getInstance().shutdown();
  267. qInfo() << "AudioSystem shut down";
  268. }
  269. void GameEngine::cleanupOpenGLResources() {
  270. qInfo() << "Cleaning up OpenGL resources...";
  271. QOpenGLContext *context = QOpenGLContext::currentContext();
  272. const bool hasValidContext = (context != nullptr);
  273. if (!hasValidContext) {
  274. qInfo() << "No valid OpenGL context, skipping OpenGL cleanup";
  275. }
  276. if (m_renderer && hasValidContext) {
  277. m_renderer->shutdown();
  278. qInfo() << "Renderer shut down";
  279. }
  280. m_passes.clear();
  281. m_ground.reset();
  282. m_terrain.reset();
  283. m_biome.reset();
  284. m_river.reset();
  285. m_riverbank.reset();
  286. m_bridge.reset();
  287. m_fog.reset();
  288. m_stone.reset();
  289. m_plant.reset();
  290. m_pine.reset();
  291. m_firecamp.reset();
  292. m_renderer.reset();
  293. m_resources.reset();
  294. qInfo() << "OpenGL resources cleaned up";
  295. }
  296. void GameEngine::onMapClicked(qreal sx, qreal sy) {
  297. if (m_window == nullptr) {
  298. return;
  299. }
  300. ensureInitialized();
  301. if (m_selectionController && m_camera) {
  302. m_selectionController->onClickSelect(sx, sy, false, m_viewport.width,
  303. m_viewport.height, m_camera.get(),
  304. m_runtime.localOwnerId);
  305. }
  306. }
  307. void GameEngine::onRightClick(qreal sx, qreal sy) {
  308. if (m_window == nullptr) {
  309. return;
  310. }
  311. ensureInitialized();
  312. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  313. if (selection_system == nullptr) {
  314. return;
  315. }
  316. if (m_cursorManager->mode() == CursorMode::Patrol ||
  317. m_cursorManager->mode() == CursorMode::Attack) {
  318. setCursorMode(CursorMode::Normal);
  319. return;
  320. }
  321. const auto &sel = selection_system->getSelectedUnits();
  322. if (sel.empty()) {
  323. return;
  324. }
  325. if (m_pickingService && m_camera) {
  326. Engine::Core::EntityID const target_id = m_pickingService->pickUnitFirst(
  327. float(sx), float(sy), *m_world, *m_camera, m_viewport.width,
  328. m_viewport.height, 0);
  329. if (target_id != 0U) {
  330. auto *target_entity = m_world->getEntity(target_id);
  331. if (target_entity != nullptr) {
  332. auto *target_unit =
  333. target_entity->getComponent<Engine::Core::UnitComponent>();
  334. if (target_unit != nullptr) {
  335. bool const is_enemy =
  336. (target_unit->owner_id != m_runtime.localOwnerId);
  337. if (is_enemy) {
  338. Game::Systems::CommandService::attack_target(*m_world, sel,
  339. target_id, true);
  340. return;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. if (m_pickingService && m_camera) {
  347. QVector3D hit;
  348. if (m_pickingService->screenToGround(QPointF(sx, sy), *m_camera,
  349. m_viewport.width, m_viewport.height,
  350. hit)) {
  351. auto targets = Game::Systems::FormationPlanner::spreadFormation(
  352. int(sel.size()), hit,
  353. Game::GameConfig::instance().gameplay().formationSpacingDefault);
  354. Game::Systems::CommandService::MoveOptions opts;
  355. opts.groupMove = sel.size() > 1;
  356. Game::Systems::CommandService::moveUnits(*m_world, sel, targets, opts);
  357. }
  358. }
  359. }
  360. void GameEngine::onAttackClick(qreal sx, qreal sy) {
  361. if (m_window == nullptr) {
  362. return;
  363. }
  364. ensureInitialized();
  365. if (!m_commandController || !m_camera) {
  366. return;
  367. }
  368. auto result = m_commandController->onAttackClick(
  369. sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
  370. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  371. if ((selection_system == nullptr) || !m_pickingService || !m_camera ||
  372. !m_world) {
  373. return;
  374. }
  375. const auto &selected = selection_system->getSelectedUnits();
  376. if (!selected.empty()) {
  377. Engine::Core::EntityID const target_id = m_pickingService->pickUnitFirst(
  378. float(sx), float(sy), *m_world, *m_camera, m_viewport.width,
  379. m_viewport.height, 0);
  380. if (target_id != 0) {
  381. auto *target_entity = m_world->getEntity(target_id);
  382. if (target_entity != nullptr) {
  383. auto *target_unit =
  384. target_entity->getComponent<Engine::Core::UnitComponent>();
  385. if ((target_unit != nullptr) &&
  386. target_unit->owner_id != m_runtime.localOwnerId) {
  387. App::Controllers::ActionVFX::spawnAttackArrow(m_world.get(),
  388. target_id);
  389. }
  390. }
  391. }
  392. }
  393. if (result.resetCursorToNormal) {
  394. setCursorMode(CursorMode::Normal);
  395. }
  396. }
  397. void GameEngine::resetMovement(Engine::Core::Entity *entity) {
  398. App::Utils::resetMovement(entity);
  399. }
  400. void GameEngine::onStopCommand() {
  401. if (!m_commandController) {
  402. return;
  403. }
  404. ensureInitialized();
  405. auto result = m_commandController->onStopCommand();
  406. if (result.resetCursorToNormal) {
  407. setCursorMode(CursorMode::Normal);
  408. }
  409. }
  410. void GameEngine::onHoldCommand() {
  411. if (!m_commandController) {
  412. return;
  413. }
  414. ensureInitialized();
  415. auto result = m_commandController->onHoldCommand();
  416. if (result.resetCursorToNormal) {
  417. setCursorMode(CursorMode::Normal);
  418. }
  419. }
  420. auto GameEngine::anySelectedInHoldMode() const -> bool {
  421. if (!m_commandController) {
  422. return false;
  423. }
  424. return m_commandController->anySelectedInHoldMode();
  425. }
  426. void GameEngine::onPatrolClick(qreal sx, qreal sy) {
  427. if (!m_commandController || !m_camera) {
  428. return;
  429. }
  430. ensureInitialized();
  431. auto result = m_commandController->onPatrolClick(
  432. sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
  433. if (result.resetCursorToNormal) {
  434. setCursorMode(CursorMode::Normal);
  435. }
  436. }
  437. void GameEngine::updateCursor(Qt::CursorShape newCursor) {
  438. if (m_window == nullptr) {
  439. return;
  440. }
  441. if (m_runtime.currentCursor != newCursor) {
  442. m_runtime.currentCursor = newCursor;
  443. m_window->setCursor(newCursor);
  444. }
  445. }
  446. void GameEngine::setError(const QString &errorMessage) {
  447. if (m_runtime.lastError != errorMessage) {
  448. m_runtime.lastError = errorMessage;
  449. qCritical() << "GameEngine error:" << errorMessage;
  450. emit lastErrorChanged();
  451. }
  452. }
  453. void GameEngine::setCursorMode(CursorMode mode) {
  454. if (!m_cursorManager) {
  455. return;
  456. }
  457. m_cursorManager->setMode(mode);
  458. m_cursorManager->updateCursorShape(m_window);
  459. }
  460. void GameEngine::setCursorMode(const QString &mode) {
  461. setCursorMode(CursorModeUtils::fromString(mode));
  462. }
  463. auto GameEngine::cursorMode() const -> QString {
  464. if (!m_cursorManager) {
  465. return "normal";
  466. }
  467. return m_cursorManager->modeString();
  468. }
  469. auto GameEngine::globalCursorX() const -> qreal {
  470. if (!m_cursorManager) {
  471. return 0;
  472. }
  473. return m_cursorManager->globalCursorX(m_window);
  474. }
  475. auto GameEngine::globalCursorY() const -> qreal {
  476. if (!m_cursorManager) {
  477. return 0;
  478. }
  479. return m_cursorManager->globalCursorY(m_window);
  480. }
  481. void GameEngine::setHoverAtScreen(qreal sx, qreal sy) {
  482. if (m_window == nullptr) {
  483. return;
  484. }
  485. ensureInitialized();
  486. if (!m_hoverTracker || !m_camera || !m_world) {
  487. return;
  488. }
  489. m_cursorManager->updateCursorShape(m_window);
  490. m_hoverTracker->updateHover(float(sx), float(sy), *m_world, *m_camera,
  491. m_viewport.width, m_viewport.height);
  492. }
  493. void GameEngine::onClickSelect(qreal sx, qreal sy, bool additive) {
  494. if (m_window == nullptr) {
  495. return;
  496. }
  497. ensureInitialized();
  498. if (m_selectionController && m_camera) {
  499. m_selectionController->onClickSelect(sx, sy, additive, m_viewport.width,
  500. m_viewport.height, m_camera.get(),
  501. m_runtime.localOwnerId);
  502. }
  503. }
  504. void GameEngine::onAreaSelected(qreal x1, qreal y1, qreal x2, qreal y2,
  505. bool additive) {
  506. if (m_window == nullptr) {
  507. return;
  508. }
  509. ensureInitialized();
  510. if (m_selectionController && m_camera) {
  511. m_selectionController->onAreaSelected(
  512. x1, y1, x2, y2, additive, m_viewport.width, m_viewport.height,
  513. m_camera.get(), m_runtime.localOwnerId);
  514. }
  515. }
  516. void GameEngine::selectAllTroops() {
  517. ensureInitialized();
  518. if (m_selectionController) {
  519. m_selectionController->selectAllPlayerTroops(m_runtime.localOwnerId);
  520. }
  521. }
  522. void GameEngine::ensureInitialized() {
  523. QString error;
  524. Game::Map::WorldBootstrap::ensureInitialized(
  525. m_runtime.initialized, *m_renderer, *m_camera, m_ground.get(), &error);
  526. if (!error.isEmpty()) {
  527. setError(error);
  528. }
  529. }
  530. auto GameEngine::enemyTroopsDefeated() const -> int {
  531. return m_enemyTroopsDefeated;
  532. }
  533. auto GameEngine::getPlayerStats(int owner_id) -> QVariantMap {
  534. QVariantMap result;
  535. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  536. const auto *stats = stats_registry.getStats(owner_id);
  537. if (stats != nullptr) {
  538. result["troopsRecruited"] = stats->troopsRecruited;
  539. result["enemiesKilled"] = stats->enemiesKilled;
  540. result["barracksOwned"] = stats->barracksOwned;
  541. result["playTimeSec"] = stats->playTimeSec;
  542. result["gameEnded"] = stats->gameEnded;
  543. } else {
  544. result["troopsRecruited"] = 0;
  545. result["enemiesKilled"] = 0;
  546. result["barracksOwned"] = 0;
  547. result["playTimeSec"] = 0.0F;
  548. result["gameEnded"] = false;
  549. }
  550. return result;
  551. }
  552. void GameEngine::update(float dt) {
  553. if (m_runtime.loading) {
  554. return;
  555. }
  556. if (m_runtime.paused) {
  557. dt = 0.0F;
  558. } else {
  559. dt *= m_runtime.timeScale;
  560. }
  561. if (!m_runtime.paused && !m_runtime.loading) {
  562. updateAmbientState(dt);
  563. }
  564. if (m_renderer) {
  565. m_renderer->updateAnimationTime(dt);
  566. }
  567. if (m_camera) {
  568. m_camera->update(dt);
  569. }
  570. if (m_world) {
  571. m_world->update(dt);
  572. auto &visibility_service = Game::Map::VisibilityService::instance();
  573. if (visibility_service.isInitialized()) {
  574. m_runtime.visibilityUpdateAccumulator += dt;
  575. const float visibility_update_interval =
  576. Game::GameConfig::instance().gameplay().visibility_update_interval;
  577. if (m_runtime.visibilityUpdateAccumulator >= visibility_update_interval) {
  578. m_runtime.visibilityUpdateAccumulator = 0.0F;
  579. visibility_service.update(*m_world, m_runtime.localOwnerId);
  580. }
  581. const auto new_version = visibility_service.version();
  582. if (new_version != m_runtime.visibilityVersion) {
  583. if (m_fog) {
  584. m_fog->updateMask(visibility_service.getWidth(),
  585. visibility_service.getHeight(),
  586. visibility_service.getTileSize(),
  587. visibility_service.snapshotCells());
  588. }
  589. m_runtime.visibilityVersion = new_version;
  590. }
  591. }
  592. }
  593. if (m_victoryService && m_world) {
  594. m_victoryService->update(*m_world, dt);
  595. }
  596. if (m_followSelectionEnabled && m_camera && m_world && m_cameraService) {
  597. m_cameraService->updateFollow(*m_camera, *m_world,
  598. m_followSelectionEnabled);
  599. }
  600. if (m_selectedUnitsModel != nullptr) {
  601. auto *selection_system =
  602. m_world->getSystem<Game::Systems::SelectionSystem>();
  603. if ((selection_system != nullptr) &&
  604. !selection_system->getSelectedUnits().empty()) {
  605. m_runtime.selectionRefreshCounter++;
  606. if (m_runtime.selectionRefreshCounter >= 15) {
  607. m_runtime.selectionRefreshCounter = 0;
  608. emit selectedUnitsDataChanged();
  609. }
  610. }
  611. }
  612. }
  613. void GameEngine::render(int pixelWidth, int pixelHeight) {
  614. if (!m_renderer || !m_world || !m_runtime.initialized || m_runtime.loading) {
  615. return;
  616. }
  617. if (pixelWidth > 0 && pixelHeight > 0) {
  618. m_viewport.width = pixelWidth;
  619. m_viewport.height = pixelHeight;
  620. m_renderer->setViewport(pixelWidth, pixelHeight);
  621. }
  622. if (auto *selection_system =
  623. m_world->getSystem<Game::Systems::SelectionSystem>()) {
  624. const auto &sel = selection_system->getSelectedUnits();
  625. std::vector<unsigned int> const ids(sel.begin(), sel.end());
  626. m_renderer->setSelectedEntities(ids);
  627. }
  628. m_renderer->beginFrame();
  629. if (auto *res = m_renderer->resources()) {
  630. for (auto *pass : m_passes) {
  631. if (pass != nullptr) {
  632. pass->submit(*m_renderer, res);
  633. }
  634. }
  635. }
  636. if (m_renderer && m_hoverTracker) {
  637. m_renderer->setHoveredEntityId(m_hoverTracker->getLastHoveredEntity());
  638. }
  639. if (m_renderer) {
  640. m_renderer->setLocalOwnerId(m_runtime.localOwnerId);
  641. }
  642. m_renderer->renderWorld(m_world.get());
  643. if (auto *arrow_system = m_world->getSystem<Game::Systems::ArrowSystem>()) {
  644. if (auto *res = m_renderer->resources()) {
  645. Render::GL::renderArrows(m_renderer.get(), res, *arrow_system);
  646. }
  647. }
  648. if (auto *res = m_renderer->resources()) {
  649. std::optional<QVector3D> preview_waypoint;
  650. if (m_commandController && m_commandController->hasPatrolFirstWaypoint()) {
  651. preview_waypoint = m_commandController->getPatrolFirstWaypoint();
  652. }
  653. Render::GL::renderPatrolFlags(m_renderer.get(), res, *m_world,
  654. preview_waypoint);
  655. }
  656. m_renderer->endFrame();
  657. qreal const current_x = globalCursorX();
  658. qreal const current_y = globalCursorY();
  659. if (current_x != m_runtime.lastCursorX ||
  660. current_y != m_runtime.lastCursorY) {
  661. m_runtime.lastCursorX = current_x;
  662. m_runtime.lastCursorY = current_y;
  663. emit globalCursorChanged();
  664. }
  665. }
  666. auto GameEngine::screenToGround(const QPointF &screenPt,
  667. QVector3D &outWorld) -> bool {
  668. return App::Utils::screenToGround(m_pickingService.get(), m_camera.get(),
  669. m_window, m_viewport.width,
  670. m_viewport.height, screenPt, outWorld);
  671. }
  672. auto GameEngine::worldToScreen(const QVector3D &world,
  673. QPointF &outScreen) const -> bool {
  674. return App::Utils::worldToScreen(m_pickingService.get(), m_camera.get(),
  675. m_window, m_viewport.width,
  676. m_viewport.height, world, outScreen);
  677. }
  678. void GameEngine::syncSelectionFlags() {
  679. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  680. if (!m_world || (selection_system == nullptr)) {
  681. return;
  682. }
  683. App::Utils::sanitizeSelection(m_world.get(), selection_system);
  684. if (selection_system->getSelectedUnits().empty()) {
  685. if (m_cursorManager && m_cursorManager->mode() != CursorMode::Normal) {
  686. setCursorMode(CursorMode::Normal);
  687. }
  688. }
  689. }
  690. void GameEngine::cameraMove(float dx, float dz) {
  691. ensureInitialized();
  692. if (!m_camera || !m_cameraService) {
  693. return;
  694. }
  695. m_cameraService->move(*m_camera, dx, dz);
  696. }
  697. void GameEngine::cameraElevate(float dy) {
  698. ensureInitialized();
  699. if (!m_camera || !m_cameraService) {
  700. return;
  701. }
  702. m_cameraService->elevate(*m_camera, dy);
  703. }
  704. void GameEngine::resetCamera() {
  705. ensureInitialized();
  706. if (!m_camera || !m_world || !m_cameraService) {
  707. return;
  708. }
  709. m_cameraService->resetCamera(*m_camera, *m_world, m_runtime.localOwnerId,
  710. m_level.playerUnitId);
  711. }
  712. void GameEngine::cameraZoom(float delta) {
  713. ensureInitialized();
  714. if (!m_camera || !m_cameraService) {
  715. return;
  716. }
  717. m_cameraService->zoom(*m_camera, delta);
  718. }
  719. auto GameEngine::cameraDistance() const -> float {
  720. if (!m_camera || !m_cameraService) {
  721. return 0.0F;
  722. }
  723. return m_cameraService->getDistance(*m_camera);
  724. }
  725. void GameEngine::cameraYaw(float degrees) {
  726. ensureInitialized();
  727. if (!m_camera || !m_cameraService) {
  728. return;
  729. }
  730. m_cameraService->yaw(*m_camera, degrees);
  731. }
  732. void GameEngine::cameraOrbit(float yaw_deg, float pitch_deg) {
  733. ensureInitialized();
  734. if (!m_camera || !m_cameraService) {
  735. return;
  736. }
  737. if (!std::isfinite(yaw_deg) || !std::isfinite(pitch_deg)) {
  738. qWarning() << "GameEngine::cameraOrbit received invalid input, ignoring:"
  739. << yaw_deg << pitch_deg;
  740. return;
  741. }
  742. m_cameraService->orbit(*m_camera, yaw_deg, pitch_deg);
  743. }
  744. void GameEngine::cameraOrbitDirection(int direction, bool shift) {
  745. if (!m_camera || !m_cameraService) {
  746. return;
  747. }
  748. m_cameraService->orbitDirection(*m_camera, direction, shift);
  749. }
  750. void GameEngine::cameraFollowSelection(bool enable) {
  751. ensureInitialized();
  752. m_followSelectionEnabled = enable;
  753. if (!m_camera || !m_world || !m_cameraService) {
  754. return;
  755. }
  756. m_cameraService->followSelection(*m_camera, *m_world, enable);
  757. }
  758. void GameEngine::cameraSetFollowLerp(float alpha) {
  759. ensureInitialized();
  760. if (!m_camera || !m_cameraService) {
  761. return;
  762. }
  763. m_cameraService->setFollowLerp(*m_camera, alpha);
  764. }
  765. auto GameEngine::selectedUnitsModel() -> QObject * {
  766. return m_selectedUnitsModel;
  767. }
  768. auto GameEngine::audio_system() -> QObject * {
  769. return m_audio_systemProxy.get();
  770. }
  771. auto GameEngine::hasUnitsSelected() const -> bool {
  772. if (!m_selectionController) {
  773. return false;
  774. }
  775. return m_selectionController->hasUnitsSelected();
  776. }
  777. auto GameEngine::playerTroopCount() const -> int {
  778. return m_entityCache.playerTroopCount;
  779. }
  780. auto GameEngine::hasSelectedType(const QString &type) const -> bool {
  781. if (!m_selectionController) {
  782. return false;
  783. }
  784. return m_selectionController->hasSelectedType(type);
  785. }
  786. void GameEngine::recruitNearSelected(const QString &unit_type) {
  787. ensureInitialized();
  788. if (!m_commandController) {
  789. return;
  790. }
  791. m_commandController->recruitNearSelected(unit_type, m_runtime.localOwnerId);
  792. }
  793. auto GameEngine::getSelectedProductionState() const -> QVariantMap {
  794. QVariantMap m;
  795. m["has_barracks"] = false;
  796. m["inProgress"] = false;
  797. m["timeRemaining"] = 0.0;
  798. m["buildTime"] = 0.0;
  799. m["producedCount"] = 0;
  800. m["maxUnits"] = 0;
  801. m["villagerCost"] = 1;
  802. if (!m_world) {
  803. return m;
  804. }
  805. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  806. if (selection_system == nullptr) {
  807. return m;
  808. }
  809. Game::Systems::ProductionState st;
  810. Game::Systems::ProductionService::getSelectedBarracksState(
  811. *m_world, selection_system->getSelectedUnits(), m_runtime.localOwnerId,
  812. st);
  813. m["has_barracks"] = st.has_barracks;
  814. m["inProgress"] = st.inProgress;
  815. m["product_type"] =
  816. QString::fromStdString(Game::Units::troop_typeToString(st.product_type));
  817. m["timeRemaining"] = st.timeRemaining;
  818. m["buildTime"] = st.buildTime;
  819. m["producedCount"] = st.producedCount;
  820. m["maxUnits"] = st.maxUnits;
  821. m["villagerCost"] = st.villagerCost;
  822. m["queueSize"] = st.queueSize;
  823. QVariantList queue_list;
  824. for (const auto &unit_type : st.productionQueue) {
  825. queue_list.append(
  826. QString::fromStdString(Game::Units::troop_typeToString(unit_type)));
  827. }
  828. m["productionQueue"] = queue_list;
  829. return m;
  830. }
  831. auto GameEngine::getSelectedUnitsCommandMode() const -> QString {
  832. if (!m_world) {
  833. return "normal";
  834. }
  835. auto *selection_system = m_world->getSystem<Game::Systems::SelectionSystem>();
  836. if (selection_system == nullptr) {
  837. return "normal";
  838. }
  839. const auto &sel = selection_system->getSelectedUnits();
  840. if (sel.empty()) {
  841. return "normal";
  842. }
  843. int attacking_count = 0;
  844. int patrolling_count = 0;
  845. int total_units = 0;
  846. for (auto id : sel) {
  847. auto *e = m_world->getEntity(id);
  848. if (e == nullptr) {
  849. continue;
  850. }
  851. auto *u = e->getComponent<Engine::Core::UnitComponent>();
  852. if (u == nullptr) {
  853. continue;
  854. }
  855. if (u->spawn_type == Game::Units::SpawnType::Barracks) {
  856. continue;
  857. }
  858. total_units++;
  859. if (e->getComponent<Engine::Core::AttackTargetComponent>() != nullptr) {
  860. attacking_count++;
  861. }
  862. auto *patrol = e->getComponent<Engine::Core::PatrolComponent>();
  863. if ((patrol != nullptr) && patrol->patrolling) {
  864. patrolling_count++;
  865. }
  866. }
  867. if (total_units == 0) {
  868. return "normal";
  869. }
  870. if (patrolling_count == total_units) {
  871. return "patrol";
  872. }
  873. if (attacking_count == total_units) {
  874. return "attack";
  875. }
  876. return "normal";
  877. }
  878. void GameEngine::setRallyAtScreen(qreal sx, qreal sy) {
  879. ensureInitialized();
  880. if (!m_commandController || !m_camera) {
  881. return;
  882. }
  883. m_commandController->setRallyAtScreen(sx, sy, m_viewport.width,
  884. m_viewport.height, m_camera.get(),
  885. m_runtime.localOwnerId);
  886. }
  887. void GameEngine::startLoadingMaps() {
  888. m_availableMaps.clear();
  889. if (m_mapCatalog) {
  890. m_mapCatalog->loadMapsAsync();
  891. }
  892. }
  893. auto GameEngine::availableMaps() const -> QVariantList {
  894. return m_availableMaps;
  895. }
  896. void GameEngine::startSkirmish(const QString &map_path,
  897. const QVariantList &playerConfigs) {
  898. clearError();
  899. m_level.map_path = map_path;
  900. m_level.map_name = map_path;
  901. if (!m_runtime.victoryState.isEmpty()) {
  902. m_runtime.victoryState = "";
  903. emit victoryStateChanged();
  904. }
  905. m_enemyTroopsDefeated = 0;
  906. if (!m_runtime.initialized) {
  907. ensureInitialized();
  908. return;
  909. }
  910. if (m_world && m_renderer && m_camera) {
  911. m_runtime.loading = true;
  912. if (m_hoverTracker) {
  913. m_hoverTracker->updateHover(-1, -1, *m_world, *m_camera, 0, 0);
  914. }
  915. m_entityCache.reset();
  916. Game::Map::SkirmishLoader loader(*m_world, *m_renderer, *m_camera);
  917. loader.setGroundRenderer(m_ground.get());
  918. loader.setTerrainRenderer(m_terrain.get());
  919. loader.setBiomeRenderer(m_biome.get());
  920. loader.setRiverRenderer(m_river.get());
  921. loader.setRiverbankRenderer(m_riverbank.get());
  922. loader.setBridgeRenderer(m_bridge.get());
  923. loader.setFogRenderer(m_fog.get());
  924. loader.setStoneRenderer(m_stone.get());
  925. loader.setPlantRenderer(m_plant.get());
  926. loader.setPineRenderer(m_pine.get());
  927. loader.setFireCampRenderer(m_firecamp.get());
  928. loader.setOnOwnersUpdated([this]() { emit ownerInfoChanged(); });
  929. loader.setOnVisibilityMaskReady([this]() {
  930. m_runtime.visibilityVersion =
  931. Game::Map::VisibilityService::instance().version();
  932. m_runtime.visibilityUpdateAccumulator = 0.0F;
  933. });
  934. int updated_player_id = m_selectedPlayerId;
  935. auto result = loader.start(map_path, playerConfigs, m_selectedPlayerId,
  936. updated_player_id);
  937. if (updated_player_id != m_selectedPlayerId) {
  938. m_selectedPlayerId = updated_player_id;
  939. emit selectedPlayerIdChanged();
  940. }
  941. if (!result.ok && !result.errorMessage.isEmpty()) {
  942. setError(result.errorMessage);
  943. }
  944. m_runtime.localOwnerId = updated_player_id;
  945. m_level.map_name = result.map_name;
  946. m_level.playerUnitId = result.playerUnitId;
  947. m_level.camFov = result.camFov;
  948. m_level.camNear = result.camNear;
  949. m_level.camFar = result.camFar;
  950. m_level.max_troops_per_player = result.max_troops_per_player;
  951. Game::GameConfig::instance().setMaxTroopsPerPlayer(
  952. result.max_troops_per_player);
  953. if (m_victoryService) {
  954. m_victoryService->configure(result.victoryConfig, m_runtime.localOwnerId);
  955. m_victoryService->setVictoryCallback([this](const QString &state) {
  956. if (m_runtime.victoryState != state) {
  957. m_runtime.victoryState = state;
  958. emit victoryStateChanged();
  959. }
  960. });
  961. }
  962. if (result.hasFocusPosition && m_camera) {
  963. const auto &cam_config = Game::GameConfig::instance().camera();
  964. m_camera->setRTSView(result.focusPosition, cam_config.defaultDistance,
  965. cam_config.defaultPitch, cam_config.defaultYaw);
  966. }
  967. m_runtime.loading = false;
  968. if (auto *ai_system = m_world->getSystem<Game::Systems::AISystem>()) {
  969. ai_system->reinitialize();
  970. }
  971. rebuildEntityCache();
  972. auto &troops = Game::Systems::TroopCountRegistry::instance();
  973. troops.rebuildFromWorld(*m_world);
  974. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  975. stats_registry.rebuildFromWorld(*m_world);
  976. auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  977. const auto &all_owners = owner_registry.getAllOwners();
  978. for (const auto &owner : all_owners) {
  979. if (owner.type == Game::Systems::OwnerType::Player ||
  980. owner.type == Game::Systems::OwnerType::AI) {
  981. stats_registry.markGameStart(owner.owner_id);
  982. }
  983. }
  984. m_currentAmbientState = Engine::Core::AmbientState::PEACEFUL;
  985. m_ambientCheckTimer = 0.0F;
  986. Engine::Core::EventManager::instance().publish(
  987. Engine::Core::AmbientStateChangedEvent(
  988. Engine::Core::AmbientState::PEACEFUL,
  989. Engine::Core::AmbientState::PEACEFUL));
  990. emit ownerInfoChanged();
  991. }
  992. }
  993. void GameEngine::openSettings() {
  994. if (m_saveLoadService) {
  995. m_saveLoadService->openSettings();
  996. }
  997. }
  998. void GameEngine::loadSave() { loadFromSlot("savegame"); }
  999. void GameEngine::saveGame(const QString &filename) {
  1000. saveToSlot(filename, filename);
  1001. }
  1002. void GameEngine::saveGameToSlot(const QString &slotName) {
  1003. saveToSlot(slotName, slotName);
  1004. }
  1005. void GameEngine::loadGameFromSlot(const QString &slotName) {
  1006. loadFromSlot(slotName);
  1007. }
  1008. auto GameEngine::loadFromSlot(const QString &slot) -> bool {
  1009. if (!m_saveLoadService || !m_world) {
  1010. setError("Load: not initialized");
  1011. return false;
  1012. }
  1013. m_runtime.loading = true;
  1014. if (!m_saveLoadService->loadGameFromSlot(*m_world, slot)) {
  1015. setError(m_saveLoadService->getLastError());
  1016. m_runtime.loading = false;
  1017. return false;
  1018. }
  1019. const QJsonObject meta = m_saveLoadService->getLastMetadata();
  1020. Game::Systems::GameStateSerializer::restoreLevelFromMetadata(meta, m_level);
  1021. Game::Systems::GameStateSerializer::restoreCameraFromMetadata(
  1022. meta, m_camera.get(), m_viewport.width, m_viewport.height);
  1023. Game::Systems::RuntimeSnapshot runtime_snap = toRuntimeSnapshot();
  1024. Game::Systems::GameStateSerializer::restoreRuntimeFromMetadata(meta,
  1025. runtime_snap);
  1026. applyRuntimeSnapshot(runtime_snap);
  1027. restoreEnvironmentFromMetadata(meta);
  1028. auto unit_reg = std::make_shared<Game::Units::UnitFactoryRegistry>();
  1029. Game::Units::registerBuiltInUnits(*unit_reg);
  1030. Game::Map::MapTransformer::setFactoryRegistry(unit_reg);
  1031. qInfo() << "Factory registry reinitialized after loading saved game";
  1032. rebuildRegistriesAfterLoad();
  1033. rebuildEntityCache();
  1034. if (auto *ai_system = m_world->getSystem<Game::Systems::AISystem>()) {
  1035. qInfo() << "Reinitializing AI system after loading saved game";
  1036. ai_system->reinitialize();
  1037. }
  1038. if (m_victoryService) {
  1039. m_victoryService->configure(Game::Map::VictoryConfig(),
  1040. m_runtime.localOwnerId);
  1041. }
  1042. m_runtime.loading = false;
  1043. qInfo() << "Game load complete, victory/defeat checks re-enabled";
  1044. emit selectedUnitsChanged();
  1045. emit ownerInfoChanged();
  1046. return true;
  1047. }
  1048. auto GameEngine::saveToSlot(const QString &slot, const QString &title) -> bool {
  1049. if (!m_saveLoadService || !m_world) {
  1050. setError("Save: not initialized");
  1051. return false;
  1052. }
  1053. Game::Systems::RuntimeSnapshot const runtime_snap = toRuntimeSnapshot();
  1054. QJsonObject meta = Game::Systems::GameStateSerializer::buildMetadata(
  1055. *m_world, m_camera.get(), m_level, runtime_snap);
  1056. meta["title"] = title;
  1057. const QByteArray screenshot = captureScreenshot();
  1058. if (!m_saveLoadService->saveGameToSlot(*m_world, slot, title,
  1059. m_level.map_name, meta, screenshot)) {
  1060. setError(m_saveLoadService->getLastError());
  1061. return false;
  1062. }
  1063. emit saveSlotsChanged();
  1064. return true;
  1065. }
  1066. auto GameEngine::getSaveSlots() const -> QVariantList {
  1067. if (!m_saveLoadService) {
  1068. qWarning() << "Cannot get save slots: service not initialized";
  1069. return {};
  1070. }
  1071. return m_saveLoadService->getSaveSlots();
  1072. }
  1073. void GameEngine::refreshSaveSlots() { emit saveSlotsChanged(); }
  1074. auto GameEngine::deleteSaveSlot(const QString &slotName) -> bool {
  1075. if (!m_saveLoadService) {
  1076. qWarning() << "Cannot delete save slot: service not initialized";
  1077. return false;
  1078. }
  1079. bool const success = m_saveLoadService->deleteSaveSlot(slotName);
  1080. if (!success) {
  1081. QString const error = m_saveLoadService->getLastError();
  1082. qWarning() << "Failed to delete save slot:" << error;
  1083. setError(error);
  1084. } else {
  1085. emit saveSlotsChanged();
  1086. }
  1087. return success;
  1088. }
  1089. void GameEngine::exitGame() {
  1090. if (m_saveLoadService) {
  1091. m_saveLoadService->exitGame();
  1092. }
  1093. }
  1094. auto GameEngine::getOwnerInfo() const -> QVariantList {
  1095. QVariantList result;
  1096. const auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1097. const auto &owners = owner_registry.getAllOwners();
  1098. for (const auto &owner : owners) {
  1099. QVariantMap owner_map;
  1100. owner_map["id"] = owner.owner_id;
  1101. owner_map["name"] = QString::fromStdString(owner.name);
  1102. owner_map["team_id"] = owner.team_id;
  1103. QString type_str;
  1104. switch (owner.type) {
  1105. case Game::Systems::OwnerType::Player:
  1106. type_str = "Player";
  1107. break;
  1108. case Game::Systems::OwnerType::AI:
  1109. type_str = "AI";
  1110. break;
  1111. case Game::Systems::OwnerType::Neutral:
  1112. type_str = "Neutral";
  1113. break;
  1114. }
  1115. owner_map["type"] = type_str;
  1116. owner_map["isLocal"] = (owner.owner_id == m_runtime.localOwnerId);
  1117. result.append(owner_map);
  1118. }
  1119. return result;
  1120. }
  1121. void GameEngine::getSelectedUnitIds(
  1122. std::vector<Engine::Core::EntityID> &out) const {
  1123. out.clear();
  1124. if (!m_selectionController) {
  1125. return;
  1126. }
  1127. m_selectionController->getSelectedUnitIds(out);
  1128. }
  1129. auto GameEngine::getUnitInfo(Engine::Core::EntityID id, QString &name,
  1130. int &health, int &max_health, bool &isBuilding,
  1131. bool &alive) const -> bool {
  1132. if (!m_world) {
  1133. return false;
  1134. }
  1135. auto *e = m_world->getEntity(id);
  1136. if (e == nullptr) {
  1137. return false;
  1138. }
  1139. isBuilding = e->hasComponent<Engine::Core::BuildingComponent>();
  1140. if (auto *u = e->getComponent<Engine::Core::UnitComponent>()) {
  1141. name =
  1142. QString::fromStdString(Game::Units::spawn_typeToString(u->spawn_type));
  1143. health = u->health;
  1144. max_health = u->max_health;
  1145. alive = (u->health > 0);
  1146. return true;
  1147. }
  1148. name = QStringLiteral("Entity");
  1149. health = max_health = 0;
  1150. alive = true;
  1151. return true;
  1152. }
  1153. void GameEngine::onUnitSpawned(const Engine::Core::UnitSpawnedEvent &event) {
  1154. auto &owners = Game::Systems::OwnerRegistry::instance();
  1155. if (event.owner_id == m_runtime.localOwnerId) {
  1156. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1157. m_entityCache.playerBarracksAlive = true;
  1158. } else {
  1159. int const individuals_per_unit =
  1160. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1161. event.spawn_type);
  1162. m_entityCache.playerTroopCount += individuals_per_unit;
  1163. }
  1164. } else if (owners.isAI(event.owner_id)) {
  1165. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1166. m_entityCache.enemyBarracksCount++;
  1167. m_entityCache.enemyBarracksAlive = true;
  1168. }
  1169. }
  1170. auto emit_if_changed = [&] {
  1171. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1172. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1173. emit troop_countChanged();
  1174. }
  1175. };
  1176. emit_if_changed();
  1177. }
  1178. void GameEngine::onUnitDied(const Engine::Core::UnitDiedEvent &event) {
  1179. auto &owners = Game::Systems::OwnerRegistry::instance();
  1180. if (event.owner_id == m_runtime.localOwnerId) {
  1181. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1182. m_entityCache.playerBarracksAlive = false;
  1183. } else {
  1184. int const individuals_per_unit =
  1185. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1186. event.spawn_type);
  1187. m_entityCache.playerTroopCount -= individuals_per_unit;
  1188. m_entityCache.playerTroopCount =
  1189. std::max(0, m_entityCache.playerTroopCount);
  1190. }
  1191. } else if (owners.isAI(event.owner_id)) {
  1192. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1193. m_entityCache.enemyBarracksCount--;
  1194. m_entityCache.enemyBarracksCount =
  1195. std::max(0, m_entityCache.enemyBarracksCount);
  1196. m_entityCache.enemyBarracksAlive = (m_entityCache.enemyBarracksCount > 0);
  1197. }
  1198. }
  1199. syncSelectionFlags();
  1200. auto emit_if_changed = [&] {
  1201. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1202. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1203. emit troop_countChanged();
  1204. }
  1205. };
  1206. emit_if_changed();
  1207. }
  1208. void GameEngine::rebuildEntityCache() {
  1209. if (!m_world) {
  1210. m_entityCache.reset();
  1211. return;
  1212. }
  1213. m_entityCache.reset();
  1214. auto &owners = Game::Systems::OwnerRegistry::instance();
  1215. auto entities = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
  1216. for (auto *e : entities) {
  1217. auto *unit = e->getComponent<Engine::Core::UnitComponent>();
  1218. if ((unit == nullptr) || unit->health <= 0) {
  1219. continue;
  1220. }
  1221. if (unit->owner_id == m_runtime.localOwnerId) {
  1222. if (unit->spawn_type == Game::Units::SpawnType::Barracks) {
  1223. m_entityCache.playerBarracksAlive = true;
  1224. } else {
  1225. int const individuals_per_unit =
  1226. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1227. unit->spawn_type);
  1228. m_entityCache.playerTroopCount += individuals_per_unit;
  1229. }
  1230. } else if (owners.isAI(unit->owner_id)) {
  1231. if (unit->spawn_type == Game::Units::SpawnType::Barracks) {
  1232. m_entityCache.enemyBarracksCount++;
  1233. m_entityCache.enemyBarracksAlive = true;
  1234. }
  1235. }
  1236. }
  1237. auto emit_if_changed = [&] {
  1238. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1239. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1240. emit troop_countChanged();
  1241. }
  1242. };
  1243. emit_if_changed();
  1244. }
  1245. void GameEngine::rebuildRegistriesAfterLoad() {
  1246. if (!m_world) {
  1247. return;
  1248. }
  1249. auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1250. m_runtime.localOwnerId = owner_registry.getLocalPlayerId();
  1251. auto &troops = Game::Systems::TroopCountRegistry::instance();
  1252. troops.rebuildFromWorld(*m_world);
  1253. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  1254. stats_registry.rebuildFromWorld(*m_world);
  1255. const auto &all_owners = owner_registry.getAllOwners();
  1256. for (const auto &owner : all_owners) {
  1257. if (owner.type == Game::Systems::OwnerType::Player ||
  1258. owner.type == Game::Systems::OwnerType::AI) {
  1259. stats_registry.markGameStart(owner.owner_id);
  1260. }
  1261. }
  1262. rebuildBuildingCollisions();
  1263. m_level.playerUnitId = 0;
  1264. auto units = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
  1265. for (auto *entity : units) {
  1266. auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
  1267. if (unit == nullptr) {
  1268. continue;
  1269. }
  1270. if (unit->owner_id == m_runtime.localOwnerId) {
  1271. m_level.playerUnitId = entity->getId();
  1272. break;
  1273. }
  1274. }
  1275. if (m_selectedPlayerId != m_runtime.localOwnerId) {
  1276. m_selectedPlayerId = m_runtime.localOwnerId;
  1277. emit selectedPlayerIdChanged();
  1278. }
  1279. }
  1280. void GameEngine::rebuildBuildingCollisions() {
  1281. auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
  1282. registry.clear();
  1283. if (!m_world) {
  1284. return;
  1285. }
  1286. auto buildings = m_world->getEntitiesWith<Engine::Core::BuildingComponent>();
  1287. for (auto *entity : buildings) {
  1288. auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
  1289. auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
  1290. if ((transform == nullptr) || (unit == nullptr)) {
  1291. continue;
  1292. }
  1293. registry.registerBuilding(
  1294. entity->getId(), Game::Units::spawn_typeToString(unit->spawn_type),
  1295. transform->position.x, transform->position.z, unit->owner_id);
  1296. }
  1297. }
  1298. auto GameEngine::toRuntimeSnapshot() const -> Game::Systems::RuntimeSnapshot {
  1299. Game::Systems::RuntimeSnapshot snap;
  1300. snap.paused = m_runtime.paused;
  1301. snap.timeScale = m_runtime.timeScale;
  1302. snap.localOwnerId = m_runtime.localOwnerId;
  1303. snap.victoryState = m_runtime.victoryState;
  1304. snap.cursorMode = CursorModeUtils::toInt(m_runtime.cursorMode);
  1305. snap.selectedPlayerId = m_selectedPlayerId;
  1306. snap.followSelection = m_followSelectionEnabled;
  1307. return snap;
  1308. }
  1309. void GameEngine::applyRuntimeSnapshot(
  1310. const Game::Systems::RuntimeSnapshot &snapshot) {
  1311. m_runtime.localOwnerId = snapshot.localOwnerId;
  1312. setPaused(snapshot.paused);
  1313. setGameSpeed(snapshot.timeScale);
  1314. if (snapshot.victoryState != m_runtime.victoryState) {
  1315. m_runtime.victoryState = snapshot.victoryState;
  1316. emit victoryStateChanged();
  1317. }
  1318. setCursorMode(CursorModeUtils::fromInt(snapshot.cursorMode));
  1319. if (snapshot.selectedPlayerId != m_selectedPlayerId) {
  1320. m_selectedPlayerId = snapshot.selectedPlayerId;
  1321. emit selectedPlayerIdChanged();
  1322. }
  1323. if (snapshot.followSelection != m_followSelectionEnabled) {
  1324. m_followSelectionEnabled = snapshot.followSelection;
  1325. if (m_camera && m_cameraService && m_world) {
  1326. m_cameraService->followSelection(*m_camera, *m_world,
  1327. m_followSelectionEnabled);
  1328. }
  1329. }
  1330. }
  1331. auto GameEngine::captureScreenshot() const -> QByteArray {
  1332. if (m_window == nullptr) {
  1333. return {};
  1334. }
  1335. QImage const image = m_window->grabWindow();
  1336. if (image.isNull()) {
  1337. return {};
  1338. }
  1339. const QSize target_size(320, 180);
  1340. QImage const scaled =
  1341. image.scaled(target_size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
  1342. QByteArray buffer;
  1343. QBuffer q_buffer(&buffer);
  1344. if (!q_buffer.open(QIODevice::WriteOnly)) {
  1345. return {};
  1346. }
  1347. if (!scaled.save(&q_buffer, "PNG")) {
  1348. return {};
  1349. }
  1350. return buffer;
  1351. }
  1352. void GameEngine::restoreEnvironmentFromMetadata(const QJsonObject &metadata) {
  1353. if (!m_world) {
  1354. return;
  1355. }
  1356. const auto fallback_grid_width = metadata.value("grid_width").toInt(50);
  1357. const auto fallback_grid_height = metadata.value("grid_height").toInt(50);
  1358. const float fallback_tile_size =
  1359. static_cast<float>(metadata.value("tile_size").toDouble(1.0));
  1360. auto &terrain_service = Game::Map::TerrainService::instance();
  1361. bool const terrain_already_restored = terrain_service.isInitialized();
  1362. Game::Map::MapDefinition def;
  1363. QString map_error;
  1364. bool loaded_definition = false;
  1365. const QString &map_path = m_level.map_path;
  1366. if (!terrain_already_restored && !map_path.isEmpty()) {
  1367. loaded_definition =
  1368. Game::Map::MapLoader::loadFromJsonFile(map_path, def, &map_error);
  1369. if (!loaded_definition) {
  1370. qWarning() << "GameEngine: Failed to load map definition from" << map_path
  1371. << "during save load:" << map_error;
  1372. }
  1373. }
  1374. if (!terrain_already_restored && loaded_definition) {
  1375. terrain_service.initialize(def);
  1376. if (!def.name.isEmpty()) {
  1377. m_level.map_name = def.name;
  1378. }
  1379. m_level.camFov = def.camera.fovY;
  1380. m_level.camNear = def.camera.near_plane;
  1381. m_level.camFar = def.camera.far_plane;
  1382. }
  1383. if (m_renderer && m_camera) {
  1384. if (loaded_definition) {
  1385. Game::Map::Environment::apply(def, *m_renderer, *m_camera);
  1386. } else {
  1387. Game::Map::Environment::applyDefault(*m_renderer, *m_camera);
  1388. }
  1389. }
  1390. if (terrain_service.isInitialized()) {
  1391. const auto *height_map = terrain_service.getHeightMap();
  1392. const int grid_width =
  1393. (height_map != nullptr) ? height_map->getWidth() : fallback_grid_width;
  1394. const int grid_height = (height_map != nullptr) ? height_map->getHeight()
  1395. : fallback_grid_height;
  1396. const float tile_size = (height_map != nullptr) ? height_map->getTileSize()
  1397. : fallback_tile_size;
  1398. if (m_ground) {
  1399. m_ground->configure(tile_size, grid_width, grid_height);
  1400. m_ground->setBiome(terrain_service.biomeSettings());
  1401. }
  1402. if (height_map != nullptr) {
  1403. if (m_terrain) {
  1404. m_terrain->configure(*height_map, terrain_service.biomeSettings());
  1405. }
  1406. if (m_river) {
  1407. m_river->configure(height_map->getRiverSegments(),
  1408. height_map->getTileSize());
  1409. }
  1410. if (m_riverbank) {
  1411. m_riverbank->configure(height_map->getRiverSegments(), *height_map);
  1412. }
  1413. if (m_bridge) {
  1414. m_bridge->configure(height_map->getBridges(),
  1415. height_map->getTileSize());
  1416. }
  1417. if (m_biome) {
  1418. m_biome->configure(*height_map, terrain_service.biomeSettings());
  1419. m_biome->refreshGrass();
  1420. }
  1421. if (m_stone) {
  1422. m_stone->configure(*height_map, terrain_service.biomeSettings());
  1423. }
  1424. if (m_plant) {
  1425. m_plant->configure(*height_map, terrain_service.biomeSettings());
  1426. }
  1427. if (m_pine) {
  1428. m_pine->configure(*height_map, terrain_service.biomeSettings());
  1429. }
  1430. if (m_firecamp) {
  1431. m_firecamp->configure(*height_map, terrain_service.biomeSettings());
  1432. }
  1433. }
  1434. Game::Systems::CommandService::initialize(grid_width, grid_height);
  1435. auto &visibility_service = Game::Map::VisibilityService::instance();
  1436. visibility_service.initialize(grid_width, grid_height, tile_size);
  1437. visibility_service.computeImmediate(*m_world, m_runtime.localOwnerId);
  1438. if (m_fog && visibility_service.isInitialized()) {
  1439. m_fog->updateMask(
  1440. visibility_service.getWidth(), visibility_service.getHeight(),
  1441. visibility_service.getTileSize(), visibility_service.snapshotCells());
  1442. }
  1443. m_runtime.visibilityVersion = visibility_service.version();
  1444. m_runtime.visibilityUpdateAccumulator = 0.0F;
  1445. } else {
  1446. if (m_renderer && m_camera) {
  1447. Game::Map::Environment::applyDefault(*m_renderer, *m_camera);
  1448. }
  1449. Game::Map::MapDefinition fallback_def;
  1450. fallback_def.grid.width = fallback_grid_width;
  1451. fallback_def.grid.height = fallback_grid_height;
  1452. fallback_def.grid.tile_size = fallback_tile_size;
  1453. fallback_def.max_troops_per_player = m_level.max_troops_per_player;
  1454. terrain_service.initialize(fallback_def);
  1455. if (m_ground) {
  1456. m_ground->configure(fallback_tile_size, fallback_grid_width,
  1457. fallback_grid_height);
  1458. }
  1459. Game::Systems::CommandService::initialize(fallback_grid_width,
  1460. fallback_grid_height);
  1461. auto &visibility_service = Game::Map::VisibilityService::instance();
  1462. visibility_service.initialize(fallback_grid_width, fallback_grid_height,
  1463. fallback_tile_size);
  1464. visibility_service.computeImmediate(*m_world, m_runtime.localOwnerId);
  1465. if (m_fog && visibility_service.isInitialized()) {
  1466. m_fog->updateMask(
  1467. visibility_service.getWidth(), visibility_service.getHeight(),
  1468. visibility_service.getTileSize(), visibility_service.snapshotCells());
  1469. }
  1470. m_runtime.visibilityVersion = visibility_service.version();
  1471. m_runtime.visibilityUpdateAccumulator = 0.0F;
  1472. }
  1473. }
  1474. auto GameEngine::hasPatrolPreviewWaypoint() const -> bool {
  1475. return m_commandController && m_commandController->hasPatrolFirstWaypoint();
  1476. }
  1477. auto GameEngine::getPatrolPreviewWaypoint() const -> QVector3D {
  1478. if (!m_commandController) {
  1479. return {};
  1480. }
  1481. return m_commandController->getPatrolFirstWaypoint();
  1482. }
  1483. void GameEngine::updateAmbientState(float dt) {
  1484. m_ambientCheckTimer += dt;
  1485. const float check_interval = 2.0F;
  1486. if (m_ambientCheckTimer < check_interval) {
  1487. return;
  1488. }
  1489. m_ambientCheckTimer = 0.0F;
  1490. Engine::Core::AmbientState new_state = Engine::Core::AmbientState::PEACEFUL;
  1491. if (!m_runtime.victoryState.isEmpty()) {
  1492. if (m_runtime.victoryState == "victory") {
  1493. new_state = Engine::Core::AmbientState::VICTORY;
  1494. } else if (m_runtime.victoryState == "defeat") {
  1495. new_state = Engine::Core::AmbientState::DEFEAT;
  1496. }
  1497. } else if (isPlayerInCombat()) {
  1498. new_state = Engine::Core::AmbientState::COMBAT;
  1499. } else if (m_entityCache.enemyBarracksAlive &&
  1500. m_entityCache.playerBarracksAlive) {
  1501. new_state = Engine::Core::AmbientState::TENSE;
  1502. }
  1503. if (new_state != m_currentAmbientState) {
  1504. Engine::Core::AmbientState const previous_state = m_currentAmbientState;
  1505. m_currentAmbientState = new_state;
  1506. Engine::Core::EventManager::instance().publish(
  1507. Engine::Core::AmbientStateChangedEvent(new_state, previous_state));
  1508. qInfo() << "Ambient state changed from" << static_cast<int>(previous_state)
  1509. << "to" << static_cast<int>(new_state);
  1510. }
  1511. }
  1512. auto GameEngine::isPlayerInCombat() const -> bool {
  1513. if (!m_world) {
  1514. return false;
  1515. }
  1516. auto units = m_world->getEntitiesWith<Engine::Core::UnitComponent>();
  1517. const float combat_check_radius = 15.0F;
  1518. for (auto *entity : units) {
  1519. auto *unit = entity->getComponent<Engine::Core::UnitComponent>();
  1520. if ((unit == nullptr) || unit->owner_id != m_runtime.localOwnerId ||
  1521. unit->health <= 0) {
  1522. continue;
  1523. }
  1524. if (entity->hasComponent<Engine::Core::AttackTargetComponent>()) {
  1525. return true;
  1526. }
  1527. auto *transform = entity->getComponent<Engine::Core::TransformComponent>();
  1528. if (transform == nullptr) {
  1529. continue;
  1530. }
  1531. for (auto *other_entity : units) {
  1532. auto *other_unit =
  1533. other_entity->getComponent<Engine::Core::UnitComponent>();
  1534. if ((other_unit == nullptr) ||
  1535. other_unit->owner_id == m_runtime.localOwnerId ||
  1536. other_unit->health <= 0) {
  1537. continue;
  1538. }
  1539. auto *other_transform =
  1540. other_entity->getComponent<Engine::Core::TransformComponent>();
  1541. if (other_transform == nullptr) {
  1542. continue;
  1543. }
  1544. float const dx = transform->position.x - other_transform->position.x;
  1545. float const dz = transform->position.z - other_transform->position.z;
  1546. float const dist_sq = dx * dx + dz * dz;
  1547. if (dist_sq < combat_check_radius * combat_check_radius) {
  1548. return true;
  1549. }
  1550. }
  1551. }
  1552. return false;
  1553. }
  1554. void GameEngine::loadAudioResources() {
  1555. auto &audio_sys = AudioSystem::getInstance();
  1556. QString const base_path =
  1557. QCoreApplication::applicationDirPath() + "/assets/audio/";
  1558. qInfo() << "Loading audio resources from:" << base_path;
  1559. QDir const audio_dir(base_path);
  1560. if (!audio_dir.exists()) {
  1561. qWarning() << "Audio assets directory does not exist:" << base_path;
  1562. qWarning() << "Application directory:"
  1563. << QCoreApplication::applicationDirPath();
  1564. return;
  1565. }
  1566. if (audio_sys.loadSound("archer_voice",
  1567. (base_path + "voices/archer_voice.wav").toStdString(),
  1568. AudioCategory::VOICE)) {
  1569. qInfo() << "Loaded archer voice";
  1570. } else {
  1571. qWarning() << "Failed to load archer voice from:"
  1572. << (base_path + "voices/archer_voice.wav");
  1573. }
  1574. if (audio_sys.loadSound("knight_voice",
  1575. (base_path + "voices/knight_voice.wav").toStdString(),
  1576. AudioCategory::VOICE)) {
  1577. qInfo() << "Loaded knight voice";
  1578. } else {
  1579. qWarning() << "Failed to load knight voice from:"
  1580. << (base_path + "voices/knight_voice.wav");
  1581. }
  1582. if (audio_sys.loadSound(
  1583. "spearman_voice",
  1584. (base_path + "voices/spearman_voice.wav").toStdString(),
  1585. AudioCategory::VOICE)) {
  1586. qInfo() << "Loaded spearman voice";
  1587. } else {
  1588. qWarning() << "Failed to load spearman voice from:"
  1589. << (base_path + "voices/spearman_voice.wav");
  1590. }
  1591. if (audio_sys.loadMusic("music_peaceful",
  1592. (base_path + "music/peaceful.wav").toStdString())) {
  1593. qInfo() << "Loaded peaceful music";
  1594. } else {
  1595. qWarning() << "Failed to load peaceful music from:"
  1596. << (base_path + "music/peaceful.wav");
  1597. }
  1598. if (audio_sys.loadMusic("music_tense",
  1599. (base_path + "music/tense.wav").toStdString())) {
  1600. qInfo() << "Loaded tense music";
  1601. } else {
  1602. qWarning() << "Failed to load tense music from:"
  1603. << (base_path + "music/tense.wav");
  1604. }
  1605. if (audio_sys.loadMusic("music_combat",
  1606. (base_path + "music/combat.wav").toStdString())) {
  1607. qInfo() << "Loaded combat music";
  1608. } else {
  1609. qWarning() << "Failed to load combat music from:"
  1610. << (base_path + "music/combat.wav");
  1611. }
  1612. if (audio_sys.loadMusic("music_victory",
  1613. (base_path + "music/victory.wav").toStdString())) {
  1614. qInfo() << "Loaded victory music";
  1615. } else {
  1616. qWarning() << "Failed to load victory music from:"
  1617. << (base_path + "music/victory.wav");
  1618. }
  1619. if (audio_sys.loadMusic("music_defeat",
  1620. (base_path + "music/defeat.wav").toStdString())) {
  1621. qInfo() << "Loaded defeat music";
  1622. } else {
  1623. qWarning() << "Failed to load defeat music from:"
  1624. << (base_path + "music/defeat.wav");
  1625. }
  1626. qInfo() << "Audio resources loading complete";
  1627. }