game_engine.cpp 58 KB

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