CRmgTemplateZone.cpp 75 KB

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