CRmgTemplateZone.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092
  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. float CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(float value)
  77. {
  78. nearestObjectDistance = std::max<float>(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, float distance)
  304. {
  305. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  306. //for (auto tile : tileinfo)
  307. //{
  308. // if (tile.dist2d(this->pos) > distance)
  309. // {
  310. // gen->setOccupied(tile, ETileType::USED);
  311. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  312. // }
  313. //}
  314. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  315. {
  316. return tile.dist2d(this->pos) > distance;
  317. });
  318. }
  319. void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
  320. {
  321. vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
  322. {
  323. return gen->isPossible(tile);
  324. });
  325. }
  326. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  327. {
  328. for (auto tile : tileinfo)
  329. {
  330. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  331. {
  332. if (!vstd::contains(this->tileinfo, pos))
  333. {
  334. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  335. {
  336. if (gen->isPossible(pos))
  337. gen->setOccupied (pos, ETileType::BLOCKED);
  338. });
  339. }
  340. });
  341. }
  342. }
  343. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  344. {
  345. for (auto tile : tileinfo)
  346. {
  347. if (gen->isFree(tile))
  348. freePaths.insert(tile);
  349. }
  350. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  351. std::set<int3> possibleTiles;
  352. std::set<int3> tilesToClear; //will be set clear
  353. std::set<int3> tilesToIgnore; //will be erased in this iteration
  354. //the more treasure density, the greater distance between paths. Scaling is experimental.
  355. const float minDistance = std::sqrt(totalDensity * 3);
  356. for (auto tile : tileinfo)
  357. {
  358. if (gen->isFree(tile))
  359. clearedTiles.push_back(tile);
  360. else if (gen->isPossible(tile))
  361. possibleTiles.insert(tile);
  362. }
  363. assert (clearedTiles.size()); //this should come from zone connections
  364. while (possibleTiles.size())
  365. {
  366. //link tiles in random order
  367. std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
  368. RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
  369. for (auto tileToMakePath : tilesToMakePath)
  370. {
  371. //find closest free tile
  372. float currentDistance = 1e10;
  373. int3 closestTile (-1,-1,-1);
  374. for (auto clearTile : clearedTiles)
  375. {
  376. float distance = tileToMakePath.dist2d(clearTile);
  377. if (distance < currentDistance)
  378. {
  379. currentDistance = distance;
  380. closestTile = clearTile;
  381. }
  382. if (currentDistance <= minDistance)
  383. {
  384. //this tile is close enough. Forget about it and check next one
  385. tilesToIgnore.insert (tileToMakePath);
  386. break;
  387. }
  388. }
  389. //if tiles is not close enough, make path to it
  390. if (currentDistance > minDistance)
  391. {
  392. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  393. break; //next iteration - use already cleared tiles
  394. }
  395. }
  396. for (auto tileToClear : tilesToClear)
  397. {
  398. //move cleared tiles from one set to another
  399. clearedTiles.push_back(tileToClear);
  400. vstd::erase_if_present(possibleTiles, tileToClear);
  401. }
  402. for (auto tileToClear : tilesToIgnore)
  403. {
  404. //these tiles are already connected, ignore them
  405. vstd::erase_if_present(possibleTiles, tileToClear);
  406. }
  407. if (tilesToClear.empty()) //nothing else can be done (?)
  408. break;
  409. tilesToClear.clear(); //empty this container
  410. tilesToIgnore.clear();
  411. }
  412. for (auto tile : clearedTiles)
  413. {
  414. freePaths.insert(tile);
  415. }
  416. if (0) //enable to debug
  417. {
  418. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  419. int levels = gen->map->twoLevel ? 2 : 1;
  420. int width = gen->map->width;
  421. int height = gen->map->height;
  422. for (int k = 0; k < levels; k++)
  423. {
  424. for(int j=0; j<height; j++)
  425. {
  426. for (int i=0; i<width; i++)
  427. {
  428. out << (int)vstd::contains(freePaths, int3(i,j,k));
  429. }
  430. out << std::endl;
  431. }
  432. out << std::endl;
  433. }
  434. }
  435. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  436. }
  437. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  438. {
  439. /*
  440. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  441. do not leave zone border
  442. */
  443. bool result = false;
  444. bool end = false;
  445. int3 currentPos = src;
  446. float distance = currentPos.dist2dSQ (dst);
  447. while (!end)
  448. {
  449. if (currentPos == dst)
  450. {
  451. result = true;
  452. break;
  453. }
  454. auto lastDistance = distance;
  455. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  456. {
  457. if (!result) //not sure if lambda is worth it...
  458. {
  459. if (pos == dst)
  460. {
  461. result = true;
  462. end = true;
  463. }
  464. if (pos.dist2dSQ (dst) < distance)
  465. {
  466. if (!gen->isBlocked(pos))
  467. {
  468. if (vstd::contains (tileinfo, pos))
  469. {
  470. if (gen->isPossible(pos))
  471. {
  472. gen->setOccupied (pos, ETileType::FREE);
  473. if (clearedTiles)
  474. clearedTiles->insert(pos);
  475. currentPos = pos;
  476. distance = currentPos.dist2dSQ (dst);
  477. }
  478. else if (gen->isFree(pos))
  479. {
  480. end = true;
  481. result = true;
  482. }
  483. }
  484. }
  485. }
  486. }
  487. });
  488. int3 anotherPos(-1, -1, -1);
  489. if (!(result || distance < lastDistance)) //we do not advance, use more advaced pathfinding algorithm?
  490. {
  491. //try any nearby tiles, even if its not closer than current
  492. float lastDistance = 2 * distance; //start with significantly larger value
  493. gen->foreach_neighbour(currentPos, [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  494. {
  495. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  496. {
  497. if (vstd::contains(tileinfo, pos))
  498. {
  499. if (gen->isPossible(pos))
  500. {
  501. if (clearedTiles)
  502. clearedTiles->insert(pos);
  503. anotherPos = pos;
  504. lastDistance = currentPos.dist2dSQ(dst);
  505. }
  506. }
  507. }
  508. });
  509. if (anotherPos.valid())
  510. {
  511. if (clearedTiles)
  512. clearedTiles->insert(anotherPos);
  513. gen->setOccupied(anotherPos, ETileType::FREE);
  514. currentPos = anotherPos;
  515. }
  516. }
  517. if (!(result || distance < lastDistance || anotherPos.valid()))
  518. {
  519. logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  520. break;
  521. }
  522. }
  523. return result;
  524. }
  525. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  526. {
  527. requiredObjects.push_back(std::make_pair(obj, strength));
  528. }
  529. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  530. {
  531. //precalculate actual (randomized) monster strength based on this post
  532. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  533. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  534. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  535. static const int value1[] = {2500, 1500, 1000, 500, 0};
  536. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  537. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  538. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  539. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  540. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  541. strength = strength1 + strength2;
  542. if (strength < 2000)
  543. return false; //no guard at all
  544. CreatureID creId = CreatureID::NONE;
  545. int amount = 0;
  546. std::vector<CreatureID> possibleCreatures;
  547. for (auto cre : VLC->creh->creatures)
  548. {
  549. if (cre->special)
  550. continue;
  551. 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
  552. {
  553. possibleCreatures.push_back(cre->idNumber);
  554. }
  555. }
  556. if (possibleCreatures.size())
  557. {
  558. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  559. amount = strength / VLC->creh->creatures[creId]->AIValue;
  560. if (amount >= 4)
  561. amount *= gen->rand.nextDouble(0.75, 1.25);
  562. }
  563. else //just pick any available creature
  564. {
  565. creId = CreatureID(132); //Azure Dragon
  566. amount = strength / VLC->creh->creatures[creId]->AIValue;
  567. }
  568. auto guard = new CGCreature();
  569. guard->ID = Obj::MONSTER;
  570. guard->subID = creId;
  571. guard->character = 1; //MUST be initialized or switch will diverge
  572. auto hlp = new CStackInstance(creId, amount);
  573. //will be set during initialization
  574. guard->putStack(SlotID(0), hlp);
  575. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  576. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  577. placeObject(gen, guard, pos);
  578. if (clearSurroundingTiles)
  579. {
  580. //do not spawn anything near monster
  581. gen->foreach_neighbour (pos, [gen](int3 pos)
  582. {
  583. if (gen->isPossible(pos))
  584. gen->setOccupied(pos, ETileType::FREE);
  585. });
  586. }
  587. return true;
  588. }
  589. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos, float minDistance)
  590. {
  591. CTreasurePileInfo info;
  592. std::map<int3, CGObjectInstance *> treasures;
  593. std::set<int3> boundary;
  594. int3 guardPos (-1,-1,-1);
  595. info.nextTreasurePos = pos;
  596. //default values
  597. int maxValue = 5000;
  598. int minValue = 1500;
  599. if (treasureInfo.size())
  600. {
  601. //roulette wheel
  602. int r = gen->rand.nextInt (1, totalDensity);
  603. for (auto t : treasureInfo)
  604. {
  605. if (r <= t.threshold)
  606. {
  607. maxValue = t.max;
  608. minValue = t.min;
  609. break;
  610. }
  611. }
  612. }
  613. ui32 desiredValue = gen->rand.nextInt(minValue, maxValue);
  614. //quantize value to let objects with value equal to max spawn too
  615. int currentValue = 0;
  616. CGObjectInstance * object = nullptr;
  617. while (currentValue < desiredValue)
  618. {
  619. treasures[info.nextTreasurePos] = nullptr;
  620. for (auto treasurePos : treasures)
  621. {
  622. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  623. {
  624. boundary.insert(pos);
  625. });
  626. }
  627. for (auto treasurePos : treasures)
  628. {
  629. //leaving only boundary around objects
  630. vstd::erase_if_present (boundary, treasurePos.first);
  631. }
  632. for (auto tile : boundary)
  633. {
  634. //we can't extend boundary anymore
  635. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  636. break;
  637. }
  638. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  639. if (!oi.value) //0 value indicates no object
  640. {
  641. vstd::erase_if_present(treasures, info.nextTreasurePos);
  642. break;
  643. }
  644. else
  645. {
  646. object = oi.generateObject();
  647. //remove from possible objects
  648. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  649. assert (oiptr != possibleObjects.end());
  650. oiptr->maxPerZone--;
  651. if (!oiptr->maxPerZone)
  652. possibleObjects.erase(oiptr);
  653. //TODO
  654. //update treasure pile area
  655. int3 visitablePos = info.nextTreasurePos;
  656. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  657. if (oi.templ.isVisitableFromTop())
  658. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  659. else
  660. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  661. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  662. {
  663. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  664. info.occupiedPositions.insert(blockPos);
  665. info.blockedPositions.insert(blockPos);
  666. }
  667. info.occupiedPositions.insert(visitablePos);
  668. currentValue += oi.value;
  669. treasures[info.nextTreasurePos] = object;
  670. //now find place for next object
  671. int3 placeFound(-1,-1,-1);
  672. //randomize next position from among possible ones
  673. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  674. RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  675. for (auto tile : boundaryCopy)
  676. {
  677. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  678. {
  679. bool here = true;
  680. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  681. {
  682. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  683. here = false;
  684. });
  685. if (here)
  686. {
  687. placeFound = tile;
  688. break;
  689. }
  690. }
  691. }
  692. if (placeFound.valid())
  693. info.nextTreasurePos = placeFound;
  694. }
  695. }
  696. if (treasures.size())
  697. {
  698. //find object closest to zone center, then connect it to the middle of the zone
  699. int3 closestFreeTile (-1,-1,-1);
  700. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  701. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  702. else
  703. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  704. int3 closestTile = int3(-1,-1,-1);
  705. float minDistance = 1e10;
  706. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  707. {
  708. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  709. {
  710. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  711. minDistance = closestFreeTile.dist2d(visitablePos);
  712. }
  713. }
  714. if (!closestTile.valid())
  715. {
  716. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  717. {
  718. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  719. {
  720. closestTile = visitablePos;
  721. minDistance = closestFreeTile.dist2d(visitablePos);
  722. }
  723. }
  724. }
  725. assert (closestTile.valid());
  726. for (auto tile : info.occupiedPositions)
  727. {
  728. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  729. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  730. }
  731. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  732. {
  733. //we can't connect this pile, just block it off and start over
  734. for (auto treasure : treasures)
  735. {
  736. if (gen->isPossible(treasure.first))
  737. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  738. }
  739. return true;
  740. }
  741. //update boundary around our objects, including knowledge about objects visitable from bottom
  742. boundary.clear();
  743. for (auto tile : info.visitableFromBottomPositions)
  744. {
  745. gen->foreach_neighbour (tile, [tile, &boundary](int3 pos)
  746. {
  747. if (pos.y >= tile.y) //don't block these objects from above
  748. boundary.insert(pos);
  749. });
  750. }
  751. for (auto tile : info.visitableFromTopPositions)
  752. {
  753. gen->foreach_neighbour (tile, [&boundary](int3 pos)
  754. {
  755. boundary.insert(pos);
  756. });
  757. }
  758. for (auto tile : boundary) //guard must be standing there
  759. {
  760. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  761. {
  762. guardPos = tile;
  763. break;
  764. }
  765. }
  766. if (guardPos.valid())
  767. {
  768. for (auto treasure : treasures)
  769. {
  770. int3 visitableOffset = treasure.second->getVisitableOffset();
  771. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  772. }
  773. if (addMonster(gen, guardPos, currentValue, false))
  774. {//block only if the object is guarded
  775. for (auto tile : boundary)
  776. {
  777. if (gen->isPossible(tile))
  778. gen->setOccupied (tile, ETileType::BLOCKED);
  779. }
  780. //do not spawn anything near monster
  781. gen->foreach_neighbour (guardPos, [gen](int3 pos)
  782. {
  783. if (gen->isPossible(pos))
  784. gen->setOccupied(pos, ETileType::FREE);
  785. });
  786. }
  787. }
  788. else //we couldn't make a connection to this location, block it
  789. {
  790. for (auto treasure : treasures)
  791. {
  792. if (gen->isPossible(treasure.first))
  793. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  794. delete treasure.second;
  795. }
  796. }
  797. return true;
  798. }
  799. else //we did not place eveyrthing successfully
  800. return false;
  801. }
  802. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  803. {
  804. //FIXME: handle case that this player is not present -> towns should be set to neutral
  805. int totalTowns = 0;
  806. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  807. {
  808. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  809. for (auto tile : town->getBlockedPos())
  810. {
  811. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  812. {
  813. if (gen->isPossible(pos))
  814. {
  815. gen->setOccupied(pos, ETileType::FREE);
  816. }
  817. });
  818. }
  819. };
  820. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  821. {
  822. for (int i = 0; i < count; i++)
  823. {
  824. auto town = new CGTownInstance();
  825. town->ID = Obj::TOWN;
  826. if (this->townsAreSameType)
  827. town->subID = townType;
  828. else
  829. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  830. town->tempOwner = player;
  831. if (hasFort)
  832. town->builtBuildings.insert(BuildingID::FORT);
  833. town->builtBuildings.insert(BuildingID::DEFAULT);
  834. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  835. {
  836. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  837. town->possibleSpells.push_back(spell->id);
  838. }
  839. if (!totalTowns)
  840. {
  841. //first town in zone sets the facton of entire zone
  842. town->subID = townType;
  843. //register MAIN town of zone
  844. gen->registerZone(town->subID);
  845. //first town in zone goes in the middle
  846. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  847. cutPathAroundTown(town);
  848. }
  849. else
  850. addRequiredObject (town);
  851. totalTowns++;
  852. }
  853. };
  854. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  855. {
  856. //set zone types to player faction, generate main town
  857. logGlobal->infoStream() << "Preparing playing zone";
  858. int player_id = *owner - 1;
  859. auto & playerInfo = gen->map->players[player_id];
  860. if (playerInfo.canAnyonePlay())
  861. {
  862. PlayerColor player(player_id);
  863. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  864. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  865. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  866. auto town = new CGTownInstance();
  867. town->ID = Obj::TOWN;
  868. town->subID = townType;
  869. town->tempOwner = player;
  870. town->builtBuildings.insert(BuildingID::FORT);
  871. town->builtBuildings.insert(BuildingID::DEFAULT);
  872. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  873. {
  874. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  875. town->possibleSpells.push_back(spell->id);
  876. }
  877. //towns are big objects and should be centered around visitable position
  878. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  879. cutPathAroundTown(town);
  880. totalTowns++;
  881. //register MAIN town of zone only
  882. gen->registerZone (town->subID);
  883. logGlobal->traceStream() << "Fill player info " << player_id;
  884. // Update player info
  885. playerInfo.allowedFactions.clear();
  886. playerInfo.allowedFactions.insert (townType);
  887. playerInfo.hasMainTown = true;
  888. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  889. playerInfo.generateHeroAtMainTown = true;
  890. //now create actual towns
  891. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  892. addNewTowns (playerTowns.getTownCount(), false, player);
  893. //requiredObjects.push_back(town);
  894. }
  895. else
  896. {
  897. type = ETemplateZoneType::TREASURE;
  898. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  899. logGlobal->infoStream() << "Skipping this zone cause no player";
  900. }
  901. }
  902. else //no player
  903. {
  904. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  905. }
  906. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  907. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  908. }
  909. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  910. {
  911. if (matchTerrainToTown)
  912. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  913. else
  914. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  915. //TODO: allow new types of terrain?
  916. if (pos.z)
  917. {
  918. if (terrainType != ETerrainType::LAVA)
  919. terrainType = ETerrainType::SUBTERRANEAN;
  920. }
  921. else
  922. {
  923. if (terrainType == ETerrainType::SUBTERRANEAN)
  924. terrainType = ETerrainType::DIRT;
  925. }
  926. paintZoneTerrain (gen, terrainType);
  927. }
  928. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  929. {
  930. std::vector<int3> tiles;
  931. for (auto tile : tileinfo)
  932. {
  933. tiles.push_back (tile);
  934. }
  935. gen->editManager->getTerrainSelection().setSelection(tiles);
  936. gen->editManager->drawTerrain(terrainType, &gen->rand);
  937. }
  938. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  939. {
  940. std::vector<Res::ERes> required_mines;
  941. required_mines.push_back(Res::ERes::WOOD);
  942. required_mines.push_back(Res::ERes::ORE);
  943. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  944. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  945. //TODO: factory / copy constructor?
  946. for (const auto & res : woodOre)
  947. {
  948. //TODO: these 2 should be close to town (within 12 tiles radius)
  949. for (int i = 0; i < mines[res]; i++)
  950. {
  951. auto mine = new CGMine();
  952. mine->ID = Obj::MINE;
  953. mine->subID = static_cast<si32>(res);
  954. mine->producedResource = res;
  955. mine->producedQuantity = mine->defaultResProduction();
  956. addRequiredObject(mine, 1500);
  957. }
  958. }
  959. for (const auto & res : preciousResources)
  960. {
  961. for (int i = 0; i < mines[res]; i++)
  962. {
  963. auto mine = new CGMine();
  964. mine->ID = Obj::MINE;
  965. mine->subID = static_cast<si32>(res);
  966. mine->producedResource = res;
  967. mine->producedQuantity = mine->defaultResProduction();
  968. addRequiredObject(mine, 3500);
  969. }
  970. }
  971. for (int i = 0; i < mines[Res::GOLD]; i++)
  972. {
  973. auto mine = new CGMine();
  974. mine->ID = Obj::MINE;
  975. mine->subID = static_cast<si32>(Res::GOLD);
  976. mine->producedResource = Res::GOLD;
  977. mine->producedQuantity = mine->defaultResProduction();
  978. addRequiredObject(mine, 7000);
  979. }
  980. return true;
  981. }
  982. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  983. {
  984. logGlobal->infoStream() << "Creating required objects";
  985. for(const auto &obj : requiredObjects)
  986. {
  987. int3 pos;
  988. logGlobal->traceStream() << "Looking for place";
  989. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  990. {
  991. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  992. //TODO CLEANUP!
  993. return false;
  994. }
  995. logGlobal->traceStream() << "Place found";
  996. placeObject (gen, obj.first, pos);
  997. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  998. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  999. }
  1000. return true;
  1001. }
  1002. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1003. {
  1004. //treasure density is proportional to map siz,e but must be scaled bakc to map size
  1005. //also, normalize it to zone count - higher count means relative smaller zones
  1006. //this is squared distance for optimization purposes
  1007. const double minDistance = std::max<float>((600.f * size * size * gen->getZones().size()) /
  1008. (gen->mapGenOptions->getWidth() * gen->mapGenOptions->getHeight() * totalDensity * (gen->map->twoLevel ? 2 : 1)), 2);
  1009. //distance lower than 2 causes objects to overlap and crash
  1010. do {
  1011. //optimization - don't check tiles which are not allowed
  1012. vstd::erase_if (possibleTiles, [gen](const int3 &tile) -> bool
  1013. {
  1014. return !gen->isPossible(tile);
  1015. });
  1016. int3 pos;
  1017. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  1018. {
  1019. break;
  1020. }
  1021. createTreasurePile (gen, pos, minDistance);
  1022. } while(true);
  1023. }
  1024. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1025. {
  1026. //tighten obstacles to improve visuals
  1027. for (int i = 0; i < 3; ++i)
  1028. {
  1029. int blockedTiles = 0;
  1030. int freeTiles = 0;
  1031. for (auto tile : tileinfo)
  1032. {
  1033. if (!gen->isPossible(tile)) //only possible tiles can change
  1034. continue;
  1035. int blockedNeighbours = 0;
  1036. int freeNeighbours = 0;
  1037. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1038. {
  1039. if (gen->isBlocked(pos))
  1040. blockedNeighbours++;
  1041. if (gen->isFree(pos))
  1042. freeNeighbours++;
  1043. });
  1044. if (blockedNeighbours > 4)
  1045. {
  1046. gen->setOccupied(tile, ETileType::BLOCKED);
  1047. blockedTiles++;
  1048. }
  1049. else if (freeNeighbours > 4)
  1050. {
  1051. gen->setOccupied(tile, ETileType::FREE);
  1052. freeTiles++;
  1053. }
  1054. }
  1055. logGlobal->infoStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1056. }
  1057. if (pos.z) //underground
  1058. {
  1059. std::vector<int3> rockTiles;
  1060. for (auto tile : tileinfo)
  1061. {
  1062. if (gen->shouldBeBlocked(tile))
  1063. {
  1064. bool placeRock = true;
  1065. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1066. {
  1067. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1068. placeRock = false;
  1069. });
  1070. if (placeRock)
  1071. {
  1072. rockTiles.push_back(tile);
  1073. }
  1074. }
  1075. }
  1076. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1077. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1078. for (auto tile : rockTiles)
  1079. {
  1080. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1081. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1082. //{
  1083. // if (!gen->isUsed(pos))
  1084. // gen->setOccupied (pos, ETileType::BLOCKED);
  1085. //});
  1086. }
  1087. }
  1088. typedef std::vector<ObjectTemplate> obstacleVector;
  1089. //obstacleVector possibleObstacles;
  1090. std::map <ui8, obstacleVector> obstaclesBySize;
  1091. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1092. std::vector<obstaclePair> possibleObstacles;
  1093. //get all possible obstacles for this terrain
  1094. for (auto primaryID : VLC->objtypeh->knownObjects())
  1095. {
  1096. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1097. {
  1098. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1099. if (handler->isStaticObject())
  1100. {
  1101. for (auto temp : handler->getTemplates())
  1102. {
  1103. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1104. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. for (auto o : obstaclesBySize)
  1110. {
  1111. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1112. }
  1113. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1114. {
  1115. return p1.first > p2.first; //bigger obstacles first
  1116. });
  1117. auto sel = gen->editManager->getTerrainSelection();
  1118. sel.clearSelection();
  1119. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1120. {
  1121. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1122. int3 obstaclePos = tile - temp.getBlockMapOffset();
  1123. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1124. {
  1125. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1126. placeObject(gen, obj, obstaclePos, false);
  1127. return true;
  1128. }
  1129. return false;
  1130. };
  1131. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1132. for (auto tile : boost::adaptors::reverse(tileinfo))
  1133. {
  1134. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1135. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1136. {
  1137. //start from biggets obstacles
  1138. for (int i = 0; i < possibleObstacles.size(); i++)
  1139. {
  1140. if (tryToPlaceObstacleHere(tile, i))
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1147. {
  1148. initTerrainType(gen);
  1149. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1150. addAllPossibleObjects (gen);
  1151. placeMines(gen);
  1152. createRequiredObjects(gen);
  1153. fractalize(gen); //after required objects are created and linked with their own paths
  1154. createTreasures(gen);
  1155. createObstacles(gen);
  1156. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1157. return true;
  1158. }
  1159. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos)
  1160. {
  1161. //si32 min_dist = sqrt(tileinfo.size()/density);
  1162. float best_distance = 0;
  1163. bool result = false;
  1164. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1165. for(auto tile : possibleTiles)
  1166. {
  1167. auto dist = gen->getNearestObjectDistance(tile);
  1168. if ((dist >= min_dist) && (dist > best_distance))
  1169. {
  1170. bool allTilesAvailable = true;
  1171. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  1172. {
  1173. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour)))
  1174. {
  1175. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1176. }
  1177. });
  1178. if (allTilesAvailable)
  1179. {
  1180. best_distance = dist;
  1181. pos = tile;
  1182. result = true;
  1183. }
  1184. }
  1185. }
  1186. if (result)
  1187. {
  1188. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1189. }
  1190. return result;
  1191. }
  1192. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1193. {
  1194. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1195. return false;
  1196. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1197. for (auto blockingTile : tilesBlockedByObject)
  1198. {
  1199. int3 t = pos + blockingTile;
  1200. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1201. {
  1202. return false; //if at least one tile is not possible, object can't be placed here
  1203. }
  1204. }
  1205. return true;
  1206. }
  1207. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1208. {
  1209. bool accessible = false;
  1210. for (int x = -1; x < 2; x++)
  1211. {
  1212. for (int y = -1; y <2; y++)
  1213. {
  1214. if (x && y) //check only if object is visitable from another tile
  1215. {
  1216. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1217. if (!vstd::contains(tilesBlockedByObject, offset))
  1218. {
  1219. int3 nearbyPos = tile + offset;
  1220. if (gen->map->isInTheMap(nearbyPos))
  1221. {
  1222. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1223. accessible = true;
  1224. }
  1225. }
  1226. }
  1227. };
  1228. }
  1229. return accessible;
  1230. }
  1231. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1232. {
  1233. //we need object apperance to deduce free tiles
  1234. if (obj->appearance.id == Obj::NO_OBJ)
  1235. {
  1236. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1237. if (templates.empty())
  1238. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1239. obj->appearance = templates.front();
  1240. }
  1241. //si32 min_dist = sqrt(tileinfo.size()/density);
  1242. int best_distance = 0;
  1243. bool result = false;
  1244. //si32 w = gen->map->width;
  1245. //si32 h = gen->map->height;
  1246. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1247. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1248. for (auto tile : tileinfo)
  1249. {
  1250. //object must be accessible from at least one surounding tile
  1251. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1252. continue;
  1253. auto ti = gen->getTile(tile);
  1254. auto dist = ti.getNearestObjectDistance();
  1255. //avoid borders
  1256. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1257. {
  1258. bool allTilesAvailable = true;
  1259. for (auto blockingTile : tilesBlockedByObject)
  1260. {
  1261. int3 t = tile + blockingTile;
  1262. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1263. {
  1264. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1265. break;
  1266. }
  1267. }
  1268. if (allTilesAvailable)
  1269. {
  1270. best_distance = dist;
  1271. pos = tile;
  1272. result = true;
  1273. }
  1274. }
  1275. }
  1276. if (result)
  1277. {
  1278. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1279. }
  1280. return result;
  1281. }
  1282. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1283. {
  1284. if (!gen->map->isInTheMap(pos))
  1285. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1286. object->pos = pos;
  1287. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1288. 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()));
  1289. for (auto tile : object->getBlockedPos())
  1290. {
  1291. if (!gen->map->isInTheMap(tile))
  1292. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1293. }
  1294. if (object->appearance.id == Obj::NO_OBJ)
  1295. {
  1296. auto terrainType = gen->map->getTile(pos).terType;
  1297. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1298. if (templates.empty())
  1299. 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));
  1300. object->appearance = templates.front();
  1301. }
  1302. gen->editManager->insertObject(object, pos);
  1303. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1304. }
  1305. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1306. {
  1307. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1308. checkAndPlaceObject (gen, object, pos);
  1309. auto points = object->getBlockedPos();
  1310. if (object->isVisitable())
  1311. points.insert(pos + object->getVisitableOffset());
  1312. points.insert(pos);
  1313. for(auto p : points)
  1314. {
  1315. if (gen->map->isInTheMap(p))
  1316. {
  1317. gen->setOccupied(p, ETileType::USED);
  1318. }
  1319. }
  1320. if (updateDistance)
  1321. {
  1322. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1323. {
  1324. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1325. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1326. }
  1327. }
  1328. }
  1329. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1330. {
  1331. placeObject(gen, object, pos);
  1332. guardObject(gen, object, str, zoneGuard);
  1333. }
  1334. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1335. {
  1336. //get all tiles from which this object can be accessed
  1337. int3 visitable = object->visitablePos();
  1338. std::vector<int3> tiles;
  1339. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1340. gen->foreach_neighbour(visitable, [&](int3& pos)
  1341. {
  1342. if (gen->isPossible(pos))
  1343. {
  1344. if (!vstd::contains(tilesBlockedByObject, pos))
  1345. {
  1346. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1347. {
  1348. tiles.push_back(pos);
  1349. }
  1350. }
  1351. };
  1352. });
  1353. return tiles;
  1354. }
  1355. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1356. {
  1357. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1358. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1359. int3 guardTile(-1,-1,-1);
  1360. for (auto tile : tiles)
  1361. {
  1362. //crunching path may fail if center of teh zone is dirrectly over wide object
  1363. //make sure object is accessible before surrounding it with blocked tiles
  1364. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1365. {
  1366. guardTile = tile;
  1367. break;
  1368. }
  1369. }
  1370. if (!guardTile.valid())
  1371. {
  1372. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1373. return false;
  1374. }
  1375. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1376. {
  1377. for (auto pos : tiles)
  1378. {
  1379. if (!gen->isFree(pos))
  1380. gen->setOccupied(pos, ETileType::BLOCKED);
  1381. }
  1382. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1383. {
  1384. if (gen->isPossible(pos))
  1385. gen->setOccupied (pos, ETileType::FREE);
  1386. });
  1387. gen->setOccupied (guardTile, ETileType::USED);
  1388. }
  1389. else //allow no guard or other object in front of this object
  1390. {
  1391. for (auto tile : tiles)
  1392. if (gen->isPossible(tile))
  1393. gen->setOccupied (tile, ETileType::FREE);
  1394. }
  1395. return true;
  1396. }
  1397. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1398. {
  1399. //int objectsVisitableFromBottom = 0; //for debug
  1400. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1401. ui32 total = 0;
  1402. //calculate actual treasure value range based on remaining value
  1403. ui32 maxVal = maxValue - currentValue;
  1404. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1405. //roulette wheel
  1406. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1407. {
  1408. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1409. {
  1410. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1411. int3 newVisitablePos = info.nextTreasurePos;
  1412. if (!oi.templ.isVisitableFromTop())
  1413. {
  1414. //objectsVisitableFromBottom++;
  1415. //there must be free tiles under object
  1416. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1417. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1418. continue;
  1419. }
  1420. //NOTE: y coordinate grows downwards
  1421. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1422. {
  1423. bool fitsHere = false;
  1424. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1425. {
  1426. for (auto tile : info.visitableFromTopPositions)
  1427. {
  1428. int3 actualTile = tile + newVisitableOffset;
  1429. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1430. {
  1431. fitsHere = true;
  1432. break;
  1433. }
  1434. }
  1435. for (auto tile : info.visitableFromBottomPositions)
  1436. {
  1437. int3 actualTile = tile + newVisitableOffset;
  1438. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1439. {
  1440. fitsHere = true;
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. else //if new object is not visitable from top, it must be accessible from below or side
  1446. {
  1447. for (auto tile : info.visitableFromTopPositions)
  1448. {
  1449. int3 actualTile = tile + newVisitableOffset;
  1450. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1451. {
  1452. fitsHere = true;
  1453. break;
  1454. }
  1455. }
  1456. for (auto tile : info.visitableFromBottomPositions)
  1457. {
  1458. int3 actualTile = tile + newVisitableOffset;
  1459. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1460. {
  1461. fitsHere = true;
  1462. break;
  1463. }
  1464. }
  1465. }
  1466. if (!fitsHere)
  1467. continue;
  1468. }
  1469. //now check blockmap, including our already reserved pile area
  1470. bool fitsBlockmap = true;
  1471. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1472. blockedOffsets.insert (newVisitableOffset);
  1473. for (auto blockingTile : blockedOffsets)
  1474. {
  1475. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1476. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1477. {
  1478. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1479. break;
  1480. }
  1481. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1482. {
  1483. fitsBlockmap = false;
  1484. break;
  1485. }
  1486. }
  1487. if (!fitsBlockmap)
  1488. continue;
  1489. total += oi.probability;
  1490. //assert (oi.value > 0);
  1491. tresholds.push_back (std::make_pair (total, oi));
  1492. }
  1493. }
  1494. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1495. if (tresholds.empty())
  1496. {
  1497. ObjectInfo oi;
  1498. //Generate pandora Box with gold if the value is extremely high
  1499. if (minValue > 20000) //we don't have object valuable enough
  1500. {
  1501. oi.generateObject = [minValue]() -> CGObjectInstance *
  1502. {
  1503. auto obj = new CGPandoraBox();
  1504. obj->ID = Obj::PANDORAS_BOX;
  1505. obj->subID = 0;
  1506. obj->resources[Res::GOLD] = minValue;
  1507. return obj;
  1508. };
  1509. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1510. oi.value = minValue;
  1511. oi.probability = 0;
  1512. }
  1513. else //generate empty object with 0 value if the value if we can't spawn anything
  1514. {
  1515. oi.generateObject = [gen]() -> CGObjectInstance *
  1516. {
  1517. return nullptr;
  1518. };
  1519. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1520. oi.value = 0; // this field is checked to determine no object
  1521. oi.probability = 0;
  1522. }
  1523. return oi;
  1524. }
  1525. else
  1526. {
  1527. int r = gen->rand.nextInt (1, total);
  1528. for (auto t : tresholds)
  1529. {
  1530. if (r <= t.first)
  1531. return t.second;
  1532. }
  1533. assert (0); //we should never be here
  1534. }
  1535. //FIXME: control reaches end of non-void function. Missing return?
  1536. }
  1537. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1538. {
  1539. ObjectInfo oi;
  1540. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1541. int numZones = gen->getZones().size();
  1542. for (auto primaryID : VLC->objtypeh->knownObjects())
  1543. {
  1544. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1545. {
  1546. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1547. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1548. {
  1549. for (auto temp : handler->getTemplates())
  1550. {
  1551. if (temp.canBePlacedAt(terrainType))
  1552. {
  1553. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1554. {
  1555. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1556. };
  1557. auto rmgInfo = handler->getRMGInfo();
  1558. oi.value = rmgInfo.value;
  1559. oi.probability = rmgInfo.rarity;
  1560. oi.templ = temp;
  1561. oi.maxPerZone = rmgInfo.zoneLimit;
  1562. vstd::amin (oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1563. possibleObjects.push_back (oi);
  1564. }
  1565. }
  1566. }
  1567. }
  1568. }
  1569. //prisons
  1570. //levels 1, 5, 10, 20, 30
  1571. static int prisonExp[] = {0, 5000, 15000, 90000, 500000};
  1572. static int prisonValues[] = {2500, 5000, 10000, 20000, 30000};
  1573. for (int i = 0; i < 5; i++)
  1574. {
  1575. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1576. {
  1577. auto obj = new CGHeroInstance;
  1578. obj->ID = Obj::PRISON;
  1579. std::vector<ui32> possibleHeroes;
  1580. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1581. {
  1582. if (gen->map->allowedHeroes[j])
  1583. possibleHeroes.push_back(j);
  1584. }
  1585. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1586. obj->subID = hid; //will be initialized later
  1587. obj->exp = prisonExp[i]; //game crashes at hero level up
  1588. //obj->exp = 0;
  1589. obj->setOwner(PlayerColor::NEUTRAL);
  1590. gen->map->allowedHeroes[hid] = false; //ban this hero
  1591. gen->decreasePrisonsRemaining();
  1592. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1593. return obj;
  1594. };
  1595. oi.setTemplate (Obj::PRISON, 0, terrainType);
  1596. oi.value = prisonValues[i];
  1597. oi.probability = 30;
  1598. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1599. possibleObjects.push_back (oi);
  1600. }
  1601. //all following objects are unlimited
  1602. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1603. //dwellings
  1604. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1605. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1606. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1607. for (int i = 0; i < 4; i++)
  1608. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1609. for (auto secondaryID : subObjects)
  1610. {
  1611. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1612. auto creatures = dwellingHandler->getProducedCreatures();
  1613. if (creatures.empty())
  1614. continue;
  1615. auto cre = creatures.front();
  1616. if (cre->faction == townType)
  1617. {
  1618. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1619. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1620. oi.probability = 40;
  1621. for (auto temp : dwellingHandler->getTemplates())
  1622. {
  1623. if (temp.canBePlacedAt(terrainType))
  1624. {
  1625. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1626. {
  1627. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1628. //dwellingHandler->configureObject(obj, gen->rand);
  1629. obj->tempOwner = PlayerColor::NEUTRAL;
  1630. return obj;
  1631. };
  1632. oi.templ = temp;
  1633. possibleObjects.push_back (oi);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1639. for (int i = 0; i < 5; i++)
  1640. {
  1641. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1642. {
  1643. auto obj = new CGArtifact();
  1644. obj->ID = Obj::SPELL_SCROLL;
  1645. obj->subID = 0;
  1646. std::vector<SpellID> out;
  1647. //TODO: unify with cb->getAllowedSpells?
  1648. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1649. {
  1650. const CSpell *spell = SpellID(i).toSpell();
  1651. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1652. {
  1653. out.push_back(spell->id);
  1654. }
  1655. }
  1656. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1657. gen->map->addNewArtifactInstance(a);
  1658. obj->storedArtifact = a;
  1659. return obj;
  1660. };
  1661. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1662. oi.value = scrollValues[i];
  1663. oi.probability = 30;
  1664. possibleObjects.push_back (oi);
  1665. }
  1666. //pandora box with gold
  1667. for (int i = 1; i < 5; i++)
  1668. {
  1669. oi.generateObject = [i]() -> CGObjectInstance *
  1670. {
  1671. auto obj = new CGPandoraBox();
  1672. obj->ID = Obj::PANDORAS_BOX;
  1673. obj->subID = 0;
  1674. obj->resources[Res::GOLD] = i * 5000;
  1675. return obj;
  1676. };
  1677. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1678. oi.value = i * 5000;;
  1679. oi.probability = 5;
  1680. possibleObjects.push_back (oi);
  1681. }
  1682. //pandora box with experience
  1683. for (int i = 1; i < 5; i++)
  1684. {
  1685. oi.generateObject = [i]() -> CGObjectInstance *
  1686. {
  1687. auto obj = new CGPandoraBox();
  1688. obj->ID = Obj::PANDORAS_BOX;
  1689. obj->subID = 0;
  1690. obj->gainedExp = i * 5000;
  1691. return obj;
  1692. };
  1693. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1694. oi.value = i * 6000;;
  1695. oi.probability = 20;
  1696. possibleObjects.push_back (oi);
  1697. }
  1698. //pandora box with creatures
  1699. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1700. for (auto creature : VLC->creh->creatures)
  1701. {
  1702. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1703. {
  1704. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1705. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1706. if (creaturesAmount <= 5)
  1707. {
  1708. }
  1709. else if (creaturesAmount <= 12)
  1710. {
  1711. (creaturesAmount /= 2) *= 2;
  1712. }
  1713. else if (creaturesAmount <= 50)
  1714. {
  1715. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1716. }
  1717. else if (creaturesAmount <= 12)
  1718. {
  1719. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1720. }
  1721. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1722. {
  1723. auto obj = new CGPandoraBox();
  1724. obj->ID = Obj::PANDORAS_BOX;
  1725. obj->subID = 0;
  1726. auto stack = new CStackInstance(creature, creaturesAmount);
  1727. obj->creatures.putStack(SlotID(0), stack);
  1728. return obj;
  1729. };
  1730. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1731. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1732. oi.probability = 3;
  1733. possibleObjects.push_back (oi);
  1734. }
  1735. }
  1736. //Pandora with 12 spells of certain level
  1737. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1738. {
  1739. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1740. {
  1741. auto obj = new CGPandoraBox();
  1742. obj->ID = Obj::PANDORAS_BOX;
  1743. obj->subID = 0;
  1744. std::vector <CSpell *> spells;
  1745. for (auto spell : VLC->spellh->objects)
  1746. {
  1747. if (!spell->isSpecialSpell() && spell->level == i)
  1748. spells.push_back(spell);
  1749. }
  1750. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1751. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1752. {
  1753. obj->spells.push_back (spells[j]->id);
  1754. }
  1755. return obj;
  1756. };
  1757. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1758. oi.value = (i + 1) * 2500; //5000 - 15000
  1759. oi.probability = 2;
  1760. possibleObjects.push_back (oi);
  1761. }
  1762. //Pandora with 15 spells of certain school
  1763. for (int i = 1; i <= 4; i++)
  1764. {
  1765. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1766. {
  1767. auto obj = new CGPandoraBox();
  1768. obj->ID = Obj::PANDORAS_BOX;
  1769. obj->subID = 0;
  1770. std::vector <CSpell *> spells;
  1771. for (auto spell : VLC->spellh->objects)
  1772. {
  1773. if (!spell->isSpecialSpell())
  1774. {
  1775. bool school = false; //TODO: we could have better interface for iterating schools
  1776. switch (i)
  1777. {
  1778. case 1:
  1779. school = spell->air;
  1780. case 2:
  1781. school = spell->earth;
  1782. case 3:
  1783. school = spell->fire;
  1784. case 4:
  1785. school = spell->water;
  1786. }
  1787. if (school)
  1788. spells.push_back(spell);
  1789. }
  1790. }
  1791. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1792. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1793. {
  1794. obj->spells.push_back (spells[j]->id);
  1795. }
  1796. return obj;
  1797. };
  1798. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1799. oi.value = 15000;
  1800. oi.probability = 2;
  1801. possibleObjects.push_back (oi);
  1802. }
  1803. // Pandora box with 60 random spells
  1804. oi.generateObject = [gen]() -> CGObjectInstance *
  1805. {
  1806. auto obj = new CGPandoraBox();
  1807. obj->ID = Obj::PANDORAS_BOX;
  1808. obj->subID = 0;
  1809. std::vector <CSpell *> spells;
  1810. for (auto spell : VLC->spellh->objects)
  1811. {
  1812. if (!spell->isSpecialSpell())
  1813. spells.push_back(spell);
  1814. }
  1815. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1816. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1817. {
  1818. obj->spells.push_back (spells[j]->id);
  1819. }
  1820. return obj;
  1821. };
  1822. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1823. oi.value = 3000;
  1824. oi.probability = 2;
  1825. possibleObjects.push_back (oi);
  1826. }
  1827. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1828. {
  1829. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1830. }