ObjectManager.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. * ObjectManager.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 "ObjectManager.h"
  12. #include "../CMapGenerator.h"
  13. #include "../TileInfo.h"
  14. #include "../RmgMap.h"
  15. #include "RoadPlacer.h"
  16. #include "RiverPlacer.h"
  17. #include "WaterAdopter.h"
  18. #include "ConnectionsPlacer.h"
  19. #include "TownPlacer.h"
  20. #include "MinePlacer.h"
  21. #include "QuestArtifactPlacer.h"
  22. #include "../../CCreatureHandler.h"
  23. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  24. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  25. #include "../../mapObjects/CGCreature.h"
  26. #include "../../mapping/CMap.h"
  27. #include "../../mapping/CMapEditManager.h"
  28. #include "../Functions.h"
  29. #include "../RmgObject.h"
  30. #include <vstd/RNG.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void ObjectManager::process()
  33. {
  34. zone.fractalize();
  35. createRequiredObjects();
  36. }
  37. void ObjectManager::init()
  38. {
  39. DEPENDENCY(WaterAdopter);
  40. //Monoliths can be placed by other zone, too
  41. // Consider only connected zones
  42. auto id = zone.getId();
  43. std::set<TRmgTemplateZoneId> connectedZones;
  44. for(auto c : map.getMapGenOptions().getMapTemplate()->getConnectedZoneIds())
  45. {
  46. // Only consider connected zones
  47. if (c.getZoneA() == id || c.getZoneB() == id)
  48. {
  49. connectedZones.insert(c.getZoneA());
  50. connectedZones.insert(c.getZoneB());
  51. }
  52. }
  53. auto zones = map.getZones();
  54. for (auto zoneId : connectedZones)
  55. {
  56. auto * cp = zones.at(zoneId)->getModificator<ConnectionsPlacer>();
  57. if (cp)
  58. {
  59. dependency(cp);
  60. }
  61. }
  62. DEPENDENCY(TownPlacer); //Only secondary towns
  63. DEPENDENCY(MinePlacer);
  64. POSTFUNCTION(RoadPlacer);
  65. createDistancesPriorityQueue();
  66. }
  67. void ObjectManager::createDistancesPriorityQueue()
  68. {
  69. const auto tiles = zone.areaPossible()->getTilesVector();
  70. RecursiveLock lock(externalAccessMutex);
  71. tilesByDistance.clear();
  72. for(const auto & tile : tiles)
  73. {
  74. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  75. }
  76. }
  77. void ObjectManager::addRequiredObject(const RequiredObjectInfo & info)
  78. {
  79. RecursiveLock lock(externalAccessMutex);
  80. requiredObjects.emplace_back(info);
  81. }
  82. void ObjectManager::addCloseObject(const RequiredObjectInfo & info)
  83. {
  84. RecursiveLock lock(externalAccessMutex);
  85. closeObjects.emplace_back(info);
  86. }
  87. void ObjectManager::addNearbyObject(const RequiredObjectInfo & info)
  88. {
  89. RecursiveLock lock(externalAccessMutex);
  90. nearbyObjects.emplace_back(info);
  91. }
  92. void ObjectManager::updateDistances(const rmg::Object & obj)
  93. {
  94. updateDistances([obj](const int3& tile) -> ui32
  95. {
  96. return obj.getArea().distanceSqr(tile); //optimization, only relative distance is interesting
  97. });
  98. }
  99. void ObjectManager::updateDistances(const int3 & pos)
  100. {
  101. updateDistances([pos](const int3& tile) -> ui32
  102. {
  103. return pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  104. });
  105. }
  106. void ObjectManager::updateDistances(std::function<ui32(const int3 & tile)> distanceFunction)
  107. {
  108. // Workaround to avoid deadlock when accessed from other zone
  109. RecursiveLock lock(zone.areaMutex, boost::try_to_lock);
  110. if (!lock.owns_lock())
  111. {
  112. // Unsolvable problem of mutual access
  113. return;
  114. }
  115. const auto tiles = zone.areaPossible()->getTilesVector();
  116. //RecursiveLock lock(externalAccessMutex);
  117. tilesByDistance.clear();
  118. for (const auto & tile : tiles) //don't need to mark distance for not possible tiles
  119. {
  120. ui32 d = distanceFunction(tile);
  121. map.setNearestObjectDistance(tile, std::min(static_cast<float>(d), map.getNearestObjectDistance(tile)));
  122. tilesByDistance.push(std::make_pair(tile, map.getNearestObjectDistance(tile)));
  123. }
  124. }
  125. const rmg::Area & ObjectManager::getVisitableArea() const
  126. {
  127. RecursiveLock lock(externalAccessMutex);
  128. return objectsVisitableArea;
  129. }
  130. std::vector<CGObjectInstance*> ObjectManager::getMines() const
  131. {
  132. std::vector<CGObjectInstance*> mines;
  133. RecursiveLock lock(externalAccessMutex);
  134. for(auto * object : objects)
  135. {
  136. if (object->ID == Obj::MINE)
  137. {
  138. mines.push_back(object);
  139. }
  140. }
  141. return mines;
  142. }
  143. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, const std::function<float(const int3)> & weightFunction, OptimizeType optimizer) const
  144. {
  145. float bestWeight = 0.f;
  146. int3 result(-1, -1, -1);
  147. //Blocked area might not cover object position if it has an offset from (0,0)
  148. auto outsideTheMap = [this, &obj]() -> bool
  149. {
  150. for (const auto& oi : obj.instances())
  151. {
  152. if (!map.isOnMap(oi->getPosition(true)))
  153. {
  154. return true;
  155. }
  156. }
  157. return false;
  158. };
  159. if(optimizer & OptimizeType::DISTANCE)
  160. {
  161. // Do not add or remove tiles while we iterate on them
  162. //RecursiveLock lock(externalAccessMutex);
  163. auto open = tilesByDistance;
  164. while(!open.empty())
  165. {
  166. auto node = open.top();
  167. open.pop();
  168. int3 tile = node.first;
  169. if(!searchArea.contains(tile))
  170. continue;
  171. obj.setPosition(tile);
  172. if (obj.getVisibleTop().y < 0)
  173. continue;
  174. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  175. continue;
  176. if (outsideTheMap())
  177. continue;
  178. float weight = weightFunction(tile);
  179. if(weight > bestWeight)
  180. {
  181. bestWeight = weight;
  182. result = tile;
  183. if(!(optimizer & OptimizeType::WEIGHT))
  184. break;
  185. }
  186. }
  187. }
  188. else
  189. {
  190. for(const auto & tile : searchArea.getTilesVector())
  191. {
  192. obj.setPosition(tile);
  193. if (obj.getVisibleTop().y < 0)
  194. continue;
  195. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  196. continue;
  197. if (outsideTheMap())
  198. continue;
  199. float weight = weightFunction(tile);
  200. if(weight > bestWeight)
  201. {
  202. bestWeight = weight;
  203. result = tile;
  204. if(!(optimizer & OptimizeType::WEIGHT))
  205. break;
  206. }
  207. }
  208. }
  209. if(result.valid())
  210. obj.setPosition(result);
  211. return result;
  212. }
  213. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, OptimizeType optimizer) const
  214. {
  215. return findPlaceForObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  216. {
  217. auto ti = map.getTileInfo(tile);
  218. float dist = ti.getNearestObjectDistance();
  219. if(dist < min_dist)
  220. return -1.f;
  221. for(const auto & t : obj.getArea().getTilesVector())
  222. {
  223. auto localDist = map.getTileInfo(t).getNearestObjectDistance();
  224. if (localDist < min_dist)
  225. {
  226. return -1.f;
  227. }
  228. else
  229. {
  230. vstd::amin(dist, localDist); //Evaluate object tile which will be closest to another object
  231. }
  232. }
  233. return dist;
  234. }, optimizer);
  235. }
  236. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, bool isGuarded, bool onlyStraight, OptimizeType optimizer) const
  237. {
  238. return placeAndConnectObject(searchArea, obj, [this, min_dist, &obj](const int3 & tile)
  239. {
  240. float bestDistance = 10e9;
  241. for(const auto & t : obj.getArea().getTilesVector())
  242. {
  243. float distance = map.getTileInfo(t).getNearestObjectDistance();
  244. if(distance < min_dist)
  245. return -1.f;
  246. else
  247. vstd::amin(bestDistance, distance);
  248. }
  249. rmg::Area perimeter;
  250. rmg::Area areaToBlock;
  251. if (obj.isGuarded())
  252. {
  253. auto guardedArea = obj.instances().back()->getAccessibleArea();
  254. guardedArea.add(obj.instances().back()->getVisitablePosition());
  255. areaToBlock = obj.getAccessibleArea(true);
  256. areaToBlock.subtract(guardedArea);
  257. if (!areaToBlock.empty())
  258. {
  259. perimeter = areaToBlock;
  260. perimeter.unite(areaToBlock.getBorderOutside());
  261. //We could have added border around guard
  262. perimeter.subtract(guardedArea);
  263. }
  264. }
  265. else
  266. {
  267. perimeter = obj.getArea();
  268. perimeter.subtract(obj.getAccessibleArea());
  269. if (!perimeter.empty())
  270. {
  271. perimeter.unite(perimeter.getBorderOutside());
  272. perimeter.subtract(obj.getAccessibleArea());
  273. }
  274. }
  275. //Check if perimeter of the object intersects with more than one blocked areas
  276. auto tiles = perimeter.getTiles();
  277. vstd::erase_if(tiles, [this](const int3& tile) -> bool
  278. {
  279. //Out-of-map area also is an obstacle
  280. if (!map.isOnMap(tile))
  281. return false;
  282. return !(map.isBlocked(tile) || map.isUsed(tile));
  283. });
  284. if (!tiles.empty())
  285. {
  286. rmg::Area border(tiles);
  287. border.subtract(areaToBlock);
  288. if (!border.connected())
  289. {
  290. //We don't want to connect two blocked areas to create impassable obstacle
  291. return -1.f;
  292. }
  293. }
  294. return bestDistance;
  295. }, isGuarded, onlyStraight, optimizer);
  296. }
  297. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, const std::function<float(const int3)> & weightFunction, bool isGuarded, bool onlyStraight, OptimizeType optimizer) const
  298. {
  299. int3 pos;
  300. auto possibleArea = searchArea;
  301. auto cachedArea = zone.areaPossible() + zone.freePaths();
  302. while(true)
  303. {
  304. pos = findPlaceForObject(possibleArea, obj, weightFunction, optimizer);
  305. if(!pos.valid())
  306. {
  307. return rmg::Path::invalid();
  308. }
  309. possibleArea.erase(pos); //do not place again at this point
  310. auto accessibleArea = obj.getAccessibleArea(isGuarded) * cachedArea;
  311. //we should exclude tiles which will be covered
  312. if(isGuarded)
  313. {
  314. const auto & guardedArea = obj.instances().back()->getAccessibleArea();
  315. accessibleArea.intersect(guardedArea);
  316. accessibleArea.add(obj.instances().back()->getPosition(true));
  317. }
  318. rmg::Area subArea;
  319. if (isGuarded)
  320. {
  321. const auto & guardedArea = obj.instances().back()->getAccessibleArea();
  322. const auto & unguardedArea = obj.getAccessibleArea(isGuarded);
  323. subArea = cachedArea.getSubarea([guardedArea, unguardedArea, obj](const int3 & t)
  324. {
  325. if(unguardedArea.contains(t) && !guardedArea.contains(t))
  326. return false;
  327. //guard position is always target
  328. if(obj.instances().back()->getPosition(true) == t)
  329. return true;
  330. return !obj.getArea().contains(t);
  331. });
  332. }
  333. else
  334. {
  335. subArea = cachedArea.getSubarea([obj](const int3 & t)
  336. {
  337. return !obj.getArea().contains(t);
  338. });
  339. }
  340. auto path = zone.searchPath(accessibleArea, onlyStraight, subArea);
  341. if(path.valid())
  342. {
  343. return path;
  344. }
  345. }
  346. }
  347. bool ObjectManager::createMonoliths()
  348. {
  349. // Special case for Junction zone only
  350. logGlobal->trace("Creating Monoliths");
  351. for(const auto & objInfo : requiredObjects)
  352. {
  353. if (objInfo.obj->ID != Obj::MONOLITH_TWO_WAY)
  354. {
  355. continue;
  356. }
  357. rmg::Object rmgObject(*objInfo.obj);
  358. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  359. bool guarded = addGuard(rmgObject, objInfo.guardStrength, true);
  360. Zone::Lock lock(zone.areaMutex);
  361. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  362. if(!path.valid())
  363. {
  364. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  365. return false;
  366. }
  367. // Once it can be created, replace with curved path
  368. auto costFunction = rmg::Path::createCurvedCostFunction(zone.area()->getBorder());
  369. rmg::Path curvedPath(zone.areaPossible() + zone.freePaths());
  370. path = curvedPath.search(rmgObject.getVisitablePosition(), true, costFunction);
  371. zone.connectPath(path);
  372. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  373. }
  374. vstd::erase_if(requiredObjects, [](const auto & objInfo)
  375. {
  376. return objInfo.obj->ID == Obj::MONOLITH_TWO_WAY;
  377. });
  378. return true;
  379. }
  380. bool ObjectManager::createRequiredObjects()
  381. {
  382. logGlobal->trace("Creating required objects");
  383. RecursiveLock lock(externalAccessMutex); //In case someone adds more objects
  384. for(const auto & objInfo : requiredObjects)
  385. {
  386. rmg::Object rmgObject(*objInfo.obj);
  387. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  388. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  389. Zone::Lock lock(zone.areaMutex);
  390. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  391. if(!path.valid())
  392. {
  393. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  394. return false;
  395. }
  396. if (objInfo.createRoad)
  397. {
  398. // Once valid path can be created, replace with curved path
  399. auto costFunction = rmg::Path::createCurvedCostFunction(zone.area()->getBorder());
  400. auto pathArea = zone.areaPossible() + zone.freePaths();
  401. rmg::Path curvedPath(pathArea);
  402. curvedPath.connect(zone.freePaths().get());
  403. curvedPath = curvedPath.search(rmgObject.getVisitablePosition(), false, costFunction);
  404. if (curvedPath.valid())
  405. {
  406. path = curvedPath;
  407. }
  408. else
  409. {
  410. logGlobal->warn("Failed to create curved path for required object at %s", rmgObject.getPosition().toString());
  411. }
  412. }
  413. zone.connectPath(path);
  414. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  415. for(const auto & nearby : nearbyObjects)
  416. {
  417. if(nearby.nearbyTarget != nearby.obj)
  418. continue;
  419. rmg::Object rmgNearObject(*nearby.obj);
  420. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  421. possibleArea.intersect(zone.areaPossible().get());
  422. if(possibleArea.empty())
  423. {
  424. rmgNearObject.clear();
  425. continue;
  426. }
  427. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), zone.getRand()));
  428. placeObject(rmgNearObject, false, false, nearby.createRoad);
  429. }
  430. }
  431. for(const auto & objInfo : closeObjects)
  432. {
  433. Zone::Lock lock(zone.areaMutex);
  434. rmg::Object rmgObject(*objInfo.obj);
  435. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  436. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  437. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject,
  438. [this, &rmgObject](const int3 & tile)
  439. {
  440. float dist = rmgObject.getArea().distanceSqr(zone.getPos());
  441. dist *= (dist > 12.f * 12.f) ? 10.f : 1.f; //tiles closer 12 are preferable
  442. dist = 1000000.f - dist; //some big number
  443. return dist + map.getNearestObjectDistance(tile);
  444. }, guarded, false, OptimizeType::WEIGHT);
  445. if(!path.valid())
  446. {
  447. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  448. return false;
  449. }
  450. zone.connectPath(path);
  451. placeObject(rmgObject, guarded, true);
  452. }
  453. for(const auto & nearby : nearbyObjects)
  454. {
  455. auto * targetObject = nearby.nearbyTarget;
  456. if (!targetObject || !targetObject->appearance)
  457. {
  458. continue;
  459. }
  460. rmg::Object rmgNearObject(*nearby.obj);
  461. std::set<int3> blockedArea = targetObject->getBlockedPos();
  462. rmg::Area areaForObject(rmg::Area(rmg::Tileset(blockedArea.begin(), blockedArea.end())).getBorderOutside());
  463. areaForObject.intersect(zone.areaPossible().get());
  464. if(areaForObject.empty())
  465. {
  466. rmgNearObject.clear();
  467. continue;
  468. }
  469. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(areaForObject.getTiles(), zone.getRand()));
  470. placeObject(rmgNearObject, false, false);
  471. auto path = zone.searchPath(rmgNearObject.getVisitablePosition(), false);
  472. if (path.valid())
  473. {
  474. zone.connectPath(path);
  475. }
  476. else
  477. {
  478. for (auto* instance : rmgNearObject.instances())
  479. {
  480. logGlobal->error("Failed to connect nearby object %s at %s",
  481. instance->object().getObjectName(), instance->getPosition(true).toString());
  482. mapProxy->removeObject(&instance->object());
  483. }
  484. }
  485. }
  486. //create object on specific positions
  487. //TODO: implement guards
  488. for (const auto &objInfo : instantObjects) //Unused ATM
  489. {
  490. rmg::Object rmgObject(*objInfo.obj);
  491. rmgObject.setPosition(objInfo.pos);
  492. placeObject(rmgObject, false, false);
  493. }
  494. requiredObjects.clear();
  495. closeObjects.clear();
  496. nearbyObjects.clear();
  497. instantObjects.clear();
  498. return true;
  499. }
  500. void ObjectManager::placeObject(rmg::Object & object, bool guarded, bool updateDistance, bool createRoad/* = false*/)
  501. {
  502. if (object.instances().size() == 1 && object.instances().front()->object().ID == Obj::MONSTER)
  503. {
  504. //Fix for HoTA offset - lonely guards
  505. auto monster = object.instances().front();
  506. if (!monster->object().appearance)
  507. {
  508. //Needed to determine visitable offset
  509. monster->setAnyTemplate(zone.getRand());
  510. }
  511. object.getPosition();
  512. auto visitableOffset = monster->object().getVisitableOffset();
  513. auto fixedPos = monster->getPosition(true) + visitableOffset;
  514. //Do not place guard outside the map
  515. vstd::abetween(fixedPos.x, visitableOffset.x, map.width() - 1);
  516. vstd::abetween(fixedPos.y, visitableOffset.y, map.height() - 1);
  517. int3 parentOffset = monster->getPosition(true) - monster->getPosition(false);
  518. monster->setPosition(fixedPos - parentOffset);
  519. }
  520. object.finalize(map, zone.getRand());
  521. {
  522. Zone::Lock lock(zone.areaMutex);
  523. zone.areaPossible()->subtract(object.getArea());
  524. bool keepVisitable = zone.freePaths()->contains(object.getVisitablePosition());
  525. zone.freePaths()->subtract(object.getArea()); //just to avoid areas overlapping
  526. if(keepVisitable)
  527. zone.freePaths()->add(object.getVisitablePosition());
  528. zone.areaUsed()->unite(object.getArea());
  529. zone.areaUsed()->erase(object.getVisitablePosition());
  530. if(guarded) //We assume the monster won't be guarded
  531. {
  532. auto guardedArea = object.instances().back()->getAccessibleArea();
  533. guardedArea.add(object.instances().back()->getVisitablePosition());
  534. auto areaToBlock = object.getAccessibleArea(true);
  535. areaToBlock.subtract(guardedArea);
  536. zone.areaPossible()->subtract(areaToBlock);
  537. for(const auto & i : areaToBlock.getTilesVector())
  538. if(map.isOnMap(i) && map.isPossible(i))
  539. map.setOccupied(i, ETileType::BLOCKED);
  540. }
  541. }
  542. if (updateDistance)
  543. {
  544. //Update distances in every adjacent zone (including this one) in case of wide connection
  545. std::set<TRmgTemplateZoneId> adjacentZones;
  546. auto objectArea = object.getArea();
  547. objectArea.unite(objectArea.getBorderOutside());
  548. for (auto tile : objectArea.getTilesVector())
  549. {
  550. if (map.isOnMap(tile))
  551. {
  552. adjacentZones.insert(map.getZoneID(tile));
  553. }
  554. }
  555. for (auto id : adjacentZones)
  556. {
  557. auto otherZone = map.getZones().at(id);
  558. if ((otherZone->getType() == ETemplateZoneType::WATER) == (zone.getType() == ETemplateZoneType::WATER))
  559. {
  560. // Do not update other zone if only one is water
  561. auto manager = otherZone->getModificator<ObjectManager>();
  562. if (manager)
  563. {
  564. manager->updateDistances(object);
  565. }
  566. }
  567. }
  568. }
  569. // TODO: Add multiple tiles in one operation to avoid multiple invalidation
  570. for(auto * instance : object.instances())
  571. {
  572. objectsVisitableArea.add(instance->getVisitablePosition());
  573. objects.push_back(&instance->object());
  574. if(auto * rp = zone.getModificator<RoadPlacer>())
  575. {
  576. if (instance->object().blockVisit && !instance->object().removable)
  577. {
  578. //Cannot be trespassed (Corpse)
  579. continue;
  580. }
  581. else if(instance->object().appearance->isVisitableFromTop())
  582. {
  583. //Passable objects
  584. rp->areaForRoads().add(instance->getVisitablePosition());
  585. }
  586. else if(!instance->object().appearance->isVisitableFromTop())
  587. {
  588. // Do not route road behind visitable tile
  589. auto borderAbove = instance->getBorderAbove();
  590. rp->areaIsolated().unite(borderAbove);
  591. }
  592. if (object.isGuarded())
  593. {
  594. rp->areaVisitable().add(instance->getVisitablePosition());
  595. }
  596. }
  597. switch (instance->object().ID.toEnum())
  598. {
  599. case Obj::RANDOM_TREASURE_ART:
  600. case Obj::RANDOM_MINOR_ART: //In OH3 quest artifacts have higher value than normal arts
  601. case Obj::RANDOM_RESOURCE:
  602. {
  603. if (auto * qap = zone.getModificator<QuestArtifactPlacer>())
  604. {
  605. qap->rememberPotentialArtifactToReplace(&instance->object());
  606. }
  607. break;
  608. }
  609. default:
  610. break;
  611. }
  612. }
  613. if (createRoad)
  614. {
  615. if (auto* m = zone.getModificator<RoadPlacer>())
  616. m->addRoadNode(object.instances().front()->getVisitablePosition());
  617. }
  618. //TODO: Add road node to these objects:
  619. /*
  620. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  621. case Obj::RANDOM_TOWN:
  622. case Obj::MONOLITH_ONE_WAY_EXIT:
  623. */
  624. switch(object.instances().front()->object().ID.toEnum())
  625. {
  626. case Obj::WATER_WHEEL:
  627. if (auto* m = zone.getModificator<RiverPlacer>())
  628. m->addRiverNode(object.instances().front()->getVisitablePosition());
  629. break;
  630. default:
  631. break;
  632. }
  633. }
  634. CGCreature * ObjectManager::chooseGuard(si32 strength, bool zoneGuard)
  635. {
  636. //precalculate actual (randomized) monster strength based on this post
  637. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  638. if(!zoneGuard && zone.monsterStrength == EMonsterStrength::ZONE_NONE)
  639. return nullptr; //no guards inside this zone except for zone guards
  640. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  641. int monsterStrength = (zoneGuard ? 0 : zone.monsterStrength - EMonsterStrength::ZONE_NORMAL) + mapMonsterStrength - 1; //array index from 0 to 4
  642. static const std::array<int, 5> value1{2500, 1500, 1000, 500, 0};
  643. static const std::array<int, 5> value2{7500, 7500, 7500, 5000, 5000};
  644. static const std::array<float, 5> multiplier1{0.5, 0.75, 1.0, 1.5, 1.5};
  645. static const std::array<float, 5> multiplier2{0.5, 0.75, 1.0, 1.0, 1.5};
  646. int strength1 = static_cast<int>(std::max(0.f, (strength - value1.at(monsterStrength)) * multiplier1.at(monsterStrength)));
  647. int strength2 = static_cast<int>(std::max(0.f, (strength - value2.at(monsterStrength)) * multiplier2.at(monsterStrength)));
  648. strength = strength1 + strength2;
  649. if (strength < generator.getConfig().minGuardStrength)
  650. return nullptr; //no guard at all
  651. CreatureID creId = CreatureID::NONE;
  652. int amount = 0;
  653. std::vector<CreatureID> possibleCreatures;
  654. for(auto const & cre : VLC->creh->objects)
  655. {
  656. if(cre->special)
  657. continue;
  658. if(!cre->getAIValue()) //bug #2681
  659. continue;
  660. if(!vstd::contains(zone.getMonsterTypes(), cre->getFactionID()))
  661. continue;
  662. if((static_cast<si32>(cre->getAIValue() * (cre->ammMin + cre->ammMax) / 2) < strength) && (strength < static_cast<si32>(cre->getAIValue()) * 100)) //at least one full monster. size between average size of given stack and 100
  663. {
  664. possibleCreatures.push_back(cre->getId());
  665. }
  666. }
  667. if(!possibleCreatures.empty())
  668. {
  669. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, zone.getRand());
  670. amount = strength / creId.toEntity(VLC)->getAIValue();
  671. if (amount >= 4)
  672. amount = static_cast<int>(amount * zone.getRand().nextDouble(0.75, 1.25));
  673. }
  674. else //just pick any available creature
  675. {
  676. creId = CreatureID::AZURE_DRAGON; //Azure Dragon
  677. amount = strength / creId.toEntity(VLC)->getAIValue();
  678. }
  679. auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  680. auto * guard = dynamic_cast<CGCreature *>(guardFactory->create(map.mapInstance->cb, nullptr));
  681. guard->character = CGCreature::HOSTILE;
  682. auto * hlp = new CStackInstance(creId, amount);
  683. //will be set during initialization
  684. guard->putStack(SlotID(0), hlp);
  685. return guard;
  686. }
  687. bool ObjectManager::addGuard(rmg::Object & object, si32 strength, bool zoneGuard)
  688. {
  689. auto * guard = chooseGuard(strength, zoneGuard);
  690. if(!guard)
  691. return false;
  692. // Prefer non-blocking tiles, if any
  693. auto entrableArea = object.getEntrableArea();
  694. if (entrableArea.empty())
  695. {
  696. entrableArea.add(object.getVisitablePosition());
  697. }
  698. rmg::Area entrableBorder = entrableArea.getBorderOutside();
  699. auto accessibleArea = object.getAccessibleArea();
  700. accessibleArea.erase_if([&](const int3 & tile)
  701. {
  702. return !entrableBorder.contains(tile);
  703. });
  704. if(accessibleArea.empty())
  705. {
  706. delete guard;
  707. return false;
  708. }
  709. auto guardTiles = accessibleArea.getTilesVector();
  710. auto guardPos = *std::min_element(guardTiles.begin(), guardTiles.end(), [&object](const int3 & l, const int3 & r)
  711. {
  712. auto p = object.getVisitablePosition();
  713. if(l.y > r.y)
  714. return true;
  715. if(l.y == r.y)
  716. return abs(l.x - p.x) < abs(r.x - p.x);
  717. return false;
  718. });
  719. auto & instance = object.addInstance(*guard);
  720. instance.setAnyTemplate(zone.getRand()); //terrain is irrelevant for monsters, but monsters need some template now
  721. //Fix HoTA monsters with offset template
  722. auto visitableOffset = instance.object().getVisitableOffset();
  723. auto fixedPos = guardPos - object.getPosition() + visitableOffset;
  724. instance.setPosition(fixedPos);
  725. return true;
  726. }
  727. RequiredObjectInfo::RequiredObjectInfo():
  728. obj(nullptr),
  729. nearbyTarget(nullptr),
  730. guardStrength(0),
  731. createRoad(true)
  732. {}
  733. RequiredObjectInfo::RequiredObjectInfo(CGObjectInstance* obj, ui32 guardStrength, bool createRoad, CGObjectInstance* nearbyTarget):
  734. obj(obj),
  735. nearbyTarget(nearbyTarget),
  736. guardStrength(guardStrength),
  737. createRoad(createRoad)
  738. {}
  739. VCMI_LIB_NAMESPACE_END