CMapEditManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. #include "StdInc.h"
  2. #include "CMapEditManager.h"
  3. #include "../JsonNode.h"
  4. #include "../filesystem/CResourceLoader.h"
  5. #include "../CDefObjInfoHandler.h"
  6. CMapOperation::CMapOperation(CMap * map) : map(map)
  7. {
  8. }
  9. std::string CMapOperation::getLabel() const
  10. {
  11. return "";
  12. }
  13. CMapUndoManager::CMapUndoManager() : undoRedoLimit(10)
  14. {
  15. }
  16. void CMapUndoManager::undo()
  17. {
  18. doOperation(undoStack, redoStack, true);
  19. }
  20. void CMapUndoManager::redo()
  21. {
  22. doOperation(redoStack, undoStack, false);
  23. }
  24. void CMapUndoManager::clearAll()
  25. {
  26. undoStack.clear();
  27. redoStack.clear();
  28. }
  29. int CMapUndoManager::getUndoRedoLimit() const
  30. {
  31. return undoRedoLimit;
  32. }
  33. void CMapUndoManager::setUndoRedoLimit(int value)
  34. {
  35. if(value < 0) throw std::runtime_error("Cannot set a negative value for the undo redo limit.");
  36. undoStack.resize(std::min(undoStack.size(), static_cast<TStack::size_type>(value)));
  37. redoStack.resize(std::min(redoStack.size(), static_cast<TStack::size_type>(value)));
  38. }
  39. const CMapOperation * CMapUndoManager::peekRedo() const
  40. {
  41. return peek(redoStack);
  42. }
  43. const CMapOperation * CMapUndoManager::peekUndo() const
  44. {
  45. return peek(undoStack);
  46. }
  47. void CMapUndoManager::addOperation(unique_ptr<CMapOperation> && operation)
  48. {
  49. undoStack.push_front(std::move(operation));
  50. if(undoStack.size() > undoRedoLimit) undoStack.pop_back();
  51. redoStack.clear();
  52. }
  53. void CMapUndoManager::doOperation(TStack & fromStack, TStack & toStack, bool doUndo)
  54. {
  55. if(fromStack.empty()) return;
  56. auto & operation = fromStack.front();
  57. if(doUndo)
  58. {
  59. operation->undo();
  60. }
  61. else
  62. {
  63. operation->redo();
  64. }
  65. toStack.push_front(std::move(operation));
  66. fromStack.pop_front();
  67. }
  68. const CMapOperation * CMapUndoManager::peek(const TStack & stack) const
  69. {
  70. if(stack.empty()) return nullptr;
  71. return stack.front().get();
  72. }
  73. CMapEditManager::CMapEditManager(CMap * map)
  74. : map(map)
  75. {
  76. }
  77. void CMapEditManager::clearTerrain(CRandomGenerator * gen)
  78. {
  79. for(int i = 0; i < map->width; ++i)
  80. {
  81. for(int j = 0; j < map->height; ++j)
  82. {
  83. map->getTile(int3(i, j, 0)).terType = ETerrainType::WATER;
  84. map->getTile(int3(i, j, 0)).terView = gen->getInteger(20, 32);
  85. if(map->twoLevel)
  86. {
  87. map->getTile(int3(i, j, 1)).terType = ETerrainType::ROCK;
  88. map->getTile(int3(i, j, 1)).terView = 0;
  89. }
  90. }
  91. }
  92. }
  93. void CMapEditManager::drawTerrain(const MapRect & rect, ETerrainType terType, CRandomGenerator * gen)
  94. {
  95. execute(make_unique<DrawTerrainOperation>(map, rect, terType, gen));
  96. }
  97. void CMapEditManager::insertObject(const int3 & pos, CGObjectInstance * obj)
  98. {
  99. execute(make_unique<InsertObjectOperation>(map, pos, obj));
  100. }
  101. void CMapEditManager::execute(unique_ptr<CMapOperation> && operation)
  102. {
  103. operation->execute();
  104. undoManager.addOperation(std::move(operation));
  105. }
  106. void CMapEditManager::undo()
  107. {
  108. undoManager.undo();
  109. }
  110. void CMapEditManager::redo()
  111. {
  112. undoManager.redo();
  113. }
  114. CMapUndoManager & CMapEditManager::getUndoManager()
  115. {
  116. return undoManager;
  117. }
  118. const std::string TerrainViewPattern::FLIP_MODE_SAME_IMAGE = "sameImage";
  119. const std::string TerrainViewPattern::FLIP_MODE_DIFF_IMAGES = "diffImages";
  120. const std::string TerrainViewPattern::RULE_DIRT = "D";
  121. const std::string TerrainViewPattern::RULE_SAND = "S";
  122. const std::string TerrainViewPattern::RULE_TRANSITION = "T";
  123. const std::string TerrainViewPattern::RULE_NATIVE = "N";
  124. const std::string TerrainViewPattern::RULE_ANY = "?";
  125. TerrainViewPattern::TerrainViewPattern() : minPoints(0), flipMode(FLIP_MODE_SAME_IMAGE),
  126. terGroup(ETerrainGroup::NORMAL)
  127. {
  128. }
  129. TerrainViewPattern::WeightedRule::WeightedRule() : points(0)
  130. {
  131. }
  132. bool TerrainViewPattern::WeightedRule::isStandardRule() const
  133. {
  134. return TerrainViewPattern::RULE_ANY == name || TerrainViewPattern::RULE_DIRT == name
  135. || TerrainViewPattern::RULE_NATIVE == name || TerrainViewPattern::RULE_SAND == name
  136. || TerrainViewPattern::RULE_TRANSITION == name;
  137. }
  138. boost::mutex CTerrainViewPatternConfig::smx;
  139. CTerrainViewPatternConfig & CTerrainViewPatternConfig::get()
  140. {
  141. TLockGuard _(smx);
  142. static CTerrainViewPatternConfig instance;
  143. return instance;
  144. }
  145. CTerrainViewPatternConfig::CTerrainViewPatternConfig()
  146. {
  147. const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
  148. const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups
  149. = boost::assign::map_list_of("normal", ETerrainGroup::NORMAL)("dirt", ETerrainGroup::DIRT)
  150. ("sand", ETerrainGroup::SAND)("water", ETerrainGroup::WATER)("rock", ETerrainGroup::ROCK);
  151. BOOST_FOREACH(auto terMapping, terGroups)
  152. {
  153. BOOST_FOREACH(const JsonNode & ptrnNode, config[terMapping.first].Vector())
  154. {
  155. TerrainViewPattern pattern;
  156. // Read pattern data
  157. const JsonVector & data = ptrnNode["data"].Vector();
  158. if(data.size() != 9)
  159. {
  160. throw std::runtime_error("Size of pattern's data vector has to be 9.");
  161. }
  162. for(int i = 0; i < data.size(); ++i)
  163. {
  164. std::string cell = data[i].String();
  165. boost::algorithm::erase_all(cell, " ");
  166. std::vector<std::string> rules;
  167. boost::split(rules, cell, boost::is_any_of(","));
  168. BOOST_FOREACH(std::string ruleStr, rules)
  169. {
  170. std::vector<std::string> ruleParts;
  171. boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
  172. TerrainViewPattern::WeightedRule rule;
  173. rule.name = ruleParts[0];
  174. if(ruleParts.size() > 1)
  175. {
  176. rule.points = boost::lexical_cast<int>(ruleParts[1]);
  177. }
  178. pattern.data[i].push_back(rule);
  179. }
  180. }
  181. // Read mapping
  182. std::string mappingStr = ptrnNode["mapping"].String();
  183. boost::algorithm::erase_all(mappingStr, " ");
  184. std::vector<std::string> mappings;
  185. boost::split(mappings, mappingStr, boost::is_any_of(","));
  186. BOOST_FOREACH(std::string mapping, mappings)
  187. {
  188. std::vector<std::string> range;
  189. boost::split(range, mapping, boost::is_any_of("-"));
  190. pattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
  191. boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
  192. }
  193. // Read optional attributes
  194. pattern.id = ptrnNode["id"].String();
  195. pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
  196. pattern.flipMode = ptrnNode["flipMode"].String();
  197. if(pattern.flipMode.empty())
  198. {
  199. pattern.flipMode = TerrainViewPattern::FLIP_MODE_SAME_IMAGE;
  200. }
  201. pattern.terGroup = terMapping.second;
  202. patterns[terMapping.second].push_back(pattern);
  203. }
  204. }
  205. }
  206. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  207. {
  208. }
  209. const std::vector<TerrainViewPattern> & CTerrainViewPatternConfig::getPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
  210. {
  211. return patterns.find(terGroup)->second;
  212. }
  213. const TerrainViewPattern & CTerrainViewPatternConfig::getPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  214. {
  215. const std::vector<TerrainViewPattern> & groupPatterns = getPatternsForGroup(terGroup);
  216. BOOST_FOREACH(const TerrainViewPattern & pattern, groupPatterns)
  217. {
  218. if(id == pattern.id)
  219. {
  220. return pattern;
  221. }
  222. }
  223. throw std::runtime_error("Pattern with ID not found: " + id);
  224. }
  225. DrawTerrainOperation::DrawTerrainOperation(CMap * map, const MapRect & rect, ETerrainType terType, CRandomGenerator * gen)
  226. : CMapOperation(map), rect(rect), terType(terType), gen(gen)
  227. {
  228. }
  229. void DrawTerrainOperation::execute()
  230. {
  231. for(int i = rect.pos.x; i < rect.pos.x + rect.width; ++i)
  232. {
  233. for(int j = rect.pos.y; j < rect.pos.y + rect.height; ++j)
  234. {
  235. map->getTile(int3(i, j, rect.pos.z)).terType = terType;
  236. }
  237. }
  238. //TODO there are situations where more tiles are affected implicitely
  239. //TODO add coastal bit to extTileFlags appropriately
  240. updateTerrainViews(MapRect(int3(rect.pos.x - 1, rect.pos.y - 1, rect.pos.z), rect.width + 2, rect.height + 2));
  241. }
  242. void DrawTerrainOperation::undo()
  243. {
  244. //TODO
  245. }
  246. void DrawTerrainOperation::redo()
  247. {
  248. //TODO
  249. }
  250. std::string DrawTerrainOperation::getLabel() const
  251. {
  252. return "Draw Terrain";
  253. }
  254. void DrawTerrainOperation::updateTerrainViews(const MapRect & rect)
  255. {
  256. for(int i = rect.pos.x; i < rect.pos.x + rect.width; ++i)
  257. {
  258. for(int j = rect.pos.y; j < rect.pos.y + rect.height; ++j)
  259. {
  260. const auto & patterns =
  261. CTerrainViewPatternConfig::get().getPatternsForGroup(getTerrainGroup(map->getTile(int3(i, j, rect.pos.z)).terType));
  262. // Detect a pattern which fits best
  263. int bestPattern = -1, bestFlip = -1;
  264. std::string transitionReplacement;
  265. for(int k = 0; k < patterns.size(); ++k)
  266. {
  267. const auto & pattern = patterns[k];
  268. for(int flip = 0; flip < 4; ++flip)
  269. {
  270. auto valRslt = validateTerrainView(int3(i, j, rect.pos.z), flip > 0 ? getFlippedPattern(pattern, flip) : pattern);
  271. if(valRslt.result)
  272. {
  273. logGlobal->debugStream() << "Pattern detected at pos " << i << "x" << j << "x" << rect.pos.z << ": P-Nr. " << k
  274. << ", Flip " << flip << ", Repl. " << valRslt.transitionReplacement;
  275. bestPattern = k;
  276. bestFlip = flip;
  277. transitionReplacement = valRslt.transitionReplacement;
  278. break;
  279. }
  280. }
  281. }
  282. if(bestPattern == -1)
  283. {
  284. // This shouldn't be the case
  285. logGlobal->warnStream() << "No pattern detected at pos " << i << "x" << j << "x" << rect.pos.z;
  286. continue;
  287. }
  288. // Get mapping
  289. const TerrainViewPattern & pattern = patterns[bestPattern];
  290. std::pair<int, int> mapping;
  291. if(transitionReplacement.empty())
  292. {
  293. mapping = pattern.mapping[0];
  294. }
  295. else
  296. {
  297. mapping = transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  298. }
  299. // Set terrain view
  300. auto & tile = map->getTile(int3(i, j, rect.pos.z));
  301. if(pattern.flipMode == TerrainViewPattern::FLIP_MODE_SAME_IMAGE)
  302. {
  303. tile.terView = gen->getInteger(mapping.first, mapping.second);
  304. tile.extTileFlags = bestFlip;
  305. }
  306. else
  307. {
  308. int range = (mapping.second - mapping.first) / 4;
  309. tile.terView = gen->getInteger(mapping.first + bestFlip * range,
  310. mapping.first + (bestFlip + 1) * range - 1);
  311. tile.extTileFlags = 0;
  312. }
  313. }
  314. }
  315. }
  316. ETerrainGroup::ETerrainGroup DrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  317. {
  318. switch(terType)
  319. {
  320. case ETerrainType::DIRT:
  321. return ETerrainGroup::DIRT;
  322. case ETerrainType::SAND:
  323. return ETerrainGroup::SAND;
  324. case ETerrainType::WATER:
  325. return ETerrainGroup::WATER;
  326. case ETerrainType::ROCK:
  327. return ETerrainGroup::ROCK;
  328. default:
  329. return ETerrainGroup::NORMAL;
  330. }
  331. }
  332. DrawTerrainOperation::ValidationResult DrawTerrainOperation::validateTerrainView(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  333. {
  334. ETerrainType centerTerType = map->getTile(pos).terType;
  335. int totalPoints = 0;
  336. std::string transitionReplacement;
  337. for(int i = 0; i < 9; ++i)
  338. {
  339. // The center, middle cell can be skipped
  340. if(i == 4)
  341. {
  342. continue;
  343. }
  344. // Get terrain group of the current cell
  345. int cx = pos.x + (i % 3) - 1;
  346. int cy = pos.y + (i / 3) - 1;
  347. bool isAlien = false;
  348. ETerrainType terType;
  349. if(cx < 0 || cx >= map->width || cy < 0 || cy >= map->height)
  350. {
  351. terType = centerTerType;
  352. }
  353. else
  354. {
  355. terType = map->getTile(int3(cx, cy, pos.z)).terType;
  356. if(terType != centerTerType)
  357. {
  358. isAlien = true;
  359. }
  360. }
  361. // Validate all rules per cell
  362. int topPoints = -1;
  363. for(int j = 0; j < pattern.data[i].size(); ++j)
  364. {
  365. TerrainViewPattern::WeightedRule rule = pattern.data[i][j];
  366. if(!rule.isStandardRule())
  367. {
  368. if(recDepth == 0)
  369. {
  370. const auto & patternForRule = CTerrainViewPatternConfig::get().getPatternById(pattern.terGroup, rule.name);
  371. auto rslt = validateTerrainView(int3(cx, cy, pos.z), patternForRule, 1);
  372. if(!rslt.result)
  373. {
  374. return ValidationResult(false);
  375. }
  376. else
  377. {
  378. topPoints = std::max(topPoints, rule.points);
  379. continue;
  380. }
  381. }
  382. else
  383. {
  384. rule.name = TerrainViewPattern::RULE_NATIVE;
  385. }
  386. }
  387. bool nativeTestOk = (rule.name == TerrainViewPattern::RULE_NATIVE || rule.name == TerrainViewPattern::RULE_ANY) && !isAlien;
  388. auto applyValidationRslt = [&](bool rslt)
  389. {
  390. if(rslt)
  391. {
  392. topPoints = std::max(topPoints, rule.points);
  393. }
  394. };
  395. // Validate cell with the ruleset of the pattern
  396. if(pattern.terGroup == ETerrainGroup::NORMAL)
  397. {
  398. bool dirtTestOk = (rule.name == TerrainViewPattern::RULE_DIRT
  399. || rule.name == TerrainViewPattern::RULE_TRANSITION || rule.name == TerrainViewPattern::RULE_ANY)
  400. && isAlien && !isSandType(terType);
  401. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION
  402. || rule.name == TerrainViewPattern::RULE_ANY)
  403. && isSandType(terType);
  404. if(transitionReplacement.empty() && (rule.name == TerrainViewPattern::RULE_TRANSITION
  405. || rule.name == TerrainViewPattern::RULE_ANY) && (dirtTestOk || sandTestOk))
  406. {
  407. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  408. }
  409. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND)
  410. || (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT)
  411. || nativeTestOk);
  412. }
  413. else if(pattern.terGroup == ETerrainGroup::DIRT)
  414. {
  415. bool sandTestOk = rule.name == TerrainViewPattern::RULE_SAND && isSandType(terType);
  416. bool dirtTestOk = rule.name == TerrainViewPattern::RULE_DIRT && !isSandType(terType) && !nativeTestOk;
  417. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || dirtTestOk || nativeTestOk);
  418. }
  419. else if(pattern.terGroup == ETerrainGroup::SAND)
  420. {
  421. bool sandTestOk = rule.name == TerrainViewPattern::RULE_SAND && isAlien;
  422. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk);
  423. }
  424. else if(pattern.terGroup == ETerrainGroup::WATER)
  425. {
  426. bool sandTestOk = rule.name == TerrainViewPattern::RULE_SAND && terType != ETerrainType::DIRT
  427. && terType != ETerrainType::WATER;
  428. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk);
  429. }
  430. else if(pattern.terGroup == ETerrainGroup::ROCK)
  431. {
  432. bool sandTestOk = rule.name == TerrainViewPattern::RULE_SAND && terType != ETerrainType::DIRT
  433. && terType != ETerrainType::ROCK;
  434. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk);
  435. }
  436. }
  437. if(topPoints == -1)
  438. {
  439. return ValidationResult(false);
  440. }
  441. else
  442. {
  443. totalPoints += topPoints;
  444. }
  445. }
  446. if(pattern.minPoints > totalPoints)
  447. {
  448. return ValidationResult(false);
  449. }
  450. return ValidationResult(true, transitionReplacement);
  451. }
  452. bool DrawTerrainOperation::isSandType(ETerrainType terType) const
  453. {
  454. switch(terType)
  455. {
  456. case ETerrainType::WATER:
  457. case ETerrainType::SAND:
  458. case ETerrainType::ROCK:
  459. return true;
  460. default:
  461. return false;
  462. }
  463. }
  464. TerrainViewPattern DrawTerrainOperation::getFlippedPattern(const TerrainViewPattern & pattern, int flip) const
  465. {
  466. if(flip == 0)
  467. {
  468. return pattern;
  469. }
  470. TerrainViewPattern ret = pattern;
  471. if(flip == FLIP_PATTERN_HORIZONTAL || flip == FLIP_PATTERN_BOTH)
  472. {
  473. for(int i = 0; i < 3; ++i)
  474. {
  475. int y = i * 3;
  476. std::swap(ret.data[y], ret.data[y + 2]);
  477. }
  478. }
  479. if(flip == FLIP_PATTERN_VERTICAL || flip == FLIP_PATTERN_BOTH)
  480. {
  481. for(int i = 0; i < 3; ++i)
  482. {
  483. std::swap(ret.data[i], ret.data[6 + i]);
  484. }
  485. }
  486. return ret;
  487. }
  488. DrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement /*= ""*/)
  489. : result(result), transitionReplacement(transitionReplacement)
  490. {
  491. }
  492. InsertObjectOperation::InsertObjectOperation(CMap * map, const int3 & pos, CGObjectInstance * obj)
  493. : CMapOperation(map), pos(pos), obj(obj)
  494. {
  495. }
  496. void InsertObjectOperation::execute()
  497. {
  498. obj->pos = pos;
  499. obj->id = ObjectInstanceID(map->objects.size());
  500. map->objects.push_back(obj);
  501. if(obj->ID == Obj::TOWN)
  502. {
  503. map->towns.push_back(static_cast<CGTownInstance *>(obj));
  504. }
  505. if(obj->ID == Obj::HERO)
  506. {
  507. map->heroes.push_back(static_cast<CGHeroInstance*>(obj));
  508. }
  509. map->addBlockVisTiles(obj);
  510. }
  511. void InsertObjectOperation::undo()
  512. {
  513. //TODO
  514. }
  515. void InsertObjectOperation::redo()
  516. {
  517. execute();
  518. }
  519. std::string InsertObjectOperation::getLabel() const
  520. {
  521. return "Insert Object";
  522. }