CRmgTemplateZone.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  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. #include "../mapObjects/CommonConstructors.h"
  19. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  20. #include "../mapObjects/CGPandoraBox.h"
  21. #include "../mapObjects/CRewardableObject.h"
  22. class CMap;
  23. class CMapEditManager;
  24. //class CGObjectInstance;
  25. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  26. {
  27. }
  28. int CRmgTemplateZone::CTownInfo::getTownCount() const
  29. {
  30. return townCount;
  31. }
  32. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  33. {
  34. if(value < 0)
  35. throw rmgException("Negative value for town count not allowed.");
  36. townCount = value;
  37. }
  38. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  39. {
  40. return castleCount;
  41. }
  42. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  43. {
  44. if(value < 0)
  45. throw rmgException("Negative value for castle count not allowed.");
  46. castleCount = value;
  47. }
  48. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  49. {
  50. return townDensity;
  51. }
  52. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  53. {
  54. if(value < 0)
  55. throw rmgException("Negative value for town density not allowed.");
  56. townDensity = value;
  57. }
  58. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  59. {
  60. return castleDensity;
  61. }
  62. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  63. {
  64. if(value < 0)
  65. throw rmgException("Negative value for castle density not allowed.");
  66. castleDensity = value;
  67. }
  68. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  69. {
  70. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  71. }
  72. int CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(int value)
  77. {
  78. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  79. }
  80. bool CTileInfo::shouldBeBlocked() const
  81. {
  82. return occupied == ETileType::BLOCKED;
  83. }
  84. bool CTileInfo::isBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  87. }
  88. bool CTileInfo::isPossible() const
  89. {
  90. return occupied == ETileType::POSSIBLE;
  91. }
  92. bool CTileInfo::isFree() const
  93. {
  94. return occupied == ETileType::FREE;
  95. }
  96. bool CTileInfo::isUsed() const
  97. {
  98. return occupied == ETileType::USED;
  99. }
  100. void CTileInfo::setOccupied(ETileType::ETileType value)
  101. {
  102. occupied = value;
  103. }
  104. ETerrainType CTileInfo::getTerrainType() const
  105. {
  106. return terrain;
  107. }
  108. void CTileInfo::setTerrainType(ETerrainType value)
  109. {
  110. terrain = value;
  111. }
  112. CRmgTemplateZone::CRmgTemplateZone() :
  113. id(0),
  114. type(ETemplateZoneType::PLAYER_START),
  115. size(1),
  116. townsAreSameType(false),
  117. matchTerrainToTown(true),
  118. townType(0),
  119. terrainType (ETerrainType::GRASS),
  120. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  121. totalDensity(0)
  122. {
  123. townTypes = getDefaultTownTypes();
  124. terrainTypes = getDefaultTerrainTypes();
  125. }
  126. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  127. {
  128. return id;
  129. }
  130. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  131. {
  132. if(value <= 0)
  133. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  134. id = value;
  135. }
  136. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  137. {
  138. return type;
  139. }
  140. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  141. {
  142. type = value;
  143. }
  144. int CRmgTemplateZone::getSize() const
  145. {
  146. return size;
  147. }
  148. void CRmgTemplateZone::setSize(int value)
  149. {
  150. if(value <= 0)
  151. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  152. size = value;
  153. }
  154. boost::optional<int> CRmgTemplateZone::getOwner() const
  155. {
  156. return owner;
  157. }
  158. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  159. {
  160. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  161. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  162. owner = value;
  163. }
  164. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  165. {
  166. return playerTowns;
  167. }
  168. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  169. {
  170. playerTowns = value;
  171. }
  172. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  173. {
  174. return neutralTowns;
  175. }
  176. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  177. {
  178. neutralTowns = value;
  179. }
  180. bool CRmgTemplateZone::getTownsAreSameType() const
  181. {
  182. return townsAreSameType;
  183. }
  184. void CRmgTemplateZone::setTownsAreSameType(bool value)
  185. {
  186. townsAreSameType = value;
  187. }
  188. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  189. {
  190. return townTypes;
  191. }
  192. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  193. {
  194. townTypes = value;
  195. }
  196. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  197. {
  198. std::set<TFaction> defaultTowns;
  199. auto towns = VLC->townh->getDefaultAllowed();
  200. for(int i = 0; i < towns.size(); ++i)
  201. {
  202. if(towns[i]) defaultTowns.insert(i);
  203. }
  204. return defaultTowns;
  205. }
  206. bool CRmgTemplateZone::getMatchTerrainToTown() const
  207. {
  208. return matchTerrainToTown;
  209. }
  210. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  211. {
  212. matchTerrainToTown = value;
  213. }
  214. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  215. {
  216. return terrainTypes;
  217. }
  218. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  219. {
  220. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  221. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  222. terrainTypes = value;
  223. }
  224. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  225. {
  226. std::set<ETerrainType> terTypes;
  227. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  228. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  229. for (auto & allowedTerType : allowedTerTypes)
  230. terTypes.insert(allowedTerType);
  231. return terTypes;
  232. }
  233. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  234. {
  235. mines[res] = amount;
  236. }
  237. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  238. {
  239. return mines;
  240. }
  241. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  242. {
  243. connections.push_back (otherZone);
  244. }
  245. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  246. {
  247. return connections;
  248. }
  249. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  250. {
  251. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  252. zoneMonsterStrength = val;
  253. }
  254. void CRmgTemplateZone::setTotalDensity (ui16 val)
  255. {
  256. totalDensity = val;
  257. }
  258. ui16 CRmgTemplateZone::getTotalDensity () const
  259. {
  260. return totalDensity;
  261. }
  262. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  263. {
  264. treasureInfo.push_back(info);
  265. }
  266. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  267. {
  268. return treasureInfo;
  269. }
  270. std::set<int3>* CRmgTemplateZone::getFreePaths()
  271. {
  272. return &freePaths;
  273. }
  274. float3 CRmgTemplateZone::getCenter() const
  275. {
  276. return center;
  277. }
  278. void CRmgTemplateZone::setCenter(const float3 &f)
  279. {
  280. //limit boundaries to (0,1) square
  281. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  282. }
  283. bool CRmgTemplateZone::pointIsIn(int x, int y)
  284. {
  285. return true;
  286. }
  287. int3 CRmgTemplateZone::getPos() const
  288. {
  289. return pos;
  290. }
  291. void CRmgTemplateZone::setPos(const int3 &Pos)
  292. {
  293. pos = Pos;
  294. }
  295. void CRmgTemplateZone::addTile (const int3 &pos)
  296. {
  297. tileinfo.insert(pos);
  298. }
  299. std::set<int3> CRmgTemplateZone::getTileInfo () const
  300. {
  301. return tileinfo;
  302. }
  303. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, int distance)
  304. {
  305. for (auto tile : tileinfo)
  306. {
  307. if (tile.dist2d(this->pos) > distance)
  308. {
  309. gen->setOccupied(tile, ETileType::USED);
  310. //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  311. }
  312. }
  313. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  314. {
  315. return tile.dist2d(this->pos) > distance;
  316. });
  317. }
  318. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  319. {
  320. for (auto tile : tileinfo)
  321. {
  322. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  323. {
  324. if (!vstd::contains(this->tileinfo, pos))
  325. {
  326. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  327. {
  328. if (gen->isPossible(pos))
  329. gen->setOccupied (pos, ETileType::BLOCKED);
  330. });
  331. }
  332. });
  333. }
  334. }
  335. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  336. {
  337. std::vector<int3> clearedTiles;
  338. std::set<int3> possibleTiles;
  339. std::set<int3> tilesToClear; //will be set clear
  340. std::set<int3> tilesToIgnore; //will be erased in this iteration
  341. const float minDistance = std::sqrt(totalDensity);
  342. for (auto tile : tileinfo)
  343. {
  344. if (gen->isFree(tile))
  345. clearedTiles.push_back(tile);
  346. else if (gen->isPossible(tile))
  347. possibleTiles.insert(tile);
  348. }
  349. if (clearedTiles.empty()) //this should come from zone connections
  350. {
  351. clearedTiles.push_back(pos); //zone center should be always clear
  352. }
  353. while (possibleTiles.size())
  354. {
  355. for (auto tileToMakePath : possibleTiles)
  356. {
  357. //find closest free tile
  358. float currentDistance = 1e10;
  359. int3 closestTile (-1,-1,-1);
  360. for (auto clearTile : clearedTiles)
  361. {
  362. float distance = tileToMakePath.dist2d(clearTile);
  363. if (distance < currentDistance)
  364. {
  365. currentDistance = distance;
  366. closestTile = clearTile;
  367. }
  368. if (currentDistance <= minDistance)
  369. {
  370. //this tile is close enough. Forget about it and check next one
  371. tilesToIgnore.insert (tileToMakePath);
  372. break;
  373. }
  374. }
  375. //if tiles is not close enough, make path to it
  376. if (currentDistance > minDistance)
  377. {
  378. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  379. break; //next iteration - use already cleared tiles
  380. }
  381. }
  382. for (auto tileToClear : tilesToClear)
  383. {
  384. //move cleared tiles from one set to another
  385. clearedTiles.push_back(tileToClear);
  386. vstd::erase_if_present(possibleTiles, tileToClear);
  387. }
  388. for (auto tileToClear : tilesToIgnore)
  389. {
  390. //these tiles are already connected, ignore them
  391. vstd::erase_if_present(possibleTiles, tileToClear);
  392. }
  393. if (tilesToClear.empty()) //nothing else can be done (?)
  394. break;
  395. tilesToClear.clear(); //empty this container
  396. tilesToIgnore.clear();
  397. }
  398. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  399. }
  400. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  401. {
  402. /*
  403. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  404. do not leave zone border
  405. */
  406. bool result = false;
  407. bool end = false;
  408. int3 currentPos = src;
  409. float distance = currentPos.dist2dSQ (dst);
  410. while (!end)
  411. {
  412. if (currentPos == dst)
  413. {
  414. result = true;
  415. break;
  416. }
  417. auto lastDistance = distance;
  418. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  419. {
  420. if (!result) //not sure if lambda is worth it...
  421. {
  422. if (pos == dst)
  423. {
  424. result = true;
  425. end = true;
  426. }
  427. if (pos.dist2dSQ (dst) < distance)
  428. {
  429. if (!gen->isBlocked(pos))
  430. {
  431. if (vstd::contains (tileinfo, pos))
  432. {
  433. if (gen->isPossible(pos))
  434. {
  435. gen->setOccupied (pos, ETileType::FREE);
  436. if (clearedTiles)
  437. clearedTiles->insert(pos);
  438. currentPos = pos;
  439. distance = currentPos.dist2dSQ (dst);
  440. }
  441. else if (gen->isFree(pos))
  442. {
  443. end = true;
  444. result = true;
  445. }
  446. else
  447. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  448. }
  449. }
  450. }
  451. }
  452. });
  453. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  454. {
  455. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  456. break;
  457. }
  458. }
  459. return result;
  460. }
  461. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  462. {
  463. requiredObjects.push_back(std::make_pair(obj, strength));
  464. }
  465. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  466. {
  467. //precalculate actual (randomized) monster strength based on this post
  468. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  469. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  470. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  471. static const int value1[] = {2500, 1500, 1000, 500, 0};
  472. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  473. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  474. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  475. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  476. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  477. strength = strength1 + strength2;
  478. if (strength < 2000)
  479. return false; //no guard at all
  480. CreatureID creId = CreatureID::NONE;
  481. int amount = 0;
  482. std::vector<CreatureID> possibleCreatures;
  483. for (auto cre : VLC->creh->creatures)
  484. {
  485. if (cre->special)
  486. continue;
  487. 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
  488. {
  489. possibleCreatures.push_back(cre->idNumber);
  490. }
  491. }
  492. if (possibleCreatures.size())
  493. {
  494. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  495. amount = strength / VLC->creh->creatures[creId]->AIValue;
  496. if (amount >= 4)
  497. amount *= gen->rand.nextDouble(0.75, 1.25);
  498. }
  499. else //just pick any available creature
  500. {
  501. creId = CreatureID(132); //Azure Dragon
  502. amount = strength / VLC->creh->creatures[creId]->AIValue;
  503. }
  504. auto guard = new CGCreature();
  505. guard->ID = Obj::MONSTER;
  506. guard->subID = creId;
  507. auto hlp = new CStackInstance(creId, amount);
  508. //will be set during initialization
  509. guard->putStack(SlotID(0), hlp);
  510. placeObject(gen, guard, pos);
  511. return true;
  512. }
  513. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  514. {
  515. std::map<int3, CGObjectInstance *> treasures;
  516. std::set<int3> boundary;
  517. int3 guardPos (-1,-1,-1);
  518. int3 nextTreasurePos = pos;
  519. //default values
  520. int maxValue = 5000;
  521. int minValue = 1500;
  522. if (treasureInfo.size())
  523. {
  524. //roulette wheel
  525. int r = gen->rand.nextInt (1, totalDensity);
  526. for (auto t : treasureInfo)
  527. {
  528. if (r <= t.threshold)
  529. {
  530. maxValue = t.max;
  531. minValue = t.min;
  532. break;
  533. }
  534. }
  535. }
  536. int currentValue = 0;
  537. CGObjectInstance * object = nullptr;
  538. while (currentValue < minValue)
  539. {
  540. //TODO: this works only for 1-tile objects
  541. //make sure our shape is consistent
  542. treasures[nextTreasurePos] = nullptr;
  543. for (auto treasurePos : treasures)
  544. {
  545. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  546. {
  547. boundary.insert(pos);
  548. });
  549. }
  550. for (auto treasurePos : treasures)
  551. {
  552. //leaving only boundary around objects
  553. vstd::erase_if_present (boundary, treasurePos.first);
  554. }
  555. for (auto tile : boundary)
  556. {
  557. //we can't extend boundary anymore
  558. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  559. break;
  560. }
  561. int remaining = maxValue - currentValue;
  562. auto oi = getRandomObject(gen, remaining);
  563. object = oi.generateObject();
  564. if (!object)
  565. break;
  566. currentValue += oi.value;
  567. treasures[nextTreasurePos] = object;
  568. //now find place for next object
  569. int3 placeFound(-1,-1,-1);
  570. //FIXME: find out why teh following code causes crashes
  571. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  572. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  573. //for (auto tile : boundaryVec)
  574. for (auto tile : boundary)
  575. {
  576. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  577. {
  578. bool here = true;
  579. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  580. {
  581. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  582. here = false;
  583. });
  584. if (here)
  585. {
  586. placeFound = tile;
  587. break;
  588. }
  589. }
  590. }
  591. if (placeFound.valid())
  592. nextTreasurePos = placeFound;
  593. }
  594. if (treasures.size())
  595. {
  596. //find object closest to zone center, then con nect it to the middle of the zone
  597. int3 zoneCenter = getPos();
  598. int3 closestTile = int3(-1,-1,-1);
  599. float minDistance = 1e10;
  600. for (auto treasure : treasures)
  601. {
  602. if (zoneCenter.dist2d(treasure.first) < minDistance)
  603. {
  604. closestTile = treasure.first;
  605. minDistance = zoneCenter.dist2d(treasure.first);
  606. }
  607. }
  608. assert (closestTile.valid());
  609. if (!crunchPath (gen, closestTile, getPos(), id)) //make sure pile is connected to the middle of zone
  610. {
  611. for (auto treasure : treasures)
  612. {
  613. if (gen->isPossible(treasure.first))
  614. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  615. }
  616. return true;
  617. }
  618. for (auto tile : boundary) //guard must be standing there
  619. {
  620. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  621. {
  622. guardPos = tile;
  623. break;
  624. }
  625. }
  626. if (guardPos.valid())
  627. {
  628. for (auto treasure : treasures)
  629. {
  630. bool objectFitsHere = true; //temporary workaround
  631. int3 visitableOffset = treasure.second->getVisitableOffset();
  632. std::set<int3> blockedOffsets = treasure.second->getBlockedOffsets();
  633. blockedOffsets.insert (visitableOffset);
  634. for (auto blockingTile : blockedOffsets)
  635. {
  636. int3 t = treasure.first + visitableOffset + blockingTile;
  637. if (!gen->map->isInTheMap(t))
  638. {
  639. objectFitsHere = false; //if at least one tile is not possible, object can't be placed here
  640. break;
  641. }
  642. }
  643. if (objectFitsHere)
  644. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  645. }
  646. if (addMonster(gen, guardPos, currentValue))
  647. {//block only if the object is guarded
  648. for (auto tile : boundary)
  649. {
  650. if (gen->isPossible(tile))
  651. gen->setOccupied (tile, ETileType::BLOCKED);
  652. }
  653. }
  654. }
  655. else //we couldn't make a connection to this location, block it
  656. {
  657. for (auto treasure : treasures)
  658. {
  659. if (gen->isPossible(treasure.first))
  660. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  661. }
  662. }
  663. return true;
  664. }
  665. else //we did not place eveyrthing successfully
  666. return false;
  667. }
  668. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  669. {
  670. //FIXME: handle case that this player is not present -> towns should be set to neutral
  671. int totalTowns = 0;
  672. auto addNewTowns = [&totalTowns, gen, this](int count, bool hasFort, PlayerColor player)
  673. {
  674. for (int i = 0; i < count; i++)
  675. {
  676. auto town = new CGTownInstance();
  677. town->ID = Obj::TOWN;
  678. if (this->townsAreSameType)
  679. town->subID = townType;
  680. else
  681. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  682. town->tempOwner = player;
  683. if (hasFort)
  684. town->builtBuildings.insert(BuildingID::FORT);
  685. town->builtBuildings.insert(BuildingID::DEFAULT);
  686. if (!totalTowns)
  687. {
  688. //first town in zone sets the facton of entire zone
  689. town->subID = townType;
  690. //first town in zone goes in the middle
  691. placeObject(gen, town, getPos() + town->getVisitableOffset());
  692. }
  693. else
  694. addRequiredObject (town);
  695. totalTowns++;
  696. }
  697. };
  698. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  699. {
  700. //set zone types to player faction, generate main town
  701. logGlobal->infoStream() << "Preparing playing zone";
  702. int player_id = *owner - 1;
  703. auto & playerInfo = gen->map->players[player_id];
  704. if (playerInfo.canAnyonePlay())
  705. {
  706. PlayerColor player(player_id);
  707. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  708. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  709. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  710. auto town = new CGTownInstance();
  711. town->ID = Obj::TOWN;
  712. town->subID = townType;
  713. town->tempOwner = player;
  714. town->builtBuildings.insert(BuildingID::FORT);
  715. town->builtBuildings.insert(BuildingID::DEFAULT);
  716. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  717. totalTowns++;
  718. logGlobal->traceStream() << "Fill player info " << player_id;
  719. // Update player info
  720. playerInfo.allowedFactions.clear();
  721. playerInfo.allowedFactions.insert (townType);
  722. playerInfo.hasMainTown = true;
  723. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  724. playerInfo.generateHeroAtMainTown = true;
  725. //now create actual towns
  726. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  727. addNewTowns (playerTowns.getTownCount(), false, player);
  728. //requiredObjects.push_back(town);
  729. }
  730. else
  731. {
  732. type = ETemplateZoneType::TREASURE;
  733. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  734. logGlobal->infoStream() << "Skipping this zone cause no player";
  735. }
  736. }
  737. else //no player
  738. {
  739. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  740. }
  741. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  742. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  743. }
  744. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  745. {
  746. if (matchTerrainToTown)
  747. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  748. else
  749. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  750. //TODO: allow new types of terrain?
  751. if (pos.z)
  752. {
  753. if (terrainType != ETerrainType::LAVA)
  754. terrainType = ETerrainType::SUBTERRANEAN;
  755. }
  756. else
  757. {
  758. if (terrainType == ETerrainType::SUBTERRANEAN)
  759. terrainType = ETerrainType::DIRT;
  760. }
  761. paintZoneTerrain (gen, terrainType);
  762. }
  763. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  764. {
  765. std::vector<int3> tiles;
  766. for (auto tile : tileinfo)
  767. {
  768. tiles.push_back (tile);
  769. }
  770. gen->editManager->getTerrainSelection().setSelection(tiles);
  771. gen->editManager->drawTerrain(terrainType, &gen->rand);
  772. }
  773. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  774. {
  775. std::vector<Res::ERes> required_mines;
  776. required_mines.push_back(Res::ERes::WOOD);
  777. required_mines.push_back(Res::ERes::ORE);
  778. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  779. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  780. //TODO: factory / copy constructor?
  781. for (const auto & res : woodOre)
  782. {
  783. //TODO: these 2 should be close to town (within 12 tiles radius)
  784. for (int i = 0; i < mines[res]; i++)
  785. {
  786. auto mine = new CGMine();
  787. mine->ID = Obj::MINE;
  788. mine->subID = static_cast<si32>(res);
  789. mine->producedResource = res;
  790. mine->producedQuantity = mine->defaultResProduction();
  791. addRequiredObject(mine, 1500);
  792. }
  793. }
  794. for (const auto & res : preciousResources)
  795. {
  796. for (int i = 0; i < mines[res]; i++)
  797. {
  798. auto mine = new CGMine();
  799. mine->ID = Obj::MINE;
  800. mine->subID = static_cast<si32>(res);
  801. mine->producedResource = res;
  802. mine->producedQuantity = mine->defaultResProduction();
  803. addRequiredObject(mine, 3500);
  804. }
  805. }
  806. for (int i = 0; i < mines[Res::GOLD]; i++)
  807. {
  808. auto mine = new CGMine();
  809. mine->ID = Obj::MINE;
  810. mine->subID = static_cast<si32>(Res::GOLD);
  811. mine->producedResource = Res::GOLD;
  812. mine->producedQuantity = mine->defaultResProduction();
  813. addRequiredObject(mine, 7000);
  814. }
  815. return true;
  816. }
  817. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  818. {
  819. logGlobal->infoStream() << "Creating required objects";
  820. for(const auto &obj : requiredObjects)
  821. {
  822. int3 pos;
  823. logGlobal->traceStream() << "Looking for place";
  824. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  825. {
  826. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  827. //TODO CLEANUP!
  828. return false;
  829. }
  830. logGlobal->traceStream() << "Place found";
  831. placeObject(gen, obj.first, pos);
  832. guardObject (gen, obj.first, obj.second);
  833. }
  834. return true;
  835. }
  836. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  837. {
  838. const double minDistance = 3;
  839. do {
  840. int3 pos;
  841. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  842. {
  843. break;
  844. }
  845. createTreasurePile (gen, pos);
  846. } while(true);
  847. }
  848. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  849. {
  850. if (pos.z) //underground
  851. {
  852. std::vector<int3> rockTiles;
  853. for (auto tile : tileinfo)
  854. {
  855. if (gen->shouldBeBlocked(tile))
  856. {
  857. bool placeRock = true;
  858. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  859. {
  860. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  861. placeRock = false;
  862. });
  863. if (placeRock)
  864. {
  865. rockTiles.push_back(tile);
  866. }
  867. }
  868. }
  869. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  870. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  871. //for (auto tile : rockTiles)
  872. //{
  873. // gen->setOccupied (tile, ETileType::USED);
  874. // gen->foreach_neighbour (tile, [gen](int3 &pos)
  875. // {
  876. // if (!gen->isUsed(pos))
  877. // gen->setOccupied (pos, ETileType::BLOCKED);
  878. // });
  879. //}
  880. }
  881. //get all possible obstacles for this terrain
  882. for (auto primaryID : VLC->objtypeh->knownObjects())
  883. {
  884. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  885. {
  886. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  887. if (handler->isStaticObject())
  888. {
  889. for (auto temp : handler->getTemplates())
  890. {
  891. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  892. possibleObstacles.push_back(temp);
  893. }
  894. }
  895. }
  896. }
  897. auto sel = gen->editManager->getTerrainSelection();
  898. sel.clearSelection();
  899. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  900. {
  901. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  902. int3 obstaclePos = tile + temp.getBlockMapOffset();
  903. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  904. {
  905. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  906. placeObject(gen, obj, obstaclePos);
  907. return true;
  908. }
  909. return false;
  910. };
  911. for (auto tile : tileinfo)
  912. {
  913. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  914. {
  915. while (!tryToPlaceObstacleHere(tile));
  916. }
  917. else if (gen->isPossible(tile))
  918. {
  919. //try to place random obstacle once - if not possible, leave it clear
  920. tryToPlaceObstacleHere(tile);
  921. }
  922. }
  923. }
  924. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  925. {
  926. initTownType(gen);
  927. initTerrainType(gen);
  928. addAllPossibleObjects (gen);
  929. placeMines(gen);
  930. createRequiredObjects(gen);
  931. fractalize(gen); //after required objects are created and linked with their own paths
  932. createTreasures(gen);
  933. createObstacles(gen);
  934. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  935. return true;
  936. }
  937. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  938. {
  939. //si32 min_dist = sqrt(tileinfo.size()/density);
  940. int best_distance = 0;
  941. bool result = false;
  942. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  943. for(auto tile : tileinfo)
  944. {
  945. auto dist = gen->getTile(tile).getNearestObjectDistance();
  946. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  947. {
  948. bool allTilesAvailable = true;
  949. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  950. {
  951. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  952. {
  953. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  954. }
  955. });
  956. if (allTilesAvailable)
  957. {
  958. best_distance = dist;
  959. pos = tile;
  960. result = true;
  961. }
  962. }
  963. }
  964. if (result)
  965. {
  966. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  967. }
  968. return result;
  969. }
  970. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  971. {
  972. auto tilesBlockedByObject = temp.getBlockedOffsets();
  973. bool allTilesAvailable = true;
  974. for (auto blockingTile : tilesBlockedByObject)
  975. {
  976. int3 t = pos + blockingTile;
  977. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  978. {
  979. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  980. break;
  981. }
  982. }
  983. return allTilesAvailable;
  984. }
  985. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  986. {
  987. //we need object apperance to deduce free tiles
  988. if (obj->appearance.id == Obj::NO_OBJ)
  989. {
  990. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  991. if (templates.empty())
  992. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  993. obj->appearance = templates.front();
  994. }
  995. //si32 min_dist = sqrt(tileinfo.size()/density);
  996. int best_distance = 0;
  997. bool result = false;
  998. //si32 w = gen->map->width;
  999. //si32 h = gen->map->height;
  1000. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1001. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1002. for (auto tile : tileinfo)
  1003. {
  1004. //object must be accessible from at least one surounding tile
  1005. bool accessible = false;
  1006. for (int x = -1; x < 2; x++)
  1007. for (int y = -1; y <2; y++)
  1008. {
  1009. if (x && y) //check only if object is visitable from another tile
  1010. {
  1011. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  1012. if (!vstd::contains(tilesBlockedByObject, offset))
  1013. {
  1014. int3 nearbyPos = tile + offset;
  1015. if (gen->map->isInTheMap(nearbyPos))
  1016. {
  1017. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1018. accessible = true;
  1019. }
  1020. }
  1021. }
  1022. };
  1023. if (!accessible)
  1024. continue;
  1025. auto ti = gen->getTile(tile);
  1026. auto dist = ti.getNearestObjectDistance();
  1027. //avoid borders
  1028. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1029. {
  1030. bool allTilesAvailable = true;
  1031. for (auto blockingTile : tilesBlockedByObject)
  1032. {
  1033. int3 t = tile + blockingTile;
  1034. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1035. {
  1036. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1037. break;
  1038. }
  1039. }
  1040. if (allTilesAvailable)
  1041. {
  1042. best_distance = dist;
  1043. pos = tile;
  1044. result = true;
  1045. }
  1046. }
  1047. }
  1048. if (result)
  1049. {
  1050. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1051. }
  1052. return result;
  1053. }
  1054. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1055. {
  1056. if (!gen->map->isInTheMap(pos))
  1057. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  1058. object->pos = pos;
  1059. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1060. 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()));
  1061. for (auto tile : object->getBlockedPos())
  1062. {
  1063. if (!gen->map->isInTheMap(tile))
  1064. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1065. }
  1066. if (object->appearance.id == Obj::NO_OBJ)
  1067. {
  1068. auto terrainType = gen->map->getTile(pos).terType;
  1069. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1070. if (templates.empty())
  1071. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
  1072. object->appearance = templates.front();
  1073. }
  1074. gen->map->addBlockVisTiles(object);
  1075. gen->editManager->insertObject(object, pos);
  1076. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1077. }
  1078. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1079. {
  1080. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1081. checkAndPlaceObject (gen, object, pos);
  1082. auto points = object->getBlockedPos();
  1083. if (object->isVisitable())
  1084. points.insert(pos + object->getVisitableOffset());
  1085. points.insert(pos);
  1086. for(auto p : points)
  1087. {
  1088. if (gen->map->isInTheMap(p))
  1089. {
  1090. gen->setOccupied(p, ETileType::USED);
  1091. }
  1092. }
  1093. for(auto tile : tileinfo)
  1094. {
  1095. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1096. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1097. }
  1098. }
  1099. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str)
  1100. {
  1101. placeObject(gen, object, pos);
  1102. guardObject(gen, object, str);
  1103. }
  1104. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1105. {
  1106. //get all tiles from which this object can be accessed
  1107. int3 visitable = object->visitablePos();
  1108. std::vector<int3> tiles;
  1109. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1110. gen->foreach_neighbour(visitable, [&](int3& pos)
  1111. {
  1112. if (gen->isPossible(pos))
  1113. {
  1114. if (!vstd::contains(tilesBlockedByObject, pos))
  1115. {
  1116. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1117. {
  1118. tiles.push_back(pos);
  1119. }
  1120. }
  1121. };
  1122. });
  1123. return tiles;
  1124. }
  1125. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  1126. {
  1127. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1128. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1129. int3 guardTile(-1,-1,-1);
  1130. for (auto tile : tiles)
  1131. {
  1132. //crunching path may fail if center of teh zone is dirrectly over wide object
  1133. if (crunchPath (gen, tile, getPos(), id)) //make sure object is accessible before surrounding it with blocked tiles
  1134. {
  1135. guardTile = tile;
  1136. break;
  1137. }
  1138. }
  1139. if (!guardTile.valid())
  1140. {
  1141. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1142. return false;
  1143. }
  1144. if (addMonster (gen, guardTile, str)) //do not place obstacles around unguarded object
  1145. {
  1146. for (auto pos : tiles)
  1147. {
  1148. if (!gen->isFree(pos))
  1149. gen->setOccupied(pos, ETileType::BLOCKED);
  1150. }
  1151. gen->setOccupied (guardTile, ETileType::USED);
  1152. }
  1153. else //allow no guard or other object in front of this object
  1154. {
  1155. for (auto tile : tiles)
  1156. gen->setOccupied (tile, ETileType::FREE);
  1157. }
  1158. return true;
  1159. }
  1160. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  1161. {
  1162. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1163. ui32 total = 0;
  1164. ui32 minValue = 0.25f * value;
  1165. //roulette wheel
  1166. for (auto oi : possibleObjects)
  1167. {
  1168. if (oi.value >= minValue && oi.value <= value)
  1169. {
  1170. //TODO: check place for non-removable object
  1171. //problem: we need at least template for the object that does not yet exist
  1172. total += oi.probability;
  1173. tresholds.push_back (std::make_pair (total, oi));
  1174. }
  1175. }
  1176. //TODO: generate pandora box with gold if the value is very high
  1177. if (tresholds.empty())
  1178. {
  1179. ObjectInfo oi;
  1180. if (minValue > 20000) //we don't have object valuable enough
  1181. {
  1182. oi.generateObject = [minValue]() -> CGObjectInstance *
  1183. {
  1184. auto obj = new CGPandoraBox();
  1185. obj->ID = Obj::PANDORAS_BOX;
  1186. obj->subID = 0;
  1187. obj->resources[Res::GOLD] = minValue;
  1188. return obj;
  1189. };
  1190. oi.value = minValue;
  1191. oi.probability = 0;
  1192. }
  1193. else
  1194. {
  1195. oi.generateObject = [gen]() -> CGObjectInstance *
  1196. {
  1197. return nullptr;
  1198. };
  1199. oi.value = 0;
  1200. oi.probability = 0;
  1201. }
  1202. return oi;
  1203. }
  1204. int r = gen->rand.nextInt (1, total);
  1205. for (auto t : tresholds)
  1206. {
  1207. if (r <= t.first)
  1208. return t.second;
  1209. }
  1210. //FIXME: control reaches end of non-void function. Missing return?
  1211. }
  1212. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1213. {
  1214. //TODO: move typical objects to config
  1215. ObjectInfo oi;
  1216. for (auto primaryID : VLC->objtypeh->knownObjects())
  1217. {
  1218. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1219. {
  1220. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1221. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1222. {
  1223. for (auto temp : handler->getTemplates())
  1224. {
  1225. if (temp.canBePlacedAt(terrainType))
  1226. {
  1227. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1228. {
  1229. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1230. };
  1231. oi.value = handler->getRMGInfo().value;
  1232. oi.probability = handler->getRMGInfo().rarity;
  1233. possibleObjects.push_back (oi);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. }
  1239. //dwellings
  1240. for (auto secondaryID : VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1))
  1241. {
  1242. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1243. auto creatures = dwellingHandler->getProducedCreatures();
  1244. if (creatures.empty())
  1245. continue;
  1246. auto cre = creatures.front();
  1247. if (cre->faction == townType)
  1248. {
  1249. oi.value = cre->AIValue * cre->growth * (1 + 0.5f); //TODO: include town count in formula
  1250. oi.probability = 40;
  1251. for (auto temp : dwellingHandler->getTemplates())
  1252. {
  1253. if (temp.canBePlacedAt(terrainType))
  1254. {
  1255. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1256. {
  1257. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1258. //dwellingHandler->configureObject(obj, gen->rand);
  1259. obj->tempOwner = PlayerColor::NEUTRAL;
  1260. return obj;
  1261. };
  1262. possibleObjects.push_back (oi);
  1263. }
  1264. }
  1265. }
  1266. }
  1267. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1268. for (int i = 0; i < 5; i++)
  1269. {
  1270. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1271. {
  1272. auto obj = new CGArtifact();
  1273. obj->ID = Obj::SPELL_SCROLL;
  1274. obj->subID = 0;
  1275. std::vector<SpellID> out;
  1276. //TODO: unify with cb->getAllowedSpells?
  1277. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1278. {
  1279. const CSpell *spell = SpellID(i).toSpell();
  1280. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1281. {
  1282. out.push_back(spell->id);
  1283. }
  1284. }
  1285. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1286. gen->map->addNewArtifactInstance(a);
  1287. obj->storedArtifact = a;
  1288. return obj;
  1289. };
  1290. oi.value = scrollValues[i];
  1291. oi.probability = 30;
  1292. possibleObjects.push_back (oi);
  1293. }
  1294. //pandora box with gold
  1295. for (int i = 1; i < 5; i++)
  1296. {
  1297. oi.generateObject = [i]() -> CGObjectInstance *
  1298. {
  1299. auto obj = new CGPandoraBox();
  1300. obj->ID = Obj::PANDORAS_BOX;
  1301. obj->subID = 0;
  1302. obj->resources[Res::GOLD] = i * 5000;
  1303. return obj;
  1304. };
  1305. oi.value = i * 5000;;
  1306. oi.probability = 5;
  1307. possibleObjects.push_back (oi);
  1308. }
  1309. //pandora box with experience
  1310. for (int i = 1; i < 5; i++)
  1311. {
  1312. oi.generateObject = [i]() -> CGObjectInstance *
  1313. {
  1314. auto obj = new CGPandoraBox();
  1315. obj->ID = Obj::PANDORAS_BOX;
  1316. obj->subID = 0;
  1317. obj->gainedExp = i * 5000;
  1318. return obj;
  1319. };
  1320. oi.value = i * 6000;;
  1321. oi.probability = 20;
  1322. possibleObjects.push_back (oi);
  1323. }
  1324. //pandora box with creatures
  1325. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1326. for (auto creature : VLC->creh->creatures)
  1327. {
  1328. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1329. {
  1330. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1331. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1332. if (creaturesAmount <= 5)
  1333. {
  1334. }
  1335. else if (creaturesAmount <= 12)
  1336. {
  1337. (creaturesAmount /= 2) *= 2;
  1338. }
  1339. else if (creaturesAmount <= 50)
  1340. {
  1341. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1342. }
  1343. else if (creaturesAmount <= 12)
  1344. {
  1345. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1346. }
  1347. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1348. {
  1349. auto obj = new CGPandoraBox();
  1350. obj->ID = Obj::PANDORAS_BOX;
  1351. obj->subID = 0;
  1352. auto stack = new CStackInstance(creature, creaturesAmount);
  1353. obj->creatures.putStack(SlotID(0), stack);
  1354. return obj;
  1355. };
  1356. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + 1) - 4000)/3; //TODO: count number of towns on the map
  1357. oi.probability = 3;
  1358. possibleObjects.push_back (oi);
  1359. }
  1360. }
  1361. //Pandora with 12 spells of certain level
  1362. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1363. {
  1364. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1365. {
  1366. auto obj = new CGPandoraBox();
  1367. obj->ID = Obj::PANDORAS_BOX;
  1368. obj->subID = 0;
  1369. std::vector <CSpell *> spells;
  1370. for (auto spell : VLC->spellh->objects)
  1371. {
  1372. if (!spell->isSpecialSpell() && spell->level == i)
  1373. spells.push_back(spell);
  1374. }
  1375. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1376. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1377. {
  1378. obj->spells.push_back (spells[j]->id);
  1379. }
  1380. return obj;
  1381. };
  1382. oi.value = (i + 1) * 2500; //5000 - 15000
  1383. oi.probability = 2;
  1384. possibleObjects.push_back (oi);
  1385. }
  1386. //Pandora with 15 spells of certain school
  1387. for (int i = 1; i <= 4; i++)
  1388. {
  1389. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1390. {
  1391. auto obj = new CGPandoraBox();
  1392. obj->ID = Obj::PANDORAS_BOX;
  1393. obj->subID = 0;
  1394. std::vector <CSpell *> spells;
  1395. for (auto spell : VLC->spellh->objects)
  1396. {
  1397. if (!spell->isSpecialSpell())
  1398. {
  1399. bool school = false; //TODO: we could have better interface for iterating schools
  1400. switch (i)
  1401. {
  1402. case 1:
  1403. school = spell->air;
  1404. case 2:
  1405. school = spell->earth;
  1406. case 3:
  1407. school = spell->fire;
  1408. case 4:
  1409. school = spell->water;
  1410. }
  1411. if (school)
  1412. spells.push_back(spell);
  1413. }
  1414. }
  1415. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1416. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1417. {
  1418. obj->spells.push_back (spells[j]->id);
  1419. }
  1420. return obj;
  1421. };
  1422. oi.value = 15000;
  1423. oi.probability = 2;
  1424. possibleObjects.push_back (oi);
  1425. }
  1426. // Pandora box with 60 random spells
  1427. oi.generateObject = [gen]() -> CGObjectInstance *
  1428. {
  1429. auto obj = new CGPandoraBox();
  1430. obj->ID = Obj::PANDORAS_BOX;
  1431. obj->subID = 0;
  1432. std::vector <CSpell *> spells;
  1433. for (auto spell : VLC->spellh->objects)
  1434. {
  1435. if (!spell->isSpecialSpell())
  1436. spells.push_back(spell);
  1437. }
  1438. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1439. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1440. {
  1441. obj->spells.push_back (spells[j]->id);
  1442. }
  1443. return obj;
  1444. };
  1445. oi.value = 3000;
  1446. oi.probability = 2;
  1447. possibleObjects.push_back (oi);
  1448. }