CMapOperation.cpp 17 KB

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