CMapEditManager.cpp 28 KB

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