CMapOperation.cpp 17 KB

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