combat_system.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #include "combat_system.h"
  2. #include "../core/component.h"
  3. #include "../core/event_manager.h"
  4. #include "../core/world.h"
  5. #include "../visuals/team_colors.h"
  6. #include "arrow_system.h"
  7. #include "building_collision_registry.h"
  8. #include "command_service.h"
  9. #include "owner_registry.h"
  10. #include <algorithm>
  11. #include <cmath>
  12. #include <limits>
  13. namespace Game::Systems {
  14. void CombatSystem::update(Engine::Core::World *world, float deltaTime) {
  15. processAttacks(world, deltaTime);
  16. }
  17. void CombatSystem::processAttacks(Engine::Core::World *world, float deltaTime) {
  18. auto units = world->getEntitiesWith<Engine::Core::UnitComponent>();
  19. ArrowSystem *arrowSys = world->getSystem<ArrowSystem>();
  20. for (auto attacker : units) {
  21. auto attackerUnit = attacker->getComponent<Engine::Core::UnitComponent>();
  22. auto attackerTransform =
  23. attacker->getComponent<Engine::Core::TransformComponent>();
  24. auto attackerAtk = attacker->getComponent<Engine::Core::AttackComponent>();
  25. if (!attackerUnit || !attackerTransform) {
  26. continue;
  27. }
  28. if (attackerUnit->health <= 0 ||
  29. attacker->hasComponent<Engine::Core::PendingRemovalComponent>())
  30. continue;
  31. if (attackerAtk && attackerAtk->inMeleeLock) {
  32. auto *lockTarget = world->getEntity(attackerAtk->meleeLockTargetId);
  33. if (!lockTarget) {
  34. attackerAtk->inMeleeLock = false;
  35. attackerAtk->meleeLockTargetId = 0;
  36. } else {
  37. auto *lockTargetUnit =
  38. lockTarget->getComponent<Engine::Core::UnitComponent>();
  39. if (!lockTargetUnit || lockTargetUnit->health <= 0) {
  40. attackerAtk->inMeleeLock = false;
  41. attackerAtk->meleeLockTargetId = 0;
  42. } else {
  43. auto *attT = attackerTransform;
  44. auto *tgtT =
  45. lockTarget->getComponent<Engine::Core::TransformComponent>();
  46. if (attT && tgtT) {
  47. float dx = tgtT->position.x - attT->position.x;
  48. float dz = tgtT->position.z - attT->position.z;
  49. float dist = std::sqrt(dx * dx + dz * dz);
  50. const float IDEAL_MELEE_DISTANCE = 0.6f;
  51. const float MAX_MELEE_SEPARATION = 0.9f;
  52. if (dist > MAX_MELEE_SEPARATION) {
  53. float pullAmount =
  54. (dist - IDEAL_MELEE_DISTANCE) * 0.3f * deltaTime * 5.0f;
  55. if (dist > 0.001f) {
  56. QVector3D direction(dx / dist, 0.0f, dz / dist);
  57. attT->position.x += direction.x() * pullAmount;
  58. attT->position.z += direction.z() * pullAmount;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }
  65. if (attackerAtk && attackerAtk->inMeleeLock &&
  66. attackerAtk->meleeLockTargetId != 0) {
  67. auto *lockTarget = world->getEntity(attackerAtk->meleeLockTargetId);
  68. if (lockTarget) {
  69. auto *attackTarget =
  70. attacker->getComponent<Engine::Core::AttackTargetComponent>();
  71. if (!attackTarget) {
  72. attackTarget =
  73. attacker->addComponent<Engine::Core::AttackTargetComponent>();
  74. }
  75. if (attackTarget) {
  76. attackTarget->targetId = attackerAtk->meleeLockTargetId;
  77. attackTarget->shouldChase = false;
  78. }
  79. }
  80. }
  81. float range = 2.0f;
  82. int damage = 10;
  83. float cooldown = 1.0f;
  84. float *tAccum = nullptr;
  85. float tmpAccum = 0.0f;
  86. if (attackerAtk) {
  87. updateCombatMode(attacker, world, attackerAtk);
  88. range = attackerAtk->getCurrentRange();
  89. damage = attackerAtk->getCurrentDamage();
  90. cooldown = attackerAtk->getCurrentCooldown();
  91. auto *holdMode =
  92. attacker->getComponent<Engine::Core::HoldModeComponent>();
  93. if (holdMode && holdMode->active && attackerUnit->unitType == "archer") {
  94. range *= 1.5f;
  95. damage = static_cast<int>(damage * 1.3f);
  96. }
  97. attackerAtk->timeSinceLast += deltaTime;
  98. tAccum = &attackerAtk->timeSinceLast;
  99. } else {
  100. tmpAccum += deltaTime;
  101. tAccum = &tmpAccum;
  102. }
  103. if (*tAccum < cooldown) {
  104. continue;
  105. }
  106. auto *attackTarget =
  107. attacker->getComponent<Engine::Core::AttackTargetComponent>();
  108. Engine::Core::Entity *bestTarget = nullptr;
  109. if (attackTarget && attackTarget->targetId != 0) {
  110. auto *target = world->getEntity(attackTarget->targetId);
  111. if (target) {
  112. auto *targetUnit = target->getComponent<Engine::Core::UnitComponent>();
  113. auto &ownerRegistry = Game::Systems::OwnerRegistry::instance();
  114. bool isAlly =
  115. ownerRegistry.areAllies(attackerUnit->ownerId, targetUnit->ownerId);
  116. if (targetUnit && targetUnit->health > 0 &&
  117. targetUnit->ownerId != attackerUnit->ownerId && !isAlly) {
  118. if (isInRange(attacker, target, range)) {
  119. bestTarget = target;
  120. if (auto *attT =
  121. attacker
  122. ->getComponent<Engine::Core::TransformComponent>()) {
  123. if (auto *tgtT =
  124. target
  125. ->getComponent<Engine::Core::TransformComponent>()) {
  126. float dx = tgtT->position.x - attT->position.x;
  127. float dz = tgtT->position.z - attT->position.z;
  128. float yaw = std::atan2(dx, dz) * 180.0f / 3.14159265f;
  129. attT->desiredYaw = yaw;
  130. attT->hasDesiredYaw = true;
  131. }
  132. }
  133. } else if (attackTarget->shouldChase) {
  134. auto *holdMode =
  135. attacker->getComponent<Engine::Core::HoldModeComponent>();
  136. if (holdMode && holdMode->active) {
  137. if (!isInRange(attacker, target, range)) {
  138. attacker
  139. ->removeComponent<Engine::Core::AttackTargetComponent>();
  140. }
  141. continue;
  142. }
  143. auto *targetTransform =
  144. target->getComponent<Engine::Core::TransformComponent>();
  145. auto *attackerTransformComponent =
  146. attacker->getComponent<Engine::Core::TransformComponent>();
  147. if (targetTransform && attackerTransformComponent) {
  148. QVector3D attackerPos(attackerTransformComponent->position.x,
  149. 0.0f,
  150. attackerTransformComponent->position.z);
  151. QVector3D targetPos(targetTransform->position.x, 0.0f,
  152. targetTransform->position.z);
  153. QVector3D desiredPos = targetPos;
  154. bool holdPosition = false;
  155. bool targetIsBuilding =
  156. target->hasComponent<Engine::Core::BuildingComponent>();
  157. if (targetIsBuilding) {
  158. float scaleX = targetTransform->scale.x;
  159. float scaleZ = targetTransform->scale.z;
  160. float targetRadius = std::max(scaleX, scaleZ) * 0.5f;
  161. QVector3D direction = targetPos - attackerPos;
  162. float distanceSq = direction.lengthSquared();
  163. if (distanceSq > 0.000001f) {
  164. float distance = std::sqrt(distanceSq);
  165. direction /= distance;
  166. float desiredDistance =
  167. targetRadius + std::max(range - 0.2f, 0.2f);
  168. if (distance > desiredDistance + 0.15f) {
  169. desiredPos = targetPos - direction * desiredDistance;
  170. } else {
  171. holdPosition = true;
  172. }
  173. }
  174. }
  175. auto *movement =
  176. attacker->getComponent<Engine::Core::MovementComponent>();
  177. if (!movement) {
  178. movement =
  179. attacker->addComponent<Engine::Core::MovementComponent>();
  180. }
  181. if (movement) {
  182. if (holdPosition) {
  183. movement->hasTarget = false;
  184. movement->vx = 0.0f;
  185. movement->vz = 0.0f;
  186. movement->path.clear();
  187. if (attackerTransformComponent) {
  188. movement->targetX = attackerTransformComponent->position.x;
  189. movement->targetY = attackerTransformComponent->position.z;
  190. movement->goalX = attackerTransformComponent->position.x;
  191. movement->goalY = attackerTransformComponent->position.z;
  192. }
  193. } else {
  194. QVector3D plannedTarget(movement->targetX, 0.0f,
  195. movement->targetY);
  196. if (!movement->path.empty()) {
  197. const auto &finalNode = movement->path.back();
  198. plannedTarget =
  199. QVector3D(finalNode.first, 0.0f, finalNode.second);
  200. }
  201. float diffSq = (plannedTarget - desiredPos).lengthSquared();
  202. bool needNewCommand = !movement->pathPending;
  203. if (movement->hasTarget && diffSq <= 0.25f * 0.25f) {
  204. needNewCommand = false;
  205. }
  206. if (needNewCommand) {
  207. CommandService::MoveOptions options;
  208. options.clearAttackIntent = false;
  209. options.allowDirectFallback = true;
  210. std::vector<Engine::Core::EntityID> unitIds = {
  211. attacker->getId()};
  212. std::vector<QVector3D> moveTargets = {desiredPos};
  213. CommandService::moveUnits(*world, unitIds, moveTargets,
  214. options);
  215. }
  216. }
  217. }
  218. }
  219. if (isInRange(attacker, target, range)) {
  220. bestTarget = target;
  221. }
  222. } else {
  223. attacker->removeComponent<Engine::Core::AttackTargetComponent>();
  224. }
  225. } else {
  226. attacker->removeComponent<Engine::Core::AttackTargetComponent>();
  227. }
  228. } else {
  229. attacker->removeComponent<Engine::Core::AttackTargetComponent>();
  230. }
  231. }
  232. if (!bestTarget && !attackTarget) {
  233. auto &ownerRegistry = Game::Systems::OwnerRegistry::instance();
  234. for (auto target : units) {
  235. if (target == attacker) {
  236. continue;
  237. }
  238. auto targetUnit = target->getComponent<Engine::Core::UnitComponent>();
  239. if (!targetUnit || targetUnit->health <= 0) {
  240. continue;
  241. }
  242. if (targetUnit->ownerId == attackerUnit->ownerId) {
  243. continue;
  244. }
  245. if (ownerRegistry.areAllies(attackerUnit->ownerId,
  246. targetUnit->ownerId)) {
  247. continue;
  248. }
  249. if (target->hasComponent<Engine::Core::BuildingComponent>()) {
  250. continue;
  251. }
  252. if (isInRange(attacker, target, range)) {
  253. bestTarget = target;
  254. break;
  255. }
  256. }
  257. }
  258. if (bestTarget) {
  259. auto *bestTargetUnit =
  260. bestTarget->getComponent<Engine::Core::UnitComponent>();
  261. if (!attacker->hasComponent<Engine::Core::AttackTargetComponent>()) {
  262. auto *newTarget =
  263. attacker->addComponent<Engine::Core::AttackTargetComponent>();
  264. newTarget->targetId = bestTarget->getId();
  265. newTarget->shouldChase = false;
  266. } else {
  267. auto *existingTarget =
  268. attacker->getComponent<Engine::Core::AttackTargetComponent>();
  269. if (existingTarget->targetId != bestTarget->getId()) {
  270. existingTarget->targetId = bestTarget->getId();
  271. existingTarget->shouldChase = false;
  272. }
  273. }
  274. if (auto *attT =
  275. attacker->getComponent<Engine::Core::TransformComponent>()) {
  276. if (auto *tgtT =
  277. bestTarget->getComponent<Engine::Core::TransformComponent>()) {
  278. float dx = tgtT->position.x - attT->position.x;
  279. float dz = tgtT->position.z - attT->position.z;
  280. float yaw = std::atan2(dx, dz) * 180.0f / 3.14159265f;
  281. attT->desiredYaw = yaw;
  282. attT->hasDesiredYaw = true;
  283. }
  284. }
  285. if (arrowSys) {
  286. auto attT = attacker->getComponent<Engine::Core::TransformComponent>();
  287. auto tgtT =
  288. bestTarget->getComponent<Engine::Core::TransformComponent>();
  289. auto attU = attacker->getComponent<Engine::Core::UnitComponent>();
  290. if (!attackerAtk ||
  291. attackerAtk->currentMode !=
  292. Engine::Core::AttackComponent::CombatMode::Melee) {
  293. QVector3D aPos(attT->position.x, attT->position.y, attT->position.z);
  294. QVector3D tPos(tgtT->position.x, tgtT->position.y, tgtT->position.z);
  295. QVector3D dir = (tPos - aPos).normalized();
  296. QVector3D start = aPos + QVector3D(0.0f, 0.6f, 0.0f) + dir * 0.35f;
  297. QVector3D end = tPos + QVector3D(0.5f, 0.5f, 0.0f);
  298. QVector3D color =
  299. attU ? Game::Visuals::teamColorForOwner(attU->ownerId)
  300. : QVector3D(0.8f, 0.9f, 1.0f);
  301. arrowSys->spawnArrow(start, end, color, 14.0f);
  302. }
  303. }
  304. if (attackerAtk && attackerAtk->currentMode ==
  305. Engine::Core::AttackComponent::CombatMode::Melee) {
  306. attackerAtk->inMeleeLock = true;
  307. attackerAtk->meleeLockTargetId = bestTarget->getId();
  308. auto *targetAtk =
  309. bestTarget->getComponent<Engine::Core::AttackComponent>();
  310. if (targetAtk) {
  311. targetAtk->inMeleeLock = true;
  312. targetAtk->meleeLockTargetId = attacker->getId();
  313. }
  314. auto *attT = attacker->getComponent<Engine::Core::TransformComponent>();
  315. auto *tgtT =
  316. bestTarget->getComponent<Engine::Core::TransformComponent>();
  317. if (attT && tgtT) {
  318. float dx = tgtT->position.x - attT->position.x;
  319. float dz = tgtT->position.z - attT->position.z;
  320. float dist = std::sqrt(dx * dx + dz * dz);
  321. const float IDEAL_MELEE_DISTANCE = 0.6f;
  322. if (dist > IDEAL_MELEE_DISTANCE + 0.1f) {
  323. float moveAmount = (dist - IDEAL_MELEE_DISTANCE) * 0.5f;
  324. if (dist > 0.001f) {
  325. QVector3D direction(dx / dist, 0.0f, dz / dist);
  326. attT->position.x += direction.x() * moveAmount;
  327. attT->position.z += direction.z() * moveAmount;
  328. tgtT->position.x -= direction.x() * moveAmount;
  329. tgtT->position.z -= direction.z() * moveAmount;
  330. }
  331. }
  332. }
  333. }
  334. dealDamage(world, bestTarget, damage, attacker->getId());
  335. *tAccum = 0.0f;
  336. } else {
  337. if (!attackTarget &&
  338. attacker->hasComponent<Engine::Core::AttackTargetComponent>()) {
  339. attacker->removeComponent<Engine::Core::AttackTargetComponent>();
  340. }
  341. }
  342. }
  343. }
  344. bool CombatSystem::isInRange(Engine::Core::Entity *attacker,
  345. Engine::Core::Entity *target, float range) {
  346. auto attackerTransform =
  347. attacker->getComponent<Engine::Core::TransformComponent>();
  348. auto targetTransform =
  349. target->getComponent<Engine::Core::TransformComponent>();
  350. if (!attackerTransform || !targetTransform) {
  351. return false;
  352. }
  353. float dx = targetTransform->position.x - attackerTransform->position.x;
  354. float dz = targetTransform->position.z - attackerTransform->position.z;
  355. float dy = targetTransform->position.y - attackerTransform->position.y;
  356. float distanceSquared = dx * dx + dz * dz;
  357. float targetRadius = 0.0f;
  358. if (target->hasComponent<Engine::Core::BuildingComponent>()) {
  359. float scaleX = targetTransform->scale.x;
  360. float scaleZ = targetTransform->scale.z;
  361. targetRadius = std::max(scaleX, scaleZ) * 0.5f;
  362. } else {
  363. float scaleX = targetTransform->scale.x;
  364. float scaleZ = targetTransform->scale.z;
  365. targetRadius = std::max(scaleX, scaleZ) * 0.5f;
  366. }
  367. float effectiveRange = range + targetRadius;
  368. if (distanceSquared > effectiveRange * effectiveRange) {
  369. return false;
  370. }
  371. auto attackerAtk = attacker->getComponent<Engine::Core::AttackComponent>();
  372. if (attackerAtk && attackerAtk->currentMode ==
  373. Engine::Core::AttackComponent::CombatMode::Melee) {
  374. float heightDiff = std::abs(dy);
  375. if (heightDiff > attackerAtk->maxHeightDifference) {
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. void CombatSystem::dealDamage(Engine::Core::World *world,
  382. Engine::Core::Entity *target, int damage,
  383. Engine::Core::EntityID attackerId) {
  384. auto unit = target->getComponent<Engine::Core::UnitComponent>();
  385. if (unit) {
  386. unit->health = std::max(0, unit->health - damage);
  387. int attackerOwnerId = 0;
  388. if (attackerId != 0 && world) {
  389. auto *attacker = world->getEntity(attackerId);
  390. if (attacker) {
  391. auto *attackerUnit =
  392. attacker->getComponent<Engine::Core::UnitComponent>();
  393. if (attackerUnit) {
  394. attackerOwnerId = attackerUnit->ownerId;
  395. }
  396. }
  397. }
  398. if (target->hasComponent<Engine::Core::BuildingComponent>() &&
  399. unit->health > 0) {
  400. Engine::Core::EventManager::instance().publish(
  401. Engine::Core::BuildingAttackedEvent(target->getId(), unit->ownerId,
  402. unit->unitType, attackerId,
  403. attackerOwnerId, damage));
  404. }
  405. if (unit->health <= 0) {
  406. int killerOwnerId = attackerOwnerId;
  407. Engine::Core::EventManager::instance().publish(
  408. Engine::Core::UnitDiedEvent(target->getId(), unit->ownerId,
  409. unit->unitType, attackerId,
  410. killerOwnerId));
  411. auto *targetAtk = target->getComponent<Engine::Core::AttackComponent>();
  412. if (targetAtk && targetAtk->inMeleeLock &&
  413. targetAtk->meleeLockTargetId != 0) {
  414. if (world) {
  415. auto *lockPartner = world->getEntity(targetAtk->meleeLockTargetId);
  416. if (lockPartner) {
  417. auto *partnerAtk =
  418. lockPartner->getComponent<Engine::Core::AttackComponent>();
  419. if (partnerAtk &&
  420. partnerAtk->meleeLockTargetId == target->getId()) {
  421. partnerAtk->inMeleeLock = false;
  422. partnerAtk->meleeLockTargetId = 0;
  423. }
  424. }
  425. }
  426. }
  427. if (target->hasComponent<Engine::Core::BuildingComponent>()) {
  428. BuildingCollisionRegistry::instance().unregisterBuilding(
  429. target->getId());
  430. }
  431. if (auto *r = target->getComponent<Engine::Core::RenderableComponent>()) {
  432. r->visible = false;
  433. }
  434. if (auto *movement =
  435. target->getComponent<Engine::Core::MovementComponent>()) {
  436. movement->hasTarget = false;
  437. movement->vx = 0.0f;
  438. movement->vz = 0.0f;
  439. movement->path.clear();
  440. movement->pathPending = false;
  441. }
  442. target->addComponent<Engine::Core::PendingRemovalComponent>();
  443. }
  444. }
  445. }
  446. void CombatSystem::updateCombatMode(Engine::Core::Entity *attacker,
  447. Engine::Core::World *world,
  448. Engine::Core::AttackComponent *attackComp) {
  449. if (!attackComp) {
  450. return;
  451. }
  452. if (attackComp->preferredMode !=
  453. Engine::Core::AttackComponent::CombatMode::Auto) {
  454. attackComp->currentMode = attackComp->preferredMode;
  455. return;
  456. }
  457. auto attackerTransform =
  458. attacker->getComponent<Engine::Core::TransformComponent>();
  459. if (!attackerTransform) {
  460. return;
  461. }
  462. auto attackerUnit = attacker->getComponent<Engine::Core::UnitComponent>();
  463. if (!attackerUnit) {
  464. return;
  465. }
  466. auto &ownerRegistry = Game::Systems::OwnerRegistry::instance();
  467. auto units = world->getEntitiesWith<Engine::Core::UnitComponent>();
  468. float closestEnemyDistSq = std::numeric_limits<float>::max();
  469. float closestHeightDiff = 0.0f;
  470. for (auto target : units) {
  471. if (target == attacker) {
  472. continue;
  473. }
  474. auto targetUnit = target->getComponent<Engine::Core::UnitComponent>();
  475. if (!targetUnit || targetUnit->health <= 0) {
  476. continue;
  477. }
  478. if (ownerRegistry.areAllies(attackerUnit->ownerId, targetUnit->ownerId)) {
  479. continue;
  480. }
  481. auto targetTransform =
  482. target->getComponent<Engine::Core::TransformComponent>();
  483. if (!targetTransform) {
  484. continue;
  485. }
  486. float dx = targetTransform->position.x - attackerTransform->position.x;
  487. float dz = targetTransform->position.z - attackerTransform->position.z;
  488. float dy = targetTransform->position.y - attackerTransform->position.y;
  489. float distSq = dx * dx + dz * dz;
  490. if (distSq < closestEnemyDistSq) {
  491. closestEnemyDistSq = distSq;
  492. closestHeightDiff = std::abs(dy);
  493. }
  494. }
  495. if (closestEnemyDistSq == std::numeric_limits<float>::max()) {
  496. if (attackComp->canRanged) {
  497. attackComp->currentMode =
  498. Engine::Core::AttackComponent::CombatMode::Ranged;
  499. } else {
  500. attackComp->currentMode =
  501. Engine::Core::AttackComponent::CombatMode::Melee;
  502. }
  503. return;
  504. }
  505. float closestDist = std::sqrt(closestEnemyDistSq);
  506. bool inMeleeRange =
  507. attackComp->isInMeleeRange(closestDist, closestHeightDiff);
  508. bool inRangedRange = attackComp->isInRangedRange(closestDist);
  509. if (inMeleeRange && attackComp->canMelee) {
  510. attackComp->currentMode = Engine::Core::AttackComponent::CombatMode::Melee;
  511. } else if (inRangedRange && attackComp->canRanged) {
  512. attackComp->currentMode = Engine::Core::AttackComponent::CombatMode::Ranged;
  513. } else if (attackComp->canRanged) {
  514. attackComp->currentMode = Engine::Core::AttackComponent::CombatMode::Ranged;
  515. } else {
  516. attackComp->currentMode = Engine::Core::AttackComponent::CombatMode::Melee;
  517. }
  518. }
  519. } // namespace Game::Systems