CRmgTemplateZone.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. /*
  2. * CRmgTemplateZone.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 "CRmgTemplateZone.h"
  12. #include "../mapping/CMapEditManager.h"
  13. #include "../mapping/CMap.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../CTownHandler.h"
  16. #include "../CCreatureHandler.h"
  17. #include "../CSpellHandler.h" //for choosing random spells
  18. class CMap;
  19. class CMapEditManager;
  20. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  21. {
  22. }
  23. int CRmgTemplateZone::CTownInfo::getTownCount() const
  24. {
  25. return townCount;
  26. }
  27. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  28. {
  29. if(value < 0)
  30. throw rmgException("Negative value for town count not allowed.");
  31. townCount = value;
  32. }
  33. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  34. {
  35. return castleCount;
  36. }
  37. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  38. {
  39. if(value < 0)
  40. throw rmgException("Negative value for castle count not allowed.");
  41. castleCount = value;
  42. }
  43. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  44. {
  45. return townDensity;
  46. }
  47. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  48. {
  49. if(value < 0)
  50. throw rmgException("Negative value for town density not allowed.");
  51. townDensity = value;
  52. }
  53. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  54. {
  55. return castleDensity;
  56. }
  57. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  58. {
  59. if(value < 0)
  60. throw rmgException("Negative value for castle density not allowed.");
  61. castleDensity = value;
  62. }
  63. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  64. {
  65. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  66. }
  67. int CTileInfo::getNearestObjectDistance() const
  68. {
  69. return nearestObjectDistance;
  70. }
  71. void CTileInfo::setNearestObjectDistance(int value)
  72. {
  73. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  74. }
  75. bool CTileInfo::shouldBeBlocked() const
  76. {
  77. return occupied == ETileType::BLOCKED;
  78. }
  79. bool CTileInfo::isBlocked() const
  80. {
  81. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  82. }
  83. bool CTileInfo::isPossible() const
  84. {
  85. return occupied == ETileType::POSSIBLE;
  86. }
  87. bool CTileInfo::isFree() const
  88. {
  89. return occupied == ETileType::FREE;
  90. }
  91. void CTileInfo::setOccupied(ETileType::ETileType value)
  92. {
  93. occupied = value;
  94. }
  95. ETerrainType CTileInfo::getTerrainType() const
  96. {
  97. return terrain;
  98. }
  99. void CTileInfo::setTerrainType(ETerrainType value)
  100. {
  101. terrain = value;
  102. }
  103. CRmgTemplateZone::CRmgTemplateZone() : id(0), type(ETemplateZoneType::PLAYER_START), size(1),
  104. townsAreSameType(false), matchTerrainToTown(true), totalDensity(0)
  105. {
  106. townTypes = getDefaultTownTypes();
  107. terrainTypes = getDefaultTerrainTypes();
  108. }
  109. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  110. {
  111. return id;
  112. }
  113. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  114. {
  115. if(value <= 0)
  116. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  117. id = value;
  118. }
  119. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  120. {
  121. return type;
  122. }
  123. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  124. {
  125. type = value;
  126. }
  127. int CRmgTemplateZone::getSize() const
  128. {
  129. return size;
  130. }
  131. void CRmgTemplateZone::setSize(int value)
  132. {
  133. if(value <= 0)
  134. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  135. size = value;
  136. }
  137. boost::optional<int> CRmgTemplateZone::getOwner() const
  138. {
  139. return owner;
  140. }
  141. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  142. {
  143. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  144. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  145. owner = value;
  146. }
  147. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  148. {
  149. return playerTowns;
  150. }
  151. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  152. {
  153. playerTowns = value;
  154. }
  155. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  156. {
  157. return neutralTowns;
  158. }
  159. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  160. {
  161. neutralTowns = value;
  162. }
  163. bool CRmgTemplateZone::getTownsAreSameType() const
  164. {
  165. return townsAreSameType;
  166. }
  167. void CRmgTemplateZone::setTownsAreSameType(bool value)
  168. {
  169. townsAreSameType = value;
  170. }
  171. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  172. {
  173. return townTypes;
  174. }
  175. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  176. {
  177. townTypes = value;
  178. }
  179. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  180. {
  181. std::set<TFaction> defaultTowns;
  182. auto towns = VLC->townh->getDefaultAllowed();
  183. for(int i = 0; i < towns.size(); ++i)
  184. {
  185. if(towns[i]) defaultTowns.insert(i);
  186. }
  187. return defaultTowns;
  188. }
  189. bool CRmgTemplateZone::getMatchTerrainToTown() const
  190. {
  191. return matchTerrainToTown;
  192. }
  193. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  194. {
  195. matchTerrainToTown = value;
  196. }
  197. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  198. {
  199. return terrainTypes;
  200. }
  201. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  202. {
  203. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  204. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  205. terrainTypes = value;
  206. }
  207. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  208. {
  209. std::set<ETerrainType> terTypes;
  210. static const ETerrainType::EETerrainType allowedTerTypes[] = { ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  211. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA };
  212. for(auto & allowedTerType : allowedTerTypes) terTypes.insert(allowedTerType);
  213. return terTypes;
  214. }
  215. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTerrainTypeLikeZone() const
  216. {
  217. return terrainTypeLikeZone;
  218. }
  219. void CRmgTemplateZone::setTerrainTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  220. {
  221. terrainTypeLikeZone = value;
  222. }
  223. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTownTypeLikeZone() const
  224. {
  225. return townTypeLikeZone;
  226. }
  227. void CRmgTemplateZone::setTownTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  228. {
  229. townTypeLikeZone = value;
  230. }
  231. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  232. {
  233. connections.push_back (otherZone);
  234. }
  235. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  236. {
  237. return connections;
  238. }
  239. void CRmgTemplateZone::setTotalDensity (ui16 val)
  240. {
  241. totalDensity = val;
  242. }
  243. ui16 CRmgTemplateZone::getTotalDensity () const
  244. {
  245. return totalDensity;
  246. }
  247. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  248. {
  249. treasureInfo.push_back(info);
  250. }
  251. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  252. {
  253. return treasureInfo;
  254. }
  255. float3 CRmgTemplateZone::getCenter() const
  256. {
  257. return center;
  258. }
  259. void CRmgTemplateZone::setCenter(const float3 &f)
  260. {
  261. //limit boundaries to (0,1) square
  262. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  263. }
  264. bool CRmgTemplateZone::pointIsIn(int x, int y)
  265. {
  266. return true;
  267. }
  268. int3 CRmgTemplateZone::getPos() const
  269. {
  270. return pos;
  271. }
  272. void CRmgTemplateZone::setPos(const int3 &Pos)
  273. {
  274. pos = Pos;
  275. }
  276. void CRmgTemplateZone::addTile (const int3 &pos)
  277. {
  278. tileinfo.insert(pos);
  279. }
  280. std::set<int3> CRmgTemplateZone::getTileInfo () const
  281. {
  282. return tileinfo;
  283. }
  284. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  285. {
  286. for (auto tile : tileinfo)
  287. {
  288. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  289. {
  290. if (!vstd::contains(this->tileinfo, pos))
  291. {
  292. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  293. {
  294. if (gen->isPossible(pos))
  295. gen->setOccupied (pos, ETileType::BLOCKED);
  296. });
  297. }
  298. });
  299. }
  300. }
  301. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  302. {
  303. std::vector<int3> clearedTiles;
  304. std::set<int3> possibleTiles;
  305. std::set<int3> tilesToClear; //will be set clear
  306. std::set<int3> tilesToIgnore; //will be erased in this iteration
  307. const float minDistance = std::sqrt(totalDensity);
  308. for (auto tile : tileinfo)
  309. {
  310. if (gen->isFree(tile))
  311. clearedTiles.push_back(tile);
  312. else if (gen->isPossible(tile));
  313. possibleTiles.insert(tile);
  314. }
  315. if (clearedTiles.empty()) //this should come from zone connections
  316. {
  317. clearedTiles.push_back(pos); //zone center should be always clear
  318. }
  319. while (possibleTiles.size())
  320. {
  321. for (auto tileToMakePath : possibleTiles)
  322. {
  323. //find closest free tile
  324. float currentDistance = 1e10;
  325. int3 closestTile (-1,-1,-1);
  326. for (auto clearTile : clearedTiles)
  327. {
  328. float distance = tileToMakePath.dist2d(clearTile);
  329. if (distance < currentDistance)
  330. {
  331. currentDistance = distance;
  332. closestTile = clearTile;
  333. }
  334. if (currentDistance <= minDistance)
  335. {
  336. //this tile is close enough. Forget about it and check next one
  337. tilesToIgnore.insert (tileToMakePath);
  338. break;
  339. }
  340. }
  341. //if tiles is not close enough, make path to it
  342. if (currentDistance > minDistance)
  343. {
  344. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  345. break; //next iteration - use already cleared tiles
  346. }
  347. }
  348. for (auto tileToClear : tilesToClear)
  349. {
  350. //move cleared tiles from one set to another
  351. clearedTiles.push_back(tileToClear);
  352. vstd::erase_if_present(possibleTiles, tileToClear);
  353. }
  354. for (auto tileToClear : tilesToIgnore)
  355. {
  356. //these tiles are already connected, ignore them
  357. vstd::erase_if_present(possibleTiles, tileToClear);
  358. }
  359. if (tilesToClear.empty()) //nothing else can be done (?)
  360. break;
  361. tilesToClear.clear(); //empty this container
  362. tilesToIgnore.clear();
  363. }
  364. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  365. }
  366. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  367. {
  368. /*
  369. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  370. do not leave zone border
  371. */
  372. bool result = false;
  373. bool end = false;
  374. int3 currentPos = src;
  375. float distance = currentPos.dist2dSQ (dst);
  376. while (!end)
  377. {
  378. if (currentPos == dst)
  379. break;
  380. auto lastDistance = distance;
  381. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  382. {
  383. if (!result) //not sure if lambda is worth it...
  384. {
  385. if (pos == dst)
  386. {
  387. result = true;
  388. end = true;
  389. }
  390. if (pos.dist2dSQ (dst) < distance)
  391. {
  392. if (!gen->isBlocked(pos))
  393. {
  394. if (vstd::contains (tileinfo, pos))
  395. {
  396. if (gen->isPossible(pos))
  397. {
  398. gen->setOccupied (pos, ETileType::FREE);
  399. if (clearedTiles)
  400. clearedTiles->insert(pos);
  401. currentPos = pos;
  402. distance = currentPos.dist2dSQ (dst);
  403. }
  404. else if (gen->isFree(pos))
  405. {
  406. end = true;
  407. result = true;
  408. }
  409. else
  410. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  411. }
  412. }
  413. }
  414. }
  415. });
  416. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  417. {
  418. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  419. break;
  420. }
  421. }
  422. return result;
  423. }
  424. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  425. {
  426. requiredObjects.push_back(std::make_pair(obj, strength));
  427. }
  428. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  429. {
  430. //precalculate actual (randomized) monster strength based on this post
  431. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  432. int zoneMonsterStrength = 0; //TODO: range -1..1 based on template settings
  433. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  434. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  435. static const int value1[] = {2500, 1500, 1000, 500, 0};
  436. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  437. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  438. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  439. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  440. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  441. strength = strength1 + strength2;
  442. if (strength < 2000)
  443. return false; //no guard at all
  444. CreatureID creId = CreatureID::NONE;
  445. int amount = 0;
  446. std::vector<CreatureID> possibleCreatures;
  447. for (auto cre : VLC->creh->creatures)
  448. {
  449. if (cre->special)
  450. continue;
  451. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between minimum size of given stack and 100
  452. {
  453. possibleCreatures.push_back(cre->idNumber);
  454. }
  455. }
  456. if (possibleCreatures.size())
  457. {
  458. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  459. amount = strength / VLC->creh->creatures[creId]->AIValue;
  460. if (amount >= 4)
  461. amount *= gen->rand.nextDouble(0.75, 1.25);
  462. }
  463. else //just pick any available creature
  464. {
  465. creId = CreatureID(132); //Azure Dragon
  466. amount = strength / VLC->creh->creatures[creId]->AIValue;
  467. }
  468. auto guard = new CGCreature();
  469. guard->ID = Obj::MONSTER;
  470. guard->subID = creId;
  471. auto hlp = new CStackInstance(creId, amount);
  472. //will be set during initialization
  473. guard->putStack(SlotID(0), hlp);
  474. placeObject(gen, guard, pos);
  475. return true;
  476. }
  477. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  478. {
  479. std::map<int3, CGObjectInstance *> treasures;
  480. std::set<int3> boundary;
  481. int3 guardPos;
  482. int3 nextTreasurePos = pos;
  483. //default values
  484. int maxValue = 5000;
  485. int minValue = 1500;
  486. if (treasureInfo.size())
  487. {
  488. //roulette wheel
  489. int r = gen->rand.nextInt (1, totalDensity);
  490. for (auto t : treasureInfo)
  491. {
  492. if (r <= t.threshold)
  493. {
  494. maxValue = t.max;
  495. minValue = t.min;
  496. break;
  497. }
  498. }
  499. }
  500. int currentValue = 0;
  501. CGObjectInstance * object = nullptr;
  502. while (currentValue < minValue)
  503. {
  504. //TODO: this works only for 1-tile objects
  505. //make sure our shape is consistent
  506. treasures[nextTreasurePos] = nullptr;
  507. for (auto treasurePos : treasures)
  508. {
  509. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  510. {
  511. boundary.insert(pos);
  512. });
  513. }
  514. for (auto treasurePos : treasures)
  515. {
  516. //leaving only boundary around objects
  517. vstd::erase_if_present (boundary, treasurePos.first);
  518. }
  519. for (auto tile : boundary)
  520. {
  521. //we can't extend boundary anymore
  522. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  523. break;
  524. }
  525. int remaining = maxValue - currentValue;
  526. auto oi = getRandomObject(gen, remaining);
  527. object = oi.generateObject();
  528. if (!object)
  529. break;
  530. currentValue += oi.value;
  531. treasures[nextTreasurePos] = object;
  532. //now find place for next object
  533. int3 placeFound(-1,-1,-1);
  534. //FIXME: find out why teh following code causes crashes
  535. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  536. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  537. //for (auto tile : boundaryVec)
  538. for (auto tile : boundary)
  539. {
  540. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  541. {
  542. bool here = true;
  543. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  544. {
  545. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  546. here = false;
  547. });
  548. if (here)
  549. {
  550. placeFound = tile;
  551. break;
  552. }
  553. }
  554. }
  555. if (placeFound.valid())
  556. nextTreasurePos = placeFound;
  557. }
  558. if (treasures.size())
  559. {
  560. for (auto treasure : treasures)
  561. {
  562. placeObject(gen, treasure.second, treasure.first - treasure.second->getVisitableOffset());
  563. }
  564. crunchPath (gen, pos, getPos(), id); //make sure pile is connected to the middle of zone
  565. for (auto tile : boundary) //guard must be standing there
  566. {
  567. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  568. {
  569. guardPos = tile;
  570. break;
  571. }
  572. }
  573. if (addMonster(gen, guardPos, currentValue))
  574. {//block only if object is guarded
  575. for (auto tile : boundary)
  576. {
  577. if (gen->isPossible(tile))
  578. gen->setOccupied (tile, ETileType::BLOCKED);
  579. }
  580. }
  581. return true;
  582. }
  583. else //we did not place eveyrthing successfully
  584. return false;
  585. }
  586. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  587. {
  588. addAllPossibleObjects (gen);
  589. int townId = 0;
  590. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  591. {
  592. logGlobal->infoStream() << "Preparing playing zone";
  593. int player_id = *owner - 1;
  594. auto & playerInfo = gen->map->players[player_id];
  595. if (playerInfo.canAnyonePlay())
  596. {
  597. PlayerColor player(player_id);
  598. auto town = new CGTownInstance();
  599. town->ID = Obj::TOWN;
  600. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  601. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  602. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  603. town->subID = townId;
  604. town->tempOwner = player;
  605. town->builtBuildings.insert(BuildingID::FORT);
  606. town->builtBuildings.insert(BuildingID::DEFAULT);
  607. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  608. logGlobal->traceStream() << "Fill player info " << player_id;
  609. // Update player info
  610. playerInfo.allowedFactions.clear();
  611. playerInfo.allowedFactions.insert(townId);
  612. playerInfo.hasMainTown = true;
  613. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  614. playerInfo.generateHeroAtMainTown = true;
  615. //requiredObjects.push_back(town);
  616. std::vector<Res::ERes> required_mines;
  617. required_mines.push_back(Res::ERes::WOOD);
  618. required_mines.push_back(Res::ERes::ORE);
  619. for(const auto res : required_mines)
  620. {
  621. auto mine = new CGMine();
  622. mine->ID = Obj::MINE;
  623. mine->subID = static_cast<si32>(res);
  624. mine->producedResource = res;
  625. mine->producedQuantity = mine->defaultResProduction();
  626. addRequiredObject(mine);
  627. }
  628. }
  629. else
  630. {
  631. type = ETemplateZoneType::TREASURE;
  632. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  633. logGlobal->infoStream() << "Skipping this zone cause no player";
  634. }
  635. }
  636. else //no player
  637. {
  638. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  639. }
  640. //paint zone with matching terrain
  641. std::vector<int3> tiles;
  642. for (auto tile : tileinfo)
  643. {
  644. tiles.push_back (tile);
  645. }
  646. gen->editManager->getTerrainSelection().setSelection(tiles);
  647. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  648. logGlobal->infoStream() << "Creating required objects";
  649. for(const auto &obj : requiredObjects)
  650. {
  651. int3 pos;
  652. logGlobal->traceStream() << "Looking for place";
  653. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  654. {
  655. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  656. //TODO CLEANUP!
  657. return false;
  658. }
  659. logGlobal->traceStream() << "Place found";
  660. placeObject(gen, obj.first, pos);
  661. crunchPath (gen, pos, getPos(), id); //make sure pile is connected to the middle of zone
  662. if (obj.second)
  663. {
  664. guardObject (gen, obj.first, obj.second);
  665. }
  666. }
  667. const double res_mindist = 5;
  668. //TODO: just placeholder to chekc for possible locations
  669. do {
  670. int3 pos;
  671. if ( ! findPlaceForTreasurePile(gen, 3, pos))
  672. {
  673. break;
  674. }
  675. createTreasurePile (gen, pos);
  676. } while(true);
  677. auto sel = gen->editManager->getTerrainSelection();
  678. sel.clearSelection();
  679. for (auto tile : tileinfo)
  680. {
  681. //test code - block all the map to show paths clearly
  682. //if (gen->isPossible(tile))
  683. // gen->setOccupied(tile, ETileType::BLOCKED);
  684. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  685. {
  686. auto obj = new CGObjectInstance();
  687. obj->ID = static_cast<Obj>(130);
  688. obj->subID = 0;
  689. placeObject(gen, obj, tile);
  690. }
  691. }
  692. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  693. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  694. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  695. return true;
  696. }
  697. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  698. {
  699. //si32 min_dist = sqrt(tileinfo.size()/density);
  700. int best_distance = 0;
  701. bool result = false;
  702. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  703. for(auto tile : tileinfo)
  704. {
  705. auto dist = gen->getTile(tile).getNearestObjectDistance();
  706. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  707. {
  708. bool allTilesAvailable = true;
  709. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  710. {
  711. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  712. {
  713. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  714. }
  715. });
  716. if (allTilesAvailable)
  717. {
  718. best_distance = dist;
  719. pos = tile;
  720. result = true;
  721. }
  722. }
  723. }
  724. if (result)
  725. {
  726. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  727. }
  728. return result;
  729. }
  730. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  731. {
  732. //we need object apperance to deduce free tiles
  733. if (obj->appearance.id == Obj::NO_OBJ)
  734. {
  735. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  736. if (templates.empty())
  737. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  738. obj->appearance = templates.front();
  739. }
  740. //si32 min_dist = sqrt(tileinfo.size()/density);
  741. int best_distance = 0;
  742. bool result = false;
  743. si32 w = gen->map->width;
  744. si32 h = gen->map->height;
  745. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  746. auto tilesBlockedByObject = obj->getBlockedOffsets();
  747. for (auto tile : tileinfo)
  748. {
  749. //object must be accessible from at least one surounding tile
  750. bool accessible = false;
  751. for (int x = -1; x < 2; x++)
  752. for (int y = -1; y <2; y++)
  753. {
  754. if (x && y) //check only if object is visitable from another tile
  755. {
  756. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  757. if (!vstd::contains(tilesBlockedByObject, offset))
  758. {
  759. int3 nearbyPos = tile + offset;
  760. if (gen->map->isInTheMap(nearbyPos))
  761. {
  762. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  763. accessible = true;
  764. }
  765. }
  766. }
  767. };
  768. if (!accessible)
  769. continue;
  770. auto ti = gen->getTile(tile);
  771. auto dist = ti.getNearestObjectDistance();
  772. //avoid borders
  773. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  774. {
  775. bool allTilesAvailable = true;
  776. for (auto blockingTile : tilesBlockedByObject)
  777. {
  778. int3 t = tile + blockingTile;
  779. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  780. {
  781. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  782. break;
  783. }
  784. }
  785. if (allTilesAvailable)
  786. {
  787. best_distance = dist;
  788. pos = tile;
  789. result = true;
  790. }
  791. }
  792. }
  793. if (result)
  794. {
  795. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  796. }
  797. return result;
  798. }
  799. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  800. {
  801. if (!gen->map->isInTheMap(pos))
  802. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  803. object->pos = pos;
  804. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  805. throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
  806. for (auto tile : object->getBlockedPos())
  807. {
  808. if (!gen->map->isInTheMap(tile))
  809. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  810. }
  811. if (object->appearance.id == Obj::NO_OBJ)
  812. {
  813. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  814. if (templates.empty())
  815. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  816. object->appearance = templates.front();
  817. }
  818. gen->map->addBlockVisTiles(object);
  819. gen->editManager->insertObject(object, pos);
  820. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  821. }
  822. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  823. {
  824. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  825. checkAndPlaceObject (gen, object, pos);
  826. auto points = object->getBlockedPos();
  827. if (object->isVisitable())
  828. points.insert(pos + object->getVisitableOffset());
  829. points.insert(pos);
  830. for(auto p : points)
  831. {
  832. if (gen->map->isInTheMap(p))
  833. {
  834. gen->setOccupied(p, ETileType::USED);
  835. }
  836. }
  837. for(auto tile : tileinfo)
  838. {
  839. si32 d = pos.dist2d(tile);
  840. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  841. }
  842. }
  843. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  844. {
  845. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  846. int3 visitable = object->visitablePos();
  847. std::vector<int3> tiles;
  848. gen->foreach_neighbour(visitable, [&](int3& pos)
  849. {
  850. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  851. if (gen->isPossible(pos))
  852. {
  853. tiles.push_back(pos);
  854. };
  855. });
  856. if ( ! tiles.size())
  857. {
  858. logGlobal->infoStream() << "Failed";
  859. return false;
  860. }
  861. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  862. if (addMonster (gen, guard_tile, str)) //do not place obstacles around unguarded object
  863. {
  864. for (auto pos : tiles)
  865. gen->setOccupied(pos, ETileType::BLOCKED);
  866. gen->setOccupied (guard_tile, ETileType::USED);
  867. }
  868. else
  869. gen->setOccupied (guard_tile, ETileType::FREE);
  870. return true;
  871. }
  872. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  873. {
  874. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  875. ui32 total = 0;
  876. ui32 minValue = 0.25f * value;
  877. //roulette wheel
  878. for (auto oi : possibleObjects)
  879. {
  880. if (oi.value >= minValue && oi.value <= value)
  881. {
  882. //TODO: check place for non-removable object
  883. //problem: we need at least template for the object that does not yet exist
  884. total += oi.probability;
  885. tresholds.push_back (std::make_pair (total, oi));
  886. }
  887. }
  888. //TODO: generate pandora box with gold if the value is very high
  889. if (tresholds.empty())
  890. {
  891. ObjectInfo oi;
  892. if (minValue > 20000) //we don't have object valuable enough
  893. {
  894. oi.generateObject = [minValue]() -> CGObjectInstance *
  895. {
  896. auto obj = new CGPandoraBox();
  897. obj->ID = Obj::PANDORAS_BOX;
  898. obj->subID = 0;
  899. obj->resources[Res::GOLD] = minValue;
  900. return obj;
  901. };
  902. oi.value = minValue;
  903. oi.probability = 0;
  904. }
  905. else
  906. {
  907. oi.generateObject = [gen]() -> CGObjectInstance *
  908. {
  909. return nullptr;
  910. };
  911. oi.value = 0;
  912. oi.probability = 0;
  913. }
  914. return oi;
  915. }
  916. int r = gen->rand.nextInt (1, total);
  917. for (auto t : tresholds)
  918. {
  919. if (r <= t.first)
  920. return t.second;
  921. }
  922. }
  923. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  924. {
  925. //TODO: move typical objects to config
  926. ObjectInfo oi;
  927. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  928. for (int i = 0; i < 4; i++)
  929. {
  930. oi.generateObject = [i, gen]() -> CGObjectInstance *
  931. {
  932. auto obj = new CGResource();
  933. obj->ID = Obj::RESOURCE;
  934. obj->subID = static_cast<si32>(preciousRes[i]);
  935. obj->amount = 0;
  936. return obj;
  937. };
  938. oi.value = 1400;
  939. oi.probability = 300;
  940. possibleObjects.push_back (oi);
  941. }
  942. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  943. for (int i = 0; i < 2; i++)
  944. {
  945. oi.generateObject = [i, gen]() -> CGObjectInstance *
  946. {
  947. auto obj = new CGResource();
  948. obj->ID = Obj::RESOURCE;
  949. obj->subID = static_cast<si32>(woodOre[i]);
  950. obj->amount = 0;
  951. return obj;
  952. };
  953. oi.value = 1400;
  954. oi.probability = 300;
  955. possibleObjects.push_back (oi);
  956. }
  957. oi.generateObject = [gen]() -> CGObjectInstance *
  958. {
  959. auto obj = new CGResource();
  960. obj->ID = Obj::RESOURCE;
  961. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  962. obj->amount = 0;
  963. return obj;
  964. };
  965. oi.value = 750;
  966. oi.probability = 300;
  967. possibleObjects.push_back (oi);
  968. oi.generateObject = [gen]() -> CGObjectInstance *
  969. {
  970. auto obj = new CGPickable();
  971. obj->ID = Obj::TREASURE_CHEST;
  972. obj->subID = 0;
  973. return obj;
  974. };
  975. oi.value = 1500;
  976. oi.probability = 1000;
  977. possibleObjects.push_back (oi);
  978. oi.generateObject = [gen]() -> CGObjectInstance *
  979. {
  980. auto obj = new CGArtifact();
  981. obj->ID = Obj::RANDOM_TREASURE_ART;
  982. obj->subID = 0;
  983. auto a = new CArtifactInstance();
  984. gen->map->addNewArtifactInstance(a);
  985. obj->storedArtifact = a;
  986. return obj;
  987. };
  988. oi.value = 2000;
  989. oi.probability = 150;
  990. possibleObjects.push_back (oi);
  991. oi.generateObject = [gen]() -> CGObjectInstance *
  992. {
  993. auto obj = new CGArtifact();
  994. obj->ID = Obj::RANDOM_MINOR_ART;
  995. obj->subID = 0;
  996. auto a = new CArtifactInstance();
  997. gen->map->addNewArtifactInstance(a);
  998. obj->storedArtifact = a;
  999. return obj;
  1000. };
  1001. oi.value = 5000;
  1002. oi.probability = 150;
  1003. possibleObjects.push_back (oi);
  1004. oi.generateObject = [gen]() -> CGObjectInstance *
  1005. {
  1006. auto obj = new CGArtifact();
  1007. obj->ID = Obj::RANDOM_MAJOR_ART;
  1008. obj->subID = 0;
  1009. auto a = new CArtifactInstance();
  1010. gen->map->addNewArtifactInstance(a);
  1011. obj->storedArtifact = a;
  1012. return obj;
  1013. };
  1014. oi.value = 10000;
  1015. oi.probability = 150;
  1016. possibleObjects.push_back (oi);
  1017. oi.generateObject = [gen]() -> CGObjectInstance *
  1018. {
  1019. auto obj = new CGArtifact();
  1020. obj->ID = Obj::RANDOM_RELIC_ART;
  1021. obj->subID = 0;
  1022. auto a = new CArtifactInstance();
  1023. gen->map->addNewArtifactInstance(a);
  1024. obj->storedArtifact = a;
  1025. return obj;
  1026. };
  1027. oi.value = 20000;
  1028. oi.probability = 150;
  1029. possibleObjects.push_back (oi);
  1030. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1031. for (int i = 0; i < 5; i++)
  1032. {
  1033. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1034. {
  1035. auto obj = new CGArtifact();
  1036. obj->ID = Obj::SPELL_SCROLL;
  1037. obj->subID = 0;
  1038. std::vector<SpellID> out;
  1039. //TODO: unify with cb->getAllowedSpells?
  1040. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1041. {
  1042. const CSpell *spell = SpellID(i).toSpell();
  1043. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1044. {
  1045. out.push_back(spell->id);
  1046. }
  1047. }
  1048. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1049. gen->map->addNewArtifactInstance(a);
  1050. obj->storedArtifact = a;
  1051. return obj;
  1052. };
  1053. oi.value = scrollValues[i];
  1054. oi.probability = 30;
  1055. possibleObjects.push_back (oi);
  1056. }
  1057. //non-removable object for test
  1058. //oi.generateObject = [gen]() -> CGObjectInstance *
  1059. //{
  1060. // auto obj = new CGMagicWell();
  1061. // obj->ID = Obj::MAGIC_WELL;
  1062. // obj->subID = 0;
  1063. // return obj;
  1064. //};
  1065. //oi.value = 250;
  1066. //oi.probability = 100;
  1067. //possibleObjects.push_back (oi);
  1068. //oi.generateObject = [gen]() -> CGObjectInstance *
  1069. //{
  1070. // auto obj = new CGObelisk();
  1071. // obj->ID = Obj::OBELISK;
  1072. // obj->subID = 0;
  1073. // return obj;
  1074. //};
  1075. //oi.value = 3500;
  1076. //oi.probability = 200;
  1077. //possibleObjects.push_back (oi);
  1078. //oi.generateObject = [gen]() -> CGObjectInstance *
  1079. //{
  1080. // auto obj = new CBank();
  1081. // obj->ID = Obj::CREATURE_BANK;
  1082. // obj->subID = 5; //naga bank
  1083. // return obj;
  1084. //};
  1085. //oi.value = 3000;
  1086. //oi.probability = 100;
  1087. //possibleObjects.push_back (oi);
  1088. }