2
0

CRmgTemplateZone.cpp 42 KB

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