CRmgTemplateZone.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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 "../CSpellHandler.h" //for choosing random spells
  18. class CMap;
  19. class CMapEditManager;
  20. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  21. {
  22. }
  23. int CRmgTemplateZone::CTownInfo::getTownCount() const
  24. {
  25. return townCount;
  26. }
  27. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  28. {
  29. if(value < 0)
  30. throw rmgException("Negative value for town count not allowed.");
  31. townCount = value;
  32. }
  33. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  34. {
  35. return castleCount;
  36. }
  37. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  38. {
  39. if(value < 0)
  40. throw rmgException("Negative value for castle count not allowed.");
  41. castleCount = value;
  42. }
  43. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  44. {
  45. return townDensity;
  46. }
  47. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  48. {
  49. if(value < 0)
  50. throw rmgException("Negative value for town density not allowed.");
  51. townDensity = value;
  52. }
  53. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  54. {
  55. return castleDensity;
  56. }
  57. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  58. {
  59. if(value < 0)
  60. throw rmgException("Negative value for castle density not allowed.");
  61. castleDensity = value;
  62. }
  63. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  64. {
  65. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  66. }
  67. int CTileInfo::getNearestObjectDistance() const
  68. {
  69. return nearestObjectDistance;
  70. }
  71. void CTileInfo::setNearestObjectDistance(int value)
  72. {
  73. nearestObjectDistance = std::max(0, value); //never negative (or unitialized)
  74. }
  75. bool CTileInfo::shouldBeBlocked() const
  76. {
  77. return occupied == ETileType::BLOCKED;
  78. }
  79. bool CTileInfo::isBlocked() const
  80. {
  81. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  82. }
  83. bool CTileInfo::isPossible() const
  84. {
  85. return occupied == ETileType::POSSIBLE;
  86. }
  87. bool CTileInfo::isFree() const
  88. {
  89. return occupied == ETileType::FREE;
  90. }
  91. void CTileInfo::setOccupied(ETileType::ETileType value)
  92. {
  93. occupied = value;
  94. }
  95. ETerrainType CTileInfo::getTerrainType() const
  96. {
  97. return terrain;
  98. }
  99. void CTileInfo::setTerrainType(ETerrainType value)
  100. {
  101. terrain = value;
  102. }
  103. CRmgTemplateZone::CRmgTemplateZone() : id(0), type(ETemplateZoneType::PLAYER_START), size(1),
  104. townsAreSameType(false), matchTerrainToTown(true), totalDensity(0)
  105. {
  106. townTypes = getDefaultTownTypes();
  107. terrainTypes = getDefaultTerrainTypes();
  108. }
  109. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  110. {
  111. return id;
  112. }
  113. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  114. {
  115. if(value <= 0)
  116. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  117. id = value;
  118. }
  119. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  120. {
  121. return type;
  122. }
  123. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  124. {
  125. type = value;
  126. }
  127. int CRmgTemplateZone::getSize() const
  128. {
  129. return size;
  130. }
  131. void CRmgTemplateZone::setSize(int value)
  132. {
  133. if(value <= 0)
  134. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  135. size = value;
  136. }
  137. boost::optional<int> CRmgTemplateZone::getOwner() const
  138. {
  139. return owner;
  140. }
  141. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  142. {
  143. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  144. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  145. owner = value;
  146. }
  147. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  148. {
  149. return playerTowns;
  150. }
  151. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  152. {
  153. playerTowns = value;
  154. }
  155. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  156. {
  157. return neutralTowns;
  158. }
  159. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  160. {
  161. neutralTowns = value;
  162. }
  163. bool CRmgTemplateZone::getTownsAreSameType() const
  164. {
  165. return townsAreSameType;
  166. }
  167. void CRmgTemplateZone::setTownsAreSameType(bool value)
  168. {
  169. townsAreSameType = value;
  170. }
  171. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  172. {
  173. return townTypes;
  174. }
  175. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  176. {
  177. townTypes = value;
  178. }
  179. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  180. {
  181. std::set<TFaction> defaultTowns;
  182. auto towns = VLC->townh->getDefaultAllowed();
  183. for(int i = 0; i < towns.size(); ++i)
  184. {
  185. if(towns[i]) defaultTowns.insert(i);
  186. }
  187. return defaultTowns;
  188. }
  189. bool CRmgTemplateZone::getMatchTerrainToTown() const
  190. {
  191. return matchTerrainToTown;
  192. }
  193. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  194. {
  195. matchTerrainToTown = value;
  196. }
  197. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  198. {
  199. return terrainTypes;
  200. }
  201. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  202. {
  203. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  204. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  205. terrainTypes = value;
  206. }
  207. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  208. {
  209. std::set<ETerrainType> terTypes;
  210. static const ETerrainType::EETerrainType allowedTerTypes[] = { ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  211. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA };
  212. for(auto & allowedTerType : allowedTerTypes) terTypes.insert(allowedTerType);
  213. return terTypes;
  214. }
  215. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTerrainTypeLikeZone() const
  216. {
  217. return terrainTypeLikeZone;
  218. }
  219. void CRmgTemplateZone::setTerrainTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  220. {
  221. terrainTypeLikeZone = value;
  222. }
  223. boost::optional<TRmgTemplateZoneId> CRmgTemplateZone::getTownTypeLikeZone() const
  224. {
  225. return townTypeLikeZone;
  226. }
  227. void CRmgTemplateZone::setTownTypeLikeZone(boost::optional<TRmgTemplateZoneId> value)
  228. {
  229. townTypeLikeZone = value;
  230. }
  231. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  232. {
  233. connections.push_back (otherZone);
  234. }
  235. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  236. {
  237. return connections;
  238. }
  239. void CRmgTemplateZone::setTotalDensity (ui16 val)
  240. {
  241. totalDensity = val;
  242. }
  243. ui16 CRmgTemplateZone::getTotalDensity () const
  244. {
  245. return totalDensity;
  246. }
  247. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  248. {
  249. treasureInfo.push_back(info);
  250. }
  251. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  252. {
  253. return treasureInfo;
  254. }
  255. float3 CRmgTemplateZone::getCenter() const
  256. {
  257. return center;
  258. }
  259. void CRmgTemplateZone::setCenter(const float3 &f)
  260. {
  261. //limit boundaries to (0,1) square
  262. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  263. }
  264. bool CRmgTemplateZone::pointIsIn(int x, int y)
  265. {
  266. return true;
  267. }
  268. int3 CRmgTemplateZone::getPos() const
  269. {
  270. return pos;
  271. }
  272. void CRmgTemplateZone::setPos(const int3 &Pos)
  273. {
  274. pos = Pos;
  275. }
  276. void CRmgTemplateZone::addTile (const int3 &pos)
  277. {
  278. tileinfo.insert(pos);
  279. }
  280. std::set<int3> CRmgTemplateZone::getTileInfo () const
  281. {
  282. return tileinfo;
  283. }
  284. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  285. {
  286. for (auto tile : tileinfo)
  287. {
  288. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  289. {
  290. if (!vstd::contains(this->tileinfo, pos))
  291. {
  292. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  293. {
  294. if (gen->isPossible(pos))
  295. gen->setOccupied (pos, ETileType::BLOCKED);
  296. });
  297. }
  298. });
  299. }
  300. }
  301. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  302. {
  303. std::vector<int3> clearedTiles;
  304. std::set<int3> possibleTiles;
  305. std::set<int3> tilesToClear; //will be set clear
  306. std::set<int3> tilesToIgnore; //will be erased in this iteration
  307. const float minDistance = std::sqrt(totalDensity);
  308. for (auto tile : tileinfo)
  309. {
  310. if (gen->isFree(tile))
  311. clearedTiles.push_back(tile);
  312. else if (gen->isPossible(tile));
  313. possibleTiles.insert(tile);
  314. }
  315. if (clearedTiles.empty()) //this should come from zone connections
  316. {
  317. clearedTiles.push_back(pos); //zone center should be always clear
  318. }
  319. while (possibleTiles.size())
  320. {
  321. for (auto tileToMakePath : possibleTiles)
  322. {
  323. //find closest free tile
  324. float currentDistance = 1e10;
  325. int3 closestTile (-1,-1,-1);
  326. for (auto clearTile : clearedTiles)
  327. {
  328. float distance = tileToMakePath.dist2d(clearTile);
  329. if (distance < currentDistance)
  330. {
  331. currentDistance = distance;
  332. closestTile = clearTile;
  333. }
  334. if (currentDistance <= minDistance)
  335. {
  336. //this tile is close enough. Forget about it and check next one
  337. tilesToIgnore.insert (tileToMakePath);
  338. break;
  339. }
  340. }
  341. //if tiles is not close enough, make path to it
  342. if (currentDistance > minDistance)
  343. {
  344. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  345. break; //next iteration - use already cleared tiles
  346. }
  347. }
  348. for (auto tileToClear : tilesToClear)
  349. {
  350. //move cleared tiles from one set to another
  351. clearedTiles.push_back(tileToClear);
  352. vstd::erase_if_present(possibleTiles, tileToClear);
  353. }
  354. for (auto tileToClear : tilesToIgnore)
  355. {
  356. //these tiles are already connected, ignore them
  357. vstd::erase_if_present(possibleTiles, tileToClear);
  358. }
  359. if (tilesToClear.empty()) //nothing else can be done (?)
  360. break;
  361. tilesToClear.clear(); //empty this container
  362. tilesToIgnore.clear();
  363. }
  364. logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  365. }
  366. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  367. {
  368. /*
  369. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  370. do not leave zone border
  371. */
  372. bool result = false;
  373. bool end = false;
  374. int3 currentPos = src;
  375. float distance = currentPos.dist2dSQ (dst);
  376. while (!end)
  377. {
  378. if (currentPos == dst)
  379. break;
  380. auto lastDistance = distance;
  381. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  382. {
  383. if (!result) //not sure if lambda is worth it...
  384. {
  385. if (pos == dst)
  386. {
  387. result = true;
  388. end = true;
  389. }
  390. if (pos.dist2dSQ (dst) < distance)
  391. {
  392. if (!gen->isBlocked(pos))
  393. {
  394. if (vstd::contains (tileinfo, pos))
  395. {
  396. if (gen->isPossible(pos))
  397. {
  398. gen->setOccupied (pos, ETileType::FREE);
  399. if (clearedTiles)
  400. clearedTiles->insert(pos);
  401. currentPos = pos;
  402. distance = currentPos.dist2dSQ (dst);
  403. }
  404. else if (gen->isFree(pos))
  405. {
  406. end = true;
  407. result = true;
  408. }
  409. else
  410. throw rmgException(boost::to_string(boost::format("Tile %s of uknown type found on path") % pos()));
  411. }
  412. }
  413. }
  414. }
  415. });
  416. if (!(result || distance < lastDistance)) //we do not advance, use more avdnaced pathfinding algorithm?
  417. {
  418. logGlobal->warnStream() << boost::format ("No tile closer than %s found on path from %s to %s") %currentPos %src %dst;
  419. break;
  420. }
  421. }
  422. return result;
  423. }
  424. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  425. {
  426. requiredObjects.push_back(std::make_pair(obj, strength));
  427. }
  428. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength)
  429. {
  430. //precalculate actual (randomized) monster strength based on this post
  431. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  432. int zoneMonsterStrength = 0; //TODO: range -1..1 based on template settings
  433. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  434. int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  435. static const int value1[] = {2500, 1500, 1000, 500, 0};
  436. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  437. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  438. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  439. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  440. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  441. strength = strength1 + strength2;
  442. if (strength < 2000)
  443. return false; //no guard at all
  444. CreatureID creId = CreatureID::NONE;
  445. int amount = 0;
  446. std::vector<CreatureID> possibleCreatures;
  447. for (auto cre : VLC->creh->creatures)
  448. {
  449. if (cre->special)
  450. continue;
  451. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between minimum size of given stack and 100
  452. {
  453. possibleCreatures.push_back(cre->idNumber);
  454. }
  455. }
  456. if (possibleCreatures.size())
  457. {
  458. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  459. amount = strength / VLC->creh->creatures[creId]->AIValue;
  460. if (amount >= 4)
  461. amount *= gen->rand.nextDouble(0.75, 1.25);
  462. }
  463. else //just pick any available creature
  464. {
  465. creId = CreatureID(132); //Azure Dragon
  466. amount = strength / VLC->creh->creatures[creId]->AIValue;
  467. }
  468. auto guard = new CGCreature();
  469. guard->ID = Obj::MONSTER;
  470. guard->subID = creId;
  471. auto hlp = new CStackInstance(creId, amount);
  472. //will be set during initialization
  473. guard->putStack(SlotID(0), hlp);
  474. placeObject(gen, guard, pos);
  475. return true;
  476. }
  477. bool CRmgTemplateZone::createTreasurePile (CMapGenerator* gen, int3 &pos)
  478. {
  479. std::map<int3, CGObjectInstance *> treasures;
  480. std::set<int3> boundary;
  481. int3 guardPos;
  482. int3 nextTreasurePos = pos;
  483. //default values
  484. int maxValue = 5000;
  485. int minValue = 1500;
  486. if (treasureInfo.size())
  487. {
  488. //roulette wheel
  489. int r = gen->rand.nextInt (1, totalDensity);
  490. for (auto t : treasureInfo)
  491. {
  492. if (r <= t.threshold)
  493. {
  494. maxValue = t.max;
  495. minValue = t.min;
  496. break;
  497. }
  498. }
  499. }
  500. int currentValue = 0;
  501. CGObjectInstance * object = nullptr;
  502. while (currentValue < minValue)
  503. {
  504. //TODO: this works only for 1-tile objects
  505. //make sure our shape is consistent
  506. treasures[nextTreasurePos] = nullptr;
  507. for (auto treasurePos : treasures)
  508. {
  509. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  510. {
  511. boundary.insert(pos);
  512. });
  513. }
  514. for (auto treasurePos : treasures)
  515. {
  516. //leaving only boundary around objects
  517. vstd::erase_if_present (boundary, treasurePos.first);
  518. }
  519. for (auto tile : boundary)
  520. {
  521. //we can't extend boundary anymore
  522. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  523. break;
  524. }
  525. int remaining = maxValue - currentValue;
  526. auto oi = getRandomObject(gen, remaining);
  527. object = oi.generateObject();
  528. if (!object)
  529. break;
  530. currentValue += oi.value;
  531. treasures[nextTreasurePos] = object;
  532. //now find place for next object
  533. int3 placeFound(-1,-1,-1);
  534. //FIXME: find out why teh following code causes crashes
  535. //std::vector<int3> boundaryVec(boundary.begin(), boundary.end());
  536. //RandomGeneratorUtil::randomShuffle(boundaryVec, gen->rand);
  537. //for (auto tile : boundaryVec)
  538. for (auto tile : boundary)
  539. {
  540. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  541. {
  542. bool here = true;
  543. gen->foreach_neighbour (tile, [gen, &here](int3 pos)
  544. {
  545. if (!(gen->isBlocked(pos) || gen->isPossible(pos)))
  546. here = false;
  547. });
  548. if (here)
  549. {
  550. placeFound = tile;
  551. break;
  552. }
  553. }
  554. }
  555. if (placeFound.valid())
  556. nextTreasurePos = placeFound;
  557. }
  558. if (treasures.size())
  559. {
  560. for (auto treasure : treasures)
  561. {
  562. placeObject(gen, treasure.second, treasure.first - treasure.second->getVisitableOffset());
  563. }
  564. //find object closest to zone center, then con nect it to the middle of the zone
  565. int3 zoneCenter = getPos();
  566. int3 closestTile = int3(-1,-1,-1);
  567. float minDistance = 1e10;
  568. for (auto treasure : treasures)
  569. {
  570. if (zoneCenter.dist2d(treasure.first) < minDistance)
  571. {
  572. closestTile = treasure.first;
  573. minDistance = zoneCenter.dist2d(treasure.first);
  574. }
  575. }
  576. assert (closestTile.valid());
  577. crunchPath (gen, closestTile, getPos(), id); //make sure pile is connected to the middle of zone
  578. for (auto tile : boundary) //guard must be standing there
  579. {
  580. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  581. {
  582. guardPos = tile;
  583. break;
  584. }
  585. }
  586. if (addMonster(gen, guardPos, currentValue))
  587. {//block only if object is guarded
  588. for (auto tile : boundary)
  589. {
  590. if (gen->isPossible(tile))
  591. gen->setOccupied (tile, ETileType::BLOCKED);
  592. }
  593. }
  594. return true;
  595. }
  596. else //we did not place eveyrthing successfully
  597. return false;
  598. }
  599. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  600. {
  601. addAllPossibleObjects (gen);
  602. int townId = 0;
  603. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  604. {
  605. logGlobal->infoStream() << "Preparing playing zone";
  606. int player_id = *owner - 1;
  607. auto & playerInfo = gen->map->players[player_id];
  608. if (playerInfo.canAnyonePlay())
  609. {
  610. PlayerColor player(player_id);
  611. auto town = new CGTownInstance();
  612. town->ID = Obj::TOWN;
  613. townId = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  614. if(townId == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  615. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand); // all possible towns, skip neutral
  616. town->subID = townId;
  617. town->tempOwner = player;
  618. town->builtBuildings.insert(BuildingID::FORT);
  619. town->builtBuildings.insert(BuildingID::DEFAULT);
  620. placeObject(gen, town, getPos() + town->getVisitableOffset()); //towns are big objects and should be centered around visitable position
  621. logGlobal->traceStream() << "Fill player info " << player_id;
  622. // Update player info
  623. playerInfo.allowedFactions.clear();
  624. playerInfo.allowedFactions.insert(townId);
  625. playerInfo.hasMainTown = true;
  626. playerInfo.posOfMainTown = town->pos - int3(2, 0, 0);
  627. playerInfo.generateHeroAtMainTown = true;
  628. //requiredObjects.push_back(town);
  629. std::vector<Res::ERes> required_mines;
  630. required_mines.push_back(Res::ERes::WOOD);
  631. required_mines.push_back(Res::ERes::ORE);
  632. for(const auto res : required_mines)
  633. {
  634. auto mine = new CGMine();
  635. mine->ID = Obj::MINE;
  636. mine->subID = static_cast<si32>(res);
  637. mine->producedResource = res;
  638. mine->producedQuantity = mine->defaultResProduction();
  639. addRequiredObject(mine);
  640. }
  641. }
  642. else
  643. {
  644. type = ETemplateZoneType::TREASURE;
  645. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  646. logGlobal->infoStream() << "Skipping this zone cause no player";
  647. }
  648. }
  649. else //no player
  650. {
  651. townId = *RandomGeneratorUtil::nextItem(VLC->townh->getAllowedFactions(), gen->rand);
  652. }
  653. //paint zone with matching terrain
  654. std::vector<int3> tiles;
  655. for (auto tile : tileinfo)
  656. {
  657. tiles.push_back (tile);
  658. }
  659. gen->editManager->getTerrainSelection().setSelection(tiles);
  660. gen->editManager->drawTerrain(VLC->townh->factions[townId]->nativeTerrain, &gen->rand);
  661. logGlobal->infoStream() << "Creating required objects";
  662. for(const auto &obj : requiredObjects)
  663. {
  664. int3 pos;
  665. logGlobal->traceStream() << "Looking for place";
  666. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  667. {
  668. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  669. //TODO CLEANUP!
  670. return false;
  671. }
  672. logGlobal->traceStream() << "Place found";
  673. placeObject(gen, obj.first, pos);
  674. crunchPath (gen, pos, getPos(), id); //make sure pile is connected to the middle of zone
  675. if (obj.second)
  676. {
  677. guardObject (gen, obj.first, obj.second);
  678. }
  679. }
  680. const double res_mindist = 5;
  681. //TODO: just placeholder to chekc for possible locations
  682. do {
  683. int3 pos;
  684. if ( ! findPlaceForTreasurePile(gen, 3, pos))
  685. {
  686. break;
  687. }
  688. createTreasurePile (gen, pos);
  689. } while(true);
  690. auto sel = gen->editManager->getTerrainSelection();
  691. sel.clearSelection();
  692. for (auto tile : tileinfo)
  693. {
  694. //test code - block all the map to show paths clearly
  695. //if (gen->isPossible(tile))
  696. // gen->setOccupied(tile, ETileType::BLOCKED);
  697. if (gen->shouldBeBlocked(tile)) //fill tiles that should be blocked with obstacles
  698. {
  699. auto obj = new CGObjectInstance();
  700. obj->ID = static_cast<Obj>(130);
  701. obj->subID = 0;
  702. placeObject(gen, obj, tile);
  703. }
  704. }
  705. //logGlobal->infoStream() << boost::format("Filling %d with ROCK") % sel.getSelectedItems().size();
  706. //gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->gen);
  707. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  708. return true;
  709. }
  710. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, si32 min_dist, int3 &pos)
  711. {
  712. //si32 min_dist = sqrt(tileinfo.size()/density);
  713. int best_distance = 0;
  714. bool result = false;
  715. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  716. for(auto tile : tileinfo)
  717. {
  718. auto dist = gen->getTile(tile).getNearestObjectDistance();
  719. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  720. {
  721. bool allTilesAvailable = true;
  722. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  723. {
  724. if (!(gen->isPossible(neighbour) || gen->isBlocked(neighbour)))
  725. {
  726. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  727. }
  728. });
  729. if (allTilesAvailable)
  730. {
  731. best_distance = dist;
  732. pos = tile;
  733. result = true;
  734. }
  735. }
  736. }
  737. if (result)
  738. {
  739. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  740. }
  741. return result;
  742. }
  743. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  744. {
  745. //we need object apperance to deduce free tiles
  746. if (obj->appearance.id == Obj::NO_OBJ)
  747. {
  748. auto templates = VLC->dobjinfo->pickCandidates(obj->ID, obj->subID, gen->map->getTile(getPos()).terType);
  749. if (templates.empty())
  750. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %obj->ID %obj->subID %pos));
  751. obj->appearance = templates.front();
  752. }
  753. //si32 min_dist = sqrt(tileinfo.size()/density);
  754. int best_distance = 0;
  755. bool result = false;
  756. si32 w = gen->map->width;
  757. si32 h = gen->map->height;
  758. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  759. auto tilesBlockedByObject = obj->getBlockedOffsets();
  760. for (auto tile : tileinfo)
  761. {
  762. //object must be accessible from at least one surounding tile
  763. bool accessible = false;
  764. for (int x = -1; x < 2; x++)
  765. for (int y = -1; y <2; y++)
  766. {
  767. if (x && y) //check only if object is visitable from another tile
  768. {
  769. int3 offset = obj->getVisitableOffset() + int3(x, y, 0);
  770. if (!vstd::contains(tilesBlockedByObject, offset))
  771. {
  772. int3 nearbyPos = tile + offset;
  773. if (gen->map->isInTheMap(nearbyPos))
  774. {
  775. if (obj->appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  776. accessible = true;
  777. }
  778. }
  779. }
  780. };
  781. if (!accessible)
  782. continue;
  783. auto ti = gen->getTile(tile);
  784. auto dist = ti.getNearestObjectDistance();
  785. //avoid borders
  786. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  787. {
  788. bool allTilesAvailable = true;
  789. for (auto blockingTile : tilesBlockedByObject)
  790. {
  791. int3 t = tile + blockingTile;
  792. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  793. {
  794. allTilesAvailable = false; //if at least one tile is not possible, object can't be placed here
  795. break;
  796. }
  797. }
  798. if (allTilesAvailable)
  799. {
  800. best_distance = dist;
  801. pos = tile;
  802. result = true;
  803. }
  804. }
  805. }
  806. if (result)
  807. {
  808. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  809. }
  810. return result;
  811. }
  812. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  813. {
  814. if (!gen->map->isInTheMap(pos))
  815. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % object->pos()));
  816. object->pos = pos;
  817. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  818. 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()));
  819. for (auto tile : object->getBlockedPos())
  820. {
  821. if (!gen->map->isInTheMap(tile))
  822. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  823. }
  824. if (object->appearance.id == Obj::NO_OBJ)
  825. {
  826. auto templates = VLC->dobjinfo->pickCandidates(object->ID, object->subID, gen->map->getTile(pos).terType);
  827. if (templates.empty())
  828. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") %object->ID %object->subID %pos));
  829. object->appearance = templates.front();
  830. }
  831. gen->map->addBlockVisTiles(object);
  832. gen->editManager->insertObject(object, pos);
  833. logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  834. }
  835. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  836. {
  837. logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  838. checkAndPlaceObject (gen, object, pos);
  839. auto points = object->getBlockedPos();
  840. if (object->isVisitable())
  841. points.insert(pos + object->getVisitableOffset());
  842. points.insert(pos);
  843. for(auto p : points)
  844. {
  845. if (gen->map->isInTheMap(p))
  846. {
  847. gen->setOccupied(p, ETileType::USED);
  848. }
  849. }
  850. for(auto tile : tileinfo)
  851. {
  852. si32 d = pos.dist2d(tile);
  853. gen->setNearestObjectDistance(tile, std::min(d, gen->getNearestObjectDistance(tile)));
  854. }
  855. }
  856. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str)
  857. {
  858. logGlobal->traceStream() << boost::format("Guard object at %d %d") % object->pos.x % object->pos.y;
  859. int3 visitable = object->visitablePos();
  860. std::vector<int3> tiles;
  861. gen->foreach_neighbour(visitable, [&](int3& pos)
  862. {
  863. logGlobal->traceStream() << boost::format("Block at %d %d") % pos.x % pos.y;
  864. if (gen->isPossible(pos))
  865. {
  866. tiles.push_back(pos);
  867. };
  868. });
  869. if ( ! tiles.size())
  870. {
  871. logGlobal->infoStream() << "Failed";
  872. return false;
  873. }
  874. auto guard_tile = *RandomGeneratorUtil::nextItem(tiles, gen->rand);
  875. if (addMonster (gen, guard_tile, str)) //do not place obstacles around unguarded object
  876. {
  877. for (auto pos : tiles)
  878. gen->setOccupied(pos, ETileType::BLOCKED);
  879. gen->setOccupied (guard_tile, ETileType::USED);
  880. }
  881. else
  882. gen->setOccupied (guard_tile, ETileType::FREE);
  883. return true;
  884. }
  885. ObjectInfo CRmgTemplateZone::getRandomObject (CMapGenerator* gen, ui32 value)
  886. {
  887. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  888. ui32 total = 0;
  889. ui32 minValue = 0.25f * value;
  890. //roulette wheel
  891. for (auto oi : possibleObjects)
  892. {
  893. if (oi.value >= minValue && oi.value <= value)
  894. {
  895. //TODO: check place for non-removable object
  896. //problem: we need at least template for the object that does not yet exist
  897. total += oi.probability;
  898. tresholds.push_back (std::make_pair (total, oi));
  899. }
  900. }
  901. //TODO: generate pandora box with gold if the value is very high
  902. if (tresholds.empty())
  903. {
  904. ObjectInfo oi;
  905. if (minValue > 20000) //we don't have object valuable enough
  906. {
  907. oi.generateObject = [minValue]() -> CGObjectInstance *
  908. {
  909. auto obj = new CGPandoraBox();
  910. obj->ID = Obj::PANDORAS_BOX;
  911. obj->subID = 0;
  912. obj->resources[Res::GOLD] = minValue;
  913. return obj;
  914. };
  915. oi.value = minValue;
  916. oi.probability = 0;
  917. }
  918. else
  919. {
  920. oi.generateObject = [gen]() -> CGObjectInstance *
  921. {
  922. return nullptr;
  923. };
  924. oi.value = 0;
  925. oi.probability = 0;
  926. }
  927. return oi;
  928. }
  929. int r = gen->rand.nextInt (1, total);
  930. for (auto t : tresholds)
  931. {
  932. if (r <= t.first)
  933. return t.second;
  934. }
  935. }
  936. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  937. {
  938. //TODO: move typical objects to config
  939. ObjectInfo oi;
  940. static const Res::ERes preciousRes[] = {Res::ERes::CRYSTAL, Res::ERes::GEMS, Res::ERes::MERCURY, Res::ERes::SULFUR};
  941. for (int i = 0; i < 4; i++)
  942. {
  943. oi.generateObject = [i, gen]() -> CGObjectInstance *
  944. {
  945. auto obj = new CGResource();
  946. obj->ID = Obj::RESOURCE;
  947. obj->subID = static_cast<si32>(preciousRes[i]);
  948. obj->amount = 0;
  949. return obj;
  950. };
  951. oi.value = 1400;
  952. oi.probability = 300;
  953. possibleObjects.push_back (oi);
  954. }
  955. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  956. for (int i = 0; i < 2; i++)
  957. {
  958. oi.generateObject = [i, gen]() -> CGObjectInstance *
  959. {
  960. auto obj = new CGResource();
  961. obj->ID = Obj::RESOURCE;
  962. obj->subID = static_cast<si32>(woodOre[i]);
  963. obj->amount = 0;
  964. return obj;
  965. };
  966. oi.value = 1400;
  967. oi.probability = 300;
  968. possibleObjects.push_back (oi);
  969. }
  970. oi.generateObject = [gen]() -> CGObjectInstance *
  971. {
  972. auto obj = new CGResource();
  973. obj->ID = Obj::RESOURCE;
  974. obj->subID = static_cast<si32>(Res::ERes::GOLD);
  975. obj->amount = 0;
  976. return obj;
  977. };
  978. oi.value = 750;
  979. oi.probability = 300;
  980. possibleObjects.push_back (oi);
  981. oi.generateObject = [gen]() -> CGObjectInstance *
  982. {
  983. auto obj = new CGPickable();
  984. obj->ID = Obj::TREASURE_CHEST;
  985. obj->subID = 0;
  986. return obj;
  987. };
  988. oi.value = 1500;
  989. oi.probability = 1000;
  990. possibleObjects.push_back (oi);
  991. oi.generateObject = [gen]() -> CGObjectInstance *
  992. {
  993. auto obj = new CGArtifact();
  994. obj->ID = Obj::RANDOM_TREASURE_ART;
  995. obj->subID = 0;
  996. auto a = new CArtifactInstance();
  997. gen->map->addNewArtifactInstance(a);
  998. obj->storedArtifact = a;
  999. return obj;
  1000. };
  1001. oi.value = 2000;
  1002. oi.probability = 150;
  1003. possibleObjects.push_back (oi);
  1004. oi.generateObject = [gen]() -> CGObjectInstance *
  1005. {
  1006. auto obj = new CGArtifact();
  1007. obj->ID = Obj::RANDOM_MINOR_ART;
  1008. obj->subID = 0;
  1009. auto a = new CArtifactInstance();
  1010. gen->map->addNewArtifactInstance(a);
  1011. obj->storedArtifact = a;
  1012. return obj;
  1013. };
  1014. oi.value = 5000;
  1015. oi.probability = 150;
  1016. possibleObjects.push_back (oi);
  1017. oi.generateObject = [gen]() -> CGObjectInstance *
  1018. {
  1019. auto obj = new CGArtifact();
  1020. obj->ID = Obj::RANDOM_MAJOR_ART;
  1021. obj->subID = 0;
  1022. auto a = new CArtifactInstance();
  1023. gen->map->addNewArtifactInstance(a);
  1024. obj->storedArtifact = a;
  1025. return obj;
  1026. };
  1027. oi.value = 10000;
  1028. oi.probability = 150;
  1029. possibleObjects.push_back (oi);
  1030. oi.generateObject = [gen]() -> CGObjectInstance *
  1031. {
  1032. auto obj = new CGArtifact();
  1033. obj->ID = Obj::RANDOM_RELIC_ART;
  1034. obj->subID = 0;
  1035. auto a = new CArtifactInstance();
  1036. gen->map->addNewArtifactInstance(a);
  1037. obj->storedArtifact = a;
  1038. return obj;
  1039. };
  1040. oi.value = 20000;
  1041. oi.probability = 150;
  1042. possibleObjects.push_back (oi);
  1043. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1044. for (int i = 0; i < 5; i++)
  1045. {
  1046. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1047. {
  1048. auto obj = new CGArtifact();
  1049. obj->ID = Obj::SPELL_SCROLL;
  1050. obj->subID = 0;
  1051. std::vector<SpellID> out;
  1052. //TODO: unify with cb->getAllowedSpells?
  1053. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1054. {
  1055. const CSpell *spell = SpellID(i).toSpell();
  1056. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1057. {
  1058. out.push_back(spell->id);
  1059. }
  1060. }
  1061. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1062. gen->map->addNewArtifactInstance(a);
  1063. obj->storedArtifact = a;
  1064. return obj;
  1065. };
  1066. oi.value = scrollValues[i];
  1067. oi.probability = 30;
  1068. possibleObjects.push_back (oi);
  1069. }
  1070. //non-removable object for test
  1071. //oi.generateObject = [gen]() -> CGObjectInstance *
  1072. //{
  1073. // auto obj = new CGMagicWell();
  1074. // obj->ID = Obj::MAGIC_WELL;
  1075. // obj->subID = 0;
  1076. // return obj;
  1077. //};
  1078. //oi.value = 250;
  1079. //oi.probability = 100;
  1080. //possibleObjects.push_back (oi);
  1081. //oi.generateObject = [gen]() -> CGObjectInstance *
  1082. //{
  1083. // auto obj = new CGObelisk();
  1084. // obj->ID = Obj::OBELISK;
  1085. // obj->subID = 0;
  1086. // return obj;
  1087. //};
  1088. //oi.value = 3500;
  1089. //oi.probability = 200;
  1090. //possibleObjects.push_back (oi);
  1091. //oi.generateObject = [gen]() -> CGObjectInstance *
  1092. //{
  1093. // auto obj = new CBank();
  1094. // obj->ID = Obj::CREATURE_BANK;
  1095. // obj->subID = 5; //naga bank
  1096. // return obj;
  1097. //};
  1098. //oi.value = 3000;
  1099. //oi.probability = 100;
  1100. //possibleObjects.push_back (oi);
  1101. }