CRmgTemplateZone.cpp 75 KB

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