CRmgTemplateZone.cpp 38 KB

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