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