CRmgTemplateZone.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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)
  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::addTreasureInfo(CTreasureInfo & info)
  240. {
  241. treasureInfo.push_back(info);
  242. }
  243. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  244. {
  245. return treasureInfo;
  246. }
  247. float3 CRmgTemplateZone::getCenter() const
  248. {
  249. return center;
  250. }
  251. void CRmgTemplateZone::setCenter(const float3 &f)
  252. {
  253. //limit boundaries to (0,1) square
  254. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  255. }
  256. bool CRmgTemplateZone::pointIsIn(int x, int y)
  257. {
  258. return true;
  259. }
  260. int3 CRmgTemplateZone::getPos() const
  261. {
  262. return pos;
  263. }
  264. void CRmgTemplateZone::setPos(const int3 &Pos)
  265. {
  266. pos = Pos;
  267. }
  268. void CRmgTemplateZone::addTile (const int3 &pos)
  269. {
  270. tileinfo.insert(pos);
  271. }
  272. std::set<int3> CRmgTemplateZone::getTileInfo () const
  273. {
  274. return tileinfo;
  275. }
  276. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  277. {
  278. for (auto tile : tileinfo)
  279. {
  280. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  281. {
  282. if (!vstd::contains(this->tileinfo, pos))
  283. {
  284. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  285. {
  286. if (gen->isPossible(pos))
  287. gen->setOccupied (pos, ETileType::BLOCKED);
  288. });
  289. }
  290. });
  291. }
  292. }
  293. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone)
  294. {
  295. /*
  296. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  297. do not leave zone border
  298. */
  299. bool result = false;
  300. bool end = false;
  301. int3 currentPos = src;
  302. float distance = currentPos.dist2dSQ (dst);
  303. while (!end)
  304. {
  305. if (currentPos == dst)
  306. break;
  307. auto lastDistance = distance;
  308. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end](int3 &pos)
  309. {
  310. if (!result) //not sure if lambda is worth it...
  311. {
  312. if (pos == dst)
  313. {
  314. result = true;
  315. end = true;
  316. }
  317. if (pos.dist2dSQ (dst) < distance)
  318. {
  319. if (!gen->isBlocked(pos))
  320. {
  321. if (vstd::contains (tileinfo, pos))
  322. {
  323. if (gen->isPossible(pos))
  324. {
  325. gen->setOccupied (pos, ETileType::FREE);
  326. currentPos = pos;
  327. distance = currentPos.dist2dSQ (dst);
  328. }
  329. else if (gen->isFree(pos))
  330. {
  331. end = true;
  332. result = true;
  333. }
  334. else
  335. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  336. }
  337. }
  338. }
  339. }
  340. });
  341. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  342. {
  343. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  344. break;
  345. }
  346. }
  347. return result;
  348. }
  349. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  350. {
  351. requiredObjects.push_back(std::make_pair(obj, strength));
  352. }
  353. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  354. {
  355. //precalculate actual (randomized) monster strength based on this post
  356. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  357. int zoneMonsterStrength = 0; //TODO: range -1..1 based on template settings
  358. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  359. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  360. static const int value1[] = {2500, 1500, 1000, 500, 0};
  361. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  362. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  363. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  364. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  365. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  366. strength = strength1 + strength2;
  367. if (strength < 2000)
  368. return false; //no guard at all
  369. CreatureID creId = CreatureID::NONE;
  370. int amount = 0;
  371. std::vector<CreatureID> possibleCreatures;
  372. for (auto cre : VLC->creh->creatures)
  373. {
  374. if (cre->special)
  375. continue;
  376. 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
  377. {
  378. possibleCreatures.push_back(cre->idNumber);
  379. }
  380. }
  381. if (possibleCreatures.size())
  382. {
  383. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  384. amount = strength / VLC->creh->creatures[creId]->AIValue;
  385. if (amount >= 4)
  386. amount *= gen->rand.nextDouble(0.75, 1.25);
  387. }
  388. else //just pick any available creature
  389. {
  390. creId = CreatureID(132); //Azure Dragon
  391. amount = strength / VLC->creh->creatures[creId]->AIValue;
  392. }
  393. auto guard = new CGCreature();
  394. guard->ID = Obj::MONSTER;
  395. guard->subID = creId;
  396. auto hlp = new CStackInstance(creId, amount);
  397. //will be set during initialization
  398. guard->putStack(SlotID(0), hlp);
  399. placeObject(gen, guard, pos);
  400. return true;
  401. }
  402. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  403. {
  404. std::map<int3, CGObjectInstance *> treasures;
  405. std::set<int3> boundary;
  406. int3 guardPos;
  407. int3 nextTreasurePos = pos;
  408. //default values
  409. int maxValue = 5000;
  410. int minValue = 1500;
  411. if (treasureInfo.size())
  412. {
  413. //roulette wheel
  414. std::vector<std::pair<ui16, CTreasureInfo>> tresholds;
  415. ui16 total = 0;
  416. //TODO: precalculate density chance for entire zone
  417. for (auto ti : treasureInfo)
  418. {
  419. total += ti.density;
  420. tresholds.push_back (std::make_pair (total, ti));
  421. }
  422. int r = gen->rand.nextInt (1, total);
  423. for (auto t : tresholds)
  424. {
  425. if (r <= t.first)
  426. {
  427. maxValue = t.second.max;
  428. minValue = t.second.min;
  429. break;
  430. }
  431. }
  432. }
  433. int currentValue = 0;
  434. CGObjectInstance * object = nullptr;
  435. while (currentValue < minValue)
  436. {
  437. //TODO: this works only for 1-tile objects
  438. //make sure our shape is consistent
  439. treasures[nextTreasurePos] = nullptr;
  440. for (auto treasurePos : treasures)
  441. {
  442. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  443. {
  444. boundary.insert(pos);
  445. });
  446. }
  447. for (auto treasurePos : treasures)
  448. {
  449. //leaving only boundary around objects
  450. vstd::erase_if_present (boundary, treasurePos.first);
  451. }
  452. for (auto tile : boundary)
  453. {
  454. //we can't extend boundary anymore
  455. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  456. break;
  457. }
  458. int remaining = maxValue - currentValue;
  459. auto oi = getRandomObject(gen, remaining);
  460. object = oi.generateObject();
  461. if (!object)
  462. break;
  463. currentValue += oi.value;
  464. treasures[nextTreasurePos] = object;
  465. //now find place for next object
  466. int3 placeFound(-1,-1,-1);
  467. //FIXME: find out why teh following code causes crashes
  468. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  469. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  470. //for (auto tile : boundaryVec)
  471. for (auto tile : boundary)
  472. {
  473. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  474. {
  475. bool here = true;
  476. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  477. {
  478. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  479. here = false;
  480. });
  481. if (here)
  482. {
  483. placeFound = tile;
  484. break;
  485. }
  486. }
  487. }
  488. if (placeFound.valid())
  489. nextTreasurePos = placeFound;
  490. }
  491. if (treasures.size())
  492. {
  493. for (auto treasure : treasures)
  494. {
  495. placeObject(gen, treasure.second, treasure.first - treasure.second->getVisitableOffset());
  496. }
  497. std::vector<int3> accessibleTiles; //we can't place guard in dead-end of zone, make sure that at least one neightbouring tile is possible and not blocked
  498. for (auto tile : boundary)
  499. {
  500. if (gen->shouldBeBlocked(tile)) //this tile could be already blocked, don't place a monster here
  501. continue;
  502. bool possible = false;
  503. gen->foreach_neighbour(tile, [gen, &accessibleTiles, &possible, boundary](int3 pos)
  504. {
  505. if (gen->isPossible(pos) && !vstd::contains(boundary, pos)) //do not check tiles that are going to be blocked
  506. possible = true;
  507. });
  508. if (possible)
  509. accessibleTiles.push_back(tile);
  510. }
  511. guardPos = *RandomGeneratorUtil::nextItem(accessibleTiles, gen->rand);
  512. if (addMonster(gen, guardPos, currentValue))
  513. {//block only if object is guarded
  514. for (auto tile : boundary)
  515. {
  516. if (gen->isPossible(tile))
  517. gen->setOccupied (tile, ETileType::BLOCKED);
  518. }
  519. }
  520. return true;
  521. }
  522. else //we did not place eveyrthing successfully
  523. return false;
  524. }
  525. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  526. {
  527. addAllPossibleObjects (gen);
  528. int townId = 0;
  529. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  530. {
  531. logGlobal->infoStream() << "Preparing playing zone";
  532. int player_id = *owner - 1;
  533. auto & playerInfo = gen->map->players[player_id];
  534. if (playerInfo.canAnyonePlay())
  535. {
  536. PlayerColor player(player_id);
  537. auto town = new CGTownInstance();
  538. town->ID = Obj::TOWN;
  539. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  540. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  541. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  542. town->subID = townId;
  543. town->tempOwner = player;
  544. town->builtBuildings.insert(BuildingID::FORT);
  545. town->builtBuildings.insert(BuildingID::DEFAULT);
  546. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  547. logGlobal->traceStream() << "Fill player info " << player_id;
  548. // Update player info
  549. playerInfo.allowedFactions.clear();
  550. playerInfo.allowedFactions.insert(townId);
  551. playerInfo.hasMainTown = true;
  552. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  553. playerInfo.generateHeroAtMainTown = true;
  554. //requiredObjects.push_back(town);
  555. std::vector<Res::ERes> required_mines;
  556. required_mines.push_back(Res::ERes::WOOD);
  557. required_mines.push_back(Res::ERes::ORE);
  558. for(const auto res : required_mines)
  559. {
  560. auto mine = new CGMine();
  561. mine->ID = Obj::MINE;
  562. mine->subID = static_cast<si32>(res);
  563. mine->producedResource = res;
  564. mine->producedQuantity = mine->defaultResProduction();
  565. addRequiredObject(mine);
  566. }
  567. }
  568. else
  569. {
  570. type = ETemplateZoneType::TREASURE;
  571. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  572. logGlobal->infoStream() << "Skipping this zone cause no player";
  573. }
  574. }
  575. else //no player
  576. {
  577. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  578. }
  579. //paint zone with matching terrain
  580. std::vector<int3> tiles;
  581. for (auto tile : tileinfo)
  582. {
  583. tiles.push_back (tile);
  584. }
  585. gen->editManager->getTerrainSelection().setSelection(tiles);
  586. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  587. logGlobal->infoStream() << "Creating required objects";
  588. for(const auto &obj : requiredObjects)
  589. {
  590. int3 pos;
  591. logGlobal->traceStream() << "Looking for place";
  592. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  593. {
  594. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  595. //TODO CLEANUP!
  596. return false;
  597. }
  598. logGlobal->traceStream() << "Place found";
  599. placeObject(gen, obj.first, pos);
  600. if (obj.second)
  601. {
  602. guardObject (gen, obj.first, obj.second);
  603. }
  604. }
  605. const double res_mindist = 5;
  606. //TODO: just placeholder to chekc for possible locations
  607. do {
  608. int3 pos;
  609. if ( ! findPlaceForTreasurePile(gen, 5, pos))
  610. {
  611. break;
  612. }
  613. createTreasurePile (gen, pos);
  614. } while(true);
  615. auto sel = gen->editManager->getTerrainSelection();
  616. sel.clearSelection();
  617. for (auto tile : tileinfo)
  618. {
  619. //test code - block all the map to show paths clearly
  620. //if (gen->isPossible(tile))
  621. // gen->setOccupied(tile, ETileType::BLOCKED);
  622. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  623. {
  624. auto obj = new CGObjectInstance();
  625. obj->ID = static_cast<Obj>(130);
  626. obj->subID = 0;
  627. placeObject(gen, obj, tile);
  628. }
  629. }
  630. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  631. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  632. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  633. return true;
  634. }
  635. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  636. {
  637. //si32 min_dist = sqrt(tileinfo.size()/density);
  638. int best_distance = 0;
  639. bool result = false;
  640. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  641. for(auto tile : tileinfo)
  642. {
  643. auto dist = gen->getTile(tile).getNearestObjectDistance();
  644. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  645. {
  646. bool allTilesAvailable = true;
  647. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  648. {
  649. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  650. {
  651. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  652. }
  653. });
  654. if (allTilesAvailable)
  655. {
  656. best_distance = dist;
  657. pos = tile;
  658. result = true;
  659. }
  660. }
  661. }
  662. if (result)
  663. {
  664. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  665. }
  666. return result;
  667. }
  668. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  669. {
  670. //we need object apperance to deduce free tiles
  671. if (obj->appearance.id == Obj::NO_OBJ)
  672. {
  673. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  674. if (templates.empty())
  675. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  676. obj->appearance = templates.front();
  677. }
  678. //si32 min_dist = sqrt(tileinfo.size()/density);
  679. int best_distance = 0;
  680. bool result = false;
  681. si32 w = gen->map->width;
  682. si32 h = gen->map->height;
  683. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  684. auto tilesBlockedByObject = obj->getBlockedOffsets();
  685. for (auto tile : tileinfo)
  686. {
  687. //object must be accessible from at least one surounding tile
  688. bool accessible = false;
  689. for (int x = -1; x < 2; x++)
  690. for (int y = -1; y <2; y++)
  691. {
  692. if (x && y) //check only if object is visitable from another tile
  693. {
  694. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  695. if (!vstd::contains(tilesBlockedByObject, offset))
  696. {
  697. int3 nearbyPos = tile + offset;
  698. if (gen->map->isInTheMap(nearbyPos))
  699. {
  700. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  701. accessible = true;
  702. }
  703. }
  704. }
  705. };
  706. if (!accessible)
  707. continue;
  708. auto ti = gen->getTile(tile);
  709. auto dist = ti.getNearestObjectDistance();
  710. //avoid borders
  711. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  712. {
  713. bool allTilesAvailable = true;
  714. for (auto blockingTile : tilesBlockedByObject)
  715. {
  716. int3 t = tile + blockingTile;
  717. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  718. {
  719. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  720. break;
  721. }
  722. }
  723. if (allTilesAvailable)
  724. {
  725. best_distance = dist;
  726. pos = tile;
  727. result = true;
  728. }
  729. }
  730. }
  731. if (result)
  732. {
  733. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  734. }
  735. return result;
  736. }
  737. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  738. {
  739. if (!gen->map->isInTheMap(pos))
  740. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  741. object->pos = pos;
  742. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  743. 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()));
  744. for (auto tile : object->getBlockedPos())
  745. {
  746. if (!gen->map->isInTheMap(tile))
  747. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  748. }
  749. if (object->appearance.id == Obj::NO_OBJ)
  750. {
  751. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  752. if (templates.empty())
  753. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  754. object->appearance = templates.front();
  755. }
  756. gen->map->addBlockVisTiles(object);
  757. gen->editManager->insertObject(object, pos);
  758. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  759. }
  760. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  761. {
  762. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  763. checkAndPlaceObject (gen, object, pos);
  764. auto points = object->getBlockedPos();
  765. if (object->isVisitable())
  766. points.insert(pos + object->getVisitableOffset());
  767. points.insert(pos);
  768. for(auto p : points)
  769. {
  770. if (gen->map->isInTheMap(p))
  771. {
  772. gen->setOccupied(p, ETileType::USED);
  773. }
  774. }
  775. for(auto tile : tileinfo)
  776. {
  777. si32 d = pos.dist2d(tile);
  778. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  779. }
  780. }
  781. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  782. {
  783. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  784. int3 visitable = object->visitablePos();
  785. std::vector<int3> tiles;
  786. gen->foreach_neighbour(visitable, [&](int3& pos)
  787. {
  788. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  789. if (gen->isPossible(pos))
  790. {
  791. tiles.push_back(pos);
  792. };
  793. });
  794. if ( ! tiles.size())
  795. {
  796. logGlobal->infoStream() << "Failed";
  797. return false;
  798. }
  799. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  800. if (addMonster (gen, guard_tile, str)) //do not place obstacles around unguarded object
  801. {
  802. for (auto pos : tiles)
  803. gen->setOccupied(pos, ETileType::BLOCKED);
  804. gen->setOccupied (guard_tile, ETileType::USED);
  805. }
  806. else
  807. gen->setOccupied (guard_tile, ETileType::FREE);
  808. return true;
  809. }
  810. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  811. {
  812. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  813. ui32 total = 0;
  814. ui32 minValue = 0.25f * value;
  815. //roulette wheel
  816. for (auto oi : possibleObjects)
  817. {
  818. if (oi.value >= minValue && oi.value <= value)
  819. {
  820. //TODO: check place for non-removable object
  821. //problem: we need at least template for the object that does not yet exist
  822. total += oi.probability;
  823. tresholds.push_back (std::make_pair (total, oi));
  824. }
  825. }
  826. //TODO: generate pandora box with gold if the value is very high
  827. if (tresholds.empty())
  828. {
  829. ObjectInfo oi;
  830. if (minValue > 20000) //we don't have object valuable enough
  831. {
  832. oi.generateObject = [minValue]() -> CGObjectInstance *
  833. {
  834. auto obj = new CGPandoraBox();
  835. obj->ID = Obj::PANDORAS_BOX;
  836. obj->subID = 0;
  837. obj->resources[Res::GOLD] = minValue;
  838. return obj;
  839. };
  840. oi.value = minValue;
  841. oi.probability = 0;
  842. }
  843. else
  844. {
  845. oi.generateObject = [gen]() -> CGObjectInstance *
  846. {
  847. return nullptr;
  848. };
  849. oi.value = 0;
  850. oi.probability = 0;
  851. }
  852. return oi;
  853. }
  854. int r = gen->rand.nextInt (1, total);
  855. for (auto t : tresholds)
  856. {
  857. if (r <= t.first)
  858. return t.second;
  859. }
  860. }
  861. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  862. {
  863. //TODO: move typical objects to config
  864. ObjectInfo oi;
  865. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  866. for (int i = 0; i < 4; i++)
  867. {
  868. oi.generateObject = [i, gen]() -> CGObjectInstance *
  869. {
  870. auto obj = new CGResource();
  871. obj->ID = Obj::RESOURCE;
  872. obj->subID = static_cast<si32>(preciousRes[i]);
  873. obj->amount = 0;
  874. return obj;
  875. };
  876. oi.value = 1400;
  877. oi.probability = 300;
  878. possibleObjects.push_back (oi);
  879. }
  880. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  881. for (int i = 0; i < 2; i++)
  882. {
  883. oi.generateObject = [i, gen]() -> CGObjectInstance *
  884. {
  885. auto obj = new CGResource();
  886. obj->ID = Obj::RESOURCE;
  887. obj->subID = static_cast<si32>(woodOre[i]);
  888. obj->amount = 0;
  889. return obj;
  890. };
  891. oi.value = 1400;
  892. oi.probability = 300;
  893. possibleObjects.push_back (oi);
  894. }
  895. oi.generateObject = [gen]() -> CGObjectInstance *
  896. {
  897. auto obj = new CGResource();
  898. obj->ID = Obj::RESOURCE;
  899. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  900. obj->amount = 0;
  901. return obj;
  902. };
  903. oi.value = 750;
  904. oi.probability = 300;
  905. possibleObjects.push_back (oi);
  906. oi.generateObject = [gen]() -> CGObjectInstance *
  907. {
  908. auto obj = new CGPickable();
  909. obj->ID = Obj::TREASURE_CHEST;
  910. obj->subID = 0;
  911. return obj;
  912. };
  913. oi.value = 1500;
  914. oi.probability = 1000;
  915. possibleObjects.push_back (oi);
  916. oi.generateObject = [gen]() -> CGObjectInstance *
  917. {
  918. auto obj = new CGArtifact();
  919. obj->ID = Obj::RANDOM_TREASURE_ART;
  920. obj->subID = 0;
  921. auto a = new CArtifactInstance();
  922. gen->map->addNewArtifactInstance(a);
  923. obj->storedArtifact = a;
  924. return obj;
  925. };
  926. oi.value = 2000;
  927. oi.probability = 150;
  928. possibleObjects.push_back (oi);
  929. oi.generateObject = [gen]() -> CGObjectInstance *
  930. {
  931. auto obj = new CGArtifact();
  932. obj->ID = Obj::RANDOM_MINOR_ART;
  933. obj->subID = 0;
  934. auto a = new CArtifactInstance();
  935. gen->map->addNewArtifactInstance(a);
  936. obj->storedArtifact = a;
  937. return obj;
  938. };
  939. oi.value = 5000;
  940. oi.probability = 150;
  941. possibleObjects.push_back (oi);
  942. oi.generateObject = [gen]() -> CGObjectInstance *
  943. {
  944. auto obj = new CGArtifact();
  945. obj->ID = Obj::RANDOM_MAJOR_ART;
  946. obj->subID = 0;
  947. auto a = new CArtifactInstance();
  948. gen->map->addNewArtifactInstance(a);
  949. obj->storedArtifact = a;
  950. return obj;
  951. };
  952. oi.value = 10000;
  953. oi.probability = 150;
  954. possibleObjects.push_back (oi);
  955. oi.generateObject = [gen]() -> CGObjectInstance *
  956. {
  957. auto obj = new CGArtifact();
  958. obj->ID = Obj::RANDOM_RELIC_ART;
  959. obj->subID = 0;
  960. auto a = new CArtifactInstance();
  961. gen->map->addNewArtifactInstance(a);
  962. obj->storedArtifact = a;
  963. return obj;
  964. };
  965. oi.value = 20000;
  966. oi.probability = 150;
  967. possibleObjects.push_back (oi);
  968. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  969. for (int i = 0; i < 5; i++)
  970. {
  971. oi.generateObject = [i, gen]() -> CGObjectInstance *
  972. {
  973. auto obj = new CGArtifact();
  974. obj->ID = Obj::SPELL_SCROLL;
  975. obj->subID = 0;
  976. std::vector<SpellID> out;
  977. //TODO: unify with cb->getAllowedSpells?
  978. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  979. {
  980. const CSpell *spell = SpellID(i).toSpell();
  981. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  982. {
  983. out.push_back(spell->id);
  984. }
  985. }
  986. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  987. gen->map->addNewArtifactInstance(a);
  988. obj->storedArtifact = a;
  989. return obj;
  990. };
  991. oi.value = scrollValues[i];
  992. oi.probability = 30;
  993. possibleObjects.push_back (oi);
  994. }
  995. //non-removable object for test
  996. //oi.generateObject = [gen]() -> CGObjectInstance *
  997. //{
  998. // auto obj = new CGMagicWell();
  999. // obj->ID = Obj::MAGIC_WELL;
  1000. // obj->subID = 0;
  1001. // return obj;
  1002. //};
  1003. //oi.value = 250;
  1004. //oi.probability = 100;
  1005. //possibleObjects.push_back (oi);
  1006. //oi.generateObject = [gen]() -> CGObjectInstance *
  1007. //{
  1008. // auto obj = new CGObelisk();
  1009. // obj->ID = Obj::OBELISK;
  1010. // obj->subID = 0;
  1011. // return obj;
  1012. //};
  1013. //oi.value = 3500;
  1014. //oi.probability = 200;
  1015. //possibleObjects.push_back (oi);
  1016. //oi.generateObject = [gen]() -> CGObjectInstance *
  1017. //{
  1018. // auto obj = new CBank();
  1019. // obj->ID = Obj::CREATURE_BANK;
  1020. // obj->subID = 5; //naga bank
  1021. // return obj;
  1022. //};
  1023. //oi.value = 3000;
  1024. //oi.probability = 100;
  1025. //possibleObjects.push_back (oi);
  1026. }