mapcontroller.cpp 17 KB

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