CMapEditManager.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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(std::string &Name) : points(0), name(Name)
  261. {
  262. standardRule = (TerrainViewPattern::RULE_ANY == Name || TerrainViewPattern::RULE_DIRT == Name
  263. || TerrainViewPattern::RULE_NATIVE == Name || TerrainViewPattern::RULE_SAND == Name
  264. || TerrainViewPattern::RULE_TRANSITION == Name || TerrainViewPattern::RULE_NATIVE_STRONG == Name);
  265. anyRule = (TerrainViewPattern::RULE_ANY == Name);
  266. dirtRule = (Name == TerrainViewPattern::RULE_DIRT);
  267. sandRule = (Name == TerrainViewPattern::RULE_SAND);
  268. transitionRule = (Name == TerrainViewPattern::RULE_TRANSITION);
  269. nativeStrongRule = (Name == TerrainViewPattern::RULE_NATIVE_STRONG);
  270. nativeRule = (Name == TerrainViewPattern::RULE_NATIVE);
  271. }
  272. void TerrainViewPattern::WeightedRule::setNative()
  273. {
  274. nativeRule = true;
  275. standardRule = true;
  276. //TODO: would look better as a bitfield
  277. dirtRule = sandRule = transitionRule = nativeStrongRule = anyRule = false; //no idea what they mean, but look mutually exclusive
  278. }
  279. CTerrainViewPatternConfig::CTerrainViewPatternConfig()
  280. {
  281. const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
  282. static const std::string patternTypes[] = { "terrainView", "terrainType" };
  283. for(int i = 0; i < ARRAY_COUNT(patternTypes); ++i)
  284. {
  285. const auto & patternsVec = config[patternTypes[i]].Vector();
  286. for(const auto & ptrnNode : patternsVec)
  287. {
  288. TerrainViewPattern pattern;
  289. // Read pattern data
  290. const JsonVector & data = ptrnNode["data"].Vector();
  291. assert(data.size() == 9);
  292. for(int j = 0; j < data.size(); ++j)
  293. {
  294. std::string cell = data[j].String();
  295. boost::algorithm::erase_all(cell, " ");
  296. std::vector<std::string> rules;
  297. boost::split(rules, cell, boost::is_any_of(","));
  298. for(std::string ruleStr : rules)
  299. {
  300. std::vector<std::string> ruleParts;
  301. boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
  302. TerrainViewPattern::WeightedRule rule(ruleParts[0]);
  303. assert(!rule.name.empty());
  304. if(ruleParts.size() > 1)
  305. {
  306. rule.points = boost::lexical_cast<int>(ruleParts[1]);
  307. }
  308. pattern.data[j].push_back(rule);
  309. }
  310. }
  311. // Read various properties
  312. pattern.id = ptrnNode["id"].String();
  313. assert(!pattern.id.empty());
  314. pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
  315. pattern.maxPoints = static_cast<int>(ptrnNode["maxPoints"].Float());
  316. if(pattern.maxPoints == 0) pattern.maxPoints = std::numeric_limits<int>::max();
  317. // Read mapping
  318. if(i == 0)
  319. {
  320. const auto & mappingStruct = ptrnNode["mapping"].Struct();
  321. for(const auto & mappingPair : mappingStruct)
  322. {
  323. TerrainViewPattern terGroupPattern = pattern;
  324. auto mappingStr = mappingPair.second.String();
  325. boost::algorithm::erase_all(mappingStr, " ");
  326. auto colonIndex = mappingStr.find_first_of(":");
  327. const auto & flipMode = mappingStr.substr(0, colonIndex);
  328. terGroupPattern.diffImages = TerrainViewPattern::FLIP_MODE_DIFF_IMAGES == &(flipMode[flipMode.length() - 1]);
  329. if(terGroupPattern.diffImages)
  330. {
  331. terGroupPattern.rotationTypesCount = boost::lexical_cast<int>(flipMode.substr(0, flipMode.length() - 1));
  332. assert(terGroupPattern.rotationTypesCount == 2 || terGroupPattern.rotationTypesCount == 4);
  333. }
  334. mappingStr = mappingStr.substr(colonIndex + 1);
  335. std::vector<std::string> mappings;
  336. boost::split(mappings, mappingStr, boost::is_any_of(","));
  337. for(std::string mapping : mappings)
  338. {
  339. std::vector<std::string> range;
  340. boost::split(range, mapping, boost::is_any_of("-"));
  341. terGroupPattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
  342. boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
  343. }
  344. // Add pattern to the patterns map
  345. const auto & terGroup = getTerrainGroup(mappingPair.first);
  346. terrainViewPatterns[terGroup].push_back(terGroupPattern);
  347. }
  348. }
  349. else if(i == 1)
  350. {
  351. terrainTypePatterns[pattern.id] = pattern;
  352. }
  353. }
  354. }
  355. }
  356. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  357. {
  358. }
  359. ETerrainGroup::ETerrainGroup CTerrainViewPatternConfig::getTerrainGroup(const std::string & terGroup) const
  360. {
  361. static const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups =
  362. {
  363. {"normal", ETerrainGroup::NORMAL},
  364. {"dirt", ETerrainGroup::DIRT},
  365. {"sand", ETerrainGroup::SAND},
  366. {"water", ETerrainGroup::WATER},
  367. {"rock", ETerrainGroup::ROCK},
  368. };
  369. auto it = terGroups.find(terGroup);
  370. if(it == terGroups.end()) throw std::runtime_error(boost::str(boost::format("Terrain group '%s' does not exist.") % terGroup));
  371. return it->second;
  372. }
  373. const std::vector<TerrainViewPattern> & CTerrainViewPatternConfig::getTerrainViewPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
  374. {
  375. return terrainViewPatterns.find(terGroup)->second;
  376. }
  377. boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  378. {
  379. const std::vector<TerrainViewPattern> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
  380. for(const TerrainViewPattern & pattern : groupPatterns)
  381. {
  382. if(id == pattern.id)
  383. {
  384. return boost::optional<const TerrainViewPattern &>(pattern);
  385. }
  386. }
  387. return boost::optional<const TerrainViewPattern &>();
  388. }
  389. const TerrainViewPattern & CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
  390. {
  391. auto it = terrainTypePatterns.find(id);
  392. assert(it != terrainTypePatterns.end());
  393. return it->second;
  394. }
  395. CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, ETerrainType terType, CRandomGenerator * gen)
  396. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  397. {
  398. }
  399. void CDrawTerrainOperation::execute()
  400. {
  401. for(const auto & pos : terrainSel.getSelectedItems())
  402. {
  403. auto & tile = map->getTile(pos);
  404. tile.terType = terType;
  405. invalidateTerrainViews(pos);
  406. }
  407. updateTerrainTypes();
  408. updateTerrainViews();
  409. }
  410. void CDrawTerrainOperation::undo()
  411. {
  412. //TODO
  413. }
  414. void CDrawTerrainOperation::redo()
  415. {
  416. //TODO
  417. }
  418. std::string CDrawTerrainOperation::getLabel() const
  419. {
  420. return "Draw Terrain";
  421. }
  422. void CDrawTerrainOperation::updateTerrainTypes()
  423. {
  424. auto positions = terrainSel.getSelectedItems();
  425. while(!positions.empty())
  426. {
  427. const auto & centerPos = *(positions.begin());
  428. auto centerTile = map->getTile(centerPos);
  429. //logGlobal->debugStream() << boost::format("Set terrain tile at pos '%s' to type '%s'") % centerPos % centerTile.terType;
  430. auto tiles = getInvalidTiles(centerPos);
  431. auto updateTerrainType = [&](const int3 & pos)
  432. {
  433. map->getTile(pos).terType = centerTile.terType;
  434. positions.insert(pos);
  435. invalidateTerrainViews(pos);
  436. //logGlobal->debugStream() << boost::format("Set additional terrain tile at pos '%s' to type '%s'") % pos % centerTile.terType;
  437. };
  438. // Fill foreign invalid tiles
  439. for(const auto & tile : tiles.foreignTiles)
  440. {
  441. updateTerrainType(tile);
  442. }
  443. tiles = getInvalidTiles(centerPos);
  444. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  445. {
  446. // Blow up
  447. auto rect = extendTileAroundSafely(centerPos);
  448. std::set<int3> suitableTiles;
  449. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  450. bool centerPosValid = false;
  451. rect.forEach([&](const int3 & posToTest)
  452. {
  453. auto & terrainTile = map->getTile(posToTest);
  454. if(centerTile.terType != terrainTile.terType)
  455. {
  456. auto formerTerType = terrainTile.terType;
  457. terrainTile.terType = centerTile.terType;
  458. auto testTile = getInvalidTiles(posToTest);
  459. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : testTile.nativeTiles.size();
  460. bool putSuitableTile = false;
  461. bool addToSuitableTiles = false;
  462. if(testTile.centerPosValid)
  463. {
  464. if (!centerPosValid)
  465. {
  466. centerPosValid = true;
  467. putSuitableTile = true;
  468. }
  469. else
  470. {
  471. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  472. {
  473. putSuitableTile = true;
  474. }
  475. else
  476. {
  477. addToSuitableTiles = true;
  478. }
  479. }
  480. }
  481. else if (!centerPosValid)
  482. {
  483. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  484. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  485. {
  486. putSuitableTile = true;
  487. }
  488. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  489. {
  490. addToSuitableTiles = true;
  491. }
  492. }
  493. if (putSuitableTile)
  494. {
  495. //if(!suitableTiles.empty())
  496. //{
  497. // logGlobal->debugStream() << "Clear suitables tiles.";
  498. //}
  499. invalidNativeTilesCnt = nativeTilesCntNorm;
  500. invalidForeignTilesCnt = testTile.foreignTiles.size();
  501. suitableTiles.clear();
  502. addToSuitableTiles = true;
  503. }
  504. if (addToSuitableTiles)
  505. {
  506. suitableTiles.insert(posToTest);
  507. //logGlobal->debugStream() << boost::format(std::string("Found suitable tile '%s' for main tile '%s': ") +
  508. // "Invalid native tiles '%i', invalid foreign tiles '%i', centerPosValid '%i'") % posToTest % centerPos % testTile.nativeTiles.size() %
  509. // testTile.foreignTiles.size() % testTile.centerPosValid;
  510. }
  511. terrainTile.terType = formerTerType;
  512. }
  513. });
  514. if(suitableTiles.size() == 1)
  515. {
  516. updateTerrainType(*suitableTiles.begin());
  517. }
  518. else
  519. {
  520. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  521. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  522. for(auto & direction : directions)
  523. {
  524. auto it = suitableTiles.find(centerPos + direction);
  525. if(it != suitableTiles.end())
  526. {
  527. updateTerrainType(*it);
  528. break;
  529. }
  530. }
  531. }
  532. }
  533. else
  534. {
  535. // add invalid native tiles which are not in the positions list
  536. for(const auto & nativeTile : tiles.nativeTiles)
  537. {
  538. if(positions.find(nativeTile) == positions.end())
  539. {
  540. positions.insert(nativeTile);
  541. }
  542. }
  543. positions.erase(centerPos);
  544. }
  545. }
  546. }
  547. void CDrawTerrainOperation::updateTerrainViews()
  548. {
  549. for(const auto & pos : invalidatedTerViews)
  550. {
  551. const auto & patterns =
  552. VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));
  553. // Detect a pattern which fits best
  554. int bestPattern = -1;
  555. ValidationResult valRslt(false);
  556. for(int k = 0; k < patterns.size(); ++k)
  557. {
  558. const auto & pattern = patterns[k];
  559. valRslt = validateTerrainView(pos, pattern);
  560. if(valRslt.result)
  561. {
  562. /*logGlobal->debugStream() << boost::format("Pattern detected at pos '%s': Pattern '%s', Flip '%i', Repl. '%s'.") %
  563. pos % pattern.id % valRslt.flip % valRslt.transitionReplacement;*/
  564. bestPattern = k;
  565. break;
  566. }
  567. }
  568. //assert(bestPattern != -1);
  569. if(bestPattern == -1)
  570. {
  571. // This shouldn't be the case
  572. logGlobal->warnStream() << boost::format("No pattern detected at pos '%s'.") % pos;
  573. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  574. continue;
  575. }
  576. // Get mapping
  577. const TerrainViewPattern & pattern = patterns[bestPattern];
  578. std::pair<int, int> mapping;
  579. if(valRslt.transitionReplacement.empty())
  580. {
  581. mapping = pattern.mapping[0];
  582. }
  583. else
  584. {
  585. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  586. }
  587. // Set terrain view
  588. auto & tile = map->getTile(pos);
  589. if(!pattern.diffImages)
  590. {
  591. tile.terView = gen->nextInt(mapping.first, mapping.second);
  592. tile.extTileFlags = valRslt.flip;
  593. }
  594. else
  595. {
  596. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  597. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  598. int firstFrame = mapping.first + flip * framesPerRot;
  599. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  600. tile.extTileFlags = 0;
  601. }
  602. }
  603. }
  604. ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  605. {
  606. switch(terType)
  607. {
  608. case ETerrainType::DIRT:
  609. return ETerrainGroup::DIRT;
  610. case ETerrainType::SAND:
  611. return ETerrainGroup::SAND;
  612. case ETerrainType::WATER:
  613. return ETerrainGroup::WATER;
  614. case ETerrainType::ROCK:
  615. return ETerrainGroup::ROCK;
  616. default:
  617. return ETerrainGroup::NORMAL;
  618. }
  619. }
  620. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  621. {
  622. //constructor for pattern object is very expensive, but we can't manipulate const object :(
  623. auto flippedPattern = pattern; //TODO: store cached patterns in 4 positions to avoid very expensive construction
  624. for(int flip = 0; flip < 4; ++flip)
  625. {
  626. if (flip > 0)
  627. flipPattern (flippedPattern, flip);
  628. auto valRslt = validateTerrainViewInner(pos, flippedPattern, recDepth);
  629. if(valRslt.result)
  630. {
  631. valRslt.flip = flip;
  632. return valRslt;
  633. }
  634. }
  635. return ValidationResult(false);
  636. }
  637. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  638. {
  639. auto centerTerType = map->getTile(pos).terType;
  640. auto centerTerGroup = getTerrainGroup(centerTerType);
  641. int totalPoints = 0;
  642. std::string transitionReplacement;
  643. for(int i = 0; i < 9; ++i)
  644. {
  645. // The center, middle cell can be skipped
  646. if(i == 4)
  647. {
  648. continue;
  649. }
  650. // Get terrain group of the current cell
  651. int cx = pos.x + (i % 3) - 1;
  652. int cy = pos.y + (i / 3) - 1;
  653. int3 currentPos(cx, cy, pos.z);
  654. bool isAlien = false;
  655. ETerrainType terType;
  656. if(!map->isInTheMap(currentPos))
  657. {
  658. // position is not in the map, so take the ter type from the neighbor tile
  659. bool widthTooHigh = currentPos.x >= map->width;
  660. bool widthTooLess = currentPos.x < 0;
  661. bool heightTooHigh = currentPos.y >= map->height;
  662. bool heightTooLess = currentPos.y < 0;
  663. if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  664. {
  665. terType = centerTerType;
  666. }
  667. else if(widthTooHigh)
  668. {
  669. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  670. }
  671. else if(heightTooHigh)
  672. {
  673. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  674. }
  675. else if (widthTooLess)
  676. {
  677. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  678. }
  679. else if (heightTooLess)
  680. {
  681. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  682. }
  683. }
  684. else
  685. {
  686. terType = map->getTile(currentPos).terType;
  687. if(terType != centerTerType)
  688. {
  689. isAlien = true;
  690. }
  691. }
  692. // Validate all rules per cell
  693. int topPoints = -1;
  694. for(auto & elem : pattern.data[i])
  695. {
  696. TerrainViewPattern::WeightedRule rule = elem;
  697. if(!rule.isStandardRule())
  698. {
  699. if(recDepth == 0 && map->isInTheMap(currentPos))
  700. {
  701. if(terType == centerTerType)
  702. {
  703. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternById(getTerrainGroup(centerTerType), rule.name);
  704. if(patternForRule)
  705. {
  706. auto rslt = validateTerrainView(currentPos, *patternForRule, 1);
  707. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  708. }
  709. }
  710. continue;
  711. }
  712. else
  713. {
  714. rule.setNative();
  715. }
  716. }
  717. auto applyValidationRslt = [&](bool rslt)
  718. {
  719. if(rslt)
  720. {
  721. topPoints = std::max(topPoints, rule.points);
  722. }
  723. };
  724. // Validate cell with the ruleset of the pattern
  725. bool nativeTestOk, nativeTestStrongOk;
  726. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  727. if(centerTerGroup == ETerrainGroup::NORMAL)
  728. {
  729. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  730. && isAlien && !isSandType(terType);
  731. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  732. && isSandType(terType);
  733. if (transitionReplacement.empty() && rule.isTransition()
  734. && (dirtTestOk || sandTestOk))
  735. {
  736. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  737. }
  738. if (rule.isTransition())
  739. {
  740. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  741. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  742. }
  743. else
  744. {
  745. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  746. }
  747. }
  748. else if(centerTerGroup == ETerrainGroup::DIRT)
  749. {
  750. nativeTestOk = rule.isNativeRule() && !isSandType(terType);
  751. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  752. && isSandType(terType);
  753. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  754. }
  755. else if(centerTerGroup == ETerrainGroup::SAND)
  756. {
  757. applyValidationRslt(true);
  758. }
  759. else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
  760. {
  761. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  762. && isAlien;
  763. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  764. }
  765. }
  766. if(topPoints == -1)
  767. {
  768. return ValidationResult(false);
  769. }
  770. else
  771. {
  772. totalPoints += topPoints;
  773. }
  774. }
  775. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  776. {
  777. return ValidationResult(true, transitionReplacement);
  778. }
  779. else
  780. {
  781. return ValidationResult(false);
  782. }
  783. }
  784. bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
  785. {
  786. switch(terType)
  787. {
  788. case ETerrainType::WATER:
  789. case ETerrainType::SAND:
  790. case ETerrainType::ROCK:
  791. return true;
  792. default:
  793. return false;
  794. }
  795. }
  796. void CDrawTerrainOperation::flipPattern(TerrainViewPattern & pattern, int flip) const
  797. {
  798. //flip in place to avoid expensive constructor. Seriously.
  799. if(flip == 0)
  800. {
  801. return;
  802. }
  803. //always flip horizontal
  804. for(int i = 0; i < 3; ++i)
  805. {
  806. int y = i * 3;
  807. std::swap(pattern.data[y], pattern.data[y + 2]);
  808. }
  809. //flip vertical only at 2nd step
  810. if(flip == FLIP_PATTERN_VERTICAL)
  811. {
  812. for(int i = 0; i < 3; ++i)
  813. {
  814. std::swap(pattern.data[i], pattern.data[6 + i]);
  815. }
  816. }
  817. }
  818. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  819. {
  820. auto rect = extendTileAroundSafely(centerPos);
  821. rect.forEach([&](const int3 & pos)
  822. {
  823. invalidatedTerViews.insert(pos);
  824. });
  825. }
  826. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  827. {
  828. //TODO: this is very expensive function for RMG, needs optimization
  829. InvalidTiles tiles;
  830. auto centerTerType = map->getTile(centerPos).terType;
  831. auto rect = extendTileAround(centerPos);
  832. rect.forEach([&](const int3 & pos)
  833. {
  834. if(map->isInTheMap(pos))
  835. {
  836. auto ptrConfig = VLC->terviewh;
  837. auto terType = map->getTile(pos).terType;
  838. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  839. // Special validity check for rock & water
  840. if(valid && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
  841. {
  842. static const std::string patternIds[] = { "s1", "s2" };
  843. for(auto & patternId : patternIds)
  844. {
  845. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  846. if(!valid) break;
  847. }
  848. }
  849. // Additional validity check for non rock OR water
  850. else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
  851. {
  852. static const std::string patternIds[] = { "n2", "n3" };
  853. for(auto & patternId : patternIds)
  854. {
  855. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  856. if(valid) break;
  857. }
  858. }
  859. if(!valid)
  860. {
  861. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  862. else tiles.foreignTiles.insert(pos);
  863. }
  864. else if(centerPos == pos)
  865. {
  866. tiles.centerPosValid = true;
  867. }
  868. }
  869. });
  870. return tiles;
  871. }
  872. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement /*= ""*/)
  873. : result(result), transitionReplacement(transitionReplacement)
  874. {
  875. }
  876. void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
  877. {
  878. logGlobal->debugStream() << "Printing detailed info about nearby map tiles of pos '" << pos << "'";
  879. for(int y = pos.y - 2; y <= pos.y + 2; ++y)
  880. {
  881. std::string line;
  882. const int PADDED_LENGTH = 10;
  883. for(int x = pos.x - 2; x <= pos.x + 2; ++x)
  884. {
  885. auto debugPos = int3(x, y, pos.z);
  886. if(map->isInTheMap(debugPos))
  887. {
  888. auto debugTile = map->getTile(debugPos);
  889. std::string terType = debugTile.terType.toString().substr(0, 6);
  890. line += terType;
  891. line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
  892. }
  893. else
  894. {
  895. line += "X";
  896. line.insert(line.end(), PADDED_LENGTH - 1, ' ');
  897. }
  898. }
  899. logGlobal->debugStream() << line;
  900. }
  901. }
  902. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  903. {
  904. CTerrainSelection terrainSel(map);
  905. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  906. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
  907. if(map->twoLevel)
  908. {
  909. terrainSel.clearSelection();
  910. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  911. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
  912. }
  913. }
  914. std::string CClearTerrainOperation::getLabel() const
  915. {
  916. return "Clear Terrain";
  917. }
  918. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj, const int3 & pos)
  919. : CMapOperation(map), pos(pos), obj(obj)
  920. {
  921. }
  922. void CInsertObjectOperation::execute()
  923. {
  924. obj->pos = pos;
  925. obj->id = ObjectInstanceID(map->objects.size());
  926. boost::format fmt("%s_%d");
  927. fmt % obj->typeName % obj->id.getNum();
  928. obj->instanceName = fmt.str();
  929. map->addNewObject(obj);
  930. }
  931. void CInsertObjectOperation::undo()
  932. {
  933. //TODO
  934. }
  935. void CInsertObjectOperation::redo()
  936. {
  937. execute();
  938. }
  939. std::string CInsertObjectOperation::getLabel() const
  940. {
  941. return "Insert Object";
  942. }