game_engine.cpp 60 KB

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