ConnectionsPlacer.cpp 16 KB

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