CRmgTemplateZone.cpp 80 KB

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