2
0

CMapEditManager.cpp 25 KB

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