2
0

ObjectManager.cpp 23 KB

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