ConnectionsPlacer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * ConnectionsPlacer.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 "ConnectionsPlacer.h"
  12. #include "../CMapGenerator.h"
  13. #include "../RmgMap.h"
  14. #include "../../TerrainHandler.h"
  15. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  16. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  17. #include "../../mapObjects/CGCreature.h"
  18. #include "../../mapping/CMapEditManager.h"
  19. #include "../RmgObject.h"
  20. #include "ObjectManager.h"
  21. #include "../Functions.h"
  22. #include "RoadPlacer.h"
  23. #include "../TileInfo.h"
  24. #include "WaterAdopter.h"
  25. #include "WaterProxy.h"
  26. #include "TownPlacer.h"
  27. #include <vstd/RNG.h>
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. std::pair<Zone::Lock, Zone::Lock> ConnectionsPlacer::lockZones(std::shared_ptr<Zone> otherZone)
  30. {
  31. if (zone.getId() == otherZone->getId())
  32. return {};
  33. while (true)
  34. {
  35. auto lock1 = Zone::Lock(zone.areaMutex, std::try_to_lock);
  36. auto lock2 = Zone::Lock(otherZone->areaMutex, std::try_to_lock);
  37. if (lock1.owns_lock() && lock2.owns_lock())
  38. {
  39. return { std::move(lock1), std::move(lock2) };
  40. }
  41. }
  42. }
  43. void ConnectionsPlacer::process()
  44. {
  45. collectNeighbourZones();
  46. auto diningPhilosophers = [this](std::function<void(const rmg::ZoneConnection&)> f)
  47. {
  48. for (auto& c : dConnections)
  49. {
  50. if (c.getZoneA() == c.getZoneB())
  51. {
  52. // Zone can always be connected to itself, but only by monolith pair
  53. RecursiveLock lock(externalAccessMutex);
  54. if (!vstd::contains(dCompleted, c))
  55. {
  56. placeMonolithConnection(c);
  57. continue;
  58. }
  59. }
  60. auto otherZone = map.getZones().at(c.getZoneB());
  61. auto* cp = otherZone->getModificator<ConnectionsPlacer>();
  62. while (cp)
  63. {
  64. RecursiveLock lock1(externalAccessMutex, std::try_to_lock);
  65. RecursiveLock lock2(cp->externalAccessMutex, std::try_to_lock);
  66. if (lock1.owns_lock() && lock2.owns_lock())
  67. {
  68. if (!vstd::contains(dCompleted, c))
  69. {
  70. f(c);
  71. }
  72. break;
  73. }
  74. }
  75. }
  76. };
  77. diningPhilosophers([this](const rmg::ZoneConnection& c)
  78. {
  79. forcePortalConnection(c);
  80. });
  81. diningPhilosophers([this](const rmg::ZoneConnection& c)
  82. {
  83. selfSideDirectConnection(c);
  84. });
  85. createBorder();
  86. diningPhilosophers([this](const rmg::ZoneConnection& c)
  87. {
  88. selfSideIndirectConnection(c);
  89. });
  90. }
  91. void ConnectionsPlacer::init()
  92. {
  93. DEPENDENCY(WaterAdopter);
  94. DEPENDENCY(TownPlacer);
  95. POSTFUNCTION(RoadPlacer);
  96. POSTFUNCTION(ObjectManager);
  97. auto id = zone.getId();
  98. for(auto c : map.getMapGenOptions().getMapTemplate()->getConnectedZoneIds())
  99. {
  100. // Only consider connected zones
  101. if (c.getZoneA() == id || c.getZoneB() == id)
  102. {
  103. addConnection(c);
  104. }
  105. }
  106. }
  107. void ConnectionsPlacer::addConnection(const rmg::ZoneConnection& connection)
  108. {
  109. dConnections.push_back(connection);
  110. }
  111. void ConnectionsPlacer::otherSideConnection(const rmg::ZoneConnection & connection)
  112. {
  113. dCompleted.push_back(connection);
  114. }
  115. void ConnectionsPlacer::forcePortalConnection(const rmg::ZoneConnection & connection)
  116. {
  117. // This should always succeed
  118. if (connection.getConnectionType() == rmg::EConnectionType::FORCE_PORTAL)
  119. {
  120. placeMonolithConnection(connection);
  121. }
  122. }
  123. void ConnectionsPlacer::selfSideDirectConnection(const rmg::ZoneConnection & connection)
  124. {
  125. bool success = false;
  126. auto otherZoneId = connection.getOtherZoneId(zone.getId());
  127. auto & otherZone = map.getZones().at(otherZoneId);
  128. bool createRoad = shouldGenerateRoad(connection);
  129. //1. Try to make direct connection
  130. //Do if it's not prohibited by terrain settings
  131. const auto * ourTerrain = LIBRARY->terrainTypeHandler->getById(zone.getTerrainType());
  132. const auto * otherTerrain = LIBRARY->terrainTypeHandler->getById(otherZone->getTerrainType());
  133. bool directProhibited = vstd::contains(ourTerrain->prohibitTransitions, otherZone->getTerrainType())
  134. || vstd::contains(otherTerrain->prohibitTransitions, zone.getTerrainType());
  135. auto lock = lockZones(otherZone);
  136. auto directConnectionIterator = dNeighbourZones.find(otherZoneId);
  137. if (directConnectionIterator != dNeighbourZones.end())
  138. {
  139. if (connection.getConnectionType() == rmg::EConnectionType::WIDE)
  140. {
  141. for (auto borderPos : directConnectionIterator->second)
  142. {
  143. //TODO: Refactor common code with direct connection
  144. int3 potentialPos = zone.areaPossible()->nearest(borderPos);
  145. assert(borderPos != potentialPos);
  146. auto safetyGap = rmg::Area({ potentialPos });
  147. safetyGap.unite(safetyGap.getBorderOutside());
  148. safetyGap.intersect(zone.areaPossible().get());
  149. if (!safetyGap.empty())
  150. {
  151. safetyGap.intersect(otherZone->areaPossible().get());
  152. if (safetyGap.empty())
  153. {
  154. rmg::Area border(zone.area()->getBorder());
  155. border.unite(otherZone->area()->getBorder());
  156. auto costFunction = [&border](const int3& s, const int3& d)
  157. {
  158. return 1.f / (1.f + border.distanceSqr(d));
  159. };
  160. auto ourArea = zone.areaForRoads();
  161. auto theirArea = otherZone->areaForRoads();
  162. theirArea.add(potentialPos);
  163. rmg::Path ourPath(ourArea);
  164. rmg::Path theirPath(theirArea);
  165. ourPath.connect(zone.freePaths().get());
  166. ourPath = ourPath.search(potentialPos, true, costFunction);
  167. theirPath.connect(otherZone->freePaths().get());
  168. theirPath = theirPath.search(potentialPos, true, costFunction);
  169. if (ourPath.valid() && theirPath.valid())
  170. {
  171. zone.connectPath(ourPath);
  172. otherZone->connectPath(theirPath);
  173. otherZone->getModificator<ObjectManager>()->updateDistances(potentialPos);
  174. success = true;
  175. break;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. }
  182. if (connection.getConnectionType() == rmg::EConnectionType::FICTIVE ||
  183. connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  184. {
  185. //Fictive or repulsive connections are not real, take no action
  186. dCompleted.push_back(connection);
  187. return;
  188. }
  189. float maxDist = -10e6;
  190. if(!success && !directProhibited && directConnectionIterator != dNeighbourZones.end())
  191. {
  192. int3 guardPos(-1, -1, -1);
  193. int3 roadNode;
  194. for (auto borderPos : directConnectionIterator->second)
  195. {
  196. int3 potentialPos = zone.areaPossible()->nearest(borderPos);
  197. assert(borderPos != potentialPos);
  198. //Check if guard pos doesn't touch any 3rd zone. This would create unwanted passage to 3rd zone
  199. bool adjacentZone = false;
  200. map.foreach_neighbour(potentialPos, [this, &adjacentZone, otherZoneId](int3 & pos)
  201. {
  202. auto zoneId = map.getZoneID(pos);
  203. if (zoneId != zone.getId() && zoneId != otherZoneId)
  204. {
  205. adjacentZone = true;
  206. }
  207. });
  208. if (adjacentZone)
  209. {
  210. continue;
  211. }
  212. //Take into account distance to objects from both sides
  213. float dist = std::min(map.getTileInfo(potentialPos).getNearestObjectDistance(),
  214. map.getTileInfo(borderPos).getNearestObjectDistance());
  215. if (dist > 3) //Don't place guards at adjacent tiles
  216. {
  217. auto safetyGap = rmg::Area({ potentialPos });
  218. safetyGap.unite(safetyGap.getBorderOutside());
  219. safetyGap.intersect(zone.areaPossible().get());
  220. if (!safetyGap.empty())
  221. {
  222. safetyGap.intersect(otherZone->areaPossible().get());
  223. if (safetyGap.empty())
  224. {
  225. float distanceToCenter = zone.getPos().dist2d(potentialPos) * otherZone->getPos().dist2d(potentialPos);
  226. auto localDist = (dist - distanceToCenter) * //Prefer close to zone center
  227. (std::max(distanceToCenter, dist) / std::min(distanceToCenter, dist));
  228. //Distance to center dominates and is negative, so imbalanced proportions will result in huge penalty
  229. if (localDist > maxDist)
  230. {
  231. maxDist = localDist;
  232. guardPos = potentialPos;
  233. roadNode = borderPos;
  234. }
  235. }
  236. }
  237. }
  238. }
  239. if(guardPos.isValid())
  240. {
  241. assert(zone.getModificator<ObjectManager>());
  242. auto & manager = *zone.getModificator<ObjectManager>();
  243. auto * monsterType = manager.chooseGuard(connection.getGuardStrength(), true);
  244. rmg::Area border(zone.area()->getBorder());
  245. border.unite(otherZone->area()->getBorder());
  246. auto localCostFunction = rmg::Path::createCurvedCostFunction(zone.area()->getBorder());
  247. auto otherCostFunction = rmg::Path::createCurvedCostFunction(otherZone->area()->getBorder());
  248. auto ourArea = zone.areaForRoads();
  249. auto theirArea = otherZone->areaForRoads();
  250. theirArea.add(guardPos);
  251. rmg::Path ourPath(ourArea);
  252. rmg::Path theirPath(theirArea);
  253. ourPath.connect(zone.freePaths().get());
  254. ourPath = ourPath.search(guardPos, true, localCostFunction);
  255. theirPath.connect(otherZone->freePaths().get());
  256. theirPath = theirPath.search(guardPos, true, otherCostFunction);
  257. if(ourPath.valid() && theirPath.valid())
  258. {
  259. zone.connectPath(ourPath);
  260. otherZone->connectPath(theirPath);
  261. if(monsterType)
  262. {
  263. rmg::Object monster(*monsterType);
  264. monster.setPosition(guardPos);
  265. manager.placeObject(monster, false, true);
  266. //Place objects away from the monster in the other zone, too
  267. otherZone->getModificator<ObjectManager>()->updateDistances(monster);
  268. }
  269. else
  270. {
  271. //Update distances from empty passage, too
  272. zone.areaPossible()->erase(guardPos);
  273. zone.freePaths()->add(guardPos);
  274. map.setOccupied(guardPos, ETileType::FREE);
  275. manager.updateDistances(guardPos);
  276. otherZone->getModificator<ObjectManager>()->updateDistances(guardPos);
  277. }
  278. if (createRoad)
  279. {
  280. assert(zone.getModificator<RoadPlacer>());
  281. zone.getModificator<RoadPlacer>()->addRoadNode(guardPos);
  282. assert(otherZone->getModificator<RoadPlacer>());
  283. otherZone->getModificator<RoadPlacer>()->addRoadNode(roadNode);
  284. }
  285. assert(otherZone->getModificator<ConnectionsPlacer>());
  286. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  287. success = true;
  288. }
  289. }
  290. }
  291. //2. connect via water
  292. bool waterMode = map.getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  293. if(waterMode && zone.isUnderground() == otherZone->isUnderground())
  294. {
  295. if(generator.getZoneWater() && generator.getZoneWater()->getModificator<WaterProxy>())
  296. {
  297. if(generator.getZoneWater()->getModificator<WaterProxy>()->waterKeepConnection(connection, createRoad))
  298. {
  299. assert(otherZone->getModificator<ConnectionsPlacer>());
  300. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  301. success = true;
  302. }
  303. }
  304. }
  305. if(success)
  306. dCompleted.push_back(connection);
  307. }
  308. void ConnectionsPlacer::selfSideIndirectConnection(const rmg::ZoneConnection & connection)
  309. {
  310. bool success = false;
  311. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  312. auto & otherZone = map.getZones().at(otherZoneId);
  313. bool allowRoad = shouldGenerateRoad(connection);
  314. //3. place subterrain gates
  315. if(zone.isUnderground() != otherZone->isUnderground())
  316. {
  317. int3 zShift(0, 0, zone.getPos().z - otherZone->getPos().z);
  318. auto lock = lockZones(otherZone);
  319. std::scoped_lock doubleLock(zone.areaMutex, otherZone->areaMutex);
  320. auto commonArea = zone.areaPossible().get() * (otherZone->areaPossible().get() + zShift);
  321. if(!commonArea.empty())
  322. {
  323. assert(zone.getModificator<ObjectManager>());
  324. auto & manager = *zone.getModificator<ObjectManager>();
  325. assert(otherZone->getModificator<ObjectManager>());
  326. auto & managerOther = *otherZone->getModificator<ObjectManager>();
  327. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  328. auto * gate1 = factory->create(map.mapInstance->cb, nullptr);
  329. auto * gate2 = factory->create(map.mapInstance->cb, nullptr);
  330. rmg::Object rmgGate1(*gate1);
  331. rmg::Object rmgGate2(*gate2);
  332. rmgGate1.setTemplate(zone.getTerrainType(), zone.getRand());
  333. rmgGate2.setTemplate(otherZone->getTerrainType(), zone.getRand());
  334. bool guarded1 = manager.addGuard(rmgGate1, connection.getGuardStrength(), true);
  335. bool guarded2 = managerOther.addGuard(rmgGate2, connection.getGuardStrength(), true);
  336. int minDist = 3;
  337. rmg::Path path2(otherZone->area().get());
  338. rmg::Path path1 = manager.placeAndConnectObject(commonArea, rmgGate1, [this, minDist, &path2, &rmgGate1, &zShift, guarded2, &managerOther, &rmgGate2 ](const int3 & tile)
  339. {
  340. auto ti = map.getTileInfo(tile);
  341. auto otherTi = map.getTileInfo(tile - zShift);
  342. float dist = ti.getNearestObjectDistance();
  343. float otherDist = otherTi.getNearestObjectDistance();
  344. if(dist < minDist || otherDist < minDist)
  345. return -1.f;
  346. //This could fail is accessibleArea is below the map
  347. rmg::Area toPlace(rmgGate1.getArea());
  348. toPlace.unite(toPlace.getBorderOutside()); // Add a bit of extra space around
  349. toPlace.erase_if([this](const int3 & tile)
  350. {
  351. return !map.isOnMap(tile);
  352. });
  353. toPlace.translate(-zShift);
  354. path2 = managerOther.placeAndConnectObject(toPlace, rmgGate2, minDist, guarded2, true, ObjectManager::OptimizeType::NONE);
  355. return path2.valid() ? (dist * otherDist) : -1.f;
  356. }, guarded1, true, ObjectManager::OptimizeType::DISTANCE);
  357. if(path1.valid() && path2.valid())
  358. {
  359. manager.placeObject(rmgGate1, guarded1, true, allowRoad);
  360. managerOther.placeObject(rmgGate2, guarded2, true, allowRoad);
  361. replaceWithCurvedPath(path1, zone, rmgGate1.getVisitablePosition());
  362. replaceWithCurvedPath(path2, *otherZone, rmgGate2.getVisitablePosition());
  363. zone.connectPath(path1);
  364. otherZone->connectPath(path2);
  365. assert(otherZone->getModificator<ConnectionsPlacer>());
  366. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  367. success = true;
  368. }
  369. }
  370. }
  371. //4. place monoliths/portals
  372. if(!success)
  373. {
  374. placeMonolithConnection(connection);
  375. }
  376. }
  377. void ConnectionsPlacer::placeMonolithConnection(const rmg::ZoneConnection & connection)
  378. {
  379. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  380. auto & otherZone = map.getZones().at(otherZoneId);
  381. bool allowRoad = shouldGenerateRoad(connection);
  382. auto factory = LIBRARY->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, generator.getNextMonlithIndex());
  383. auto * teleport1 = factory->create(map.mapInstance->cb, nullptr);
  384. auto * teleport2 = factory->create(map.mapInstance->cb, nullptr);
  385. RequiredObjectInfo obj1(teleport1, connection.getGuardStrength(), allowRoad);
  386. RequiredObjectInfo obj2(teleport2, connection.getGuardStrength(), allowRoad);
  387. zone.getModificator<ObjectManager>()->addRequiredObject(obj1);
  388. otherZone->getModificator<ObjectManager>()->addRequiredObject(obj2);
  389. dCompleted.push_back(connection);
  390. assert(otherZone->getModificator<ConnectionsPlacer>());
  391. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  392. }
  393. void ConnectionsPlacer::collectNeighbourZones()
  394. {
  395. auto border = zone.area()->getBorderOutside();
  396. for(const auto & i : border)
  397. {
  398. if(!map.isOnMap(i))
  399. continue;
  400. auto zid = map.getZoneID(i);
  401. assert(zid != zone.getId());
  402. dNeighbourZones[zid].insert(i);
  403. }
  404. }
  405. bool ConnectionsPlacer::shouldGenerateRoad(const rmg::ZoneConnection& connection) const
  406. {
  407. return connection.getRoadOption() == rmg::ERoadOption::ROAD_TRUE;
  408. }
  409. void ConnectionsPlacer::createBorder()
  410. {
  411. rmg::Area borderArea(zone.area()->getBorder());
  412. rmg::Area borderOutsideArea(zone.area()->getBorderOutside());
  413. auto blockBorder = borderArea.getSubarea([this, &borderOutsideArea](const int3 & t)
  414. {
  415. auto tile = borderOutsideArea.nearest(t);
  416. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getType() != ETemplateZoneType::WATER;
  417. });
  418. //No border for wide connections
  419. for (auto& connection : zone.getConnections()) // We actually placed that connection already
  420. {
  421. auto otherZone = connection.getOtherZoneId(zone.getId());
  422. if (connection.getConnectionType() == rmg::EConnectionType::WIDE)
  423. {
  424. auto sharedBorder = borderArea.getSubarea([this, otherZone, &borderOutsideArea](const int3 & t)
  425. {
  426. auto tile = borderOutsideArea.nearest(t);
  427. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getId() == otherZone;
  428. });
  429. blockBorder.subtract(sharedBorder);
  430. }
  431. };
  432. auto areaPossible = zone.areaPossible();
  433. for(const auto & tile : blockBorder.getTilesVector())
  434. {
  435. if(map.isPossible(tile))
  436. {
  437. map.setOccupied(tile, ETileType::BLOCKED);
  438. areaPossible->erase(tile);
  439. }
  440. map.foreachDirectNeighbour(tile, [this, &areaPossible](int3 &nearbyPos)
  441. {
  442. if(map.isPossible(nearbyPos) && map.getZoneID(nearbyPos) == zone.getId())
  443. {
  444. map.setOccupied(nearbyPos, ETileType::BLOCKED);
  445. areaPossible->erase(nearbyPos);
  446. }
  447. });
  448. }
  449. }
  450. VCMI_LIB_NAMESPACE_END