CMapOperation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*
  2. * CMapOperation.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 "CMapOperation.h"
  12. #include "../VCMI_Lib.h"
  13. #include "CMap.h"
  14. #include "MapEditUtils.h"
  15. CMapOperation::CMapOperation(CMap* map) : map(map)
  16. {
  17. }
  18. std::string CMapOperation::getLabel() const
  19. {
  20. return "";
  21. }
  22. MapRect CMapOperation::extendTileAround(const int3& centerPos) const
  23. {
  24. return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
  25. }
  26. MapRect CMapOperation::extendTileAroundSafely(const int3& centerPos) const
  27. {
  28. return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
  29. }
  30. CComposedOperation::CComposedOperation(CMap* map) : CMapOperation(map)
  31. {
  32. }
  33. void CComposedOperation::execute()
  34. {
  35. for(auto & operation : operations)
  36. {
  37. operation->execute();
  38. }
  39. }
  40. void CComposedOperation::undo()
  41. {
  42. //reverse order
  43. for(auto operation = operations.rbegin(); operation != operations.rend(); operation++)
  44. {
  45. operation->get()->undo();
  46. }
  47. }
  48. void CComposedOperation::redo()
  49. {
  50. for(auto & operation : operations)
  51. {
  52. operation->redo();
  53. }
  54. }
  55. std::string CComposedOperation::getLabel() const
  56. {
  57. std::string ret = "Composed operation: ";
  58. for(auto & operation : operations)
  59. {
  60. ret.append(operation->getLabel() + ";");
  61. }
  62. return ret;
  63. }
  64. void CComposedOperation::addOperation(std::unique_ptr<CMapOperation>&& operation)
  65. {
  66. operations.push_back(std::move(operation));
  67. }
  68. CDrawTerrainOperation::CDrawTerrainOperation(CMap* map, const CTerrainSelection& terrainSel, TTerrainId terType, CRandomGenerator* gen):
  69. CMapOperation(map),
  70. terrainSel(terrainSel),
  71. terType(terType),
  72. gen(gen)
  73. {
  74. }
  75. void CDrawTerrainOperation::execute()
  76. {
  77. for(const auto & pos : terrainSel.getSelectedItems())
  78. {
  79. auto & tile = map->getTile(pos);
  80. tile.terType = VLC->terrainTypeHandler->terrains()[terType];
  81. invalidateTerrainViews(pos);
  82. }
  83. updateTerrainTypes();
  84. updateTerrainViews();
  85. }
  86. void CDrawTerrainOperation::undo()
  87. {
  88. //TODO
  89. }
  90. void CDrawTerrainOperation::redo()
  91. {
  92. //TODO
  93. }
  94. std::string CDrawTerrainOperation::getLabel() const
  95. {
  96. return "Draw Terrain";
  97. }
  98. void CDrawTerrainOperation::updateTerrainTypes()
  99. {
  100. auto positions = terrainSel.getSelectedItems();
  101. while(!positions.empty())
  102. {
  103. const auto & centerPos = *(positions.begin());
  104. auto centerTile = map->getTile(centerPos);
  105. //logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
  106. auto tiles = getInvalidTiles(centerPos);
  107. auto updateTerrainType = [&](const int3& pos)
  108. {
  109. map->getTile(pos).terType = centerTile.terType;
  110. positions.insert(pos);
  111. invalidateTerrainViews(pos);
  112. //logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
  113. };
  114. // Fill foreign invalid tiles
  115. for(const auto & tile : tiles.foreignTiles)
  116. {
  117. updateTerrainType(tile);
  118. }
  119. tiles = getInvalidTiles(centerPos);
  120. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  121. {
  122. // Blow up
  123. auto rect = extendTileAroundSafely(centerPos);
  124. std::set<int3> suitableTiles;
  125. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  126. bool centerPosValid = false;
  127. rect.forEach([&](const int3& posToTest)
  128. {
  129. auto & terrainTile = map->getTile(posToTest);
  130. if(centerTile.terType->id != terrainTile.terType->id)
  131. {
  132. auto formerTerType = terrainTile.terType;
  133. terrainTile.terType = centerTile.terType;
  134. auto testTile = getInvalidTiles(posToTest);
  135. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : (int)testTile.nativeTiles.size();
  136. bool putSuitableTile = false;
  137. bool addToSuitableTiles = false;
  138. if(testTile.centerPosValid)
  139. {
  140. if(!centerPosValid)
  141. {
  142. centerPosValid = true;
  143. putSuitableTile = true;
  144. }
  145. else
  146. {
  147. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  148. {
  149. putSuitableTile = true;
  150. }
  151. else
  152. {
  153. addToSuitableTiles = true;
  154. }
  155. }
  156. }
  157. else if(!centerPosValid)
  158. {
  159. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  160. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  161. {
  162. putSuitableTile = true;
  163. }
  164. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  165. {
  166. addToSuitableTiles = true;
  167. }
  168. }
  169. if(putSuitableTile)
  170. {
  171. //if(!suitableTiles.empty())
  172. //{
  173. // logGlobal->debug("Clear suitables tiles.");
  174. //}
  175. invalidNativeTilesCnt = nativeTilesCntNorm;
  176. invalidForeignTilesCnt = static_cast<int>(testTile.foreignTiles.size());
  177. suitableTiles.clear();
  178. addToSuitableTiles = true;
  179. }
  180. if(addToSuitableTiles)
  181. {
  182. suitableTiles.insert(posToTest);
  183. }
  184. terrainTile.terType = formerTerType;
  185. }
  186. });
  187. if(suitableTiles.size() == 1)
  188. {
  189. updateTerrainType(*suitableTiles.begin());
  190. }
  191. else
  192. {
  193. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  194. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0) };
  195. for(auto & direction : directions)
  196. {
  197. auto it = suitableTiles.find(centerPos + direction);
  198. if (it != suitableTiles.end())
  199. {
  200. updateTerrainType(*it);
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. else
  207. {
  208. // add invalid native tiles which are not in the positions list
  209. for(const auto & nativeTile : tiles.nativeTiles)
  210. {
  211. if (positions.find(nativeTile) == positions.end())
  212. {
  213. positions.insert(nativeTile);
  214. }
  215. }
  216. positions.erase(centerPos);
  217. }
  218. }
  219. }
  220. void CDrawTerrainOperation::updateTerrainViews()
  221. {
  222. for(const auto & pos : invalidatedTerViews)
  223. {
  224. const auto & patterns = VLC->terviewh->getTerrainViewPatterns(map->getTile(pos).terType->id);
  225. // Detect a pattern which fits best
  226. int bestPattern = -1;
  227. ValidationResult valRslt(false);
  228. for(int k = 0; k < patterns.size(); ++k)
  229. {
  230. const auto & pattern = patterns[k];
  231. //(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
  232. valRslt = validateTerrainView(pos, &pattern);
  233. if (valRslt.result)
  234. {
  235. bestPattern = k;
  236. break;
  237. }
  238. }
  239. //assert(bestPattern != -1);
  240. if(bestPattern == -1)
  241. {
  242. // This shouldn't be the case
  243. logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
  244. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  245. continue;
  246. }
  247. // Get mapping
  248. const TerrainViewPattern& pattern = patterns[bestPattern][valRslt.flip];
  249. std::pair<int, int> mapping;
  250. if(valRslt.transitionReplacement.empty())
  251. {
  252. mapping = pattern.mapping[0];
  253. }
  254. else
  255. {
  256. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  257. }
  258. // Set terrain view
  259. auto & tile = map->getTile(pos);
  260. if(!pattern.diffImages)
  261. {
  262. tile.terView = gen->nextInt(mapping.first, mapping.second);
  263. tile.extTileFlags = valRslt.flip;
  264. }
  265. else
  266. {
  267. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  268. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  269. int firstFrame = mapping.first + flip * framesPerRot;
  270. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  271. tile.extTileFlags = 0;
  272. }
  273. }
  274. }
  275. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3& pos, const std::vector<TerrainViewPattern>* pattern, int recDepth) const
  276. {
  277. for(int flip = 0; flip < 4; ++flip)
  278. {
  279. auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
  280. if(valRslt.result)
  281. {
  282. valRslt.flip = flip;
  283. return valRslt;
  284. }
  285. }
  286. return ValidationResult(false);
  287. }
  288. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3& pos, const TerrainViewPattern& pattern, int recDepth) const
  289. {
  290. auto centerTerType = map->getTile(pos).terType;
  291. int totalPoints = 0;
  292. std::string transitionReplacement;
  293. for(int i = 0; i < 9; ++i)
  294. {
  295. // The center, middle cell can be skipped
  296. if(i == 4)
  297. {
  298. continue;
  299. }
  300. // Get terrain group of the current cell
  301. int cx = pos.x + (i % 3) - 1;
  302. int cy = pos.y + (i / 3) - 1;
  303. int3 currentPos(cx, cy, pos.z);
  304. bool isAlien = false;
  305. TerrainType * terType = nullptr;
  306. if(!map->isInTheMap(currentPos))
  307. {
  308. // position is not in the map, so take the ter type from the neighbor tile
  309. bool widthTooHigh = currentPos.x >= map->width;
  310. bool widthTooLess = currentPos.x < 0;
  311. bool heightTooHigh = currentPos.y >= map->height;
  312. bool heightTooLess = currentPos.y < 0;
  313. if((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  314. {
  315. terType = centerTerType;
  316. }
  317. else if(widthTooHigh)
  318. {
  319. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  320. }
  321. else if(heightTooHigh)
  322. {
  323. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  324. }
  325. else if(widthTooLess)
  326. {
  327. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  328. }
  329. else if(heightTooLess)
  330. {
  331. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  332. }
  333. }
  334. else
  335. {
  336. terType = map->getTile(currentPos).terType;
  337. if(terType != centerTerType && (terType->isPassable() || centerTerType->isPassable()))
  338. {
  339. isAlien = true;
  340. }
  341. }
  342. // Validate all rules per cell
  343. int topPoints = -1;
  344. for(auto & elem : pattern.data[i])
  345. {
  346. TerrainViewPattern::WeightedRule rule = elem;
  347. if(!rule.isStandardRule())
  348. {
  349. if(recDepth == 0 && map->isInTheMap(currentPos))
  350. {
  351. if(terType->id == centerTerType->id)
  352. {
  353. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType->id, rule.name);
  354. if(auto p = patternForRule)
  355. {
  356. auto rslt = validateTerrainView(currentPos, &(*p), 1);
  357. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  358. }
  359. }
  360. continue;
  361. }
  362. else
  363. {
  364. rule.setNative();
  365. }
  366. }
  367. auto applyValidationRslt = [&](bool rslt)
  368. {
  369. if(rslt)
  370. {
  371. topPoints = std::max(topPoints, rule.points);
  372. }
  373. };
  374. // Validate cell with the ruleset of the pattern
  375. bool nativeTestOk, nativeTestStrongOk;
  376. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  377. if(centerTerType->id == Terrain::DIRT)
  378. {
  379. nativeTestOk = rule.isNativeRule() && !terType->isTransitionRequired();
  380. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  381. && terType->isTransitionRequired();
  382. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  383. }
  384. else if(centerTerType->id == Terrain::SAND)
  385. {
  386. applyValidationRslt(true);
  387. }
  388. else if(centerTerType->isTransitionRequired()) //water, rock and some special terrains require sand transition
  389. {
  390. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  391. && isAlien;
  392. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  393. }
  394. else
  395. {
  396. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  397. && isAlien && !terType->isTransitionRequired();
  398. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  399. && terType->isTransitionRequired();
  400. if(transitionReplacement.empty() && rule.isTransition()
  401. && (dirtTestOk || sandTestOk))
  402. {
  403. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  404. }
  405. if(rule.isTransition())
  406. {
  407. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  408. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  409. }
  410. else
  411. {
  412. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  413. }
  414. }
  415. }
  416. if(topPoints == -1)
  417. {
  418. return ValidationResult(false);
  419. }
  420. else
  421. {
  422. totalPoints += topPoints;
  423. }
  424. }
  425. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  426. {
  427. return ValidationResult(true, transitionReplacement);
  428. }
  429. else
  430. {
  431. return ValidationResult(false);
  432. }
  433. }
  434. void CDrawTerrainOperation::invalidateTerrainViews(const int3& centerPos)
  435. {
  436. auto rect = extendTileAroundSafely(centerPos);
  437. rect.forEach([&](const int3& pos)
  438. {
  439. invalidatedTerViews.insert(pos);
  440. });
  441. }
  442. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3& centerPos) const
  443. {
  444. //TODO: this is very expensive function for RMG, needs optimization
  445. InvalidTiles tiles;
  446. auto centerTerType = map->getTile(centerPos).terType;
  447. auto rect = extendTileAround(centerPos);
  448. rect.forEach([&](const int3& pos)
  449. {
  450. if(map->isInTheMap(pos))
  451. {
  452. auto ptrConfig = VLC->terviewh;
  453. auto terType = map->getTile(pos).terType;
  454. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  455. // Special validity check for rock & water
  456. if(valid && (terType->isWater() || !terType->isPassable()))
  457. {
  458. static const std::string patternIds[] = { "s1", "s2" };
  459. for(auto & patternId : patternIds)
  460. {
  461. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  462. if(!valid) break;
  463. }
  464. }
  465. // Additional validity check for non rock OR water
  466. else if(!valid && (terType->isLand() && terType->isPassable()))
  467. {
  468. static const std::string patternIds[] = { "n2", "n3" };
  469. for (auto & patternId : patternIds)
  470. {
  471. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  472. if(valid) break;
  473. }
  474. }
  475. if(!valid)
  476. {
  477. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  478. else tiles.foreignTiles.insert(pos);
  479. }
  480. else if(centerPos == pos)
  481. {
  482. tiles.centerPosValid = true;
  483. }
  484. }
  485. });
  486. return tiles;
  487. }
  488. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string& transitionReplacement)
  489. : result(result), transitionReplacement(transitionReplacement), flip(0)
  490. {
  491. }
  492. CClearTerrainOperation::CClearTerrainOperation(CMap* map, CRandomGenerator* gen) : CComposedOperation(map)
  493. {
  494. CTerrainSelection terrainSel(map);
  495. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  496. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain::WATER, gen));
  497. if(map->twoLevel)
  498. {
  499. terrainSel.clearSelection();
  500. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  501. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain::ROCK, gen));
  502. }
  503. }
  504. std::string CClearTerrainOperation::getLabel() const
  505. {
  506. return "Clear Terrain";
  507. }
  508. CInsertObjectOperation::CInsertObjectOperation(CMap* map, CGObjectInstance* obj)
  509. : CMapOperation(map), obj(obj)
  510. {
  511. }
  512. void CInsertObjectOperation::execute()
  513. {
  514. obj->id = ObjectInstanceID(map->objects.size());
  515. do
  516. {
  517. map->setUniqueInstanceName(obj);
  518. } while(vstd::contains(map->instanceNames, obj->instanceName));
  519. map->addNewObject(obj);
  520. }
  521. void CInsertObjectOperation::undo()
  522. {
  523. map->removeObject(obj);
  524. }
  525. void CInsertObjectOperation::redo()
  526. {
  527. execute();
  528. }
  529. std::string CInsertObjectOperation::getLabel() const
  530. {
  531. return "Insert Object";
  532. }
  533. CMoveObjectOperation::CMoveObjectOperation(CMap* map, CGObjectInstance* obj, const int3& targetPosition)
  534. : CMapOperation(map),
  535. obj(obj),
  536. initialPos(obj->pos),
  537. targetPos(targetPosition)
  538. {
  539. }
  540. void CMoveObjectOperation::execute()
  541. {
  542. map->moveObject(obj, targetPos);
  543. }
  544. void CMoveObjectOperation::undo()
  545. {
  546. map->moveObject(obj, initialPos);
  547. }
  548. void CMoveObjectOperation::redo()
  549. {
  550. execute();
  551. }
  552. std::string CMoveObjectOperation::getLabel() const
  553. {
  554. return "Move Object";
  555. }
  556. CRemoveObjectOperation::CRemoveObjectOperation(CMap* map, CGObjectInstance* obj)
  557. : CMapOperation(map), obj(obj)
  558. {
  559. }
  560. CRemoveObjectOperation::~CRemoveObjectOperation()
  561. {
  562. //when operation is destroyed and wasn't undone, the object is lost forever
  563. if(!obj)
  564. {
  565. return;
  566. }
  567. //do not destroy an object that belongs to map
  568. if(!vstd::contains(map->instanceNames, obj->instanceName))
  569. {
  570. delete obj;
  571. obj = nullptr;
  572. }
  573. }
  574. void CRemoveObjectOperation::execute()
  575. {
  576. map->removeObject(obj);
  577. }
  578. void CRemoveObjectOperation::undo()
  579. {
  580. try
  581. {
  582. //set new id, but do not rename object
  583. obj->id = ObjectInstanceID((si32)map->objects.size());
  584. map->addNewObject(obj);
  585. }
  586. catch(const std::exception& e)
  587. {
  588. logGlobal->error(e.what());
  589. }
  590. }
  591. void CRemoveObjectOperation::redo()
  592. {
  593. execute();
  594. }
  595. std::string CRemoveObjectOperation::getLabel() const
  596. {
  597. return "Remove Object";
  598. }