ObjectManager.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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.areaForRoads();
  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. replaceWithCurvedPath(path, zone, rmgObject.getVisitablePosition());
  369. zone.connectPath(path);
  370. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  371. }
  372. vstd::erase_if(requiredObjects, [](const auto & objInfo)
  373. {
  374. return objInfo.obj->ID == Obj::MONOLITH_TWO_WAY;
  375. });
  376. return true;
  377. }
  378. bool ObjectManager::createRequiredObjects()
  379. {
  380. logGlobal->trace("Creating required objects");
  381. RecursiveLock lock(externalAccessMutex); //In case someone adds more objects
  382. for(const auto & objInfo : requiredObjects)
  383. {
  384. rmg::Object rmgObject(*objInfo.obj);
  385. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  386. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  387. Zone::Lock lock(zone.areaMutex);
  388. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject, 3, guarded, false, OptimizeType::DISTANCE);
  389. if(!path.valid())
  390. {
  391. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  392. return false;
  393. }
  394. if (objInfo.createRoad)
  395. {
  396. // Once valid path can be created, replace with curved path
  397. replaceWithCurvedPath(path, zone, rmgObject.getVisitablePosition());
  398. }
  399. zone.connectPath(path);
  400. placeObject(rmgObject, guarded, true, objInfo.createRoad);
  401. for(const auto & nearby : nearbyObjects)
  402. {
  403. if(nearby.nearbyTarget != nearby.obj)
  404. continue;
  405. rmg::Object rmgNearObject(*nearby.obj);
  406. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  407. possibleArea.intersect(zone.areaPossible().get());
  408. if(possibleArea.empty())
  409. {
  410. rmgNearObject.clear();
  411. continue;
  412. }
  413. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), zone.getRand()));
  414. placeObject(rmgNearObject, false, false, nearby.createRoad);
  415. }
  416. }
  417. for(const auto & objInfo : closeObjects)
  418. {
  419. Zone::Lock lock(zone.areaMutex);
  420. rmg::Object rmgObject(*objInfo.obj);
  421. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  422. bool guarded = addGuard(rmgObject, objInfo.guardStrength, (objInfo.obj->ID == Obj::MONOLITH_TWO_WAY));
  423. auto path = placeAndConnectObject(zone.areaPossible().get(), rmgObject,
  424. [this, &rmgObject](const int3 & tile)
  425. {
  426. float dist = rmgObject.getArea().distanceSqr(zone.getPos());
  427. dist *= (dist > 12.f * 12.f) ? 10.f : 1.f; //tiles closer 12 are preferable
  428. dist = 1000000.f - dist; //some big number
  429. return dist + map.getNearestObjectDistance(tile);
  430. }, guarded, false, OptimizeType::WEIGHT);
  431. if(!path.valid())
  432. {
  433. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  434. return false;
  435. }
  436. zone.connectPath(path);
  437. placeObject(rmgObject, guarded, true);
  438. }
  439. for(const auto & nearby : nearbyObjects)
  440. {
  441. auto * targetObject = nearby.nearbyTarget;
  442. if (!targetObject || !targetObject->appearance)
  443. {
  444. continue;
  445. }
  446. rmg::Object rmgNearObject(*nearby.obj);
  447. std::set<int3> blockedArea = targetObject->getBlockedPos();
  448. rmg::Area areaForObject(rmg::Area(rmg::Tileset(blockedArea.begin(), blockedArea.end())).getBorderOutside());
  449. areaForObject.intersect(zone.areaPossible().get());
  450. if(areaForObject.empty())
  451. {
  452. rmgNearObject.clear();
  453. continue;
  454. }
  455. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(areaForObject.getTiles(), zone.getRand()));
  456. placeObject(rmgNearObject, false, false);
  457. auto path = zone.searchPath(rmgNearObject.getVisitablePosition(), false);
  458. if (path.valid())
  459. {
  460. zone.connectPath(path);
  461. }
  462. else
  463. {
  464. for (auto* instance : rmgNearObject.instances())
  465. {
  466. logGlobal->error("Failed to connect nearby object %s at %s",
  467. instance->object().getObjectName(), instance->getPosition(true).toString());
  468. mapProxy->removeObject(&instance->object());
  469. }
  470. }
  471. }
  472. //create object on specific positions
  473. //TODO: implement guards
  474. for (const auto &objInfo : instantObjects) //Unused ATM
  475. {
  476. rmg::Object rmgObject(*objInfo.obj);
  477. rmgObject.setPosition(objInfo.pos);
  478. placeObject(rmgObject, false, false);
  479. }
  480. requiredObjects.clear();
  481. closeObjects.clear();
  482. nearbyObjects.clear();
  483. instantObjects.clear();
  484. return true;
  485. }
  486. void ObjectManager::placeObject(rmg::Object & object, bool guarded, bool updateDistance, bool createRoad/* = false*/)
  487. {
  488. if (object.instances().size() == 1 && object.instances().front()->object().ID == Obj::MONSTER)
  489. {
  490. //Fix for HoTA offset - lonely guards
  491. auto monster = object.instances().front();
  492. if (!monster->object().appearance)
  493. {
  494. //Needed to determine visitable offset
  495. monster->setAnyTemplate(zone.getRand());
  496. }
  497. object.getPosition();
  498. auto visitableOffset = monster->object().getVisitableOffset();
  499. auto fixedPos = monster->getPosition(true) + visitableOffset;
  500. //Do not place guard outside the map
  501. vstd::abetween(fixedPos.x, visitableOffset.x, map.width() - 1);
  502. vstd::abetween(fixedPos.y, visitableOffset.y, map.height() - 1);
  503. int3 parentOffset = monster->getPosition(true) - monster->getPosition(false);
  504. monster->setPosition(fixedPos - parentOffset);
  505. }
  506. object.finalize(map, zone.getRand());
  507. {
  508. Zone::Lock lock(zone.areaMutex);
  509. zone.areaPossible()->subtract(object.getArea());
  510. bool keepVisitable = zone.freePaths()->contains(object.getVisitablePosition());
  511. zone.freePaths()->subtract(object.getArea()); //just to avoid areas overlapping
  512. if(keepVisitable)
  513. zone.freePaths()->add(object.getVisitablePosition());
  514. zone.areaUsed()->unite(object.getArea());
  515. zone.areaUsed()->erase(object.getVisitablePosition());
  516. if(guarded) //We assume the monster won't be guarded
  517. {
  518. auto guardedArea = object.instances().back()->getAccessibleArea();
  519. guardedArea.add(object.instances().back()->getVisitablePosition());
  520. auto areaToBlock = object.getAccessibleArea(true);
  521. areaToBlock.subtract(guardedArea);
  522. zone.areaPossible()->subtract(areaToBlock);
  523. for(const auto & i : areaToBlock.getTilesVector())
  524. if(map.isOnMap(i) && map.isPossible(i))
  525. map.setOccupied(i, ETileType::BLOCKED);
  526. }
  527. }
  528. if (updateDistance)
  529. {
  530. //Update distances in every adjacent zone (including this one) in case of wide connection
  531. std::set<TRmgTemplateZoneId> adjacentZones;
  532. auto objectArea = object.getArea();
  533. objectArea.unite(objectArea.getBorderOutside());
  534. for (auto tile : objectArea.getTilesVector())
  535. {
  536. if (map.isOnMap(tile))
  537. {
  538. adjacentZones.insert(map.getZoneID(tile));
  539. }
  540. }
  541. for (auto id : adjacentZones)
  542. {
  543. auto otherZone = map.getZones().at(id);
  544. if ((otherZone->getType() == ETemplateZoneType::WATER) == (zone.getType() == ETemplateZoneType::WATER))
  545. {
  546. // Do not update other zone if only one is water
  547. auto manager = otherZone->getModificator<ObjectManager>();
  548. if (manager)
  549. {
  550. manager->updateDistances(object);
  551. }
  552. }
  553. }
  554. }
  555. // TODO: Add multiple tiles in one operation to avoid multiple invalidation
  556. for(auto * instance : object.instances())
  557. {
  558. objectsVisitableArea.add(instance->getVisitablePosition());
  559. objects.push_back(&instance->object());
  560. if(auto * rp = zone.getModificator<RoadPlacer>())
  561. {
  562. if (instance->object().blockVisit && !instance->object().removable)
  563. {
  564. //Cannot be trespassed (Corpse)
  565. continue;
  566. }
  567. else if(instance->object().appearance->isVisitableFromTop())
  568. {
  569. //Passable objects
  570. rp->areaForRoads().add(instance->getVisitablePosition());
  571. }
  572. else if(!instance->object().appearance->isVisitableFromTop())
  573. {
  574. // Do not route road behind visitable tile
  575. auto borderAbove = instance->getBorderAbove();
  576. rp->areaIsolated().unite(borderAbove);
  577. }
  578. if (object.isGuarded())
  579. {
  580. rp->areaVisitable().add(instance->getVisitablePosition());
  581. }
  582. }
  583. switch (instance->object().ID.toEnum())
  584. {
  585. case Obj::RANDOM_TREASURE_ART:
  586. case Obj::RANDOM_MINOR_ART: //In OH3 quest artifacts have higher value than normal arts
  587. case Obj::RANDOM_RESOURCE:
  588. {
  589. if (auto * qap = zone.getModificator<QuestArtifactPlacer>())
  590. {
  591. qap->rememberPotentialArtifactToReplace(&instance->object());
  592. }
  593. break;
  594. }
  595. default:
  596. break;
  597. }
  598. }
  599. if (createRoad)
  600. {
  601. if (auto* m = zone.getModificator<RoadPlacer>())
  602. m->addRoadNode(object.instances().front()->getVisitablePosition());
  603. }
  604. //TODO: Add road node to these objects:
  605. /*
  606. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  607. case Obj::RANDOM_TOWN:
  608. case Obj::MONOLITH_ONE_WAY_EXIT:
  609. */
  610. switch(object.instances().front()->object().ID.toEnum())
  611. {
  612. case Obj::WATER_WHEEL:
  613. if (auto* m = zone.getModificator<RiverPlacer>())
  614. m->addRiverNode(object.instances().front()->getVisitablePosition());
  615. break;
  616. default:
  617. break;
  618. }
  619. }
  620. CGCreature * ObjectManager::chooseGuard(si32 strength, bool zoneGuard)
  621. {
  622. //precalculate actual (randomized) monster strength based on this post
  623. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  624. if(!zoneGuard && zone.monsterStrength == EMonsterStrength::ZONE_NONE)
  625. return nullptr; //no guards inside this zone except for zone guards
  626. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  627. int monsterStrength = (zoneGuard ? 0 : zone.monsterStrength - EMonsterStrength::ZONE_NORMAL) + mapMonsterStrength - 1; //array index from 0 to 4
  628. static const std::array<int, 5> value1{2500, 1500, 1000, 500, 0};
  629. static const std::array<int, 5> value2{7500, 7500, 7500, 5000, 5000};
  630. static const std::array<float, 5> multiplier1{0.5, 0.75, 1.0, 1.5, 1.5};
  631. static const std::array<float, 5> multiplier2{0.5, 0.75, 1.0, 1.0, 1.5};
  632. int strength1 = static_cast<int>(std::max(0.f, (strength - value1.at(monsterStrength)) * multiplier1.at(monsterStrength)));
  633. int strength2 = static_cast<int>(std::max(0.f, (strength - value2.at(monsterStrength)) * multiplier2.at(monsterStrength)));
  634. strength = strength1 + strength2;
  635. if (strength < generator.getConfig().minGuardStrength)
  636. return nullptr; //no guard at all
  637. CreatureID creId = CreatureID::NONE;
  638. int amount = 0;
  639. std::vector<CreatureID> possibleCreatures;
  640. for(auto const & cre : VLC->creh->objects)
  641. {
  642. if(cre->special)
  643. continue;
  644. if(!cre->getAIValue()) //bug #2681
  645. continue;
  646. if(!vstd::contains(zone.getMonsterTypes(), cre->getFactionID()))
  647. continue;
  648. 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
  649. {
  650. possibleCreatures.push_back(cre->getId());
  651. }
  652. }
  653. if(!possibleCreatures.empty())
  654. {
  655. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, zone.getRand());
  656. amount = strength / creId.toEntity(VLC)->getAIValue();
  657. if (amount >= 4)
  658. amount = static_cast<int>(amount * zone.getRand().nextDouble(0.75, 1.25));
  659. }
  660. else //just pick any available creature
  661. {
  662. creId = CreatureID::AZURE_DRAGON; //Azure Dragon
  663. amount = strength / creId.toEntity(VLC)->getAIValue();
  664. }
  665. auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  666. auto * guard = dynamic_cast<CGCreature *>(guardFactory->create(map.mapInstance->cb, nullptr));
  667. guard->character = CGCreature::HOSTILE;
  668. auto * hlp = new CStackInstance(creId, amount);
  669. //will be set during initialization
  670. guard->putStack(SlotID(0), hlp);
  671. return guard;
  672. }
  673. bool ObjectManager::addGuard(rmg::Object & object, si32 strength, bool zoneGuard)
  674. {
  675. auto * guard = chooseGuard(strength, zoneGuard);
  676. if(!guard)
  677. return false;
  678. // Prefer non-blocking tiles, if any
  679. auto entrableArea = object.getEntrableArea();
  680. if (entrableArea.empty())
  681. {
  682. entrableArea.add(object.getVisitablePosition());
  683. }
  684. rmg::Area entrableBorder = entrableArea.getBorderOutside();
  685. auto accessibleArea = object.getAccessibleArea();
  686. accessibleArea.erase_if([&](const int3 & tile)
  687. {
  688. return !entrableBorder.contains(tile);
  689. });
  690. if(accessibleArea.empty())
  691. {
  692. delete guard;
  693. return false;
  694. }
  695. auto guardTiles = accessibleArea.getTilesVector();
  696. auto guardPos = *std::min_element(guardTiles.begin(), guardTiles.end(), [&object](const int3 & l, const int3 & r)
  697. {
  698. auto p = object.getVisitablePosition();
  699. if(l.y > r.y)
  700. return true;
  701. if(l.y == r.y)
  702. return abs(l.x - p.x) < abs(r.x - p.x);
  703. return false;
  704. });
  705. auto & instance = object.addInstance(*guard);
  706. instance.setAnyTemplate(zone.getRand()); //terrain is irrelevant for monsters, but monsters need some template now
  707. //Fix HoTA monsters with offset template
  708. auto visitableOffset = instance.object().getVisitableOffset();
  709. auto fixedPos = guardPos - object.getPosition() + visitableOffset;
  710. instance.setPosition(fixedPos);
  711. return true;
  712. }
  713. RequiredObjectInfo::RequiredObjectInfo():
  714. obj(nullptr),
  715. nearbyTarget(nullptr),
  716. guardStrength(0),
  717. createRoad(true)
  718. {}
  719. RequiredObjectInfo::RequiredObjectInfo(CGObjectInstance* obj, ui32 guardStrength, bool createRoad, CGObjectInstance* nearbyTarget):
  720. obj(obj),
  721. nearbyTarget(nearbyTarget),
  722. guardStrength(guardStrength),
  723. createRoad(createRoad)
  724. {}
  725. VCMI_LIB_NAMESPACE_END