CRmgTemplateZone.cpp 81 KB

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