CRmgTemplateZone.cpp 82 KB

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