CMapEditManager.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. #include "StdInc.h"
  2. #include "CMapEditManager.h"
  3. #include "../JsonNode.h"
  4. #include "../filesystem/Filesystem.h"
  5. #include "../CDefObjInfoHandler.h"
  6. #include "../VCMI_Lib.h"
  7. MapRect::MapRect() : x(0), y(0), z(0), width(0), height(0)
  8. {
  9. }
  10. MapRect::MapRect(int3 pos, si32 width, si32 height) : x(pos.x), y(pos.y), z(pos.z), width(width), height(height)
  11. {
  12. }
  13. MapRect MapRect::operator&(const MapRect & rect) const
  14. {
  15. bool intersect = right() > rect.left() && rect.right() > left() &&
  16. bottom() > rect.top() && rect.bottom() > top() &&
  17. z == rect.z;
  18. if(intersect)
  19. {
  20. MapRect ret;
  21. ret.x = std::max(left(), rect.left());
  22. ret.y = std::max(top(), rect.top());
  23. ret.z = rect.z;
  24. ret.width = std::min(right(), rect.right()) - ret.x;
  25. ret.height = std::min(bottom(), rect.bottom()) - ret.y;
  26. return ret;
  27. }
  28. else
  29. {
  30. return MapRect();
  31. }
  32. }
  33. si32 MapRect::left() const
  34. {
  35. return x;
  36. }
  37. si32 MapRect::right() const
  38. {
  39. return x + width;
  40. }
  41. si32 MapRect::top() const
  42. {
  43. return y;
  44. }
  45. si32 MapRect::bottom() const
  46. {
  47. return y + height;
  48. }
  49. int3 MapRect::topLeft() const
  50. {
  51. return int3(x, y, z);
  52. }
  53. int3 MapRect::topRight() const
  54. {
  55. return int3(right(), y, z);
  56. }
  57. int3 MapRect::bottomLeft() const
  58. {
  59. return int3(x, bottom(), z);
  60. }
  61. int3 MapRect::bottomRight() const
  62. {
  63. return int3(right(), bottom(), z);
  64. }
  65. CTerrainSelection::CTerrainSelection(CMap * map) : CMapSelection(map)
  66. {
  67. }
  68. void CTerrainSelection::selectRange(const MapRect & rect)
  69. {
  70. rect.forEach([this](const int3 pos)
  71. {
  72. this->select(pos);
  73. });
  74. }
  75. void CTerrainSelection::deselectRange(const MapRect & rect)
  76. {
  77. rect.forEach([this](const int3 pos)
  78. {
  79. this->deselect(pos);
  80. });
  81. }
  82. void CTerrainSelection::selectAll()
  83. {
  84. selectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
  85. selectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
  86. }
  87. void CTerrainSelection::clearSelection()
  88. {
  89. deselectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
  90. deselectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
  91. }
  92. CObjectSelection::CObjectSelection(CMap * map) : CMapSelection(map)
  93. {
  94. }
  95. CMapOperation::CMapOperation(CMap * map) : map(map)
  96. {
  97. }
  98. std::string CMapOperation::getLabel() const
  99. {
  100. return "";
  101. }
  102. CMapUndoManager::CMapUndoManager() : undoRedoLimit(10)
  103. {
  104. }
  105. void CMapUndoManager::undo()
  106. {
  107. doOperation(undoStack, redoStack, true);
  108. }
  109. void CMapUndoManager::redo()
  110. {
  111. doOperation(redoStack, undoStack, false);
  112. }
  113. void CMapUndoManager::clearAll()
  114. {
  115. undoStack.clear();
  116. redoStack.clear();
  117. }
  118. int CMapUndoManager::getUndoRedoLimit() const
  119. {
  120. return undoRedoLimit;
  121. }
  122. void CMapUndoManager::setUndoRedoLimit(int value)
  123. {
  124. assert(value >= 0);
  125. undoStack.resize(std::min(undoStack.size(), static_cast<TStack::size_type>(value)));
  126. redoStack.resize(std::min(redoStack.size(), static_cast<TStack::size_type>(value)));
  127. }
  128. const CMapOperation * CMapUndoManager::peekRedo() const
  129. {
  130. return peek(redoStack);
  131. }
  132. const CMapOperation * CMapUndoManager::peekUndo() const
  133. {
  134. return peek(undoStack);
  135. }
  136. void CMapUndoManager::addOperation(unique_ptr<CMapOperation> && operation)
  137. {
  138. undoStack.push_front(std::move(operation));
  139. if(undoStack.size() > undoRedoLimit) undoStack.pop_back();
  140. redoStack.clear();
  141. }
  142. void CMapUndoManager::doOperation(TStack & fromStack, TStack & toStack, bool doUndo)
  143. {
  144. if(fromStack.empty()) return;
  145. auto & operation = fromStack.front();
  146. if(doUndo)
  147. {
  148. operation->undo();
  149. }
  150. else
  151. {
  152. operation->redo();
  153. }
  154. toStack.push_front(std::move(operation));
  155. fromStack.pop_front();
  156. }
  157. const CMapOperation * CMapUndoManager::peek(const TStack & stack) const
  158. {
  159. if(stack.empty()) return nullptr;
  160. return stack.front().get();
  161. }
  162. CMapEditManager::CMapEditManager(CMap * map)
  163. : map(map), terrainSel(map), objectSel(map)
  164. {
  165. }
  166. CMap * CMapEditManager::getMap()
  167. {
  168. return map;
  169. }
  170. void CMapEditManager::clearTerrain(CRandomGenerator * gen/* = nullptr*/)
  171. {
  172. execute(make_unique<CClearTerrainOperation>(map, gen ? gen : &(this->gen)));
  173. }
  174. void CMapEditManager::drawTerrain(ETerrainType terType, CRandomGenerator * gen/* = nullptr*/)
  175. {
  176. execute(make_unique<CDrawTerrainOperation>(map, terrainSel, terType, gen ? gen : &(this->gen)));
  177. terrainSel.clearSelection();
  178. }
  179. void CMapEditManager::insertObject(CGObjectInstance * obj, const int3 & pos)
  180. {
  181. execute(make_unique<CInsertObjectOperation>(map, obj, pos));
  182. }
  183. void CMapEditManager::execute(unique_ptr<CMapOperation> && operation)
  184. {
  185. operation->execute();
  186. undoManager.addOperation(std::move(operation));
  187. }
  188. CTerrainSelection & CMapEditManager::getTerrainSelection()
  189. {
  190. return terrainSel;
  191. }
  192. CObjectSelection & CMapEditManager::getObjectSelection()
  193. {
  194. return objectSel;
  195. }
  196. CMapUndoManager & CMapEditManager::getUndoManager()
  197. {
  198. return undoManager;
  199. }
  200. CComposedOperation::CComposedOperation(CMap * map) : CMapOperation(map)
  201. {
  202. }
  203. void CComposedOperation::execute()
  204. {
  205. for(auto & operation : operations)
  206. {
  207. operation->execute();
  208. }
  209. }
  210. void CComposedOperation::undo()
  211. {
  212. for(auto & operation : operations)
  213. {
  214. operation->undo();
  215. }
  216. }
  217. void CComposedOperation::redo()
  218. {
  219. for(auto & operation : operations)
  220. {
  221. operation->redo();
  222. }
  223. }
  224. void CComposedOperation::addOperation(unique_ptr<CMapOperation> && operation)
  225. {
  226. operations.push_back(std::move(operation));
  227. }
  228. const std::string TerrainViewPattern::FLIP_MODE_DIFF_IMAGES = "D";
  229. const std::string TerrainViewPattern::RULE_DIRT = "D";
  230. const std::string TerrainViewPattern::RULE_SAND = "S";
  231. const std::string TerrainViewPattern::RULE_TRANSITION = "T";
  232. const std::string TerrainViewPattern::RULE_NATIVE = "N";
  233. const std::string TerrainViewPattern::RULE_NATIVE_STRONG = "N!";
  234. const std::string TerrainViewPattern::RULE_ANY = "?";
  235. TerrainViewPattern::TerrainViewPattern() : diffImages(false), rotationTypesCount(0), minPoints(0)
  236. {
  237. maxPoints = std::numeric_limits<int>::max();
  238. }
  239. TerrainViewPattern::WeightedRule::WeightedRule() : points(0)
  240. {
  241. }
  242. bool TerrainViewPattern::WeightedRule::isStandardRule() const
  243. {
  244. return TerrainViewPattern::RULE_ANY == name || TerrainViewPattern::RULE_DIRT == name
  245. || TerrainViewPattern::RULE_NATIVE == name || TerrainViewPattern::RULE_SAND == name
  246. || TerrainViewPattern::RULE_TRANSITION == name || TerrainViewPattern::RULE_NATIVE_STRONG == name;
  247. }
  248. CTerrainViewPatternConfig::CTerrainViewPatternConfig()
  249. {
  250. const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
  251. static const std::string patternTypes[] = { "terrainView", "terrainType" };
  252. for(int i = 0; i < ARRAY_COUNT(patternTypes); ++i)
  253. {
  254. const auto & patternsVec = config[patternTypes[i]].Vector();
  255. for(const auto & ptrnNode : patternsVec)
  256. {
  257. TerrainViewPattern pattern;
  258. // Read pattern data
  259. const JsonVector & data = ptrnNode["data"].Vector();
  260. assert(data.size() == 9);
  261. for(int j = 0; j < data.size(); ++j)
  262. {
  263. std::string cell = data[j].String();
  264. boost::algorithm::erase_all(cell, " ");
  265. std::vector<std::string> rules;
  266. boost::split(rules, cell, boost::is_any_of(","));
  267. for(std::string ruleStr : rules)
  268. {
  269. std::vector<std::string> ruleParts;
  270. boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
  271. TerrainViewPattern::WeightedRule rule;
  272. rule.name = ruleParts[0];
  273. assert(!rule.name.empty());
  274. if(ruleParts.size() > 1)
  275. {
  276. rule.points = boost::lexical_cast<int>(ruleParts[1]);
  277. }
  278. pattern.data[j].push_back(rule);
  279. }
  280. }
  281. // Read various properties
  282. pattern.id = ptrnNode["id"].String();
  283. assert(!pattern.id.empty());
  284. pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
  285. pattern.maxPoints = static_cast<int>(ptrnNode["maxPoints"].Float());
  286. if(pattern.maxPoints == 0) pattern.maxPoints = std::numeric_limits<int>::max();
  287. // Read mapping
  288. if(i == 0)
  289. {
  290. const auto & mappingStruct = ptrnNode["mapping"].Struct();
  291. for(const auto & mappingPair : mappingStruct)
  292. {
  293. TerrainViewPattern terGroupPattern = pattern;
  294. auto mappingStr = mappingPair.second.String();
  295. boost::algorithm::erase_all(mappingStr, " ");
  296. auto colonIndex = mappingStr.find_first_of(":");
  297. const auto & flipMode = mappingStr.substr(0, colonIndex);
  298. terGroupPattern.diffImages = TerrainViewPattern::FLIP_MODE_DIFF_IMAGES == &(flipMode[flipMode.length() - 1]);
  299. if(terGroupPattern.diffImages)
  300. {
  301. terGroupPattern.rotationTypesCount = boost::lexical_cast<int>(flipMode.substr(0, flipMode.length() - 1));
  302. assert(terGroupPattern.rotationTypesCount == 2 || terGroupPattern.rotationTypesCount == 4);
  303. }
  304. mappingStr = mappingStr.substr(colonIndex + 1);
  305. std::vector<std::string> mappings;
  306. boost::split(mappings, mappingStr, boost::is_any_of(","));
  307. for(std::string mapping : mappings)
  308. {
  309. std::vector<std::string> range;
  310. boost::split(range, mapping, boost::is_any_of("-"));
  311. terGroupPattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
  312. boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
  313. }
  314. // Add pattern to the patterns map
  315. const auto & terGroup = getTerrainGroup(mappingPair.first);
  316. terrainViewPatterns[terGroup].push_back(terGroupPattern);
  317. }
  318. }
  319. else if(i == 1)
  320. {
  321. terrainTypePatterns[pattern.id] = pattern;
  322. }
  323. }
  324. }
  325. }
  326. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  327. {
  328. }
  329. ETerrainGroup::ETerrainGroup CTerrainViewPatternConfig::getTerrainGroup(const std::string & terGroup) const
  330. {
  331. static const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups
  332. = boost::assign::map_list_of("normal", ETerrainGroup::NORMAL)("dirt", ETerrainGroup::DIRT)
  333. ("sand", ETerrainGroup::SAND)("water", ETerrainGroup::WATER)("rock", ETerrainGroup::ROCK);
  334. auto it = terGroups.find(terGroup);
  335. if(it == terGroups.end()) throw std::runtime_error(boost::str(boost::format("Terrain group '%s' does not exist.") % terGroup));
  336. return it->second;
  337. }
  338. const std::vector<TerrainViewPattern> & CTerrainViewPatternConfig::getTerrainViewPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
  339. {
  340. return terrainViewPatterns.find(terGroup)->second;
  341. }
  342. boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  343. {
  344. const std::vector<TerrainViewPattern> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
  345. for(const TerrainViewPattern & pattern : groupPatterns)
  346. {
  347. if(id == pattern.id)
  348. {
  349. return boost::optional<const TerrainViewPattern &>(pattern);
  350. }
  351. }
  352. return boost::optional<const TerrainViewPattern &>();
  353. }
  354. const TerrainViewPattern & CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
  355. {
  356. auto it = terrainTypePatterns.find(id);
  357. assert(it != terrainTypePatterns.end());
  358. return it->second;
  359. }
  360. CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, ETerrainType terType, CRandomGenerator * gen)
  361. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  362. {
  363. }
  364. void CDrawTerrainOperation::execute()
  365. {
  366. for(const auto & pos : terrainSel.getSelectedItems())
  367. {
  368. auto & tile = map->getTile(pos);
  369. tile.terType = terType;
  370. invalidateTerrainViews(pos);
  371. }
  372. updateTerrainTypes();
  373. updateTerrainViews();
  374. //TODO add coastal bit to extTileFlags appropriately
  375. }
  376. void CDrawTerrainOperation::undo()
  377. {
  378. //TODO
  379. }
  380. void CDrawTerrainOperation::redo()
  381. {
  382. //TODO
  383. }
  384. std::string CDrawTerrainOperation::getLabel() const
  385. {
  386. return "Draw Terrain";
  387. }
  388. void CDrawTerrainOperation::updateTerrainTypes()
  389. {
  390. auto positions = terrainSel.getSelectedItems();
  391. while(!positions.empty())
  392. {
  393. const auto & centerPos = *(positions.begin());
  394. auto centerTile = map->getTile(centerPos);
  395. auto tiles = getInvalidTiles(centerPos);
  396. auto updateTerrainType = [&](const int3 & pos, bool tileRequiresValidation)
  397. {
  398. map->getTile(pos).terType = centerTile.terType;
  399. if(tileRequiresValidation) positions.insert(pos);
  400. invalidateTerrainViews(pos);
  401. logGlobal->debugStream() << boost::format("Update terrain tile at '%s' to type '%i'.") % pos % centerTile.terType;
  402. };
  403. // Fill foreign invalid tiles
  404. for(const auto & tile : tiles.foreignTiles)
  405. {
  406. updateTerrainType(tile, true);
  407. }
  408. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  409. {
  410. // Blow up
  411. auto rect = extendTileAroundSafely(centerPos);
  412. std::set<int3> suitableTiles;
  413. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  414. rect.forEach([&](const int3 & posToTest)
  415. {
  416. auto & terrainTile = map->getTile(posToTest);
  417. if(centerTile.terType != terrainTile.terType)
  418. {
  419. auto formerTerType = terrainTile.terType;
  420. terrainTile.terType = centerTile.terType;
  421. auto testTile = getInvalidTiles(posToTest);
  422. auto addToSuitableTiles = [&](const int3 & pos)
  423. {
  424. suitableTiles.insert(pos);
  425. logGlobal->debugStream() << boost::format(std::string("Found suitable tile '%s' for main tile '%s': ") +
  426. "Invalid native tiles '%i', invalid foreign tiles '%i'.") % pos % centerPos % testTile.nativeTiles.size() %
  427. testTile.foreignTiles.size();
  428. };
  429. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : testTile.nativeTiles.size();
  430. if(nativeTilesCntNorm > invalidNativeTilesCnt ||
  431. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  432. {
  433. invalidNativeTilesCnt = nativeTilesCntNorm;
  434. invalidForeignTilesCnt = testTile.foreignTiles.size();
  435. suitableTiles.clear();
  436. addToSuitableTiles(posToTest);
  437. }
  438. else if(nativeTilesCntNorm == invalidNativeTilesCnt &&
  439. testTile.foreignTiles.size() == invalidForeignTilesCnt)
  440. {
  441. addToSuitableTiles(posToTest);
  442. }
  443. terrainTile.terType = formerTerType;
  444. }
  445. });
  446. bool tileRequiresValidation = invalidForeignTilesCnt > 0;
  447. if(suitableTiles.size() == 1)
  448. {
  449. updateTerrainType(*suitableTiles.begin(), tileRequiresValidation);
  450. }
  451. else
  452. {
  453. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  454. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  455. for(auto & direction : directions)
  456. {
  457. auto it = suitableTiles.find(centerPos + direction);
  458. if(it != suitableTiles.end())
  459. {
  460. updateTerrainType(*it, tileRequiresValidation);
  461. break;
  462. }
  463. }
  464. }
  465. }
  466. else
  467. {
  468. positions.erase(centerPos);
  469. }
  470. }
  471. }
  472. void CDrawTerrainOperation::updateTerrainViews()
  473. {
  474. for(const auto & pos : invalidatedTerViews)
  475. {
  476. const auto & patterns =
  477. VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));
  478. // Detect a pattern which fits best
  479. int bestPattern = -1;
  480. ValidationResult valRslt(false);
  481. for(int k = 0; k < patterns.size(); ++k)
  482. {
  483. const auto & pattern = patterns[k];
  484. valRslt = validateTerrainView(pos, pattern);
  485. if(valRslt.result)
  486. {
  487. /*logGlobal->debugStream() << boost::format("Pattern detected at pos '%s': Pattern '%s', Flip '%i', Repl. '%s'.") %
  488. pos % pattern.id % valRslt.flip % valRslt.transitionReplacement;*/
  489. bestPattern = k;
  490. break;
  491. }
  492. }
  493. //assert(bestPattern != -1);
  494. if(bestPattern == -1)
  495. {
  496. // This shouldn't be the case
  497. logGlobal->warnStream() << boost::format("No pattern detected at pos '%s'.") % pos;
  498. continue;
  499. }
  500. // Get mapping
  501. const TerrainViewPattern & pattern = patterns[bestPattern];
  502. std::pair<int, int> mapping;
  503. if(valRslt.transitionReplacement.empty())
  504. {
  505. mapping = pattern.mapping[0];
  506. }
  507. else
  508. {
  509. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  510. }
  511. // Set terrain view
  512. auto & tile = map->getTile(pos);
  513. if(!pattern.diffImages)
  514. {
  515. tile.terView = gen->getInteger(mapping.first, mapping.second);
  516. tile.extTileFlags = valRslt.flip;
  517. }
  518. else
  519. {
  520. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  521. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  522. int firstFrame = mapping.first + flip * framesPerRot;
  523. tile.terView = gen->getInteger(firstFrame, firstFrame + framesPerRot - 1);
  524. tile.extTileFlags = 0;
  525. }
  526. }
  527. }
  528. ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  529. {
  530. switch(terType)
  531. {
  532. case ETerrainType::DIRT:
  533. return ETerrainGroup::DIRT;
  534. case ETerrainType::SAND:
  535. return ETerrainGroup::SAND;
  536. case ETerrainType::WATER:
  537. return ETerrainGroup::WATER;
  538. case ETerrainType::ROCK:
  539. return ETerrainGroup::ROCK;
  540. default:
  541. return ETerrainGroup::NORMAL;
  542. }
  543. }
  544. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  545. {
  546. for(int flip = 0; flip < 4; ++flip)
  547. {
  548. auto valRslt = validateTerrainViewInner(pos, flip > 0 ? getFlippedPattern(pattern, flip) : pattern, recDepth);
  549. if(valRslt.result)
  550. {
  551. valRslt.flip = flip;
  552. return valRslt;
  553. }
  554. }
  555. return ValidationResult(false);
  556. }
  557. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  558. {
  559. auto centerTerType = map->getTile(pos).terType;
  560. auto centerTerGroup = getTerrainGroup(centerTerType);
  561. int totalPoints = 0;
  562. std::string transitionReplacement;
  563. for(int i = 0; i < 9; ++i)
  564. {
  565. // The center, middle cell can be skipped
  566. if(i == 4)
  567. {
  568. continue;
  569. }
  570. // Get terrain group of the current cell
  571. int cx = pos.x + (i % 3) - 1;
  572. int cy = pos.y + (i / 3) - 1;
  573. int3 currentPos(cx, cy, pos.z);
  574. bool isAlien = false;
  575. ETerrainType terType;
  576. if(!map->isInTheMap(currentPos))
  577. {
  578. terType = centerTerType;
  579. }
  580. else
  581. {
  582. terType = map->getTile(currentPos).terType;
  583. if(terType != centerTerType)
  584. {
  585. isAlien = true;
  586. }
  587. }
  588. // Validate all rules per cell
  589. int topPoints = -1;
  590. for(auto & elem : pattern.data[i])
  591. {
  592. TerrainViewPattern::WeightedRule rule = elem;
  593. if(!rule.isStandardRule())
  594. {
  595. if(recDepth == 0 && map->isInTheMap(currentPos))
  596. {
  597. if(terType == centerTerType)
  598. {
  599. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternById(getTerrainGroup(centerTerType), rule.name);
  600. if(patternForRule)
  601. {
  602. auto rslt = validateTerrainView(currentPos, *patternForRule, 1);
  603. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  604. }
  605. }
  606. continue;
  607. }
  608. else
  609. {
  610. rule.name = TerrainViewPattern::RULE_NATIVE;
  611. }
  612. }
  613. auto applyValidationRslt = [&](bool rslt)
  614. {
  615. if(rslt)
  616. {
  617. topPoints = std::max(topPoints, rule.points);
  618. }
  619. };
  620. // Validate cell with the ruleset of the pattern
  621. bool nativeTestOk, nativeTestStrongOk;
  622. nativeTestOk = nativeTestStrongOk = (rule.name == TerrainViewPattern::RULE_NATIVE_STRONG || rule.name == TerrainViewPattern::RULE_NATIVE) && !isAlien;
  623. if(centerTerGroup == ETerrainGroup::NORMAL)
  624. {
  625. bool dirtTestOk = (rule.name == TerrainViewPattern::RULE_DIRT || rule.name == TerrainViewPattern::RULE_TRANSITION)
  626. && isAlien && !isSandType(terType);
  627. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  628. && isSandType(terType);
  629. if(transitionReplacement.empty() && rule.name == TerrainViewPattern::RULE_TRANSITION
  630. && (dirtTestOk || sandTestOk))
  631. {
  632. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  633. }
  634. if(rule.name == TerrainViewPattern::RULE_TRANSITION)
  635. {
  636. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  637. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  638. }
  639. else
  640. {
  641. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || dirtTestOk || sandTestOk || nativeTestOk);
  642. }
  643. }
  644. else if(centerTerGroup == ETerrainGroup::DIRT)
  645. {
  646. nativeTestOk = rule.name == TerrainViewPattern::RULE_NATIVE && !isSandType(terType);
  647. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  648. && isSandType(terType);
  649. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk || nativeTestStrongOk);
  650. }
  651. else if(centerTerGroup == ETerrainGroup::SAND)
  652. {
  653. applyValidationRslt(true);
  654. }
  655. else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
  656. {
  657. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  658. && isAlien;
  659. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk);
  660. }
  661. }
  662. if(topPoints == -1)
  663. {
  664. return ValidationResult(false);
  665. }
  666. else
  667. {
  668. totalPoints += topPoints;
  669. }
  670. }
  671. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  672. {
  673. return ValidationResult(true, transitionReplacement);
  674. }
  675. else
  676. {
  677. return ValidationResult(false);
  678. }
  679. }
  680. bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
  681. {
  682. switch(terType)
  683. {
  684. case ETerrainType::WATER:
  685. case ETerrainType::SAND:
  686. case ETerrainType::ROCK:
  687. return true;
  688. default:
  689. return false;
  690. }
  691. }
  692. TerrainViewPattern CDrawTerrainOperation::getFlippedPattern(const TerrainViewPattern & pattern, int flip) const
  693. {
  694. if(flip == 0)
  695. {
  696. return pattern;
  697. }
  698. TerrainViewPattern ret = pattern;
  699. if(flip == FLIP_PATTERN_HORIZONTAL || flip == FLIP_PATTERN_BOTH)
  700. {
  701. for(int i = 0; i < 3; ++i)
  702. {
  703. int y = i * 3;
  704. std::swap(ret.data[y], ret.data[y + 2]);
  705. }
  706. }
  707. if(flip == FLIP_PATTERN_VERTICAL || flip == FLIP_PATTERN_BOTH)
  708. {
  709. for(int i = 0; i < 3; ++i)
  710. {
  711. std::swap(ret.data[i], ret.data[6 + i]);
  712. }
  713. }
  714. return ret;
  715. }
  716. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  717. {
  718. auto rect = extendTileAroundSafely(centerPos);
  719. rect.forEach([&](const int3 & pos)
  720. {
  721. invalidatedTerViews.insert(pos);
  722. });
  723. }
  724. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  725. {
  726. InvalidTiles tiles;
  727. auto centerTerType = map->getTile(centerPos).terType;
  728. auto rect = extendTileAround(centerPos);
  729. rect.forEach([&](const int3 & pos)
  730. {
  731. if(map->isInTheMap(pos))
  732. {
  733. auto ptrConfig = VLC->terviewh;
  734. auto terType = map->getTile(pos).terType;
  735. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  736. // Special validity check for rock & water
  737. if(valid && centerTerType != terType && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
  738. {
  739. static const std::string patternIds[] = { "s1", "s2" };
  740. for(auto & patternId : patternIds)
  741. {
  742. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  743. if(!valid) break;
  744. }
  745. }
  746. // Additional validity check for non rock OR water
  747. else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
  748. {
  749. static const std::string patternIds[] = { "n2", "n3" };
  750. for(auto & patternId : patternIds)
  751. {
  752. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  753. if(valid) break;
  754. }
  755. }
  756. if(!valid)
  757. {
  758. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  759. else tiles.foreignTiles.insert(pos);
  760. }
  761. }
  762. });
  763. return tiles;
  764. }
  765. MapRect CDrawTerrainOperation::extendTileAround(const int3 & centerPos) const
  766. {
  767. return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
  768. }
  769. MapRect CDrawTerrainOperation::extendTileAroundSafely(const int3 & centerPos) const
  770. {
  771. return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
  772. }
  773. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement /*= ""*/)
  774. : result(result), transitionReplacement(transitionReplacement)
  775. {
  776. }
  777. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  778. {
  779. CTerrainSelection terrainSel(map);
  780. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  781. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
  782. if(map->twoLevel)
  783. {
  784. terrainSel.clearSelection();
  785. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  786. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
  787. }
  788. }
  789. std::string CClearTerrainOperation::getLabel() const
  790. {
  791. return "Clear Terrain";
  792. }
  793. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj, const int3 & pos)
  794. : CMapOperation(map), pos(pos), obj(obj)
  795. {
  796. }
  797. void CInsertObjectOperation::execute()
  798. {
  799. obj->pos = pos;
  800. obj->id = ObjectInstanceID(map->objects.size());
  801. map->objects.push_back(obj);
  802. if(obj->ID == Obj::TOWN)
  803. {
  804. map->towns.push_back(static_cast<CGTownInstance *>(obj));
  805. }
  806. if(obj->ID == Obj::HERO)
  807. {
  808. map->heroesOnMap.push_back(static_cast<CGHeroInstance*>(obj));
  809. }
  810. map->addBlockVisTiles(obj);
  811. }
  812. void CInsertObjectOperation::undo()
  813. {
  814. //TODO
  815. }
  816. void CInsertObjectOperation::redo()
  817. {
  818. execute();
  819. }
  820. std::string CInsertObjectOperation::getLabel() const
  821. {
  822. return "Insert Object";
  823. }