ConnectionsPlacer.cpp 16 KB

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