CRmgTemplateZone.cpp 80 KB

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