CMapOperation.cpp 17 KB

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