CRmgTemplateZone.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811
  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 "../spells/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. void CRmgTemplateZone::addRoadNode(const int3& node)
  29. {
  30. roadNodes.insert(node);
  31. }
  32. int CRmgTemplateZone::CTownInfo::getTownCount() const
  33. {
  34. return townCount;
  35. }
  36. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  37. {
  38. if(value < 0)
  39. throw rmgException("Negative value for town count not allowed.");
  40. townCount = value;
  41. }
  42. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  43. {
  44. return castleCount;
  45. }
  46. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  47. {
  48. if(value < 0)
  49. throw rmgException("Negative value for castle count not allowed.");
  50. castleCount = value;
  51. }
  52. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  53. {
  54. return townDensity;
  55. }
  56. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  57. {
  58. if(value < 0)
  59. throw rmgException("Negative value for town density not allowed.");
  60. townDensity = value;
  61. }
  62. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  63. {
  64. return castleDensity;
  65. }
  66. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  67. {
  68. if(value < 0)
  69. throw rmgException("Negative value for castle density not allowed.");
  70. castleDensity = value;
  71. }
  72. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG),roadType(ERoadType::NO_ROAD)
  73. {
  74. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  75. }
  76. float CTileInfo::getNearestObjectDistance() const
  77. {
  78. return nearestObjectDistance;
  79. }
  80. void CTileInfo::setNearestObjectDistance(float value)
  81. {
  82. nearestObjectDistance = std::max<float>(0, value); //never negative (or unitialized)
  83. }
  84. bool CTileInfo::shouldBeBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED;
  87. }
  88. bool CTileInfo::isBlocked() const
  89. {
  90. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  91. }
  92. bool CTileInfo::isPossible() const
  93. {
  94. return occupied == ETileType::POSSIBLE;
  95. }
  96. bool CTileInfo::isFree() const
  97. {
  98. return occupied == ETileType::FREE;
  99. }
  100. bool CTileInfo::isRoad() const
  101. {
  102. return roadType != ERoadType::NO_ROAD;
  103. }
  104. bool CTileInfo::isUsed() const
  105. {
  106. return occupied == ETileType::USED;
  107. }
  108. void CTileInfo::setOccupied(ETileType::ETileType value)
  109. {
  110. occupied = value;
  111. }
  112. ETileType::ETileType CTileInfo::getTileType() const
  113. {
  114. return occupied;
  115. }
  116. ETerrainType CTileInfo::getTerrainType() const
  117. {
  118. return terrain;
  119. }
  120. void CTileInfo::setTerrainType(ETerrainType value)
  121. {
  122. terrain = value;
  123. }
  124. void CTileInfo::setRoadType(ERoadType::ERoadType value)
  125. {
  126. roadType = value;
  127. // setOccupied(ETileType::FREE);
  128. }
  129. CRmgTemplateZone::CRmgTemplateZone() :
  130. id(0),
  131. type(ETemplateZoneType::PLAYER_START),
  132. size(1),
  133. townsAreSameType(false),
  134. matchTerrainToTown(true),
  135. townType(ETownType::NEUTRAL),
  136. terrainType (ETerrainType::GRASS),
  137. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
  138. minGuardedValue(0),
  139. questArtZone(nullptr)
  140. {
  141. terrainTypes = getDefaultTerrainTypes();
  142. }
  143. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  144. {
  145. return id;
  146. }
  147. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  148. {
  149. if(value <= 0)
  150. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  151. id = value;
  152. }
  153. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  154. {
  155. return type;
  156. }
  157. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  158. {
  159. type = value;
  160. }
  161. int CRmgTemplateZone::getSize() const
  162. {
  163. return size;
  164. }
  165. void CRmgTemplateZone::setSize(int value)
  166. {
  167. if(value <= 0)
  168. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  169. size = value;
  170. }
  171. boost::optional<int> CRmgTemplateZone::getOwner() const
  172. {
  173. return owner;
  174. }
  175. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  176. {
  177. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  178. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  179. owner = value;
  180. }
  181. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  182. {
  183. return playerTowns;
  184. }
  185. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  186. {
  187. playerTowns = value;
  188. }
  189. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  190. {
  191. return neutralTowns;
  192. }
  193. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  194. {
  195. neutralTowns = value;
  196. }
  197. bool CRmgTemplateZone::getTownsAreSameType() const
  198. {
  199. return townsAreSameType;
  200. }
  201. void CRmgTemplateZone::setTownsAreSameType(bool value)
  202. {
  203. townsAreSameType = value;
  204. }
  205. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  206. {
  207. return townTypes;
  208. }
  209. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  210. {
  211. townTypes = value;
  212. }
  213. void CRmgTemplateZone::setMonsterTypes(const std::set<TFaction> & value)
  214. {
  215. monsterTypes = value;
  216. }
  217. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  218. {
  219. std::set<TFaction> defaultTowns;
  220. auto towns = VLC->townh->getDefaultAllowed();
  221. for(int i = 0; i < towns.size(); ++i)
  222. {
  223. if(towns[i]) defaultTowns.insert(i);
  224. }
  225. return defaultTowns;
  226. }
  227. bool CRmgTemplateZone::getMatchTerrainToTown() const
  228. {
  229. return matchTerrainToTown;
  230. }
  231. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  232. {
  233. matchTerrainToTown = value;
  234. }
  235. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  236. {
  237. return terrainTypes;
  238. }
  239. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  240. {
  241. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  242. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  243. terrainTypes = value;
  244. }
  245. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  246. {
  247. std::set<ETerrainType> terTypes;
  248. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  249. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  250. for (auto & allowedTerType : allowedTerTypes)
  251. terTypes.insert(allowedTerType);
  252. return terTypes;
  253. }
  254. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  255. {
  256. mines[res] = amount;
  257. }
  258. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  259. {
  260. return mines;
  261. }
  262. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  263. {
  264. connections.push_back (otherZone);
  265. }
  266. void CRmgTemplateZone::setQuestArtZone(CRmgTemplateZone * otherZone)
  267. {
  268. questArtZone = otherZone;
  269. }
  270. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  271. {
  272. return connections;
  273. }
  274. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  275. {
  276. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  277. zoneMonsterStrength = val;
  278. }
  279. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  280. {
  281. treasureInfo.push_back(info);
  282. }
  283. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  284. {
  285. return treasureInfo;
  286. }
  287. std::set<int3>* CRmgTemplateZone::getFreePaths()
  288. {
  289. return &freePaths;
  290. }
  291. float3 CRmgTemplateZone::getCenter() const
  292. {
  293. return center;
  294. }
  295. void CRmgTemplateZone::setCenter(const float3 &f)
  296. {
  297. //limit boundaries to (0,1) square
  298. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  299. }
  300. bool CRmgTemplateZone::pointIsIn(int x, int y)
  301. {
  302. return true;
  303. }
  304. int3 CRmgTemplateZone::getPos() const
  305. {
  306. return pos;
  307. }
  308. void CRmgTemplateZone::setPos(const int3 &Pos)
  309. {
  310. pos = Pos;
  311. }
  312. void CRmgTemplateZone::addTile (const int3 &pos)
  313. {
  314. tileinfo.insert(pos);
  315. }
  316. std::set<int3> CRmgTemplateZone::getTileInfo () const
  317. {
  318. return tileinfo;
  319. }
  320. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  321. {
  322. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  323. //for (auto tile : tileinfo)
  324. //{
  325. // if (tile.dist2d(this->pos) > distance)
  326. // {
  327. // gen->setOccupied(tile, ETileType::USED);
  328. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  329. // }
  330. //}
  331. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  332. {
  333. return tile.dist2d(this->pos) > distance;
  334. });
  335. }
  336. void CRmgTemplateZone::clearTiles()
  337. {
  338. tileinfo.clear();
  339. }
  340. void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
  341. {
  342. vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
  343. {
  344. return gen->isPossible(tile);
  345. });
  346. if (freePaths.empty())
  347. freePaths.insert(pos); //zone must have at least one free tile where other paths go - for instance in the center
  348. }
  349. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  350. {
  351. for (auto tile : tileinfo)
  352. {
  353. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  354. {
  355. if (!vstd::contains(this->tileinfo, pos))
  356. {
  357. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  358. {
  359. if (gen->isPossible(pos))
  360. gen->setOccupied (pos, ETileType::BLOCKED);
  361. });
  362. }
  363. });
  364. }
  365. }
  366. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  367. {
  368. for (auto tile : tileinfo)
  369. {
  370. if (gen->isFree(tile))
  371. freePaths.insert(tile);
  372. }
  373. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  374. std::set<int3> possibleTiles;
  375. std::set<int3> tilesToIgnore; //will be erased in this iteration
  376. //the more treasure density, the greater distance between paths. Scaling is experimental.
  377. int totalDensity = 0;
  378. for (auto ti : treasureInfo)
  379. totalDensity += ti.density;
  380. const float minDistance = 10 * 10; //squared
  381. for (auto tile : tileinfo)
  382. {
  383. if (gen->isFree(tile))
  384. clearedTiles.push_back(tile);
  385. else if (gen->isPossible(tile))
  386. possibleTiles.insert(tile);
  387. }
  388. assert (clearedTiles.size()); //this should come from zone connections
  389. std::vector<int3> nodes; //connect them with a grid
  390. if (type != ETemplateZoneType::JUNCTION)
  391. {
  392. //junction is not fractalized, has only one straight path
  393. //everything else remains blocked
  394. while (possibleTiles.size())
  395. {
  396. //link tiles in random order
  397. std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
  398. RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
  399. int3 nodeFound(-1, -1, -1);
  400. for (auto tileToMakePath : tilesToMakePath)
  401. {
  402. //find closest free tile
  403. float currentDistance = 1e10;
  404. int3 closestTile(-1, -1, -1);
  405. for (auto clearTile : clearedTiles)
  406. {
  407. float distance = tileToMakePath.dist2dSQ(clearTile);
  408. if (distance < currentDistance)
  409. {
  410. currentDistance = distance;
  411. closestTile = clearTile;
  412. }
  413. if (currentDistance <= minDistance)
  414. {
  415. //this tile is close enough. Forget about it and check next one
  416. tilesToIgnore.insert(tileToMakePath);
  417. break;
  418. }
  419. }
  420. //if tiles is not close enough, make path to it
  421. if (currentDistance > minDistance)
  422. {
  423. nodeFound = tileToMakePath;
  424. nodes.push_back(nodeFound);
  425. clearedTiles.push_back(nodeFound); //from now on nearby tiles will be considered handled
  426. break; //next iteration - use already cleared tiles
  427. }
  428. }
  429. for (auto tileToClear : tilesToIgnore)
  430. {
  431. //these tiles are already connected, ignore them
  432. vstd::erase_if_present(possibleTiles, tileToClear);
  433. }
  434. if (!nodeFound.valid()) //nothing else can be done (?)
  435. break;
  436. tilesToIgnore.clear();
  437. }
  438. }
  439. for (auto node : nodes)
  440. {
  441. boost::sort(nodes, [&node](const int3& ourNode, const int3& otherNode) -> bool
  442. {
  443. return node.dist2dSQ(ourNode) < node.dist2dSQ(otherNode);
  444. }
  445. );
  446. std::vector <int3> nearbyNodes;
  447. if (nodes.size() >= 2)
  448. {
  449. nearbyNodes.push_back(nodes[1]); //node[0] is our node we want to connect
  450. }
  451. if (nodes.size() >= 3)
  452. {
  453. nearbyNodes.push_back(nodes[2]);
  454. }
  455. //connect with all the paths
  456. crunchPath(gen, node, findClosestTile(freePaths, node), true, &freePaths);
  457. //connect with nearby nodes
  458. for (auto nearbyNode : nearbyNodes)
  459. {
  460. crunchPath(gen, node, nearbyNode, true, &freePaths);
  461. }
  462. }
  463. for (auto node : nodes)
  464. gen->setOccupied(node, ETileType::FREE); //make sure they are clear
  465. //now block most distant tiles away from passages
  466. float blockDistance = minDistance * 0.25f;
  467. for (auto tile : tileinfo)
  468. {
  469. if (!gen->isPossible(tile))
  470. continue;
  471. bool closeTileFound = false;
  472. for (auto clearTile : freePaths)
  473. {
  474. float distance = tile.dist2dSQ(clearTile);
  475. if (distance < blockDistance)
  476. {
  477. closeTileFound = true;
  478. break;
  479. }
  480. }
  481. if (!closeTileFound) //this tile is far enough from passages
  482. gen->setOccupied(tile, ETileType::BLOCKED);
  483. }
  484. #define PRINT_FRACTALIZED_MAP false
  485. if (PRINT_FRACTALIZED_MAP) //enable to debug
  486. {
  487. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  488. int levels = gen->map->twoLevel ? 2 : 1;
  489. int width = gen->map->width;
  490. int height = gen->map->height;
  491. for (int k = 0; k < levels; k++)
  492. {
  493. for(int j=0; j<height; j++)
  494. {
  495. for (int i=0; i<width; i++)
  496. {
  497. char t = '?';
  498. switch (gen->getTile(int3(i, j, k)).getTileType())
  499. {
  500. case ETileType::FREE:
  501. t = ' '; break;
  502. case ETileType::BLOCKED:
  503. t = '#'; break;
  504. case ETileType::POSSIBLE:
  505. t = '-'; break;
  506. case ETileType::USED:
  507. t = 'O'; break;
  508. }
  509. out << t;
  510. }
  511. out << std::endl;
  512. }
  513. out << std::endl;
  514. }
  515. out << std::endl;
  516. }
  517. //logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  518. }
  519. void CRmgTemplateZone::connectLater(CMapGenerator* gen)
  520. {
  521. for (const int3 node : tilesToConnectLater)
  522. {
  523. if (!connectWithCenter(gen, node, true))
  524. logGlobal->errorStream() << boost::format("Failed to connect node %s with center of the zone") % node;
  525. }
  526. }
  527. bool CRmgTemplateZone::crunchPath(CMapGenerator* gen, const int3 &src, const int3 &dst, bool onlyStraight, std::set<int3>* clearedTiles)
  528. {
  529. /*
  530. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  531. do not leave zone border
  532. */
  533. bool result = false;
  534. bool end = false;
  535. int3 currentPos = src;
  536. float distance = currentPos.dist2dSQ (dst);
  537. while (!end)
  538. {
  539. if (currentPos == dst)
  540. {
  541. result = true;
  542. break;
  543. }
  544. auto lastDistance = distance;
  545. auto processNeighbours = [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  546. {
  547. if (!result) //not sure if lambda is worth it...
  548. {
  549. if (pos == dst)
  550. {
  551. result = true;
  552. end = true;
  553. }
  554. if (pos.dist2dSQ (dst) < distance)
  555. {
  556. if (!gen->isBlocked(pos))
  557. {
  558. if (vstd::contains (tileinfo, pos))
  559. {
  560. if (gen->isPossible(pos))
  561. {
  562. gen->setOccupied (pos, ETileType::FREE);
  563. if (clearedTiles)
  564. clearedTiles->insert(pos);
  565. currentPos = pos;
  566. distance = currentPos.dist2dSQ (dst);
  567. }
  568. else if (gen->isFree(pos))
  569. {
  570. end = true;
  571. result = true;
  572. }
  573. }
  574. }
  575. }
  576. }
  577. };
  578. if (onlyStraight)
  579. gen->foreachDirectNeighbour (currentPos, processNeighbours);
  580. else
  581. gen->foreach_neighbour (currentPos,processNeighbours);
  582. int3 anotherPos(-1, -1, -1);
  583. if (!(result || distance < lastDistance)) //we do not advance, use more advanced pathfinding algorithm?
  584. {
  585. //try any nearby tiles, even if its not closer than current
  586. float lastDistance = 2 * distance; //start with significantly larger value
  587. auto processNeighbours2 = [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  588. {
  589. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  590. {
  591. if (vstd::contains(tileinfo, pos))
  592. {
  593. if (gen->isPossible(pos))
  594. {
  595. if (clearedTiles)
  596. clearedTiles->insert(pos);
  597. anotherPos = pos;
  598. lastDistance = currentPos.dist2dSQ(dst);
  599. }
  600. }
  601. }
  602. };
  603. if (onlyStraight)
  604. gen->foreachDirectNeighbour(currentPos, processNeighbours2);
  605. else
  606. gen->foreach_neighbour(currentPos, processNeighbours2);
  607. if (anotherPos.valid())
  608. {
  609. if (clearedTiles)
  610. clearedTiles->insert(anotherPos);
  611. gen->setOccupied(anotherPos, ETileType::FREE);
  612. currentPos = anotherPos;
  613. }
  614. }
  615. if (!(result || distance < lastDistance || anotherPos.valid()))
  616. {
  617. //FIXME: seemingly this condition is messed up, tells nothing
  618. //logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  619. break;
  620. }
  621. }
  622. return result;
  623. }
  624. bool CRmgTemplateZone::createRoad(CMapGenerator* gen, const int3& src, const int3& dst)
  625. {
  626. //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
  627. std::set<int3> closed; // The set of nodes already evaluated.
  628. std::set<int3> open{src}; // The set of tentative nodes to be evaluated, initially containing the start node
  629. std::map<int3, int3> cameFrom; // The map of navigated nodes.
  630. std::map<int3, float> distances;
  631. //int3 currentNode = src;
  632. gen->setRoad (src, ERoadType::NO_ROAD); //just in case zone guard already has road under it. Road under nodes will be added at very end
  633. cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
  634. distances[src] = 0;
  635. // Cost from start along best known path.
  636. // Estimated total cost from start to goal through y.
  637. while (open.size())
  638. {
  639. int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
  640. {
  641. return distances[pos1] < distances[pos2];
  642. });
  643. vstd::erase_if_present (open, currentNode);
  644. closed.insert (currentNode);
  645. if (currentNode == dst || gen->isRoad(currentNode))
  646. {
  647. // The goal node was reached. Trace the path using
  648. // the saved parent information and return path
  649. int3 backTracking = currentNode;
  650. while (cameFrom[backTracking].valid())
  651. {
  652. // add node to path
  653. roads.insert (backTracking);
  654. gen->setRoad (backTracking, ERoadType::COBBLESTONE_ROAD);
  655. //logGlobal->traceStream() << boost::format("Setting road at tile %s") % backTracking;
  656. // do the same for the predecessor
  657. backTracking = cameFrom[backTracking];
  658. }
  659. return true;
  660. }
  661. else
  662. {
  663. bool directNeighbourFound = false;
  664. float movementCost = 1;
  665. auto foo = [gen, this, &open, &closed, &cameFrom, &currentNode, &distances, &dst, &directNeighbourFound, movementCost](int3& pos) -> void
  666. {
  667. float distance = distances[currentNode] + movementCost;
  668. int bestDistanceSoFar = 1e6; //FIXME: boost::limits
  669. auto it = distances.find(pos);
  670. if (it != distances.end())
  671. bestDistanceSoFar = it->second;
  672. if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
  673. {
  674. auto obj = gen->map->getTile(pos).topVisitableObj();
  675. //if (gen->map->checkForVisitableDir(currentNode, &gen->map->getTile(pos), pos)) //TODO: why it has no effect?
  676. if (gen->isFree(pos) || pos == dst || (obj && obj->ID == Obj::MONSTER))
  677. {
  678. if (vstd::contains(this->tileinfo, pos) || pos == dst) //otherwise guard position may appear already connected to other zone.
  679. {
  680. cameFrom[pos] = currentNode;
  681. open.insert(pos);
  682. distances[pos] = distance;
  683. directNeighbourFound = true;
  684. //logGlobal->traceStream() << boost::format("Found connection between node %s and %s, current distance %d") % currentNode % pos % distance;
  685. }
  686. }
  687. }
  688. };
  689. gen->foreachDirectNeighbour (currentNode, foo); // roads cannot be rendered correctly for diagonal directions
  690. if (!directNeighbourFound)
  691. {
  692. movementCost = 2.1f; //moving diagonally is penalized over moving two tiles straight
  693. gen->foreach_neighbour(currentNode, foo);
  694. }
  695. }
  696. }
  697. logGlobal->warnStream() << boost::format("Failed to create road from %s to %s") % src %dst;
  698. return false;
  699. }
  700. bool CRmgTemplateZone::connectPath(CMapGenerator* gen, const int3& src, bool onlyStraight)
  701. ///connect current tile to any other free tile within zone
  702. {
  703. //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
  704. std::set<int3> closed; // The set of nodes already evaluated.
  705. std::set<int3> open{ src }; // The set of tentative nodes to be evaluated, initially containing the start node
  706. std::map<int3, int3> cameFrom; // The map of navigated nodes.
  707. std::map<int3, float> distances;
  708. //int3 currentNode = src;
  709. cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
  710. distances[src] = 0;
  711. // Cost from start along best known path.
  712. // Estimated total cost from start to goal through y.
  713. while (open.size())
  714. {
  715. int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
  716. {
  717. return distances[pos1] < distances[pos2];
  718. });
  719. vstd::erase_if_present(open, currentNode);
  720. closed.insert(currentNode);
  721. if (gen->isFree(currentNode)) //we reached free paths, stop
  722. {
  723. // Trace the path using the saved parent information and return path
  724. int3 backTracking = currentNode;
  725. while (cameFrom[backTracking].valid())
  726. {
  727. gen->setOccupied(backTracking, ETileType::FREE);
  728. backTracking = cameFrom[backTracking];
  729. }
  730. return true;
  731. }
  732. else
  733. {
  734. auto foo = [gen, this, &open, &closed, &cameFrom, &currentNode, &distances](int3& pos) -> void
  735. {
  736. int distance = distances[currentNode] + 1;
  737. int bestDistanceSoFar = 1e6; //FIXME: boost::limits
  738. auto it = distances.find(pos);
  739. if (it != distances.end())
  740. bestDistanceSoFar = it->second;
  741. if (gen->isBlocked(pos)) //no paths through blocked or occupied tiles
  742. return;
  743. if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
  744. {
  745. //auto obj = gen->map->getTile(pos).topVisitableObj();
  746. if (vstd::contains(this->tileinfo, pos))
  747. {
  748. cameFrom[pos] = currentNode;
  749. open.insert(pos);
  750. distances[pos] = distance;
  751. }
  752. }
  753. };
  754. if (onlyStraight)
  755. gen->foreachDirectNeighbour(currentNode, foo);
  756. else
  757. gen->foreach_neighbour(currentNode, foo);
  758. }
  759. }
  760. for (auto tile : closed) //these tiles are sealed off and can't be connected anymore
  761. {
  762. //TODO: refactor, unify?
  763. gen->setOccupied (tile, ETileType::BLOCKED);
  764. vstd::erase_if_present(possibleTiles, tile);
  765. }
  766. return false;
  767. }
  768. bool CRmgTemplateZone::connectWithCenter(CMapGenerator* gen, const int3& src, bool onlyStraight)
  769. ///connect current tile to any other free tile within zone
  770. {
  771. //A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
  772. std::set<int3> closed; // The set of nodes already evaluated.
  773. std::set<int3> open{ src }; // The set of tentative nodes to be evaluated, initially containing the start node
  774. std::map<int3, int3> cameFrom; // The map of navigated nodes.
  775. std::map<int3, float> distances;
  776. //int3 currentNode = src;
  777. cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
  778. distances[src] = 0;
  779. // Cost from start along best known path.
  780. // Estimated total cost from start to goal through y.
  781. while (open.size())
  782. {
  783. int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
  784. {
  785. return distances[pos1] < distances[pos2];
  786. });
  787. vstd::erase_if_present(open, currentNode);
  788. closed.insert(currentNode);
  789. if (currentNode == pos) //we reached center of the zone, stop
  790. {
  791. // Trace the path using the saved parent information and return path
  792. int3 backTracking = currentNode;
  793. while (cameFrom[backTracking].valid())
  794. {
  795. gen->setOccupied(backTracking, ETileType::FREE);
  796. backTracking = cameFrom[backTracking];
  797. }
  798. return true;
  799. }
  800. else
  801. {
  802. auto foo = [gen, this, &open, &closed, &cameFrom, &currentNode, &distances](int3& pos) -> void
  803. {
  804. float movementCost = 0;
  805. if (gen->isFree(pos))
  806. movementCost = 1;
  807. else if (gen->isPossible(pos))
  808. movementCost = 2;
  809. else
  810. return;
  811. float distance = distances[currentNode] + movementCost; //we prefer to use already free paths
  812. int bestDistanceSoFar = 1e6; //FIXME: boost::limits
  813. auto it = distances.find(pos);
  814. if (it != distances.end())
  815. bestDistanceSoFar = it->second;
  816. if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
  817. {
  818. //auto obj = gen->map->getTile(pos).topVisitableObj();
  819. if (vstd::contains(this->tileinfo, pos))
  820. {
  821. cameFrom[pos] = currentNode;
  822. open.insert(pos);
  823. distances[pos] = distance;
  824. }
  825. }
  826. };
  827. if (onlyStraight)
  828. gen->foreachDirectNeighbour(currentNode, foo);
  829. else
  830. gen->foreach_neighbour(currentNode, foo);
  831. }
  832. }
  833. return false;
  834. }
  835. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  836. {
  837. requiredObjects.push_back(std::make_pair(obj, strength));
  838. }
  839. void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
  840. {
  841. closeObjects.push_back(std::make_pair(obj, strength));
  842. }
  843. void CRmgTemplateZone::addToConnectLater(const int3& src)
  844. {
  845. tilesToConnectLater.insert(src);
  846. }
  847. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  848. {
  849. //precalculate actual (randomized) monster strength based on this post
  850. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  851. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  852. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  853. static const int value1[] = {2500, 1500, 1000, 500, 0};
  854. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  855. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  856. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  857. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  858. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  859. strength = strength1 + strength2;
  860. if (strength < 2000)
  861. return false; //no guard at all
  862. CreatureID creId = CreatureID::NONE;
  863. int amount = 0;
  864. std::vector<CreatureID> possibleCreatures;
  865. for (auto cre : VLC->creh->creatures)
  866. {
  867. if (cre->special)
  868. continue;
  869. if (!vstd::contains(monsterTypes, cre->faction))
  870. continue;
  871. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100
  872. {
  873. possibleCreatures.push_back(cre->idNumber);
  874. }
  875. }
  876. if (possibleCreatures.size())
  877. {
  878. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  879. amount = strength / VLC->creh->creatures[creId]->AIValue;
  880. if (amount >= 4)
  881. amount *= gen->rand.nextDouble(0.75, 1.25);
  882. }
  883. else //just pick any available creature
  884. {
  885. creId = CreatureID(132); //Azure Dragon
  886. amount = strength / VLC->creh->creatures[creId]->AIValue;
  887. }
  888. auto guard = new CGCreature();
  889. guard->ID = Obj::MONSTER;
  890. guard->subID = creId;
  891. guard->character = CGCreature::HOSTILE;
  892. auto hlp = new CStackInstance(creId, amount);
  893. //will be set during initialization
  894. guard->putStack(SlotID(0), hlp);
  895. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  896. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  897. placeObject(gen, guard, pos);
  898. if (clearSurroundingTiles)
  899. {
  900. //do not spawn anything near monster
  901. gen->foreach_neighbour (pos, [gen](int3 pos)
  902. {
  903. if (gen->isPossible(pos))
  904. gen->setOccupied(pos, ETileType::FREE);
  905. });
  906. }
  907. return true;
  908. }
  909. bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  910. {
  911. CTreasurePileInfo info;
  912. std::map<int3, CGObjectInstance *> treasures;
  913. std::set<int3> boundary;
  914. int3 guardPos (-1,-1,-1);
  915. info.nextTreasurePos = pos;
  916. int maxValue = treasureInfo.max;
  917. int minValue = treasureInfo.min;
  918. ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
  919. int currentValue = 0;
  920. CGObjectInstance * object = nullptr;
  921. while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable
  922. {
  923. treasures[info.nextTreasurePos] = nullptr;
  924. for (auto treasurePos : treasures)
  925. {
  926. gen->foreach_neighbour(treasurePos.first, [gen, &boundary](int3 pos)
  927. {
  928. boundary.insert(pos);
  929. });
  930. }
  931. for (auto treasurePos : treasures)
  932. {
  933. //leaving only boundary around objects
  934. vstd::erase_if_present(boundary, treasurePos.first);
  935. }
  936. for (auto tile : boundary)
  937. {
  938. //we can't extend boundary anymore
  939. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  940. break;
  941. }
  942. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  943. if (!oi.value) //0 value indicates no object
  944. {
  945. vstd::erase_if_present(treasures, info.nextTreasurePos);
  946. break;
  947. }
  948. else
  949. {
  950. object = oi.generateObject();
  951. //remove from possible objects
  952. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  953. assert (oiptr != possibleObjects.end());
  954. oiptr->maxPerZone--;
  955. if (!oiptr->maxPerZone)
  956. possibleObjects.erase(oiptr);
  957. //update treasure pile area
  958. int3 visitablePos = info.nextTreasurePos;
  959. if (oi.templ.isVisitableFromTop())
  960. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  961. else
  962. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  963. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  964. {
  965. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  966. info.occupiedPositions.insert(blockPos);
  967. info.blockedPositions.insert(blockPos);
  968. }
  969. info.occupiedPositions.insert(visitablePos);
  970. currentValue += oi.value;
  971. treasures[info.nextTreasurePos] = object;
  972. //now find place for next object
  973. int3 placeFound(-1,-1,-1);
  974. //randomize next position from among possible ones
  975. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  976. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  977. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  978. {
  979. return lhs.y < rhs.y;
  980. };
  981. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  982. for (auto tile : boundaryCopy)
  983. {
  984. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  985. {
  986. bool here = true;
  987. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  988. {
  989. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  990. here = false;
  991. });
  992. if (here)
  993. {
  994. placeFound = tile;
  995. break;
  996. }
  997. }
  998. }
  999. if (placeFound.valid())
  1000. info.nextTreasurePos = placeFound;
  1001. else
  1002. break; //no more place to add any objects
  1003. }
  1004. }
  1005. if (treasures.size())
  1006. {
  1007. //find object closest to free path, then connect it to the middle of the zone
  1008. int3 closestTile = int3(-1,-1,-1);
  1009. float minDistance = 1e10;
  1010. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  1011. {
  1012. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  1013. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  1014. {
  1015. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map, to not make path up through it
  1016. minDistance = closestFreeTile.dist2d(visitablePos);
  1017. }
  1018. }
  1019. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  1020. {
  1021. int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
  1022. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  1023. {
  1024. closestTile = visitablePos;
  1025. minDistance = closestFreeTile.dist2d(visitablePos);
  1026. }
  1027. }
  1028. assert (closestTile.valid());
  1029. for (auto tile : info.occupiedPositions)
  1030. {
  1031. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  1032. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  1033. }
  1034. if (!connectPath (gen, closestTile, false)) //this place is sealed off, need to find new position
  1035. {
  1036. return false;
  1037. }
  1038. //update boundary around our objects, including knowledge about objects visitable from bottom
  1039. boundary.clear();
  1040. for (auto tile : info.visitableFromBottomPositions)
  1041. {
  1042. gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
  1043. {
  1044. if (pos.y >= tile.y) //don't block these objects from above
  1045. boundary.insert(pos);
  1046. });
  1047. }
  1048. for (auto tile : info.visitableFromTopPositions)
  1049. {
  1050. gen->foreach_neighbour(tile, [&boundary](int3 pos)
  1051. {
  1052. boundary.insert(pos);
  1053. });
  1054. }
  1055. bool isPileGuarded = currentValue >= minGuardedValue;
  1056. for (auto tile : boundary) //guard must be standing there
  1057. {
  1058. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  1059. {
  1060. guardPos = tile;
  1061. break;
  1062. }
  1063. }
  1064. if (guardPos.valid())
  1065. {
  1066. for (auto treasure : treasures)
  1067. {
  1068. int3 visitableOffset = treasure.second->getVisitableOffset();
  1069. if (treasure.second->ID == Obj::SEER_HUT) //FIXME: find generic solution or figure out why Seer Hut doesn't behave correctly
  1070. visitableOffset.x += 1;
  1071. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  1072. }
  1073. if (addMonster(gen, guardPos, currentValue, false))
  1074. {//block only if the object is guarded
  1075. for (auto tile : boundary)
  1076. {
  1077. if (gen->isPossible(tile))
  1078. gen->setOccupied(tile, ETileType::BLOCKED);
  1079. }
  1080. //do not spawn anything near monster
  1081. gen->foreach_neighbour(guardPos, [gen](int3 pos)
  1082. {
  1083. if (gen->isPossible(pos))
  1084. gen->setOccupied(pos, ETileType::FREE);
  1085. });
  1086. }
  1087. else //mo monster in this pile, make some free space (needed?)
  1088. {
  1089. for (auto tile : boundary)
  1090. if (gen->isPossible(tile))
  1091. gen->setOccupied(tile, ETileType::FREE);
  1092. }
  1093. }
  1094. else if (isPileGuarded)//we couldn't make a connection to this location, block it
  1095. {
  1096. for (auto treasure : treasures)
  1097. {
  1098. if (gen->isPossible(treasure.first))
  1099. gen->setOccupied(treasure.first, ETileType::BLOCKED);
  1100. delete treasure.second;
  1101. }
  1102. }
  1103. return true;
  1104. }
  1105. else //we did not place eveyrthing successfully
  1106. {
  1107. gen->setOccupied(pos, ETileType::BLOCKED); //TODO: refactor stop condition
  1108. vstd::erase_if_present(possibleTiles, pos);
  1109. return false;
  1110. }
  1111. }
  1112. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  1113. {
  1114. //FIXME: handle case that this player is not present -> towns should be set to neutral
  1115. int totalTowns = 0;
  1116. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  1117. {
  1118. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  1119. for (auto tile : town->getBlockedPos())
  1120. {
  1121. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  1122. {
  1123. if (gen->isPossible(pos))
  1124. {
  1125. gen->setOccupied(pos, ETileType::FREE);
  1126. }
  1127. });
  1128. }
  1129. };
  1130. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  1131. {
  1132. for (int i = 0; i < count; i++)
  1133. {
  1134. auto town = new CGTownInstance();
  1135. town->ID = Obj::TOWN;
  1136. if (this->townsAreSameType)
  1137. town->subID = townType;
  1138. else
  1139. {
  1140. if (townTypes.size())
  1141. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1142. else
  1143. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  1144. }
  1145. town->tempOwner = player;
  1146. if (hasFort)
  1147. town->builtBuildings.insert(BuildingID::FORT);
  1148. town->builtBuildings.insert(BuildingID::DEFAULT);
  1149. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  1150. {
  1151. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  1152. town->possibleSpells.push_back(spell->id);
  1153. }
  1154. if (!totalTowns)
  1155. {
  1156. //first town in zone sets the facton of entire zone
  1157. town->subID = townType;
  1158. //register MAIN town of zone
  1159. gen->registerZone(town->subID);
  1160. //first town in zone goes in the middle
  1161. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  1162. cutPathAroundTown(town);
  1163. setPos(town->visitablePos() + int3(0, 1, 0)); //new center of zone that paths connect to
  1164. }
  1165. else
  1166. addRequiredObject (town);
  1167. totalTowns++;
  1168. }
  1169. };
  1170. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  1171. {
  1172. //set zone types to player faction, generate main town
  1173. logGlobal->infoStream() << "Preparing playing zone";
  1174. int player_id = *owner - 1;
  1175. auto & playerInfo = gen->map->players[player_id];
  1176. PlayerColor player(player_id);
  1177. if (playerInfo.canAnyonePlay())
  1178. {
  1179. player = PlayerColor(player_id);
  1180. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  1181. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  1182. randomizeTownType(gen);
  1183. }
  1184. else //no player - randomize town
  1185. {
  1186. player = PlayerColor::NEUTRAL;
  1187. randomizeTownType(gen);
  1188. }
  1189. auto town = new CGTownInstance();
  1190. town->ID = Obj::TOWN;
  1191. town->subID = townType;
  1192. town->tempOwner = player;
  1193. town->builtBuildings.insert(BuildingID::FORT);
  1194. town->builtBuildings.insert(BuildingID::DEFAULT);
  1195. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  1196. {
  1197. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  1198. town->possibleSpells.push_back(spell->id);
  1199. }
  1200. //towns are big objects and should be centered around visitable position
  1201. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  1202. cutPathAroundTown(town);
  1203. setPos(town->visitablePos() + int3(0, 1, 0)); //new center of zone that paths connect to
  1204. totalTowns++;
  1205. //register MAIN town of zone only
  1206. gen->registerZone (town->subID);
  1207. if (playerInfo.canAnyonePlay()) //configure info for owning player
  1208. {
  1209. logGlobal->traceStream() << "Fill player info " << player_id;
  1210. // Update player info
  1211. playerInfo.allowedFactions.clear();
  1212. playerInfo.allowedFactions.insert(townType);
  1213. playerInfo.hasMainTown = true;
  1214. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  1215. playerInfo.generateHeroAtMainTown = true;
  1216. //now create actual towns
  1217. addNewTowns(playerTowns.getCastleCount() - 1, true, player);
  1218. addNewTowns(playerTowns.getTownCount(), false, player);
  1219. }
  1220. else
  1221. {
  1222. addNewTowns(playerTowns.getCastleCount() - 1, true, PlayerColor::NEUTRAL);
  1223. addNewTowns(playerTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1224. }
  1225. }
  1226. else //randomize town types for any other zones as well
  1227. {
  1228. randomizeTownType(gen);
  1229. }
  1230. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  1231. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  1232. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  1233. {
  1234. //25% chance for neutral
  1235. if (gen->rand.nextInt(1, 100) <= 25)
  1236. {
  1237. townType = ETownType::NEUTRAL;
  1238. }
  1239. else
  1240. {
  1241. if (townTypes.size())
  1242. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1243. else if (monsterTypes.size())
  1244. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  1245. else //just in any case
  1246. randomizeTownType(gen);
  1247. }
  1248. }
  1249. }
  1250. void CRmgTemplateZone::randomizeTownType (CMapGenerator* gen)
  1251. {
  1252. if (townTypes.size())
  1253. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  1254. else
  1255. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed, we still need some
  1256. }
  1257. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  1258. {
  1259. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  1260. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  1261. else
  1262. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  1263. //TODO: allow new types of terrain?
  1264. if (pos.z)
  1265. {
  1266. if (terrainType != ETerrainType::LAVA)
  1267. terrainType = ETerrainType::SUBTERRANEAN;
  1268. }
  1269. else
  1270. {
  1271. if (terrainType == ETerrainType::SUBTERRANEAN)
  1272. terrainType = ETerrainType::DIRT;
  1273. }
  1274. paintZoneTerrain (gen, terrainType);
  1275. }
  1276. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  1277. {
  1278. std::vector<int3> tiles;
  1279. for (auto tile : tileinfo)
  1280. {
  1281. tiles.push_back (tile);
  1282. }
  1283. gen->editManager->getTerrainSelection().setSelection(tiles);
  1284. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1285. }
  1286. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  1287. {
  1288. std::vector<Res::ERes> required_mines;
  1289. required_mines.push_back(Res::ERes::WOOD);
  1290. required_mines.push_back(Res::ERes::ORE);
  1291. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  1292. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  1293. for (const auto & res : woodOre)
  1294. {
  1295. for (int i = 0; i < mines[res]; i++)
  1296. {
  1297. auto mine = new CGMine();
  1298. mine->ID = Obj::MINE;
  1299. mine->subID = static_cast<si32>(res);
  1300. mine->producedResource = res;
  1301. mine->producedQuantity = mine->defaultResProduction();
  1302. if (!i)
  1303. addCloseObject(mine, 1500); //only firts one is close
  1304. else
  1305. addRequiredObject(mine, 1500);
  1306. }
  1307. }
  1308. for (const auto & res : preciousResources)
  1309. {
  1310. for (int i = 0; i < mines[res]; i++)
  1311. {
  1312. auto mine = new CGMine();
  1313. mine->ID = Obj::MINE;
  1314. mine->subID = static_cast<si32>(res);
  1315. mine->producedResource = res;
  1316. mine->producedQuantity = mine->defaultResProduction();
  1317. addRequiredObject(mine, 3500);
  1318. }
  1319. }
  1320. for (int i = 0; i < mines[Res::GOLD]; i++)
  1321. {
  1322. auto mine = new CGMine();
  1323. mine->ID = Obj::MINE;
  1324. mine->subID = static_cast<si32>(Res::GOLD);
  1325. mine->producedResource = Res::GOLD;
  1326. mine->producedQuantity = mine->defaultResProduction();
  1327. addRequiredObject(mine, 7000);
  1328. }
  1329. return true;
  1330. }
  1331. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1332. {
  1333. logGlobal->traceStream() << "Creating required objects";
  1334. for(const auto &object : requiredObjects)
  1335. {
  1336. auto obj = object.first;
  1337. int3 pos;
  1338. int3 accessibleOffset;
  1339. while (true)
  1340. {
  1341. if (!findPlaceForObject(gen, obj, 3, pos))
  1342. {
  1343. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1344. return false;
  1345. }
  1346. //check if we can find a path around this object. Tiles will be set to "USED" after object is successfully placed.
  1347. obj->pos = pos;
  1348. gen->setOccupied (obj->visitablePos(), ETileType::BLOCKED);
  1349. for (auto tile : obj->getBlockedPos())
  1350. {
  1351. if (gen->map->isInTheMap(tile))
  1352. gen->setOccupied(tile, ETileType::BLOCKED);
  1353. }
  1354. accessibleOffset = getAccessibleOffset(gen, obj->appearance, pos);
  1355. if (!accessibleOffset.valid())
  1356. {
  1357. logGlobal->warnStream() << boost::format("Cannot access required object at position %s, retrying") % pos;
  1358. continue;
  1359. }
  1360. if (!connectPath(gen, accessibleOffset, true))
  1361. {
  1362. logGlobal->warnStream() << boost::format("Failed to create path to required object at position %s, retrying") % pos;
  1363. continue;
  1364. }
  1365. else
  1366. break;
  1367. }
  1368. placeObject(gen, obj, pos);
  1369. guardObject (gen, obj, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY), true);
  1370. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1371. }
  1372. for (const auto &obj : closeObjects)
  1373. {
  1374. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1375. // smallest distance to zone center, greatest distance to nearest object
  1376. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1377. {
  1378. float lDist = this->pos.dist2d(lhs);
  1379. float rDist = this->pos.dist2d(rhs);
  1380. lDist *= (lDist > 12) ? 10 : 1; //objects within 12 tile radius are preferred (smaller distance rating)
  1381. rDist *= (rDist > 12) ? 10 : 1;
  1382. return (lDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(lhs))) < (rDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(rhs)));
  1383. };
  1384. boost::sort (tiles, isCloser);
  1385. setTemplateForObject(gen, obj.first);
  1386. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1387. bool result = false;
  1388. for (auto tile : tiles)
  1389. {
  1390. //object must be accessible from at least one surounding tile
  1391. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile))
  1392. continue;
  1393. //avoid borders
  1394. if (gen->isPossible(tile))
  1395. {
  1396. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1397. {
  1398. placeObject(gen, obj.first, tile);
  1399. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1400. result = true;
  1401. break;
  1402. }
  1403. }
  1404. }
  1405. if (!result)
  1406. {
  1407. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1408. //TODO CLEANUP!
  1409. return false;
  1410. }
  1411. }
  1412. return true;
  1413. }
  1414. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1415. {
  1416. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  1417. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  1418. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  1419. minGuardedValue = minGuardedValues[monsterStrength];
  1420. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1421. {
  1422. return lhs.max > rhs.max;
  1423. };
  1424. //place biggest treasures first at large distance, place smaller ones inbetween
  1425. boost::sort(treasureInfo, valueComparator);
  1426. int totalDensity = 0;
  1427. for (auto t : treasureInfo)
  1428. {
  1429. //discard objects with too high value to be ever placed
  1430. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  1431. {
  1432. return oi.value > t.max;
  1433. });
  1434. totalDensity += t.density;
  1435. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1436. //also, normalize it to zone count - higher count means relatively smaller zones
  1437. //this is squared distance for optimization purposes
  1438. const double minDistance = std::max<float>((125.f / totalDensity), 2);
  1439. //distance lower than 2 causes objects to overlap and crash
  1440. bool stop = false;
  1441. do {
  1442. //optimization - don't check tiles which are not allowed
  1443. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1444. {
  1445. return !gen->isPossible(tile);
  1446. });
  1447. int3 treasureTilePos;
  1448. //If we are able to place at least one object with value lower than minGuardedValue, it's ok
  1449. do
  1450. {
  1451. if (!findPlaceForTreasurePile(gen, minDistance, treasureTilePos, t.min))
  1452. {
  1453. stop = true;
  1454. break;
  1455. }
  1456. }
  1457. while (!createTreasurePile(gen, treasureTilePos, minDistance, t)); //failed creation - position was wrong, cannot connect it
  1458. } while (!stop);
  1459. }
  1460. }
  1461. void CRmgTemplateZone::createObstacles1(CMapGenerator * gen)
  1462. {
  1463. if (pos.z) //underground
  1464. {
  1465. //now make sure all accessible tiles have no additional rock on them
  1466. std::vector<int3> accessibleTiles;
  1467. for (auto tile : tileinfo)
  1468. {
  1469. if (gen->isFree(tile) || gen->isUsed(tile))
  1470. {
  1471. accessibleTiles.push_back(tile);
  1472. }
  1473. }
  1474. gen->editManager->getTerrainSelection().setSelection(accessibleTiles);
  1475. gen->editManager->drawTerrain(terrainType, &gen->rand);
  1476. }
  1477. }
  1478. void CRmgTemplateZone::createObstacles2(CMapGenerator* gen)
  1479. {
  1480. typedef std::vector<ObjectTemplate> obstacleVector;
  1481. //obstacleVector possibleObstacles;
  1482. std::map <ui8, obstacleVector> obstaclesBySize;
  1483. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1484. std::vector<obstaclePair> possibleObstacles;
  1485. //get all possible obstacles for this terrain
  1486. for (auto primaryID : VLC->objtypeh->knownObjects())
  1487. {
  1488. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1489. {
  1490. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1491. if (handler->isStaticObject())
  1492. {
  1493. for (auto temp : handler->getTemplates())
  1494. {
  1495. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1496. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1497. }
  1498. }
  1499. }
  1500. }
  1501. for (auto o : obstaclesBySize)
  1502. {
  1503. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1504. }
  1505. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1506. {
  1507. return p1.first > p2.first; //bigger obstacles first
  1508. });
  1509. auto sel = gen->editManager->getTerrainSelection();
  1510. sel.clearSelection();
  1511. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1512. {
  1513. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1514. int3 obstaclePos = tile + temp.getBlockMapOffset();
  1515. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1516. {
  1517. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1518. placeObject(gen, obj, obstaclePos, false);
  1519. return true;
  1520. }
  1521. return false;
  1522. };
  1523. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1524. for (auto tile : boost::adaptors::reverse(tileinfo))
  1525. {
  1526. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1527. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1528. {
  1529. //start from biggets obstacles
  1530. for (int i = 0; i < possibleObstacles.size(); i++)
  1531. {
  1532. if (tryToPlaceObstacleHere(tile, i))
  1533. break;
  1534. }
  1535. }
  1536. }
  1537. //cleanup - remove unused possible tiles to make space for roads
  1538. for (auto tile : tileinfo)
  1539. {
  1540. if (gen->isPossible(tile))
  1541. {
  1542. gen->setOccupied (tile, ETileType::FREE);
  1543. }
  1544. }
  1545. }
  1546. void CRmgTemplateZone::connectRoads(CMapGenerator* gen)
  1547. {
  1548. logGlobal->debug("Started building roads");
  1549. std::set<int3> roadNodesCopy(roadNodes);
  1550. std::set<int3> processed;
  1551. while(!roadNodesCopy.empty())
  1552. {
  1553. int3 node = *roadNodesCopy.begin();
  1554. roadNodesCopy.erase(node);
  1555. int3 cross(-1, -1, -1);
  1556. auto comparator = [=](int3 lhs, int3 rhs) { return node.dist2dSQ(lhs) < node.dist2dSQ(rhs); };
  1557. if (processed.size()) //connect with already existing network
  1558. {
  1559. cross = *boost::range::min_element(processed, comparator); //find another remaining node
  1560. }
  1561. else if (roadNodesCopy.size()) //connect with any other unconnected node
  1562. {
  1563. cross = *boost::range::min_element(roadNodesCopy, comparator); //find another remaining node
  1564. }
  1565. else //no other nodes left, for example single road node in this zone
  1566. break;
  1567. logGlobal->debugStream() << "Building road from " << node << " to " << cross;
  1568. if (createRoad(gen, node, cross))
  1569. {
  1570. processed.insert(cross); //don't draw road starting at end point which is already connected
  1571. vstd::erase_if_present(roadNodesCopy, cross);
  1572. }
  1573. processed.insert(node);
  1574. }
  1575. drawRoads(gen);
  1576. logGlobal->debug("Finished building roads");
  1577. }
  1578. void CRmgTemplateZone::drawRoads(CMapGenerator* gen)
  1579. {
  1580. std::vector<int3> tiles;
  1581. for (auto tile : roads)
  1582. {
  1583. if(gen->map->isInTheMap(tile))
  1584. tiles.push_back (tile);
  1585. }
  1586. for (auto tile : roadNodes)
  1587. {
  1588. if (vstd::contains(tileinfo, tile)) //mark roads for our nodes, but not for zone guards in other zones
  1589. tiles.push_back(tile);
  1590. }
  1591. gen->editManager->getTerrainSelection().setSelection(tiles);
  1592. gen->editManager->drawRoad(ERoadType::COBBLESTONE_ROAD, &gen->rand);
  1593. }
  1594. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1595. {
  1596. initTerrainType(gen);
  1597. //zone center should be always clear to allow other tiles to connect
  1598. gen->setOccupied(this->getPos(), ETileType::FREE);
  1599. freePaths.insert(pos);
  1600. addAllPossibleObjects (gen);
  1601. connectLater(gen); //ideally this should work after fractalize, but fails
  1602. fractalize(gen);
  1603. placeMines(gen);
  1604. createRequiredObjects(gen);
  1605. createTreasures(gen);
  1606. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1607. return true;
  1608. }
  1609. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
  1610. {
  1611. float best_distance = 0;
  1612. bool result = false;
  1613. bool needsGuard = value > minGuardedValue;
  1614. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1615. for(auto tile : possibleTiles)
  1616. {
  1617. auto dist = gen->getNearestObjectDistance(tile);
  1618. if ((dist >= min_dist) && (dist > best_distance))
  1619. {
  1620. bool allTilesAvailable = true;
  1621. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
  1622. {
  1623. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
  1624. {
  1625. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1626. }
  1627. });
  1628. if (allTilesAvailable)
  1629. {
  1630. best_distance = dist;
  1631. pos = tile;
  1632. result = true;
  1633. }
  1634. }
  1635. }
  1636. if (result)
  1637. {
  1638. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
  1639. }
  1640. return result;
  1641. }
  1642. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1643. {
  1644. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1645. return false;
  1646. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1647. for (auto blockingTile : tilesBlockedByObject)
  1648. {
  1649. int3 t = pos + blockingTile;
  1650. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1651. {
  1652. return false; //if at least one tile is not possible, object can't be placed here
  1653. }
  1654. }
  1655. return true;
  1656. }
  1657. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile) const
  1658. {
  1659. return getAccessibleOffset(gen, appearance, tile).valid();
  1660. }
  1661. int3 CRmgTemplateZone::getAccessibleOffset(CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile) const
  1662. {
  1663. auto tilesBlockedByObject = appearance.getBlockedOffsets();
  1664. int3 ret(-1, -1, -1);
  1665. for (int x = -1; x < 2; x++)
  1666. {
  1667. for (int y = -1; y <2; y++)
  1668. {
  1669. if (x && y) //check only if object is visitable from another tile
  1670. {
  1671. int3 offset = int3(x, y, 0) - appearance.getVisitableOffset();
  1672. if (!vstd::contains(tilesBlockedByObject, offset))
  1673. {
  1674. int3 nearbyPos = tile + offset;
  1675. if (gen->map->isInTheMap(nearbyPos))
  1676. {
  1677. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1678. ret = nearbyPos;
  1679. }
  1680. }
  1681. }
  1682. };
  1683. }
  1684. return ret;
  1685. }
  1686. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1687. {
  1688. if (obj->appearance.id == Obj::NO_OBJ)
  1689. {
  1690. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1691. if (templates.empty())
  1692. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1693. obj->appearance = templates.front();
  1694. }
  1695. }
  1696. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1697. {
  1698. for (auto blockingTile : tilesBlockedByObject)
  1699. {
  1700. int3 t = tile + blockingTile;
  1701. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1702. {
  1703. //if at least one tile is not possible, object can't be placed here
  1704. return false;
  1705. }
  1706. }
  1707. return true;
  1708. }
  1709. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1710. {
  1711. //we need object apperance to deduce free tile
  1712. setTemplateForObject(gen, obj);
  1713. //si32 min_dist = sqrt(tileinfo.size()/density);
  1714. int best_distance = 0;
  1715. bool result = false;
  1716. //si32 w = gen->map->width;
  1717. //si32 h = gen->map->height;
  1718. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1719. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1720. for (auto tile : tileinfo)
  1721. {
  1722. //object must be accessible from at least one surounding tile
  1723. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile))
  1724. continue;
  1725. auto ti = gen->getTile(tile);
  1726. auto dist = ti.getNearestObjectDistance();
  1727. //avoid borders
  1728. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1729. {
  1730. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1731. {
  1732. best_distance = dist;
  1733. pos = tile;
  1734. result = true;
  1735. }
  1736. }
  1737. }
  1738. if (result)
  1739. {
  1740. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1741. }
  1742. return result;
  1743. }
  1744. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1745. {
  1746. if (!gen->map->isInTheMap(pos))
  1747. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1748. object->pos = pos;
  1749. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1750. 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()));
  1751. for (auto tile : object->getBlockedPos())
  1752. {
  1753. if (!gen->map->isInTheMap(tile))
  1754. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1755. }
  1756. if (object->appearance.id == Obj::NO_OBJ)
  1757. {
  1758. auto terrainType = gen->map->getTile(pos).terType;
  1759. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1760. if (templates.empty())
  1761. 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));
  1762. object->appearance = templates.front();
  1763. }
  1764. gen->editManager->insertObject(object, pos);
  1765. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1766. }
  1767. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1768. {
  1769. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1770. checkAndPlaceObject (gen, object, pos);
  1771. auto points = object->getBlockedPos();
  1772. if (object->isVisitable())
  1773. points.insert(pos + object->getVisitableOffset());
  1774. points.insert(pos);
  1775. for(auto p : points)
  1776. {
  1777. if (gen->map->isInTheMap(p))
  1778. {
  1779. gen->setOccupied(p, ETileType::USED);
  1780. }
  1781. }
  1782. if (updateDistance)
  1783. {
  1784. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1785. {
  1786. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1787. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1788. }
  1789. }
  1790. if (object->ID == Obj::SEER_HUT) //debug
  1791. {
  1792. CGSeerHut * sh = dynamic_cast<CGSeerHut *>(object);
  1793. auto artid = sh->quest->m5arts.front();
  1794. logGlobal->warnStream() << boost::format("Placed Seer Hut at %s, quest artifact %d is %s") % object->pos % artid % VLC->arth->artifacts[artid]->Name();
  1795. }
  1796. switch (object->ID)
  1797. {
  1798. case Obj::TOWN:
  1799. case Obj::RANDOM_TOWN:
  1800. case Obj::MONOLITH_TWO_WAY:
  1801. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  1802. case Obj::MONOLITH_ONE_WAY_EXIT:
  1803. case Obj::SUBTERRANEAN_GATE:
  1804. {
  1805. addRoadNode(object->visitablePos());
  1806. }
  1807. break;
  1808. default:
  1809. break;
  1810. }
  1811. }
  1812. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1813. {
  1814. placeObject(gen, object, pos);
  1815. guardObject(gen, object, str, zoneGuard);
  1816. }
  1817. void CRmgTemplateZone::placeSubterraneanGate(CMapGenerator* gen, int3 pos, si32 guardStrength)
  1818. {
  1819. auto gate = new CGSubterraneanGate;
  1820. gate->ID = Obj::SUBTERRANEAN_GATE;
  1821. gate->subID = 0;
  1822. placeObject (gen, gate, pos, true);
  1823. addToConnectLater (getAccessibleOffset (gen, gate->appearance, pos)); //guard will be placed on accessibleOffset
  1824. guardObject (gen, gate, guardStrength, true);
  1825. }
  1826. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1827. {
  1828. //get all tiles from which this object can be accessed
  1829. int3 visitable = object->visitablePos();
  1830. std::vector<int3> tiles;
  1831. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1832. gen->foreach_neighbour(visitable, [&](int3& pos)
  1833. {
  1834. if (gen->isPossible(pos) || gen->isFree(pos))
  1835. {
  1836. if (!vstd::contains(tilesBlockedByObject, pos))
  1837. {
  1838. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1839. {
  1840. tiles.push_back(pos);
  1841. }
  1842. }
  1843. };
  1844. });
  1845. return tiles;
  1846. }
  1847. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1848. {
  1849. std::vector<int3> tiles = getAccessibleOffsets(gen, object);
  1850. int3 guardTile(-1, -1, -1);
  1851. if (tiles.size())
  1852. {
  1853. //guardTile = tiles.front();
  1854. guardTile = getAccessibleOffset(gen, object->appearance, object->pos);
  1855. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1856. }
  1857. else
  1858. {
  1859. logGlobal->errorStream() << boost::format("Failed to guard object at %s") % object->pos();
  1860. return false;
  1861. }
  1862. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1863. {
  1864. for (auto pos : tiles)
  1865. {
  1866. if (!gen->isFree(pos))
  1867. gen->setOccupied(pos, ETileType::BLOCKED);
  1868. }
  1869. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1870. {
  1871. if (gen->isPossible(pos))
  1872. gen->setOccupied (pos, ETileType::FREE);
  1873. });
  1874. gen->setOccupied (guardTile, ETileType::USED);
  1875. }
  1876. else //allow no guard or other object in front of this object
  1877. {
  1878. for (auto tile : tiles)
  1879. if (gen->isPossible(tile))
  1880. gen->setOccupied (tile, ETileType::FREE);
  1881. }
  1882. return true;
  1883. }
  1884. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1885. {
  1886. //int objectsVisitableFromBottom = 0; //for debug
  1887. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1888. ui32 total = 0;
  1889. //calculate actual treasure value range based on remaining value
  1890. ui32 maxVal = desiredValue - currentValue;
  1891. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1892. //roulette wheel
  1893. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1894. {
  1895. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1896. {
  1897. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1898. int3 newVisitablePos = info.nextTreasurePos;
  1899. if (!oi.templ.isVisitableFromTop())
  1900. {
  1901. //objectsVisitableFromBottom++;
  1902. //there must be free tiles under object
  1903. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1904. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos))
  1905. continue;
  1906. }
  1907. //NOTE: y coordinate grows downwards
  1908. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1909. {
  1910. bool fitsHere = false;
  1911. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1912. {
  1913. for (auto tile : info.visitableFromTopPositions)
  1914. {
  1915. int3 actualTile = tile + newVisitableOffset;
  1916. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1917. {
  1918. fitsHere = true;
  1919. break;
  1920. }
  1921. }
  1922. for (auto tile : info.visitableFromBottomPositions)
  1923. {
  1924. int3 actualTile = tile + newVisitableOffset;
  1925. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1926. {
  1927. fitsHere = true;
  1928. break;
  1929. }
  1930. }
  1931. }
  1932. else //if new object is not visitable from top, it must be accessible from below or side
  1933. {
  1934. for (auto tile : info.visitableFromTopPositions)
  1935. {
  1936. int3 actualTile = tile + newVisitableOffset;
  1937. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1938. {
  1939. fitsHere = true;
  1940. break;
  1941. }
  1942. }
  1943. for (auto tile : info.visitableFromBottomPositions)
  1944. {
  1945. int3 actualTile = tile + newVisitableOffset;
  1946. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1947. {
  1948. fitsHere = true;
  1949. break;
  1950. }
  1951. }
  1952. }
  1953. if (!fitsHere)
  1954. continue;
  1955. }
  1956. //now check blockmap, including our already reserved pile area
  1957. bool fitsBlockmap = true;
  1958. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1959. blockedOffsets.insert (newVisitableOffset);
  1960. for (auto blockingTile : blockedOffsets)
  1961. {
  1962. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1963. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1964. {
  1965. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1966. break;
  1967. }
  1968. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1969. {
  1970. fitsBlockmap = false;
  1971. break;
  1972. }
  1973. }
  1974. if (!fitsBlockmap)
  1975. continue;
  1976. total += oi.probability;
  1977. //assert (oi.value > 0);
  1978. tresholds.push_back (std::make_pair (total, oi));
  1979. }
  1980. }
  1981. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1982. if (tresholds.empty())
  1983. {
  1984. ObjectInfo oi;
  1985. //Generate pandora Box with gold if the value is extremely high
  1986. if (minValue > 20000) //we don't have object valuable enough
  1987. {
  1988. oi.generateObject = [minValue]() -> CGObjectInstance *
  1989. {
  1990. auto obj = new CGPandoraBox();
  1991. obj->ID = Obj::PANDORAS_BOX;
  1992. obj->subID = 0;
  1993. obj->resources[Res::GOLD] = minValue;
  1994. return obj;
  1995. };
  1996. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1997. oi.value = minValue;
  1998. oi.probability = 0;
  1999. }
  2000. else //generate empty object with 0 value if the value if we can't spawn anything
  2001. {
  2002. oi.generateObject = [gen]() -> CGObjectInstance *
  2003. {
  2004. return nullptr;
  2005. };
  2006. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  2007. oi.value = 0; // this field is checked to determine no object
  2008. oi.probability = 0;
  2009. }
  2010. return oi;
  2011. }
  2012. else
  2013. {
  2014. int r = gen->rand.nextInt (1, total);
  2015. for (auto t : tresholds)
  2016. {
  2017. if (r <= t.first)
  2018. return t.second;
  2019. }
  2020. assert (0); //we should never be here
  2021. }
  2022. return ObjectInfo(); // unreachable
  2023. }
  2024. void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
  2025. {
  2026. ObjectInfo oi;
  2027. oi.maxPerMap = std::numeric_limits<ui32>().max();
  2028. int numZones = gen->getZones().size();
  2029. std::vector<CCreature *> creatures; //native creatures for this zone
  2030. for (auto cre : VLC->creh->creatures)
  2031. {
  2032. if (!cre->special && cre->faction == townType)
  2033. {
  2034. creatures.push_back(cre);
  2035. }
  2036. }
  2037. for (auto primaryID : VLC->objtypeh->knownObjects())
  2038. {
  2039. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  2040. {
  2041. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  2042. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  2043. {
  2044. for (auto temp : handler->getTemplates())
  2045. {
  2046. if (temp.canBePlacedAt(terrainType))
  2047. {
  2048. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  2049. {
  2050. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  2051. };
  2052. auto rmgInfo = handler->getRMGInfo();
  2053. oi.value = rmgInfo.value;
  2054. oi.probability = rmgInfo.rarity;
  2055. oi.templ = temp;
  2056. oi.maxPerZone = rmgInfo.zoneLimit;
  2057. vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  2058. possibleObjects.push_back(oi);
  2059. }
  2060. }
  2061. }
  2062. }
  2063. }
  2064. //prisons
  2065. //levels 1, 5, 10, 20, 30
  2066. static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
  2067. static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
  2068. for (int i = 0; i < 5; i++)
  2069. {
  2070. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  2071. {
  2072. auto obj = new CGHeroInstance;
  2073. obj->ID = Obj::PRISON;
  2074. std::vector<ui32> possibleHeroes;
  2075. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  2076. {
  2077. if (gen->map->allowedHeroes[j])
  2078. possibleHeroes.push_back(j);
  2079. }
  2080. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  2081. obj->subID = hid; //will be initialized later
  2082. obj->exp = prisonExp[i];
  2083. obj->setOwner(PlayerColor::NEUTRAL);
  2084. gen->map->allowedHeroes[hid] = false; //ban this hero
  2085. gen->decreasePrisonsRemaining();
  2086. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  2087. return obj;
  2088. };
  2089. oi.setTemplate(Obj::PRISON, 0, terrainType);
  2090. oi.value = prisonValues[i];
  2091. oi.probability = 30;
  2092. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  2093. possibleObjects.push_back(oi);
  2094. }
  2095. //all following objects are unlimited
  2096. oi.maxPerZone = std::numeric_limits<ui32>().max();
  2097. //dwellings
  2098. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  2099. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  2100. static int elementalConfluxROE[] = { 7, 13, 16, 47 };
  2101. for (int i = 0; i < 4; i++)
  2102. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  2103. for (auto secondaryID : subObjects)
  2104. {
  2105. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  2106. auto creatures = dwellingHandler->getProducedCreatures();
  2107. if (creatures.empty())
  2108. continue;
  2109. auto cre = creatures.front();
  2110. if (cre->faction == townType)
  2111. {
  2112. float nativeZonesCount = gen->getZoneCount(cre->faction);
  2113. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  2114. oi.probability = 40;
  2115. for (auto temp : dwellingHandler->getTemplates())
  2116. {
  2117. if (temp.canBePlacedAt(terrainType))
  2118. {
  2119. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  2120. {
  2121. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  2122. //dwellingHandler->configureObject(obj, gen->rand);
  2123. obj->tempOwner = PlayerColor::NEUTRAL;
  2124. return obj;
  2125. };
  2126. oi.templ = temp;
  2127. possibleObjects.push_back(oi);
  2128. }
  2129. }
  2130. }
  2131. }
  2132. static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
  2133. for (int i = 0; i < 5; i++)
  2134. {
  2135. oi.generateObject = [i, gen]() -> CGObjectInstance *
  2136. {
  2137. auto obj = new CGArtifact();
  2138. obj->ID = Obj::SPELL_SCROLL;
  2139. obj->subID = 0;
  2140. std::vector<SpellID> out;
  2141. for (auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  2142. {
  2143. if (gen->isAllowedSpell(spell->id) && spell->level == i + 1)
  2144. {
  2145. out.push_back(spell->id);
  2146. }
  2147. }
  2148. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  2149. gen->map->addNewArtifactInstance(a);
  2150. obj->storedArtifact = a;
  2151. return obj;
  2152. };
  2153. oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
  2154. oi.value = scrollValues[i];
  2155. oi.probability = 30;
  2156. possibleObjects.push_back(oi);
  2157. }
  2158. //pandora box with gold
  2159. for (int i = 1; i < 5; i++)
  2160. {
  2161. oi.generateObject = [i]() -> CGObjectInstance *
  2162. {
  2163. auto obj = new CGPandoraBox();
  2164. obj->ID = Obj::PANDORAS_BOX;
  2165. obj->subID = 0;
  2166. obj->resources[Res::GOLD] = i * 5000;
  2167. return obj;
  2168. };
  2169. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2170. oi.value = i * 5000;;
  2171. oi.probability = 5;
  2172. possibleObjects.push_back(oi);
  2173. }
  2174. //pandora box with experience
  2175. for (int i = 1; i < 5; i++)
  2176. {
  2177. oi.generateObject = [i]() -> CGObjectInstance *
  2178. {
  2179. auto obj = new CGPandoraBox();
  2180. obj->ID = Obj::PANDORAS_BOX;
  2181. obj->subID = 0;
  2182. obj->gainedExp = i * 5000;
  2183. return obj;
  2184. };
  2185. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2186. oi.value = i * 6000;;
  2187. oi.probability = 20;
  2188. possibleObjects.push_back(oi);
  2189. }
  2190. //pandora box with creatures
  2191. static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
  2192. auto creatureToCount = [](CCreature * creature) -> int
  2193. {
  2194. int actualTier = creature->level > 7 ? 6 : creature->level - 1;
  2195. float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
  2196. if (creaturesAmount <= 5)
  2197. {
  2198. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  2199. if (creaturesAmount < 1)
  2200. return 0;
  2201. }
  2202. else if (creaturesAmount <= 12)
  2203. {
  2204. (creaturesAmount /= 2) *= 2;
  2205. }
  2206. else if (creaturesAmount <= 50)
  2207. {
  2208. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  2209. }
  2210. else
  2211. {
  2212. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  2213. }
  2214. return creaturesAmount;
  2215. };
  2216. for (auto creature : creatures)
  2217. {
  2218. int creaturesAmount = creatureToCount(creature);
  2219. if (!creaturesAmount)
  2220. continue;
  2221. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  2222. {
  2223. auto obj = new CGPandoraBox();
  2224. obj->ID = Obj::PANDORAS_BOX;
  2225. obj->subID = 0;
  2226. auto stack = new CStackInstance(creature, creaturesAmount);
  2227. obj->creatures.putStack(SlotID(0), stack);
  2228. return obj;
  2229. };
  2230. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2231. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
  2232. oi.probability = 3;
  2233. possibleObjects.push_back(oi);
  2234. }
  2235. //Pandora with 12 spells of certain level
  2236. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  2237. {
  2238. oi.generateObject = [i, gen]() -> CGObjectInstance *
  2239. {
  2240. auto obj = new CGPandoraBox();
  2241. obj->ID = Obj::PANDORAS_BOX;
  2242. obj->subID = 0;
  2243. std::vector <CSpell *> spells;
  2244. for (auto spell : VLC->spellh->objects)
  2245. {
  2246. if (gen->isAllowedSpell(spell->id) && spell->level == i)
  2247. spells.push_back(spell);
  2248. }
  2249. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2250. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  2251. {
  2252. obj->spells.push_back(spells[j]->id);
  2253. }
  2254. return obj;
  2255. };
  2256. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2257. oi.value = (i + 1) * 2500; //5000 - 15000
  2258. oi.probability = 2;
  2259. possibleObjects.push_back(oi);
  2260. }
  2261. //Pandora with 15 spells of certain school
  2262. for (int i = 0; i < 4; i++)
  2263. {
  2264. oi.generateObject = [i,gen]() -> CGObjectInstance *
  2265. {
  2266. auto obj = new CGPandoraBox();
  2267. obj->ID = Obj::PANDORAS_BOX;
  2268. obj->subID = 0;
  2269. std::vector <CSpell *> spells;
  2270. for (auto spell : VLC->spellh->objects)
  2271. {
  2272. if (gen->isAllowedSpell(spell->id) && spell->school[(ESpellSchool)i])
  2273. spells.push_back(spell);
  2274. }
  2275. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2276. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  2277. {
  2278. obj->spells.push_back(spells[j]->id);
  2279. }
  2280. return obj;
  2281. };
  2282. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2283. oi.value = 15000;
  2284. oi.probability = 2;
  2285. possibleObjects.push_back(oi);
  2286. }
  2287. // Pandora box with 60 random spells
  2288. oi.generateObject = [gen]() -> CGObjectInstance *
  2289. {
  2290. auto obj = new CGPandoraBox();
  2291. obj->ID = Obj::PANDORAS_BOX;
  2292. obj->subID = 0;
  2293. std::vector <CSpell *> spells;
  2294. for (auto spell : VLC->spellh->objects)
  2295. {
  2296. if (gen->isAllowedSpell(spell->id))
  2297. spells.push_back(spell);
  2298. }
  2299. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  2300. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  2301. {
  2302. obj->spells.push_back(spells[j]->id);
  2303. }
  2304. return obj;
  2305. };
  2306. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  2307. oi.value = 30000;
  2308. oi.probability = 2;
  2309. possibleObjects.push_back(oi);
  2310. //seer huts with creatures or generic rewards
  2311. if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
  2312. {
  2313. static const int genericSeerHuts = 8;
  2314. int seerHutsPerType = 0;
  2315. const int questArtsRemaining = gen->getQuestArtsRemaning().size();
  2316. //general issue is that not many artifact types are available for quests
  2317. if (questArtsRemaining >= genericSeerHuts + creatures.size())
  2318. {
  2319. seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
  2320. }
  2321. else if (questArtsRemaining >= genericSeerHuts)
  2322. {
  2323. seerHutsPerType = 1;
  2324. }
  2325. oi.maxPerZone = seerHutsPerType;
  2326. RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
  2327. auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
  2328. {
  2329. ObjectInfo artInfo;
  2330. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  2331. artInfo.maxPerZone = 1;
  2332. artInfo.value = 2000; //treasure art
  2333. artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
  2334. artInfo.generateObject = [id]() -> CGObjectInstance *
  2335. {
  2336. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  2337. return handler->create(handler->getTemplates().front());
  2338. };
  2339. return artInfo;
  2340. };
  2341. for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
  2342. {
  2343. auto creature = creatures[i];
  2344. int creaturesAmount = creatureToCount(creature);
  2345. if (!creaturesAmount)
  2346. continue;
  2347. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2348. oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2349. {
  2350. auto obj = new CGSeerHut();
  2351. obj->ID = Obj::SEER_HUT;
  2352. obj->subID = randomAppearance;
  2353. obj->rewardType = CGSeerHut::CREATURE;
  2354. obj->rID = creature->idNumber;
  2355. obj->rVal = creaturesAmount;
  2356. obj->quest->missionType = CQuest::MISSION_ART;
  2357. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2358. obj->quest->m5arts.push_back(artid);
  2359. obj->quest->lastDay = -1;
  2360. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2361. gen->banQuestArt(artid);
  2362. gen->map->addQuest(obj);
  2363. this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
  2364. return obj;
  2365. };
  2366. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2367. oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
  2368. oi.probability = 3;
  2369. possibleObjects.push_back(oi);
  2370. }
  2371. static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
  2372. static int seerValues[] = { 2000, 5333, 8666, 12000 };
  2373. for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
  2374. {
  2375. int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
  2376. oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
  2377. oi.value = seerValues[i];
  2378. oi.probability = 10;
  2379. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2380. {
  2381. auto obj = new CGSeerHut();
  2382. obj->ID = Obj::SEER_HUT;
  2383. obj->subID = randomAppearance;
  2384. obj->rewardType = CGSeerHut::EXPERIENCE;
  2385. obj->rID = 0; //unitialized?
  2386. obj->rVal = seerExpGold[i];
  2387. obj->quest->missionType = CQuest::MISSION_ART;
  2388. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2389. obj->quest->m5arts.push_back(artid);
  2390. obj->quest->lastDay = -1;
  2391. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2392. gen->banQuestArt(artid);
  2393. gen->map->addQuest(obj);
  2394. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2395. return obj;
  2396. };
  2397. possibleObjects.push_back(oi);
  2398. oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
  2399. {
  2400. auto obj = new CGSeerHut();
  2401. obj->ID = Obj::SEER_HUT;
  2402. obj->subID = randomAppearance;
  2403. obj->rewardType = CGSeerHut::RESOURCES;
  2404. obj->rID = Res::GOLD;
  2405. obj->rVal = seerExpGold[i];
  2406. obj->quest->missionType = CQuest::MISSION_ART;
  2407. ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
  2408. obj->quest->m5arts.push_back(artid);
  2409. obj->quest->lastDay = -1;
  2410. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  2411. gen->banQuestArt(artid);
  2412. gen->map->addQuest(obj);
  2413. this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
  2414. return obj;
  2415. };
  2416. possibleObjects.push_back(oi);
  2417. }
  2418. }
  2419. }
  2420. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  2421. {
  2422. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  2423. }