ObjectManager.cpp 24 KB

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