CRmgTemplateZone.cpp 39 KB

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