CMapEditManager.cpp 28 KB

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