CRmgTemplateZone.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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, bool clearSurroundingTiles, bool zoneGuard)
  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 = (zoneGuard ? 0 : 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. logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  536. % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  537. placeObject(gen, guard, pos);
  538. if (clearSurroundingTiles)
  539. {
  540. //do not spawn anything near monster
  541. gen->foreach_neighbour (pos, [gen](int3 pos)
  542. {
  543. if (gen->isPossible(pos))
  544. gen->setOccupied(pos, ETileType::FREE);
  545. });
  546. }
  547. return true;
  548. }
  549. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  550. {
  551. CTreasurePileInfo info;
  552. std::map<int3, CGObjectInstance *> treasures;
  553. std::set<int3> boundary;
  554. int3 guardPos (-1,-1,-1);
  555. info.nextTreasurePos = pos;
  556. //default values
  557. int maxValue = 5000;
  558. int minValue = 1500;
  559. if (treasureInfo.size())
  560. {
  561. //roulette wheel
  562. int r = gen->rand.nextInt (1, totalDensity);
  563. for (auto t : treasureInfo)
  564. {
  565. if (r <= t.threshold)
  566. {
  567. maxValue = t.max;
  568. minValue = t.min;
  569. break;
  570. }
  571. }
  572. }
  573. int currentValue = 0;
  574. CGObjectInstance * object = nullptr;
  575. while (currentValue < minValue)
  576. {
  577. treasures[info.nextTreasurePos] = nullptr;
  578. for (auto treasurePos : treasures)
  579. {
  580. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  581. {
  582. boundary.insert(pos);
  583. });
  584. }
  585. for (auto treasurePos : treasures)
  586. {
  587. //leaving only boundary around objects
  588. vstd::erase_if_present (boundary, treasurePos.first);
  589. }
  590. for (auto tile : boundary)
  591. {
  592. //we can't extend boundary anymore
  593. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  594. break;
  595. }
  596. int remaining = maxValue - currentValue;
  597. ObjectInfo oi = getRandomObject(gen, info, remaining);
  598. object = oi.generateObject();
  599. if (!object)
  600. {
  601. vstd::erase_if_present(treasures, info.nextTreasurePos);
  602. break;
  603. }
  604. else
  605. {
  606. //update treasure pile area
  607. int3 visitablePos = info.nextTreasurePos;
  608. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  609. if (oi.templ.isVisitableFromTop())
  610. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  611. else
  612. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  613. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  614. {
  615. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  616. info.occupiedPositions.insert(blockPos);
  617. info.blockedPositions.insert(blockPos);
  618. }
  619. info.occupiedPositions.insert(visitablePos);
  620. }
  621. currentValue += oi.value;
  622. treasures[info.nextTreasurePos] = object;
  623. //now find place for next object
  624. int3 placeFound(-1,-1,-1);
  625. for (auto tile : boundary)
  626. {
  627. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  628. {
  629. bool here = true;
  630. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  631. {
  632. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  633. here = false;
  634. });
  635. if (here)
  636. {
  637. placeFound = tile;
  638. break;
  639. }
  640. }
  641. }
  642. if (placeFound.valid())
  643. info.nextTreasurePos = placeFound;
  644. }
  645. if (treasures.size())
  646. {
  647. //find object closest to zone center, then connect it to the middle of the zone
  648. int3 closestFreeTile (-1,-1,-1);
  649. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  650. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  651. else
  652. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  653. int3 closestTile = int3(-1,-1,-1);
  654. float minDistance = 1e10;
  655. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  656. {
  657. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  658. {
  659. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  660. minDistance = closestFreeTile.dist2d(visitablePos);
  661. }
  662. }
  663. if (!closestTile.valid())
  664. {
  665. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  666. {
  667. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  668. {
  669. closestTile = visitablePos;
  670. minDistance = closestFreeTile.dist2d(visitablePos);
  671. }
  672. }
  673. }
  674. assert (closestTile.valid());
  675. for (auto tile : info.occupiedPositions)
  676. {
  677. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  678. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  679. }
  680. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  681. {
  682. //we can't connect this pile, just block it off and start over
  683. for (auto treasure : treasures)
  684. {
  685. if (gen->isPossible(treasure.first))
  686. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  687. }
  688. return true;
  689. }
  690. //update boundary around our objects, including knowledge about objects visitable from bottom
  691. boundary.clear();
  692. for (auto tile : info.visitableFromBottomPositions)
  693. {
  694. gen->foreach_neighbour (tile, [tile, &boundary](int3 pos)
  695. {
  696. if (pos.y >= tile.y) //don't block these objects from above
  697. boundary.insert(pos);
  698. });
  699. }
  700. for (auto tile : info.visitableFromTopPositions)
  701. {
  702. gen->foreach_neighbour (tile, [&boundary](int3 pos)
  703. {
  704. boundary.insert(pos);
  705. });
  706. }
  707. for (auto tile : boundary) //guard must be standing there
  708. {
  709. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  710. {
  711. guardPos = tile;
  712. break;
  713. }
  714. }
  715. if (guardPos.valid())
  716. {
  717. for (auto treasure : treasures)
  718. {
  719. int3 visitableOffset = treasure.second->getVisitableOffset();
  720. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  721. }
  722. if (addMonster(gen, guardPos, currentValue, false))
  723. {//block only if the object is guarded
  724. for (auto tile : boundary)
  725. {
  726. if (gen->isPossible(tile))
  727. gen->setOccupied (tile, ETileType::BLOCKED);
  728. }
  729. //do not spawn anything near monster
  730. gen->foreach_neighbour (guardPos, [gen](int3 pos)
  731. {
  732. if (gen->isPossible(pos))
  733. gen->setOccupied(pos, ETileType::FREE);
  734. });
  735. }
  736. }
  737. else //we couldn't make a connection to this location, block it
  738. {
  739. for (auto treasure : treasures)
  740. {
  741. if (gen->isPossible(treasure.first))
  742. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  743. }
  744. }
  745. return true;
  746. }
  747. else //we did not place eveyrthing successfully
  748. return false;
  749. }
  750. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  751. {
  752. //FIXME: handle case that this player is not present -> towns should be set to neutral
  753. int totalTowns = 0;
  754. auto addNewTowns = [&totalTowns, gen, this](int count, bool hasFort, PlayerColor player)
  755. {
  756. for (int i = 0; i < count; i++)
  757. {
  758. auto town = new CGTownInstance();
  759. town->ID = Obj::TOWN;
  760. if (this->townsAreSameType)
  761. town->subID = townType;
  762. else
  763. town->subID = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); //TODO: check allowed town types for this zone
  764. town->tempOwner = player;
  765. if (hasFort)
  766. town->builtBuildings.insert(BuildingID::FORT);
  767. town->builtBuildings.insert(BuildingID::DEFAULT);
  768. if (!totalTowns)
  769. {
  770. //first town in zone sets the facton of entire zone
  771. town->subID = townType;
  772. //register MAIN town of zone
  773. gen->registerZone(town->subID);
  774. //first town in zone goes in the middle
  775. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  776. }
  777. else
  778. addRequiredObject (town);
  779. totalTowns++;
  780. }
  781. };
  782. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  783. {
  784. //set zone types to player faction, generate main town
  785. logGlobal->infoStream() << "Preparing playing zone";
  786. int player_id = *owner - 1;
  787. auto & playerInfo = gen->map->players[player_id];
  788. if (playerInfo.canAnyonePlay())
  789. {
  790. PlayerColor player(player_id);
  791. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  792. if(townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  793. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  794. auto town = new CGTownInstance();
  795. town->ID = Obj::TOWN;
  796. town->subID = townType;
  797. town->tempOwner = player;
  798. town->builtBuildings.insert(BuildingID::FORT);
  799. town->builtBuildings.insert(BuildingID::DEFAULT);
  800. //towns are big objects and should be centered around visitable position
  801. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  802. totalTowns++;
  803. //register MAIN town of zone only
  804. gen->registerZone (town->subID);
  805. logGlobal->traceStream() << "Fill player info " << player_id;
  806. // Update player info
  807. playerInfo.allowedFactions.clear();
  808. playerInfo.allowedFactions.insert (townType);
  809. playerInfo.hasMainTown = true;
  810. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  811. playerInfo.generateHeroAtMainTown = true;
  812. //now create actual towns
  813. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  814. addNewTowns (playerTowns.getTownCount(), false, player);
  815. //requiredObjects.push_back(town);
  816. }
  817. else
  818. {
  819. type = ETemplateZoneType::TREASURE;
  820. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  821. logGlobal->infoStream() << "Skipping this zone cause no player";
  822. }
  823. }
  824. else //no player
  825. {
  826. townType = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  827. }
  828. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  829. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  830. }
  831. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  832. {
  833. if (matchTerrainToTown)
  834. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  835. else
  836. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  837. //TODO: allow new types of terrain?
  838. if (pos.z)
  839. {
  840. if (terrainType != ETerrainType::LAVA)
  841. terrainType = ETerrainType::SUBTERRANEAN;
  842. }
  843. else
  844. {
  845. if (terrainType == ETerrainType::SUBTERRANEAN)
  846. terrainType = ETerrainType::DIRT;
  847. }
  848. paintZoneTerrain (gen, terrainType);
  849. }
  850. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  851. {
  852. std::vector<int3> tiles;
  853. for (auto tile : tileinfo)
  854. {
  855. tiles.push_back (tile);
  856. }
  857. gen->editManager->getTerrainSelection().setSelection(tiles);
  858. gen->editManager->drawTerrain(terrainType, &gen->rand);
  859. }
  860. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  861. {
  862. std::vector<Res::ERes> required_mines;
  863. required_mines.push_back(Res::ERes::WOOD);
  864. required_mines.push_back(Res::ERes::ORE);
  865. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  866. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  867. //TODO: factory / copy constructor?
  868. for (const auto & res : woodOre)
  869. {
  870. //TODO: these 2 should be close to town (within 12 tiles radius)
  871. for (int i = 0; i < mines[res]; i++)
  872. {
  873. auto mine = new CGMine();
  874. mine->ID = Obj::MINE;
  875. mine->subID = static_cast<si32>(res);
  876. mine->producedResource = res;
  877. mine->producedQuantity = mine->defaultResProduction();
  878. addRequiredObject(mine, 1500);
  879. }
  880. }
  881. for (const auto & res : preciousResources)
  882. {
  883. for (int i = 0; i < mines[res]; i++)
  884. {
  885. auto mine = new CGMine();
  886. mine->ID = Obj::MINE;
  887. mine->subID = static_cast<si32>(res);
  888. mine->producedResource = res;
  889. mine->producedQuantity = mine->defaultResProduction();
  890. addRequiredObject(mine, 3500);
  891. }
  892. }
  893. for (int i = 0; i < mines[Res::GOLD]; i++)
  894. {
  895. auto mine = new CGMine();
  896. mine->ID = Obj::MINE;
  897. mine->subID = static_cast<si32>(Res::GOLD);
  898. mine->producedResource = Res::GOLD;
  899. mine->producedQuantity = mine->defaultResProduction();
  900. addRequiredObject(mine, 7000);
  901. }
  902. return true;
  903. }
  904. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  905. {
  906. logGlobal->infoStream() << "Creating required objects";
  907. for(const auto &obj : requiredObjects)
  908. {
  909. int3 pos;
  910. logGlobal->traceStream() << "Looking for place";
  911. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  912. {
  913. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  914. //TODO CLEANUP!
  915. return false;
  916. }
  917. logGlobal->traceStream() << "Place found";
  918. placeObject (gen, obj.first, pos);
  919. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY));
  920. }
  921. return true;
  922. }
  923. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  924. {
  925. const double minDistance = 3;
  926. do {
  927. int3 pos;
  928. if ( ! findPlaceForTreasurePile(gen, minDistance, pos))
  929. {
  930. break;
  931. }
  932. createTreasurePile (gen, pos);
  933. } while(true);
  934. }
  935. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  936. {
  937. if (pos.z) //underground
  938. {
  939. std::vector<int3> rockTiles;
  940. for (auto tile : tileinfo)
  941. {
  942. if (gen->shouldBeBlocked(tile))
  943. {
  944. bool placeRock = true;
  945. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  946. {
  947. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  948. placeRock = false;
  949. });
  950. if (placeRock)
  951. {
  952. rockTiles.push_back(tile);
  953. }
  954. }
  955. }
  956. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  957. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  958. //for (auto tile : rockTiles)
  959. //{
  960. // gen->setOccupied (tile, ETileType::USED);
  961. // gen->foreach_neighbour (tile, [gen](int3 &pos)
  962. // {
  963. // if (!gen->isUsed(pos))
  964. // gen->setOccupied (pos, ETileType::BLOCKED);
  965. // });
  966. //}
  967. }
  968. //get all possible obstacles for this terrain
  969. for (auto primaryID : VLC->objtypeh->knownObjects())
  970. {
  971. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  972. {
  973. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  974. if (handler->isStaticObject())
  975. {
  976. for (auto temp : handler->getTemplates())
  977. {
  978. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  979. possibleObstacles.push_back(temp);
  980. }
  981. }
  982. }
  983. }
  984. auto sel = gen->editManager->getTerrainSelection();
  985. sel.clearSelection();
  986. auto tryToPlaceObstacleHere = [this, gen](int3& tile)-> bool
  987. {
  988. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles, gen->rand);
  989. int3 obstaclePos = tile - temp.getBlockMapOffset();
  990. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  991. {
  992. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  993. placeObject(gen, obj, obstaclePos);
  994. return true;
  995. }
  996. return false;
  997. };
  998. for (auto tile : tileinfo)
  999. {
  1000. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  1001. {
  1002. while (!tryToPlaceObstacleHere(tile));
  1003. }
  1004. else if (gen->isPossible(tile))
  1005. {
  1006. //try to place random obstacle once - if not possible, leave it clear
  1007. tryToPlaceObstacleHere(tile);
  1008. }
  1009. }
  1010. }
  1011. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1012. {
  1013. initTownType(gen);
  1014. initTerrainType(gen);
  1015. addAllPossibleObjects (gen);
  1016. placeMines(gen);
  1017. createRequiredObjects(gen);
  1018. fractalize(gen); //after required objects are created and linked with their own paths
  1019. createTreasures(gen);
  1020. createObstacles(gen);
  1021. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1022. return true;
  1023. }
  1024. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  1025. {
  1026. //si32 min_dist = sqrt(tileinfo.size()/density);
  1027. int best_distance = 0;
  1028. bool result = false;
  1029. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1030. for(auto tile : tileinfo)
  1031. {
  1032. auto dist = gen->getTile(tile).getNearestObjectDistance();
  1033. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1034. {
  1035. bool allTilesAvailable = true;
  1036. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  1037. {
  1038. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  1039. {
  1040. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1041. }
  1042. });
  1043. if (allTilesAvailable)
  1044. {
  1045. best_distance = dist;
  1046. pos = tile;
  1047. result = true;
  1048. }
  1049. }
  1050. }
  1051. if (result)
  1052. {
  1053. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1054. }
  1055. return result;
  1056. }
  1057. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1058. {
  1059. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1060. return false;
  1061. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1062. for (auto blockingTile : tilesBlockedByObject)
  1063. {
  1064. int3 t = pos + blockingTile;
  1065. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1066. {
  1067. return false; //if at least one tile is not possible, object can't be placed here
  1068. }
  1069. }
  1070. return true;
  1071. }
  1072. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, std::set<int3> &tilesBlockedByObject) const
  1073. {
  1074. bool accessible = false;
  1075. for (int x = -1; x < 2; x++)
  1076. {
  1077. for (int y = -1; y <2; y++)
  1078. {
  1079. if (x && y) //check only if object is visitable from another tile
  1080. {
  1081. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1082. if (!vstd::contains(tilesBlockedByObject, offset))
  1083. {
  1084. int3 nearbyPos = tile + offset;
  1085. if (gen->map->isInTheMap(nearbyPos))
  1086. {
  1087. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1088. accessible = true;
  1089. }
  1090. }
  1091. }
  1092. };
  1093. }
  1094. return accessible;
  1095. }
  1096. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1097. {
  1098. //we need object apperance to deduce free tiles
  1099. if (obj->appearance.id == Obj::NO_OBJ)
  1100. {
  1101. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1102. if (templates.empty())
  1103. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  1104. obj->appearance = templates.front();
  1105. }
  1106. //si32 min_dist = sqrt(tileinfo.size()/density);
  1107. int best_distance = 0;
  1108. bool result = false;
  1109. //si32 w = gen->map->width;
  1110. //si32 h = gen->map->height;
  1111. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1112. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1113. for (auto tile : tileinfo)
  1114. {
  1115. //object must be accessible from at least one surounding tile
  1116. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1117. continue;
  1118. auto ti = gen->getTile(tile);
  1119. auto dist = ti.getNearestObjectDistance();
  1120. //avoid borders
  1121. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1122. {
  1123. bool allTilesAvailable = true;
  1124. for (auto blockingTile : tilesBlockedByObject)
  1125. {
  1126. int3 t = tile + blockingTile;
  1127. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1128. {
  1129. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  1130. break;
  1131. }
  1132. }
  1133. if (allTilesAvailable)
  1134. {
  1135. best_distance = dist;
  1136. pos = tile;
  1137. result = true;
  1138. }
  1139. }
  1140. }
  1141. if (result)
  1142. {
  1143. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1144. }
  1145. return result;
  1146. }
  1147. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1148. {
  1149. if (!gen->map->isInTheMap(pos))
  1150. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1151. object->pos = pos;
  1152. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1153. 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()));
  1154. for (auto tile : object->getBlockedPos())
  1155. {
  1156. if (!gen->map->isInTheMap(tile))
  1157. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1158. }
  1159. if (object->appearance.id == Obj::NO_OBJ)
  1160. {
  1161. auto terrainType = gen->map->getTile(pos).terType;
  1162. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1163. if (templates.empty())
  1164. 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));
  1165. object->appearance = templates.front();
  1166. }
  1167. gen->map->addBlockVisTiles(object);
  1168. gen->editManager->insertObject(object, pos);
  1169. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1170. }
  1171. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1172. {
  1173. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1174. checkAndPlaceObject (gen, object, pos);
  1175. auto points = object->getBlockedPos();
  1176. if (object->isVisitable())
  1177. points.insert(pos + object->getVisitableOffset());
  1178. points.insert(pos);
  1179. for(auto p : points)
  1180. {
  1181. if (gen->map->isInTheMap(p))
  1182. {
  1183. gen->setOccupied(p, ETileType::USED);
  1184. }
  1185. }
  1186. for(auto tile : tileinfo)
  1187. {
  1188. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1189. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  1190. }
  1191. }
  1192. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1193. {
  1194. placeObject(gen, object, pos);
  1195. guardObject(gen, object, str, zoneGuard);
  1196. }
  1197. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1198. {
  1199. //get all tiles from which this object can be accessed
  1200. int3 visitable = object->visitablePos();
  1201. std::vector<int3> tiles;
  1202. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1203. gen->foreach_neighbour(visitable, [&](int3& pos)
  1204. {
  1205. if (gen->isPossible(pos))
  1206. {
  1207. if (!vstd::contains(tilesBlockedByObject, pos))
  1208. {
  1209. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1210. {
  1211. tiles.push_back(pos);
  1212. }
  1213. }
  1214. };
  1215. });
  1216. return tiles;
  1217. }
  1218. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard)
  1219. {
  1220. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1221. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1222. int3 guardTile(-1,-1,-1);
  1223. for (auto tile : tiles)
  1224. {
  1225. //crunching path may fail if center of teh zone is dirrectly over wide object
  1226. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id)) //make sure object is accessible before surrounding it with blocked tiles
  1227. {
  1228. guardTile = tile;
  1229. break;
  1230. }
  1231. }
  1232. if (!guardTile.valid())
  1233. {
  1234. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1235. return false;
  1236. }
  1237. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1238. {
  1239. for (auto pos : tiles)
  1240. {
  1241. if (!gen->isFree(pos))
  1242. gen->setOccupied(pos, ETileType::BLOCKED);
  1243. }
  1244. gen->setOccupied (guardTile, ETileType::USED);
  1245. }
  1246. else //allow no guard or other object in front of this object
  1247. {
  1248. for (auto tile : tiles)
  1249. gen->setOccupied (tile, ETileType::FREE);
  1250. }
  1251. return true;
  1252. }
  1253. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, CTreasurePileInfo &info, ui32 value)
  1254. {
  1255. //int objectsVisitableFromBottom = 0; //for debug
  1256. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1257. ui32 total = 0;
  1258. ui32 minValue = 0.25f * value;
  1259. //roulette wheel
  1260. for (auto oi : possibleObjects)
  1261. {
  1262. if (oi.value >= minValue && oi.value <= value)
  1263. {
  1264. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1265. int3 newVisitablePos = info.nextTreasurePos;
  1266. if (!oi.templ.isVisitableFromTop())
  1267. {
  1268. //objectsVisitableFromBottom++;
  1269. //there must be free tiles under object
  1270. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, oi.templ.getBlockedOffsets()))
  1271. continue;
  1272. }
  1273. //NOTE: y coordinate grows downwards
  1274. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1275. {
  1276. bool fitsHere = false;
  1277. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1278. {
  1279. for (auto tile : info.visitableFromTopPositions)
  1280. {
  1281. int3 actualTile = tile + newVisitableOffset;
  1282. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1283. {
  1284. fitsHere = true;
  1285. break;
  1286. }
  1287. }
  1288. for (auto tile : info.visitableFromBottomPositions)
  1289. {
  1290. int3 actualTile = tile + newVisitableOffset;
  1291. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1292. {
  1293. fitsHere = true;
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. else //if new object is not visitable from top, it must be accessible from below or side
  1299. {
  1300. for (auto tile : info.visitableFromTopPositions)
  1301. {
  1302. int3 actualTile = tile + newVisitableOffset;
  1303. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1304. {
  1305. fitsHere = true;
  1306. break;
  1307. }
  1308. }
  1309. for (auto tile : info.visitableFromBottomPositions)
  1310. {
  1311. int3 actualTile = tile + newVisitableOffset;
  1312. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1313. {
  1314. fitsHere = true;
  1315. break;
  1316. }
  1317. }
  1318. }
  1319. if (!fitsHere)
  1320. continue;
  1321. }
  1322. //now check blockmap, including our already reserved pile area
  1323. bool fitsBlockmap = true;
  1324. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1325. blockedOffsets.insert (newVisitableOffset);
  1326. for (auto blockingTile : blockedOffsets)
  1327. {
  1328. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1329. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1330. {
  1331. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1332. break;
  1333. }
  1334. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1335. {
  1336. fitsBlockmap = false;
  1337. break;
  1338. }
  1339. }
  1340. if (!fitsBlockmap)
  1341. continue;
  1342. total += oi.probability;
  1343. tresholds.push_back (std::make_pair (total, oi));
  1344. }
  1345. }
  1346. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1347. //Generate pandora Box with gold if the value is extremely high
  1348. ObjectInfo oi;
  1349. if (tresholds.empty())
  1350. {
  1351. if (minValue > 20000) //we don't have object valuable enough
  1352. {
  1353. oi.generateObject = [minValue]() -> CGObjectInstance *
  1354. {
  1355. auto obj = new CGPandoraBox();
  1356. obj->ID = Obj::PANDORAS_BOX;
  1357. obj->subID = 0;
  1358. obj->resources[Res::GOLD] = minValue;
  1359. return obj;
  1360. };
  1361. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1362. oi.value = minValue;
  1363. oi.probability = 0;
  1364. }
  1365. else
  1366. {
  1367. oi.generateObject = [gen]() -> CGObjectInstance *
  1368. {
  1369. return nullptr;
  1370. };
  1371. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1372. oi.value = 0;
  1373. oi.probability = 0;
  1374. }
  1375. return oi;
  1376. }
  1377. int r = gen->rand.nextInt (1, total);
  1378. for (auto t : tresholds)
  1379. {
  1380. if (r <= t.first)
  1381. return t.second;
  1382. }
  1383. //FIXME: control reaches end of non-void function. Missing return?
  1384. }
  1385. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1386. {
  1387. ObjectInfo oi;
  1388. for (auto primaryID : VLC->objtypeh->knownObjects())
  1389. {
  1390. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1391. {
  1392. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1393. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1394. {
  1395. for (auto temp : handler->getTemplates())
  1396. {
  1397. if (temp.canBePlacedAt(terrainType))
  1398. {
  1399. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1400. {
  1401. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1402. };
  1403. oi.value = handler->getRMGInfo().value;
  1404. oi.probability = handler->getRMGInfo().rarity;
  1405. oi.templ = temp;
  1406. possibleObjects.push_back (oi);
  1407. }
  1408. }
  1409. }
  1410. }
  1411. }
  1412. //dwellings
  1413. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1414. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1415. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1416. for (int i = 0; i < 4; i++)
  1417. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1418. for (auto secondaryID : subObjects)
  1419. {
  1420. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1421. auto creatures = dwellingHandler->getProducedCreatures();
  1422. if (creatures.empty())
  1423. continue;
  1424. auto cre = creatures.front();
  1425. if (cre->faction == townType)
  1426. {
  1427. 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
  1428. oi.probability = 40;
  1429. for (auto temp : dwellingHandler->getTemplates())
  1430. {
  1431. if (temp.canBePlacedAt(terrainType))
  1432. {
  1433. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1434. {
  1435. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1436. //dwellingHandler->configureObject(obj, gen->rand);
  1437. obj->tempOwner = PlayerColor::NEUTRAL;
  1438. return obj;
  1439. };
  1440. oi.templ = temp;
  1441. possibleObjects.push_back (oi);
  1442. }
  1443. }
  1444. }
  1445. }
  1446. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1447. for (int i = 0; i < 5; i++)
  1448. {
  1449. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1450. {
  1451. auto obj = new CGArtifact();
  1452. obj->ID = Obj::SPELL_SCROLL;
  1453. obj->subID = 0;
  1454. std::vector<SpellID> out;
  1455. //TODO: unify with cb->getAllowedSpells?
  1456. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1457. {
  1458. const CSpell *spell = SpellID(i).toSpell();
  1459. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1460. {
  1461. out.push_back(spell->id);
  1462. }
  1463. }
  1464. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1465. gen->map->addNewArtifactInstance(a);
  1466. obj->storedArtifact = a;
  1467. return obj;
  1468. };
  1469. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1470. oi.value = scrollValues[i];
  1471. oi.probability = 30;
  1472. possibleObjects.push_back (oi);
  1473. }
  1474. //pandora box with gold
  1475. for (int i = 1; i < 5; i++)
  1476. {
  1477. oi.generateObject = [i]() -> CGObjectInstance *
  1478. {
  1479. auto obj = new CGPandoraBox();
  1480. obj->ID = Obj::PANDORAS_BOX;
  1481. obj->subID = 0;
  1482. obj->resources[Res::GOLD] = i * 5000;
  1483. return obj;
  1484. };
  1485. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1486. oi.value = i * 5000;;
  1487. oi.probability = 5;
  1488. possibleObjects.push_back (oi);
  1489. }
  1490. //pandora box with experience
  1491. for (int i = 1; i < 5; i++)
  1492. {
  1493. oi.generateObject = [i]() -> CGObjectInstance *
  1494. {
  1495. auto obj = new CGPandoraBox();
  1496. obj->ID = Obj::PANDORAS_BOX;
  1497. obj->subID = 0;
  1498. obj->gainedExp = i * 5000;
  1499. return obj;
  1500. };
  1501. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1502. oi.value = i * 6000;;
  1503. oi.probability = 20;
  1504. possibleObjects.push_back (oi);
  1505. }
  1506. //pandora box with creatures
  1507. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1508. for (auto creature : VLC->creh->creatures)
  1509. {
  1510. if (!creature->special && VLC->townh->factions[creature->faction]->nativeTerrain == terrainType)
  1511. {
  1512. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1513. int creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1514. if (creaturesAmount <= 5)
  1515. {
  1516. }
  1517. else if (creaturesAmount <= 12)
  1518. {
  1519. (creaturesAmount /= 2) *= 2;
  1520. }
  1521. else if (creaturesAmount <= 50)
  1522. {
  1523. creaturesAmount = boost::math::round((float)creaturesAmount / 5) * 5;
  1524. }
  1525. else if (creaturesAmount <= 12)
  1526. {
  1527. creaturesAmount = boost::math::round((float)creaturesAmount / 10) * 10;
  1528. }
  1529. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1530. {
  1531. auto obj = new CGPandoraBox();
  1532. obj->ID = Obj::PANDORAS_BOX;
  1533. obj->subID = 0;
  1534. auto stack = new CStackInstance(creature, creaturesAmount);
  1535. obj->creatures.putStack(SlotID(0), stack);
  1536. return obj;
  1537. };
  1538. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1539. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1540. oi.probability = 3;
  1541. possibleObjects.push_back (oi);
  1542. }
  1543. }
  1544. //Pandora with 12 spells of certain level
  1545. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1546. {
  1547. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1548. {
  1549. auto obj = new CGPandoraBox();
  1550. obj->ID = Obj::PANDORAS_BOX;
  1551. obj->subID = 0;
  1552. std::vector <CSpell *> spells;
  1553. for (auto spell : VLC->spellh->objects)
  1554. {
  1555. if (!spell->isSpecialSpell() && spell->level == i)
  1556. spells.push_back(spell);
  1557. }
  1558. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1559. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1560. {
  1561. obj->spells.push_back (spells[j]->id);
  1562. }
  1563. return obj;
  1564. };
  1565. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1566. oi.value = (i + 1) * 2500; //5000 - 15000
  1567. oi.probability = 2;
  1568. possibleObjects.push_back (oi);
  1569. }
  1570. //Pandora with 15 spells of certain school
  1571. for (int i = 1; i <= 4; i++)
  1572. {
  1573. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1574. {
  1575. auto obj = new CGPandoraBox();
  1576. obj->ID = Obj::PANDORAS_BOX;
  1577. obj->subID = 0;
  1578. std::vector <CSpell *> spells;
  1579. for (auto spell : VLC->spellh->objects)
  1580. {
  1581. if (!spell->isSpecialSpell())
  1582. {
  1583. bool school = false; //TODO: we could have better interface for iterating schools
  1584. switch (i)
  1585. {
  1586. case 1:
  1587. school = spell->air;
  1588. case 2:
  1589. school = spell->earth;
  1590. case 3:
  1591. school = spell->fire;
  1592. case 4:
  1593. school = spell->water;
  1594. }
  1595. if (school)
  1596. spells.push_back(spell);
  1597. }
  1598. }
  1599. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1600. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1601. {
  1602. obj->spells.push_back (spells[j]->id);
  1603. }
  1604. return obj;
  1605. };
  1606. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1607. oi.value = 15000;
  1608. oi.probability = 2;
  1609. possibleObjects.push_back (oi);
  1610. }
  1611. // Pandora box with 60 random spells
  1612. oi.generateObject = [gen]() -> CGObjectInstance *
  1613. {
  1614. auto obj = new CGPandoraBox();
  1615. obj->ID = Obj::PANDORAS_BOX;
  1616. obj->subID = 0;
  1617. std::vector <CSpell *> spells;
  1618. for (auto spell : VLC->spellh->objects)
  1619. {
  1620. if (!spell->isSpecialSpell())
  1621. spells.push_back(spell);
  1622. }
  1623. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1624. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1625. {
  1626. obj->spells.push_back (spells[j]->id);
  1627. }
  1628. return obj;
  1629. };
  1630. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1631. oi.value = 3000;
  1632. oi.probability = 2;
  1633. possibleObjects.push_back (oi);
  1634. }
  1635. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1636. {
  1637. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1638. }