CRmgTemplateZone.cpp 81 KB

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