CRmgTemplateZone.cpp 32 KB

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