selected_units_model.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "selected_units_model.h"
  2. #include "../../game/core/component.h"
  3. #include "../../game/core/world.h"
  4. #include "../../game/systems/selection_system.h"
  5. #include "../core/game_engine.h"
  6. #include <algorithm>
  7. SelectedUnitsModel::SelectedUnitsModel(GameEngine *engine, QObject *parent)
  8. : QAbstractListModel(parent), m_engine(engine) {}
  9. int SelectedUnitsModel::rowCount(const QModelIndex &parent) const {
  10. if (parent.isValid())
  11. return 0;
  12. return static_cast<int>(m_ids.size());
  13. }
  14. QVariant SelectedUnitsModel::data(const QModelIndex &index, int role) const {
  15. if (!index.isValid() || index.row() < 0 ||
  16. index.row() >= static_cast<int>(m_ids.size()))
  17. return {};
  18. auto id = m_ids[index.row()];
  19. if (!m_engine)
  20. return {};
  21. QString name;
  22. int hp = 0, maxHp = 0;
  23. bool isB = false, alive = false;
  24. if (role == UnitIdRole)
  25. return QVariant::fromValue<int>(static_cast<int>(id));
  26. if (!m_engine->getUnitInfo(id, name, hp, maxHp, isB, alive))
  27. return {};
  28. if (role == NameRole)
  29. return name;
  30. if (role == HealthRole)
  31. return hp;
  32. if (role == MaxHealthRole)
  33. return maxHp;
  34. if (role == HealthRatioRole)
  35. return (maxHp > 0 ? static_cast<double>(std::clamp(hp, 0, maxHp)) /
  36. static_cast<double>(maxHp)
  37. : 0.0);
  38. return {};
  39. }
  40. QHash<int, QByteArray> SelectedUnitsModel::roleNames() const {
  41. return {{UnitIdRole, "unitId"},
  42. {NameRole, "name"},
  43. {HealthRole, "health"},
  44. {MaxHealthRole, "maxHealth"},
  45. {HealthRatioRole, "healthRatio"}};
  46. }
  47. void SelectedUnitsModel::refresh() {
  48. if (!m_engine)
  49. return;
  50. std::vector<Engine::Core::EntityID> ids;
  51. m_engine->getSelectedUnitIds(ids);
  52. if (ids.size() == m_ids.size() &&
  53. std::equal(ids.begin(), ids.end(), m_ids.begin())) {
  54. if (!m_ids.empty()) {
  55. QModelIndex first = index(0, 0);
  56. QModelIndex last = index(static_cast<int>(m_ids.size()) - 1, 0);
  57. emit dataChanged(first, last,
  58. {HealthRole, MaxHealthRole, HealthRatioRole});
  59. }
  60. return;
  61. }
  62. beginResetModel();
  63. m_ids.clear();
  64. for (auto id : ids) {
  65. QString nm;
  66. int hp = 0, maxHp = 0;
  67. bool isB = false, alive = false;
  68. if (!m_engine->getUnitInfo(id, nm, hp, maxHp, isB, alive))
  69. continue;
  70. if (isB)
  71. continue;
  72. if (!alive)
  73. continue;
  74. m_ids.push_back(id);
  75. }
  76. endResetModel();
  77. }