CMapOperation.cpp 17 KB

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