mapcontroller.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. /*
  2. * mapcontroller.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "mapcontroller.h"
  12. #include "../lib/ArtifactUtils.h"
  13. #include "../lib/GameConstants.h"
  14. #include "../lib/entities/hero/CHeroClass.h"
  15. #include "../lib/entities/hero/CHeroHandler.h"
  16. #include "../lib/mapObjectConstructors/AObjectTypeHandler.h"
  17. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  18. #include "../lib/mapObjects/ObjectTemplate.h"
  19. #include "../lib/mapping/CMapService.h"
  20. #include "../lib/mapping/CMap.h"
  21. #include "../lib/mapping/CMapEditManager.h"
  22. #include "../lib/mapping/ObstacleProxy.h"
  23. #include "../lib/modding/CModHandler.h"
  24. #include "../lib/modding/ModDescription.h"
  25. #include "../lib/TerrainHandler.h"
  26. #include "../lib/CSkillHandler.h"
  27. #include "../lib/spells/CSpellHandler.h"
  28. #include "../lib/CRandomGenerator.h"
  29. #include "../lib/serializer/CMemorySerializer.h"
  30. #include "mapview.h"
  31. #include "scenelayer.h"
  32. #include "maphandler.h"
  33. #include "mainwindow.h"
  34. #include "inspector/inspector.h"
  35. #include "GameLibrary.h"
  36. MapController::MapController(MainWindow * m): main(m)
  37. {
  38. for(int i : {0, 1})
  39. {
  40. _scenes[i].reset(new MapScene(i));
  41. _miniscenes[i].reset(new MinimapScene(i));
  42. }
  43. connectScenes();
  44. }
  45. void MapController::connectScenes()
  46. {
  47. for (int level = 0; level <= 1; level++)
  48. {
  49. //selections for both layers will be handled separately
  50. QObject::connect(_scenes[level].get(), &MapScene::selected, [this, level](bool anythingSelected)
  51. {
  52. main->onSelectionMade(level, anythingSelected);
  53. });
  54. }
  55. }
  56. MapController::~MapController()
  57. {
  58. main = nullptr;
  59. }
  60. const std::unique_ptr<CMap> & MapController::getMapUniquePtr() const
  61. {
  62. return _map;
  63. }
  64. CMap * MapController::map()
  65. {
  66. return _map.get();
  67. }
  68. MapHandler * MapController::mapHandler()
  69. {
  70. return _mapHandler.get();
  71. }
  72. MapScene * MapController::scene(int level)
  73. {
  74. return _scenes[level].get();
  75. }
  76. MinimapScene * MapController::miniScene(int level)
  77. {
  78. return _miniscenes[level].get();
  79. }
  80. void MapController::repairMap()
  81. {
  82. repairMap(map());
  83. }
  84. void MapController::repairMap(CMap * map)
  85. {
  86. if(!map)
  87. return;
  88. //make sure events/rumors has name to have proper identifiers
  89. int emptyNameId = 1;
  90. for(auto & e : map->events)
  91. if(e.name.empty())
  92. e.name = "event_" + std::to_string(emptyNameId++);
  93. emptyNameId = 1;
  94. for(auto & e : map->rumors)
  95. if(e.name.empty())
  96. e.name = "rumor_" + std::to_string(emptyNameId++);
  97. //fix owners for objects
  98. auto allImpactedObjects(map->objects);
  99. for (const auto & hero : map->predefinedHeroes)
  100. allImpactedObjects.push_back(hero);
  101. for(auto obj : allImpactedObjects)
  102. {
  103. //fix flags
  104. if(obj->getOwner() == PlayerColor::UNFLAGGABLE)
  105. {
  106. if(obj->asOwnable())
  107. obj->tempOwner = PlayerColor::NEUTRAL;
  108. }
  109. //fix hero instance
  110. if(auto * nih = dynamic_cast<CGHeroInstance*>(obj.get()))
  111. {
  112. // All heroes present on map or in prisons need to be allowed to rehire them after they are defeated
  113. // FIXME: How about custom scenarios where defeated hero cannot be hired again?
  114. map->allowedHeroes.insert(nih->getHeroTypeID());
  115. auto const & type = LIBRARY->heroh->objects[nih->subID];
  116. assert(type->heroClass);
  117. if(nih->ID == Obj::HERO) //not prison
  118. nih->appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->getIndex())->getTemplates().front();
  119. //fix spellbook
  120. if(nih->spellbookContainsSpell(SpellID::SPELLBOOK_PRESET))
  121. {
  122. nih->removeSpellFromSpellbook(SpellID::SPELLBOOK_PRESET);
  123. if(!nih->getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook)
  124. nih->putArtifact(ArtifactPosition::SPELLBOOK, map->createArtifact(ArtifactID::SPELLBOOK));
  125. }
  126. }
  127. //fix town instance
  128. if(auto * tnh = dynamic_cast<CGTownInstance*>(obj.get()))
  129. {
  130. if(tnh->getTown())
  131. {
  132. for(const auto & building : tnh->getBuildings())
  133. {
  134. if(!tnh->getTown()->buildings.count(building))
  135. tnh->removeBuilding(building);
  136. }
  137. vstd::erase_if(tnh->forbiddenBuildings, [tnh](BuildingID bid)
  138. {
  139. return !tnh->getTown()->buildings.count(bid);
  140. });
  141. }
  142. }
  143. //fix spell scrolls
  144. if(auto * art = dynamic_cast<CGArtifact*>(obj.get()))
  145. {
  146. if(art->ID == Obj::SPELL_SCROLL && !art->storedArtifact)
  147. {
  148. std::vector<SpellID> out;
  149. for(auto const & spell : LIBRARY->spellh->objects) //spellh size appears to be greater (?)
  150. {
  151. //if(map->isAllowedSpell(spell->id))
  152. {
  153. out.push_back(spell->id);
  154. }
  155. }
  156. auto a = map->createScroll(*RandomGeneratorUtil::nextItem(out, CRandomGenerator::getDefault()));
  157. art->storedArtifact = a;
  158. }
  159. }
  160. //fix mines
  161. if(auto * mine = dynamic_cast<CGMine*>(obj.get()))
  162. {
  163. if(!mine->isAbandoned())
  164. {
  165. mine->producedResource = GameResID(mine->subID);
  166. mine->producedQuantity = mine->defaultResProduction();
  167. }
  168. }
  169. }
  170. }
  171. void MapController::setMap(std::unique_ptr<CMap> cmap)
  172. {
  173. _map = std::move(cmap);
  174. repairMap();
  175. for(int i : {0, 1})
  176. {
  177. _scenes[i].reset(new MapScene(i));
  178. _miniscenes[i].reset(new MinimapScene(i));
  179. }
  180. resetMapHandler();
  181. sceneForceUpdate();
  182. connectScenes();
  183. _map->getEditManager()->getUndoManager().setUndoCallback([this](bool allowUndo, bool allowRedo)
  184. {
  185. if(!main)
  186. return;
  187. main->enableUndo(allowUndo);
  188. main->enableRedo(allowRedo);
  189. }
  190. );
  191. _map->getEditManager()->getUndoManager().clearAll();
  192. initObstaclePainters(_map.get());
  193. }
  194. void MapController::initObstaclePainters(CMap * map)
  195. {
  196. for (auto const & terrain : LIBRARY->terrainTypeHandler->objects)
  197. {
  198. auto terrainId = terrain->getId();
  199. _obstaclePainters[terrainId] = std::make_unique<EditorObstaclePlacer>(map);
  200. _obstaclePainters[terrainId]->collectPossibleObstacles(terrainId);
  201. }
  202. }
  203. void MapController::sceneForceUpdate()
  204. {
  205. _scenes[0]->updateViews();
  206. _miniscenes[0]->updateViews();
  207. if(_map->twoLevel)
  208. {
  209. _scenes[1]->updateViews();
  210. _miniscenes[1]->updateViews();
  211. }
  212. }
  213. void MapController::sceneForceUpdate(int level)
  214. {
  215. _scenes[level]->updateViews();
  216. _miniscenes[level]->updateViews();
  217. }
  218. void MapController::resetMapHandler()
  219. {
  220. if(!_mapHandler)
  221. _mapHandler.reset(new MapHandler());
  222. _mapHandler->reset(map());
  223. for(int i : {0, 1})
  224. {
  225. _scenes[i]->initialize(*this);
  226. _miniscenes[i]->initialize(*this);
  227. }
  228. }
  229. void MapController::commitTerrainChange(int level, const TerrainId & terrain)
  230. {
  231. static const int terrainDecorationPercentageLevel = 10;
  232. std::vector<int3> v(_scenes[level]->selectionTerrainView.selection().begin(),
  233. _scenes[level]->selectionTerrainView.selection().end());
  234. if(v.empty())
  235. return;
  236. _scenes[level]->selectionTerrainView.clear();
  237. _scenes[level]->selectionTerrainView.draw();
  238. _map->getEditManager()->getTerrainSelection().setSelection(v);
  239. _map->getEditManager()->drawTerrain(terrain, terrainDecorationPercentageLevel, &CRandomGenerator::getDefault());
  240. for(auto & t : v)
  241. _scenes[level]->terrainView.setDirty(t);
  242. _scenes[level]->terrainView.draw();
  243. _miniscenes[level]->updateViews();
  244. main->mapChanged();
  245. }
  246. void MapController::commitRoadOrRiverChange(int level, ui8 type, bool isRoad)
  247. {
  248. std::vector<int3> v(_scenes[level]->selectionTerrainView.selection().begin(),
  249. _scenes[level]->selectionTerrainView.selection().end());
  250. if(v.empty())
  251. return;
  252. _scenes[level]->selectionTerrainView.clear();
  253. _scenes[level]->selectionTerrainView.draw();
  254. _map->getEditManager()->getTerrainSelection().setSelection(v);
  255. if(isRoad)
  256. _map->getEditManager()->drawRoad(RoadId(type), &CRandomGenerator::getDefault());
  257. else
  258. _map->getEditManager()->drawRiver(RiverId(type), &CRandomGenerator::getDefault());
  259. for(auto & t : v)
  260. _scenes[level]->terrainView.setDirty(t);
  261. _scenes[level]->terrainView.draw();
  262. _miniscenes[level]->updateViews();
  263. main->mapChanged();
  264. }
  265. void MapController::commitObjectErase(int level)
  266. {
  267. auto selectedObjects = _scenes[level]->selectionObjectsView.getSelection();
  268. if (selectedObjects.size() > 1)
  269. {
  270. //mass erase => undo in one operation
  271. _map->getEditManager()->removeObjects(selectedObjects);
  272. }
  273. else if (selectedObjects.size() == 1)
  274. {
  275. _map->getEditManager()->removeObject(*selectedObjects.begin());
  276. }
  277. else //nothing to erase - shouldn't be here
  278. {
  279. return;
  280. }
  281. for (auto & obj : selectedObjects)
  282. {
  283. //invalidate tiles under objects
  284. _mapHandler->removeObject(obj);
  285. _scenes[level]->objectsView.setDirty(obj);
  286. }
  287. _scenes[level]->selectionObjectsView.clear();
  288. _scenes[level]->objectsView.draw();
  289. _scenes[level]->selectionObjectsView.draw();
  290. _scenes[level]->passabilityView.update();
  291. _miniscenes[level]->updateViews();
  292. main->mapChanged();
  293. }
  294. void MapController::copyToClipboard(int level)
  295. {
  296. _clipboard.clear();
  297. _clipboardShiftIndex = 0;
  298. auto selectedObjects = _scenes[level]->selectionObjectsView.getSelection();
  299. for(auto * obj : selectedObjects)
  300. {
  301. assert(obj->pos.z == level);
  302. _clipboard.push_back(CMemorySerializer::deepCopy(*obj));
  303. }
  304. }
  305. void MapController::pasteFromClipboard(int level)
  306. {
  307. _scenes[level]->selectionObjectsView.clear();
  308. auto shift = int3::getDirs()[_clipboardShiftIndex++];
  309. if(_clipboardShiftIndex == int3::getDirs().size())
  310. _clipboardShiftIndex = 0;
  311. QStringList errors;
  312. for(auto & objUniquePtr : _clipboard)
  313. {
  314. auto obj = CMemorySerializer::deepCopyShared(*objUniquePtr);
  315. QString errorMsg;
  316. if (!canPlaceObject(level, obj.get(), errorMsg))
  317. {
  318. errors.push_back(std::move(errorMsg));
  319. continue;
  320. }
  321. auto newPos = objUniquePtr->pos + shift;
  322. if(_map->isInTheMap(newPos))
  323. obj->pos = newPos;
  324. obj->pos.z = level;
  325. Initializer init(*this, obj.get(), defaultPlayer);
  326. _map->getEditManager()->insertObject(obj);
  327. _scenes[level]->selectionObjectsView.selectObject(obj.get());
  328. _mapHandler->invalidate(obj.get());
  329. }
  330. if(!errors.isEmpty())
  331. QMessageBox::warning(main, QObject::tr("Can't place object"), errors.join('\n'));
  332. _scenes[level]->objectsView.draw();
  333. _scenes[level]->passabilityView.update();
  334. _scenes[level]->selectionObjectsView.draw();
  335. _miniscenes[level]->updateViews();
  336. main->mapChanged();
  337. }
  338. bool MapController::discardObject(int level) const
  339. {
  340. _scenes[level]->selectionObjectsView.clear();
  341. if(_scenes[level]->selectionObjectsView.newObject)
  342. {
  343. _scenes[level]->selectionObjectsView.newObject.reset();
  344. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  345. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  346. _scenes[level]->selectionObjectsView.draw();
  347. return true;
  348. }
  349. return false;
  350. }
  351. void MapController::createObject(int level, std::shared_ptr<CGObjectInstance> obj) const
  352. {
  353. _scenes[level]->selectionObjectsView.newObject = obj;
  354. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::MOVEMENT;
  355. _scenes[level]->selectionObjectsView.draw();
  356. }
  357. void MapController::commitObstacleFill(int level)
  358. {
  359. auto selection = _scenes[level]->selectionTerrainView.selection();
  360. if(selection.empty())
  361. return;
  362. //split by zones
  363. for (auto & painter : _obstaclePainters)
  364. {
  365. painter.second->clearBlockedArea();
  366. }
  367. for(auto & t : selection)
  368. {
  369. auto tl = _map->getTile(t);
  370. if(tl.blocked() || tl.visitable())
  371. continue;
  372. auto terrain = tl.getTerrainID();
  373. _obstaclePainters[terrain]->addBlockedTile(t);
  374. }
  375. for(auto & sel : _obstaclePainters)
  376. {
  377. for(auto o : sel.second->placeObstacles(CRandomGenerator::getDefault()))
  378. {
  379. _mapHandler->invalidate(o.get());
  380. _scenes[level]->objectsView.setDirty(o.get());
  381. }
  382. }
  383. _scenes[level]->selectionTerrainView.clear();
  384. _scenes[level]->selectionTerrainView.draw();
  385. _scenes[level]->objectsView.draw();
  386. _scenes[level]->passabilityView.update();
  387. _miniscenes[level]->updateViews();
  388. main->mapChanged();
  389. }
  390. void MapController::commitObjectChange(int level)
  391. {
  392. for( auto * o : _scenes[level]->selectionObjectsView.getSelection())
  393. _scenes[level]->objectsView.setDirty(o);
  394. _scenes[level]->objectsView.draw();
  395. _scenes[level]->selectionObjectsView.draw();
  396. _scenes[level]->passabilityView.update();
  397. _miniscenes[level]->updateViews();
  398. main->mapChanged();
  399. }
  400. void MapController::commitChangeWithoutRedraw()
  401. {
  402. //DO NOT REDRAW
  403. main->mapChanged();
  404. }
  405. void MapController::commitObjectShift(int level)
  406. {
  407. auto shift = _scenes[level]->selectionObjectsView.shift;
  408. bool makeShift = !shift.isNull();
  409. if(makeShift)
  410. {
  411. for(auto * obj : _scenes[level]->selectionObjectsView.getSelection())
  412. {
  413. int3 pos = obj->pos;
  414. pos.z = level;
  415. pos.x += shift.x(); pos.y += shift.y();
  416. _scenes[level]->objectsView.setDirty(obj); //set dirty before movement
  417. _map->getEditManager()->moveObject(obj, pos);
  418. _mapHandler->invalidate(obj);
  419. }
  420. }
  421. _scenes[level]->selectionObjectsView.newObject = nullptr;
  422. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  423. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  424. if(makeShift)
  425. {
  426. _scenes[level]->objectsView.draw();
  427. _scenes[level]->selectionObjectsView.draw();
  428. _scenes[level]->passabilityView.update();
  429. _miniscenes[level]->updateViews();
  430. main->mapChanged();
  431. }
  432. }
  433. void MapController::commitObjectCreate(int level)
  434. {
  435. auto newObj = _scenes[level]->selectionObjectsView.newObject;
  436. if(!newObj)
  437. return;
  438. auto shift = _scenes[level]->selectionObjectsView.shift;
  439. int3 pos = newObj->pos;
  440. pos.z = level;
  441. pos.x += shift.x(); pos.y += shift.y();
  442. newObj->pos = pos;
  443. Initializer init(*this, newObj.get(), defaultPlayer);
  444. _map->getEditManager()->insertObject(newObj);
  445. _mapHandler->invalidate(newObj.get());
  446. _scenes[level]->objectsView.setDirty(newObj.get());
  447. _scenes[level]->selectionObjectsView.newObject = nullptr;
  448. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  449. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  450. _scenes[level]->objectsView.draw();
  451. _scenes[level]->selectionObjectsView.draw();
  452. _scenes[level]->passabilityView.update();
  453. _miniscenes[level]->updateViews();
  454. main->mapChanged();
  455. }
  456. bool MapController::canPlaceObject(int level, CGObjectInstance * newObj, QString & error) const
  457. {
  458. //find all objects of such type
  459. int objCounter = 0;
  460. for(auto o : _map->objects)
  461. {
  462. if(o->ID == newObj->ID && o->subID == newObj->subID)
  463. {
  464. ++objCounter;
  465. }
  466. }
  467. if(newObj->ID == Obj::GRAIL && objCounter >= 1) //special case for grail
  468. {
  469. error = QObject::tr("There can only be one grail object on the map.");
  470. return false; //maplimit reached
  471. }
  472. if(defaultPlayer == PlayerColor::NEUTRAL && (newObj->ID == Obj::HERO || newObj->ID == Obj::RANDOM_HERO))
  473. {
  474. error = QObject::tr("Hero %1 cannot be created as NEUTRAL.").arg(QString::fromStdString(newObj->instanceName));
  475. return false;
  476. }
  477. return true;
  478. }
  479. void MapController::undo()
  480. {
  481. _map->getEditManager()->getUndoManager().undo();
  482. resetMapHandler();
  483. sceneForceUpdate(); //TODO: use smart invalidation (setDirty)
  484. main->mapChanged();
  485. }
  486. void MapController::redo()
  487. {
  488. _map->getEditManager()->getUndoManager().redo();
  489. resetMapHandler();
  490. sceneForceUpdate(); //TODO: use smart invalidation (setDirty)
  491. main->mapChanged();
  492. }
  493. ModCompatibilityInfo MapController::modAssessmentAll()
  494. {
  495. ModCompatibilityInfo result;
  496. for(auto primaryID : LIBRARY->objtypeh->knownObjects())
  497. {
  498. for(auto secondaryID : LIBRARY->objtypeh->knownSubObjects(primaryID))
  499. {
  500. auto handler = LIBRARY->objtypeh->getHandlerFor(primaryID, secondaryID);
  501. auto modName = QString::fromStdString(handler->getJsonKey()).split(":").at(0).toStdString();
  502. if(modName != "core")
  503. result[modName] = LIBRARY->modh->getModInfo(modName).getVerificationInfo();
  504. }
  505. }
  506. return result;
  507. }
  508. ModCompatibilityInfo MapController::modAssessmentMap(const CMap & map)
  509. {
  510. ModCompatibilityInfo result;
  511. auto extractEntityMod = [&result](const auto & entity)
  512. {
  513. auto modScope = entity->getModScope();
  514. if(modScope != "core")
  515. result[modScope] = LIBRARY->modh->getModInfo(modScope).getVerificationInfo();
  516. };
  517. for(auto obj : map.objects)
  518. {
  519. auto handler = obj->getObjectHandler();
  520. auto modScope = handler->getModScope();
  521. if(modScope != "core")
  522. result[modScope] = LIBRARY->modh->getModInfo(modScope).getVerificationInfo();
  523. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  524. {
  525. auto town = dynamic_cast<CGTownInstance *>(obj.get());
  526. for(const auto & spellID : town->possibleSpells)
  527. {
  528. if(spellID == SpellID::PRESET)
  529. continue;
  530. extractEntityMod(spellID.toEntity(LIBRARY));
  531. }
  532. for(const auto & spellID : town->obligatorySpells)
  533. {
  534. extractEntityMod(spellID.toEntity(LIBRARY));
  535. }
  536. }
  537. if(obj->ID == Obj::HERO || obj->ID == Obj::RANDOM_HERO)
  538. {
  539. auto hero = dynamic_cast<CGHeroInstance *>(obj.get());
  540. for(const auto & spellID : hero->getSpellsInSpellbook())
  541. {
  542. if(spellID == SpellID::PRESET || spellID == SpellID::SPELLBOOK_PRESET)
  543. continue;
  544. extractEntityMod(spellID.toEntity(LIBRARY));
  545. }
  546. for(const auto & [_, slotInfo] : hero->artifactsWorn)
  547. {
  548. extractEntityMod(slotInfo.artifact->getTypeId().toEntity(LIBRARY));
  549. }
  550. for(const auto & art : hero->artifactsInBackpack)
  551. {
  552. extractEntityMod(art.artifact->getTypeId().toEntity(LIBRARY));
  553. }
  554. }
  555. }
  556. //TODO: terrains?
  557. return result;
  558. }