CMapOperation.cpp 17 KB

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