CRmgTemplateZone.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  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, 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::createBorder(CMapGenerator* gen)
  320. {
  321. for (auto tile : tileinfo)
  322. {
  323. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  324. {
  325. if (!vstd::contains(this->tileinfo, pos))
  326. {
  327. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  328. {
  329. if (gen->isPossible(pos))
  330. gen->setOccupied (pos, ETileType::BLOCKED);
  331. });
  332. }
  333. });
  334. }
  335. }
  336. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  337. {
  338. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  339. std::set<int3> possibleTiles;
  340. std::set<int3> tilesToClear; //will be set clear
  341. std::set<int3> tilesToIgnore; //will be erased in this iteration
  342. //the more treasure density, the greater distance between paths. Scaling is experimental.
  343. const float minDistance = std::sqrt(totalDensity * 3);
  344. for (auto tile : tileinfo)
  345. {
  346. if (gen->isFree(tile))
  347. clearedTiles.push_back(tile);
  348. else if (gen->isPossible(tile))
  349. possibleTiles.insert(tile);
  350. }
  351. if (clearedTiles.empty()) //this should come from zone connections
  352. {
  353. clearedTiles.push_back(pos); //zone center should be always clear
  354. }
  355. while (possibleTiles.size())
  356. {
  357. for (auto tileToMakePath : possibleTiles)
  358. {
  359. //find closest free tile
  360. float currentDistance = 1e10;
  361. int3 closestTile (-1,-1,-1);
  362. for (auto clearTile : clearedTiles)
  363. {
  364. float distance = tileToMakePath.dist2d(clearTile);
  365. if (distance < currentDistance)
  366. {
  367. currentDistance = distance;
  368. closestTile = clearTile;
  369. }
  370. if (currentDistance <= minDistance)
  371. {
  372. //this tile is close enough. Forget about it and check next one
  373. tilesToIgnore.insert (tileToMakePath);
  374. break;
  375. }
  376. }
  377. //if tiles is not close enough, make path to it
  378. if (currentDistance > minDistance)
  379. {
  380. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  381. break; //next iteration - use already cleared tiles
  382. }
  383. }
  384. for (auto tileToClear : tilesToClear)
  385. {
  386. //move cleared tiles from one set to another
  387. clearedTiles.push_back(tileToClear);
  388. vstd::erase_if_present(possibleTiles, tileToClear);
  389. }
  390. for (auto tileToClear : tilesToIgnore)
  391. {
  392. //these tiles are already connected, ignore them
  393. vstd::erase_if_present(possibleTiles, tileToClear);
  394. }
  395. if (tilesToClear.empty()) //nothing else can be done (?)
  396. break;
  397. tilesToClear.clear(); //empty this container
  398. tilesToIgnore.clear();
  399. }
  400. for (auto tile : clearedTiles)
  401. {
  402. freePaths.insert(tile);
  403. }
  404. if (0) //enable to debug
  405. {
  406. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  407. int levels = gen->map->twoLevel ? 2 : 1;
  408. int width = gen->map->width;
  409. int height = gen->map->height;
  410. for (int k = 0; k < levels; k++)
  411. {
  412. for(int j=0; j<height; j++)
  413. {
  414. for (int i=0; i<width; i++)
  415. {
  416. out << (int)vstd::contains(freePaths, int3(i,j,k));
  417. }
  418. out << std::endl;
  419. }
  420. out << std::endl;
  421. }
  422. }
  423. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  424. }
  425. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  426. {
  427. /*
  428. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  429. do not leave zone border
  430. */
  431. bool result = false;
  432. bool end = false;
  433. int3 currentPos = src;
  434. float distance = currentPos.dist2dSQ (dst);
  435. while (!end)
  436. {
  437. if (currentPos == dst)
  438. {
  439. result = true;
  440. break;
  441. }
  442. auto lastDistance = distance;
  443. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  444. {
  445. if (!result) //not sure if lambda is worth it...
  446. {
  447. if (pos == dst)
  448. {
  449. result = true;
  450. end = true;
  451. }
  452. if (pos.dist2dSQ (dst) < distance)
  453. {
  454. if (!gen->isBlocked(pos))
  455. {
  456. if (vstd::contains (tileinfo, pos))
  457. {
  458. if (gen->isPossible(pos))
  459. {
  460. gen->setOccupied (pos, ETileType::FREE);
  461. if (clearedTiles)
  462. clearedTiles->insert(pos);
  463. currentPos = pos;
  464. distance = currentPos.dist2dSQ (dst);
  465. }
  466. else if (gen->isFree(pos))
  467. {
  468. end = true;
  469. result = true;
  470. }
  471. else
  472. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  473. }
  474. }
  475. }
  476. }
  477. });
  478. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  479. {
  480. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  481. break;
  482. }
  483. }
  484. return result;
  485. }
  486. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  487. {
  488. requiredObjects.push_back(std::make_pair(obj, strength));
  489. }
  490. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  491. {
  492. //precalculate actual (randomized) monster strength based on this post
  493. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  494. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  495. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  496. static const int value1[] = {2500, 1500, 1000, 500, 0};
  497. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  498. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  499. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  500. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  501. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  502. strength = strength1 + strength2;
  503. if (strength < 2000)
  504. return false; //no guard at all
  505. CreatureID creId = CreatureID::NONE;
  506. int amount = 0;
  507. std::vector<CreatureID> possibleCreatures;
  508. for (auto cre : VLC->creh->creatures)
  509. {
  510. if (cre->special)
  511. continue;
  512. 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
  513. {
  514. possibleCreatures.push_back(cre->idNumber);
  515. }
  516. }
  517. if (possibleCreatures.size())
  518. {
  519. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  520. amount = strength / VLC->creh->creatures[creId]->AIValue;
  521. if (amount >= 4)
  522. amount *= gen->rand.nextDouble(0.75, 1.25);
  523. }
  524. else //just pick any available creature
  525. {
  526. creId = CreatureID(132); //Azure Dragon
  527. amount = strength / VLC->creh->creatures[creId]->AIValue;
  528. }
  529. auto guard = new CGCreature();
  530. guard->ID = Obj::MONSTER;
  531. guard->subID = creId;
  532. auto hlp = new CStackInstance(creId, amount);
  533. //will be set during initialization
  534. guard->putStack(SlotID(0), hlp);
  535. placeObject(gen, guard, pos);
  536. return true;
  537. }
  538. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  539. {
  540. std::map<int3, CGObjectInstance *> treasures;
  541. std::set<int3> boundary;
  542. int3 guardPos (-1,-1,-1);
  543. int3 nextTreasurePos = pos;
  544. //default values
  545. int maxValue = 5000;
  546. int minValue = 1500;
  547. if (treasureInfo.size())
  548. {
  549. //roulette wheel
  550. int r = gen->rand.nextInt (1, totalDensity);
  551. for (auto t : treasureInfo)
  552. {
  553. if (r <= t.threshold)
  554. {
  555. maxValue = t.max;
  556. minValue = t.min;
  557. break;
  558. }
  559. }
  560. }
  561. int currentValue = 0;
  562. CGObjectInstance * object = nullptr;
  563. while (currentValue < minValue)
  564. {
  565. //TODO: this works only for 1-tile objects
  566. //make sure our shape is consistent
  567. treasures[nextTreasurePos] = nullptr;
  568. for (auto treasurePos : treasures)
  569. {
  570. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  571. {
  572. boundary.insert(pos);
  573. });
  574. }
  575. for (auto treasurePos : treasures)
  576. {
  577. //leaving only boundary around objects
  578. vstd::erase_if_present (boundary, treasurePos.first);
  579. }
  580. for (auto tile : boundary)
  581. {
  582. //we can't extend boundary anymore
  583. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  584. break;
  585. }
  586. int remaining = maxValue - currentValue;
  587. auto oi = getRandomObject(gen, remaining);
  588. object = oi.generateObject();
  589. if (!object)
  590. break;
  591. currentValue += oi.value;
  592. treasures[nextTreasurePos] = object;
  593. //now find place for next object
  594. int3 placeFound(-1,-1,-1);
  595. //FIXME: find out why teh following code causes crashes
  596. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  597. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  598. //for (auto tile : boundaryVec)
  599. for (auto tile : boundary)
  600. {
  601. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  602. {
  603. bool here = true;
  604. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  605. {
  606. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  607. here = false;
  608. });
  609. if (here)
  610. {
  611. placeFound = tile;
  612. break;
  613. }
  614. }
  615. }
  616. if (placeFound.valid())
  617. nextTreasurePos = placeFound;
  618. }
  619. if (treasures.size())
  620. {
  621. //find object closest to zone center, then con nect it to the middle of the zone
  622. int3 zoneCenter = getPos();
  623. int3 closestTile = int3(-1,-1,-1);
  624. float minDistance = 1e10;
  625. for (auto treasure : treasures)
  626. {
  627. if (zoneCenter.dist2d(treasure.first) < minDistance)
  628. {
  629. closestTile = treasure.first;
  630. minDistance = zoneCenter.dist2d(treasure.first);
  631. }
  632. }
  633. assert (closestTile.valid());
  634. if (!crunchPath (gen, closestTile, findClosestTile(freePaths, closestTile), id)) //make sure pile is connected to the middle of zone
  635. {
  636. for (auto treasure : treasures)
  637. {
  638. if (gen->isPossible(treasure.first))
  639. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  640. }
  641. return true;
  642. }
  643. for (auto tile : boundary) //guard must be standing there
  644. {
  645. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  646. {
  647. guardPos = tile;
  648. break;
  649. }
  650. }
  651. if (guardPos.valid())
  652. {
  653. for (auto treasure : treasures)
  654. {
  655. bool objectFitsHere = true; //temporary workaround
  656. int3 visitableOffset = treasure.second->getVisitableOffset();
  657. std::set<int3> blockedOffsets = treasure.second->getBlockedOffsets();
  658. blockedOffsets.insert (visitableOffset);
  659. for (auto blockingTile : blockedOffsets)
  660. {
  661. int3 t = treasure.first + visitableOffset + blockingTile;
  662. if (!gen->map->isInTheMap(t))
  663. {
  664. objectFitsHere = false; //if at least one tile is not possible, object can't be placed here
  665. break;
  666. }
  667. }
  668. if (objectFitsHere)
  669. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  670. }
  671. if (addMonster(gen, guardPos, currentValue))
  672. {//block only if the object is guarded
  673. for (auto tile : boundary)
  674. {
  675. if (gen->isPossible(tile))
  676. gen->setOccupied (tile, ETileType::BLOCKED);
  677. }
  678. }
  679. }
  680. else //we couldn't make a connection to this location, block it
  681. {
  682. for (auto treasure : treasures)
  683. {
  684. if (gen->isPossible(treasure.first))
  685. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  686. }
  687. }
  688. return true;
  689. }
  690. else //we did not place eveyrthing successfully
  691. return false;
  692. }
  693. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  694. {
  695. //FIXME: handle case that this player is not present -> towns should be set to neutral
  696. int totalTowns = 0;
  697. auto addNewTowns = [&totalTowns, gen, this](int count, bool hasFort, PlayerColor player)
  698. {
  699. for (int i = 0; i < count; i++)
  700. {
  701. auto town = new CGTownInstance();
  702. town->ID = Obj::TOWN;
  703. if (this->townsAreSameType)
  704. town->subID = townType;
  705. else
  706. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  707. town->tempOwner = player;
  708. if (hasFort)
  709. town->builtBuildings.insert(BuildingID::FORT);
  710. town->builtBuildings.insert(BuildingID::DEFAULT);
  711. if (!totalTowns)
  712. {
  713. //first town in zone sets the facton of entire zone
  714. town->subID = townType;
  715. //register MAIN town of zone
  716. gen->registerZone(town->subID);
  717. //first town in zone goes in the middle
  718. placeObject(gen, town, getPos() + town->getVisitableOffset());
  719. }
  720. else
  721. addRequiredObject (town);
  722. totalTowns++;
  723. }
  724. };
  725. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  726. {
  727. //set zone types to player faction, generate main town
  728. logGlobal->infoStream() << "Preparing playing zone";
  729. int player_id = *owner - 1;
  730. auto & playerInfo = gen->map->players[player_id];
  731. if (playerInfo.canAnyonePlay())
  732. {
  733. PlayerColor player(player_id);
  734. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  735. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  736. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  737. auto town = new CGTownInstance();
  738. town->ID = Obj::TOWN;
  739. town->subID = townType;
  740. town->tempOwner = player;
  741. town->builtBuildings.insert(BuildingID::FORT);
  742. town->builtBuildings.insert(BuildingID::DEFAULT);
  743. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  744. totalTowns++;
  745. //register MAIN town of zone only
  746. gen->registerZone (town->subID);
  747. logGlobal->traceStream() << "Fill player info " << player_id;
  748. // Update player info
  749. playerInfo.allowedFactions.clear();
  750. playerInfo.allowedFactions.insert (townType);
  751. playerInfo.hasMainTown = true;
  752. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  753. playerInfo.generateHeroAtMainTown = true;
  754. //now create actual towns
  755. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  756. addNewTowns (playerTowns.getTownCount(), false, player);
  757. //requiredObjects.push_back(town);
  758. }
  759. else
  760. {
  761. type = ETemplateZoneType::TREASURE;
  762. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  763. logGlobal->infoStream() << "Skipping this zone cause no player";
  764. }
  765. }
  766. else //no player
  767. {
  768. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  769. }
  770. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  771. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  772. }
  773. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  774. {
  775. if (matchTerrainToTown)
  776. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  777. else
  778. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  779. //TODO: allow new types of terrain?
  780. if (pos.z)
  781. {
  782. if (terrainType != ETerrainType::LAVA)
  783. terrainType = ETerrainType::SUBTERRANEAN;
  784. }
  785. else
  786. {
  787. if (terrainType == ETerrainType::SUBTERRANEAN)
  788. terrainType = ETerrainType::DIRT;
  789. }
  790. paintZoneTerrain (gen, terrainType);
  791. }
  792. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  793. {
  794. std::vector<int3> tiles;
  795. for (auto tile : tileinfo)
  796. {
  797. tiles.push_back (tile);
  798. }
  799. gen->editManager->getTerrainSelection().setSelection(tiles);
  800. gen->editManager->drawTerrain(terrainType, &gen->rand);
  801. }
  802. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  803. {
  804. std::vector<Res::ERes> required_mines;
  805. required_mines.push_back(Res::ERes::WOOD);
  806. required_mines.push_back(Res::ERes::ORE);
  807. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  808. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  809. //TODO: factory / copy constructor?
  810. for (const auto & res : woodOre)
  811. {
  812. //TODO: these 2 should be close to town (within 12 tiles radius)
  813. for (int i = 0; i < mines[res]; i++)
  814. {
  815. auto mine = new CGMine();
  816. mine->ID = Obj::MINE;
  817. mine->subID = static_cast<si32>(res);
  818. mine->producedResource = res;
  819. mine->producedQuantity = mine->defaultResProduction();
  820. addRequiredObject(mine, 1500);
  821. }
  822. }
  823. for (const auto & res : preciousResources)
  824. {
  825. for (int i = 0; i < mines[res]; i++)
  826. {
  827. auto mine = new CGMine();
  828. mine->ID = Obj::MINE;
  829. mine->subID = static_cast<si32>(res);
  830. mine->producedResource = res;
  831. mine->producedQuantity = mine->defaultResProduction();
  832. addRequiredObject(mine, 3500);
  833. }
  834. }
  835. for (int i = 0; i < mines[Res::GOLD]; i++)
  836. {
  837. auto mine = new CGMine();
  838. mine->ID = Obj::MINE;
  839. mine->subID = static_cast<si32>(Res::GOLD);
  840. mine->producedResource = Res::GOLD;
  841. mine->producedQuantity = mine->defaultResProduction();
  842. addRequiredObject(mine, 7000);
  843. }
  844. return true;
  845. }
  846. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  847. {
  848. logGlobal->infoStream() << "Creating required objects";
  849. for(const auto &obj : requiredObjects)
  850. {
  851. int3 pos;
  852. logGlobal->traceStream() << "Looking for place";
  853. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  854. {
  855. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  856. //TODO CLEANUP!
  857. return false;
  858. }
  859. logGlobal->traceStream() << "Place found";
  860. placeObject(gen, obj.first, pos);
  861. guardObject (gen, obj.first, obj.second);
  862. }
  863. return true;
  864. }
  865. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  866. {
  867. const double minDistance = 3;
  868. do {
  869. int3 pos;
  870. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  871. {
  872. break;
  873. }
  874. createTreasurePile (gen, pos);
  875. } while(true);
  876. }
  877. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  878. {
  879. if (pos.z) //underground
  880. {
  881. std::vector<int3> rockTiles;
  882. for (auto tile : tileinfo)
  883. {
  884. if (gen->shouldBeBlocked(tile))
  885. {
  886. bool placeRock = true;
  887. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  888. {
  889. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  890. placeRock = false;
  891. });
  892. if (placeRock)
  893. {
  894. rockTiles.push_back(tile);
  895. }
  896. }
  897. }
  898. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  899. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  900. //for (auto tile : rockTiles)
  901. //{
  902. // gen->setOccupied (tile, ETileType::USED);
  903. // gen->foreach_neighbour (tile, [gen](int3 &pos)
  904. // {
  905. // if (!gen->isUsed(pos))
  906. // gen->setOccupied (pos, ETileType::BLOCKED);
  907. // });
  908. //}
  909. }
  910. //get all possible obstacles for this terrain
  911. for (auto primaryID : VLC->objtypeh->knownObjects())
  912. {
  913. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  914. {
  915. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  916. if (handler->isStaticObject())
  917. {
  918. for (auto temp : handler->getTemplates())
  919. {
  920. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  921. possibleObstacles.push_back(temp);
  922. }
  923. }
  924. }
  925. }
  926. auto sel = gen->editManager->getTerrainSelection();
  927. sel.clearSelection();
  928. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  929. {
  930. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  931. int3 obstaclePos = tile - temp.getBlockMapOffset();
  932. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  933. {
  934. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  935. placeObject(gen, obj, obstaclePos);
  936. return true;
  937. }
  938. return false;
  939. };
  940. for (auto tile : tileinfo)
  941. {
  942. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  943. {
  944. while (!tryToPlaceObstacleHere(tile));
  945. }
  946. else if (gen->isPossible(tile))
  947. {
  948. //try to place random obstacle once - if not possible, leave it clear
  949. tryToPlaceObstacleHere(tile);
  950. }
  951. }
  952. }
  953. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  954. {
  955. initTownType(gen);
  956. initTerrainType(gen);
  957. addAllPossibleObjects (gen);
  958. placeMines(gen);
  959. createRequiredObjects(gen);
  960. fractalize(gen); //after required objects are created and linked with their own paths
  961. createTreasures(gen);
  962. createObstacles(gen);
  963. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  964. return true;
  965. }
  966. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  967. {
  968. //si32 min_dist = sqrt(tileinfo.size()/density);
  969. int best_distance = 0;
  970. bool result = false;
  971. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  972. for(auto tile : tileinfo)
  973. {
  974. auto dist = gen->getTile(tile).getNearestObjectDistance();
  975. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  976. {
  977. bool allTilesAvailable = true;
  978. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  979. {
  980. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  981. {
  982. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  983. }
  984. });
  985. if (allTilesAvailable)
  986. {
  987. best_distance = dist;
  988. pos = tile;
  989. result = true;
  990. }
  991. }
  992. }
  993. if (result)
  994. {
  995. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  996. }
  997. return result;
  998. }
  999. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1000. {
  1001. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1002. return false;
  1003. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1004. for (auto blockingTile : tilesBlockedByObject)
  1005. {
  1006. int3 t = pos + blockingTile;
  1007. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1008. {
  1009. return false; //if at least one tile is not possible, object can't be placed here
  1010. }
  1011. }
  1012. return true;
  1013. }
  1014. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1015. {
  1016. //we need object apperance to deduce free tiles
  1017. if (obj->appearance.id == Obj::NO_OBJ)
  1018. {
  1019. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1020. if (templates.empty())
  1021. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1022. obj->appearance = templates.front();
  1023. }
  1024. //si32 min_dist = sqrt(tileinfo.size()/density);
  1025. int best_distance = 0;
  1026. bool result = false;
  1027. //si32 w = gen->map->width;
  1028. //si32 h = gen->map->height;
  1029. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1030. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1031. for (auto tile : tileinfo)
  1032. {
  1033. //object must be accessible from at least one surounding tile
  1034. bool accessible = false;
  1035. for (int x = -1; x < 2; x++)
  1036. for (int y = -1; y <2; y++)
  1037. {
  1038. if (x && y) //check only if object is visitable from another tile
  1039. {
  1040. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  1041. if (!vstd::contains(tilesBlockedByObject, offset))
  1042. {
  1043. int3 nearbyPos = tile + offset;
  1044. if (gen->map->isInTheMap(nearbyPos))
  1045. {
  1046. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1047. accessible = true;
  1048. }
  1049. }
  1050. }
  1051. };
  1052. if (!accessible)
  1053. continue;
  1054. auto ti = gen->getTile(tile);
  1055. auto dist = ti.getNearestObjectDistance();
  1056. //avoid borders
  1057. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1058. {
  1059. bool allTilesAvailable = true;
  1060. for (auto blockingTile : tilesBlockedByObject)
  1061. {
  1062. int3 t = tile + blockingTile;
  1063. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1064. {
  1065. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1066. break;
  1067. }
  1068. }
  1069. if (allTilesAvailable)
  1070. {
  1071. best_distance = dist;
  1072. pos = tile;
  1073. result = true;
  1074. }
  1075. }
  1076. }
  1077. if (result)
  1078. {
  1079. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1080. }
  1081. return result;
  1082. }
  1083. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1084. {
  1085. if (!gen->map->isInTheMap(pos))
  1086. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1087. object->pos = pos;
  1088. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1089. 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()));
  1090. for (auto tile : object->getBlockedPos())
  1091. {
  1092. if (!gen->map->isInTheMap(tile))
  1093. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1094. }
  1095. if (object->appearance.id == Obj::NO_OBJ)
  1096. {
  1097. auto terrainType = gen->map->getTile(pos).terType;
  1098. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1099. if (templates.empty())
  1100. 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));
  1101. object->appearance = templates.front();
  1102. }
  1103. gen->map->addBlockVisTiles(object);
  1104. gen->editManager->insertObject(object, pos);
  1105. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1106. }
  1107. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1108. {
  1109. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1110. checkAndPlaceObject (gen, object, pos);
  1111. auto points = object->getBlockedPos();
  1112. if (object->isVisitable())
  1113. points.insert(pos + object->getVisitableOffset());
  1114. points.insert(pos);
  1115. for(auto p : points)
  1116. {
  1117. if (gen->map->isInTheMap(p))
  1118. {
  1119. gen->setOccupied(p, ETileType::USED);
  1120. }
  1121. }
  1122. for(auto tile : tileinfo)
  1123. {
  1124. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1125. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1126. }
  1127. }
  1128. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str)
  1129. {
  1130. placeObject(gen, object, pos);
  1131. guardObject(gen, object, str);
  1132. }
  1133. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1134. {
  1135. //get all tiles from which this object can be accessed
  1136. int3 visitable = object->visitablePos();
  1137. std::vector<int3> tiles;
  1138. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1139. gen->foreach_neighbour(visitable, [&](int3& pos)
  1140. {
  1141. if (gen->isPossible(pos))
  1142. {
  1143. if (!vstd::contains(tilesBlockedByObject, pos))
  1144. {
  1145. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1146. {
  1147. tiles.push_back(pos);
  1148. }
  1149. }
  1150. };
  1151. });
  1152. return tiles;
  1153. }
  1154. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  1155. {
  1156. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1157. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1158. int3 guardTile(-1,-1,-1);
  1159. for (auto tile : tiles)
  1160. {
  1161. //crunching path may fail if center of teh zone is dirrectly over wide object
  1162. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id)) //make sure object is accessible before surrounding it with blocked tiles
  1163. {
  1164. guardTile = tile;
  1165. break;
  1166. }
  1167. }
  1168. if (!guardTile.valid())
  1169. {
  1170. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1171. return false;
  1172. }
  1173. if (addMonster (gen, guardTile, str)) //do not place obstacles around unguarded object
  1174. {
  1175. for (auto pos : tiles)
  1176. {
  1177. if (!gen->isFree(pos))
  1178. gen->setOccupied(pos, ETileType::BLOCKED);
  1179. }
  1180. gen->setOccupied (guardTile, ETileType::USED);
  1181. }
  1182. else //allow no guard or other object in front of this object
  1183. {
  1184. for (auto tile : tiles)
  1185. gen->setOccupied (tile, ETileType::FREE);
  1186. }
  1187. return true;
  1188. }
  1189. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  1190. {
  1191. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1192. ui32 total = 0;
  1193. ui32 minValue = 0.25f * value;
  1194. //roulette wheel
  1195. for (auto oi : possibleObjects)
  1196. {
  1197. if (oi.value >= minValue && oi.value <= value)
  1198. {
  1199. //TODO: check place for non-removable object
  1200. //problem: we need at least template for the object that does not yet exist
  1201. total += oi.probability;
  1202. tresholds.push_back (std::make_pair (total, oi));
  1203. }
  1204. }
  1205. //TODO: generate pandora box with gold if the value is very high
  1206. if (tresholds.empty())
  1207. {
  1208. ObjectInfo oi;
  1209. if (minValue > 20000) //we don't have object valuable enough
  1210. {
  1211. oi.generateObject = [minValue]() -> CGObjectInstance *
  1212. {
  1213. auto obj = new CGPandoraBox();
  1214. obj->ID = Obj::PANDORAS_BOX;
  1215. obj->subID = 0;
  1216. obj->resources[Res::GOLD] = minValue;
  1217. return obj;
  1218. };
  1219. oi.value = minValue;
  1220. oi.probability = 0;
  1221. }
  1222. else
  1223. {
  1224. oi.generateObject = [gen]() -> CGObjectInstance *
  1225. {
  1226. return nullptr;
  1227. };
  1228. oi.value = 0;
  1229. oi.probability = 0;
  1230. }
  1231. return oi;
  1232. }
  1233. int r = gen->rand.nextInt (1, total);
  1234. for (auto t : tresholds)
  1235. {
  1236. if (r <= t.first)
  1237. return t.second;
  1238. }
  1239. //FIXME: control reaches end of non-void function. Missing return?
  1240. }
  1241. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1242. {
  1243. //TODO: move typical objects to config
  1244. ObjectInfo oi;
  1245. for (auto primaryID : VLC->objtypeh->knownObjects())
  1246. {
  1247. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1248. {
  1249. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1250. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1251. {
  1252. for (auto temp : handler->getTemplates())
  1253. {
  1254. if (temp.canBePlacedAt(terrainType))
  1255. {
  1256. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1257. {
  1258. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1259. };
  1260. oi.value = handler->getRMGInfo().value;
  1261. oi.probability = handler->getRMGInfo().rarity;
  1262. possibleObjects.push_back (oi);
  1263. }
  1264. }
  1265. }
  1266. }
  1267. }
  1268. //dwellings
  1269. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1270. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1271. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1272. for (int i = 0; i < 4; i++)
  1273. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1274. for (auto secondaryID : subObjects)
  1275. {
  1276. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1277. auto creatures = dwellingHandler->getProducedCreatures();
  1278. if (creatures.empty())
  1279. continue;
  1280. auto cre = creatures.front();
  1281. if (cre->faction == townType)
  1282. {
  1283. oi.value = cre->AIValue * cre->growth * (1 + (float)(gen->getZoneCount(cre->faction)) / gen->getTotalZoneCount() + (float)(gen->getZoneCount(cre->faction) / 2)); //TODO: include town count in formula
  1284. oi.probability = 40;
  1285. for (auto temp : dwellingHandler->getTemplates())
  1286. {
  1287. if (temp.canBePlacedAt(terrainType))
  1288. {
  1289. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1290. {
  1291. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1292. //dwellingHandler->configureObject(obj, gen->rand);
  1293. obj->tempOwner = PlayerColor::NEUTRAL;
  1294. return obj;
  1295. };
  1296. possibleObjects.push_back (oi);
  1297. }
  1298. }
  1299. }
  1300. }
  1301. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1302. for (int i = 0; i < 5; i++)
  1303. {
  1304. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1305. {
  1306. auto obj = new CGArtifact();
  1307. obj->ID = Obj::SPELL_SCROLL;
  1308. obj->subID = 0;
  1309. std::vector<SpellID> out;
  1310. //TODO: unify with cb->getAllowedSpells?
  1311. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1312. {
  1313. const CSpell *spell = SpellID(i).toSpell();
  1314. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1315. {
  1316. out.push_back(spell->id);
  1317. }
  1318. }
  1319. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1320. gen->map->addNewArtifactInstance(a);
  1321. obj->storedArtifact = a;
  1322. return obj;
  1323. };
  1324. oi.value = scrollValues[i];
  1325. oi.probability = 30;
  1326. possibleObjects.push_back (oi);
  1327. }
  1328. //pandora box with gold
  1329. for (int i = 1; i < 5; i++)
  1330. {
  1331. oi.generateObject = [i]() -> CGObjectInstance *
  1332. {
  1333. auto obj = new CGPandoraBox();
  1334. obj->ID = Obj::PANDORAS_BOX;
  1335. obj->subID = 0;
  1336. obj->resources[Res::GOLD] = i * 5000;
  1337. return obj;
  1338. };
  1339. oi.value = i * 5000;;
  1340. oi.probability = 5;
  1341. possibleObjects.push_back (oi);
  1342. }
  1343. //pandora box with experience
  1344. for (int i = 1; i < 5; i++)
  1345. {
  1346. oi.generateObject = [i]() -> CGObjectInstance *
  1347. {
  1348. auto obj = new CGPandoraBox();
  1349. obj->ID = Obj::PANDORAS_BOX;
  1350. obj->subID = 0;
  1351. obj->gainedExp = i * 5000;
  1352. return obj;
  1353. };
  1354. oi.value = i * 6000;;
  1355. oi.probability = 20;
  1356. possibleObjects.push_back (oi);
  1357. }
  1358. //pandora box with creatures
  1359. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1360. for (auto creature : VLC->creh->creatures)
  1361. {
  1362. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1363. {
  1364. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1365. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1366. if (creaturesAmount <= 5)
  1367. {
  1368. }
  1369. else if (creaturesAmount <= 12)
  1370. {
  1371. (creaturesAmount /= 2) *= 2;
  1372. }
  1373. else if (creaturesAmount <= 50)
  1374. {
  1375. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1376. }
  1377. else if (creaturesAmount <= 12)
  1378. {
  1379. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1380. }
  1381. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1382. {
  1383. auto obj = new CGPandoraBox();
  1384. obj->ID = Obj::PANDORAS_BOX;
  1385. obj->subID = 0;
  1386. auto stack = new CStackInstance(creature, creaturesAmount);
  1387. obj->creatures.putStack(SlotID(0), stack);
  1388. return obj;
  1389. };
  1390. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1391. oi.probability = 3;
  1392. possibleObjects.push_back (oi);
  1393. }
  1394. }
  1395. //Pandora with 12 spells of certain level
  1396. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1397. {
  1398. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1399. {
  1400. auto obj = new CGPandoraBox();
  1401. obj->ID = Obj::PANDORAS_BOX;
  1402. obj->subID = 0;
  1403. std::vector <CSpell *> spells;
  1404. for (auto spell : VLC->spellh->objects)
  1405. {
  1406. if (!spell->isSpecialSpell() && spell->level == i)
  1407. spells.push_back(spell);
  1408. }
  1409. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1410. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1411. {
  1412. obj->spells.push_back (spells[j]->id);
  1413. }
  1414. return obj;
  1415. };
  1416. oi.value = (i + 1) * 2500; //5000 - 15000
  1417. oi.probability = 2;
  1418. possibleObjects.push_back (oi);
  1419. }
  1420. //Pandora with 15 spells of certain school
  1421. for (int i = 1; i <= 4; i++)
  1422. {
  1423. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1424. {
  1425. auto obj = new CGPandoraBox();
  1426. obj->ID = Obj::PANDORAS_BOX;
  1427. obj->subID = 0;
  1428. std::vector <CSpell *> spells;
  1429. for (auto spell : VLC->spellh->objects)
  1430. {
  1431. if (!spell->isSpecialSpell())
  1432. {
  1433. bool school = false; //TODO: we could have better interface for iterating schools
  1434. switch (i)
  1435. {
  1436. case 1:
  1437. school = spell->air;
  1438. case 2:
  1439. school = spell->earth;
  1440. case 3:
  1441. school = spell->fire;
  1442. case 4:
  1443. school = spell->water;
  1444. }
  1445. if (school)
  1446. spells.push_back(spell);
  1447. }
  1448. }
  1449. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1450. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1451. {
  1452. obj->spells.push_back (spells[j]->id);
  1453. }
  1454. return obj;
  1455. };
  1456. oi.value = 15000;
  1457. oi.probability = 2;
  1458. possibleObjects.push_back (oi);
  1459. }
  1460. // Pandora box with 60 random spells
  1461. oi.generateObject = [gen]() -> CGObjectInstance *
  1462. {
  1463. auto obj = new CGPandoraBox();
  1464. obj->ID = Obj::PANDORAS_BOX;
  1465. obj->subID = 0;
  1466. std::vector <CSpell *> spells;
  1467. for (auto spell : VLC->spellh->objects)
  1468. {
  1469. if (!spell->isSpecialSpell())
  1470. spells.push_back(spell);
  1471. }
  1472. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1473. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1474. {
  1475. obj->spells.push_back (spells[j]->id);
  1476. }
  1477. return obj;
  1478. };
  1479. oi.value = 3000;
  1480. oi.probability = 2;
  1481. possibleObjects.push_back (oi);
  1482. }