ConnectionsPlacer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 "../../mapping/CMapEditManager.h"
  18. #include "../RmgObject.h"
  19. #include "ObjectManager.h"
  20. #include "../Functions.h"
  21. #include "RoadPlacer.h"
  22. #include "../TileInfo.h"
  23. #include "WaterAdopter.h"
  24. #include "WaterProxy.h"
  25. #include "TownPlacer.h"
  26. #include <boost/interprocess/sync/scoped_lock.hpp>
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. void ConnectionsPlacer::process()
  29. {
  30. collectNeighbourZones();
  31. auto diningPhilosophers = [this](std::function<void(const rmg::ZoneConnection&)> f)
  32. {
  33. for (auto& c : dConnections)
  34. {
  35. if (c.getZoneA() != zone.getId() && c.getZoneB() != zone.getId())
  36. continue;
  37. auto otherZone = map.getZones().at(c.getZoneB());
  38. auto* cp = otherZone->getModificator<ConnectionsPlacer>();
  39. while (cp)
  40. {
  41. RecursiveLock lock1(externalAccessMutex, boost::try_to_lock_t{});
  42. RecursiveLock lock2(cp->externalAccessMutex, boost::try_to_lock_t{});
  43. if (lock1.owns_lock() && lock2.owns_lock())
  44. {
  45. if (!vstd::contains(dCompleted, c))
  46. {
  47. f(c);
  48. }
  49. break;
  50. }
  51. }
  52. }
  53. };
  54. diningPhilosophers([this](const rmg::ZoneConnection& c)
  55. {
  56. selfSideDirectConnection(c);
  57. });
  58. createBorder();
  59. diningPhilosophers([this](const rmg::ZoneConnection& c)
  60. {
  61. selfSideIndirectConnection(c);
  62. });
  63. }
  64. void ConnectionsPlacer::init()
  65. {
  66. DEPENDENCY(WaterAdopter);
  67. DEPENDENCY(TownPlacer);
  68. POSTFUNCTION(RoadPlacer);
  69. POSTFUNCTION(ObjectManager);
  70. for(auto c : map.getMapGenOptions().getMapTemplate()->getConnectedZoneIds())
  71. addConnection(c);
  72. }
  73. void ConnectionsPlacer::addConnection(const rmg::ZoneConnection& connection)
  74. {
  75. dConnections.push_back(connection);
  76. }
  77. void ConnectionsPlacer::otherSideConnection(const rmg::ZoneConnection & connection)
  78. {
  79. dCompleted.push_back(connection);
  80. }
  81. void ConnectionsPlacer::selfSideDirectConnection(const rmg::ZoneConnection & connection)
  82. {
  83. bool success = false;
  84. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  85. auto & otherZone = map.getZones().at(otherZoneId);
  86. //1. Try to make direct connection
  87. //Do if it's not prohibited by terrain settings
  88. const auto * ourTerrain = VLC->terrainTypeHandler->getById(zone.getTerrainType());
  89. const auto * otherTerrain = VLC->terrainTypeHandler->getById(otherZone->getTerrainType());
  90. bool directProhibited = vstd::contains(ourTerrain->prohibitTransitions, otherZone->getTerrainType())
  91. || vstd::contains(otherTerrain->prohibitTransitions, zone.getTerrainType());
  92. auto directConnectionIterator = dNeighbourZones.find(otherZoneId);
  93. if (directConnectionIterator != dNeighbourZones.end())
  94. {
  95. if (connection.getConnectionType() == EConnectionType::EConnectionType::WIDE)
  96. {
  97. for (auto borderPos : directConnectionIterator->second)
  98. {
  99. //TODO: Refactor common code with direct connection
  100. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  101. assert(borderPos != potentialPos);
  102. auto safetyGap = rmg::Area({ potentialPos });
  103. safetyGap.unite(safetyGap.getBorderOutside());
  104. safetyGap.intersect(zone.areaPossible());
  105. if (!safetyGap.empty())
  106. {
  107. safetyGap.intersect(otherZone->areaPossible());
  108. if (safetyGap.empty())
  109. {
  110. rmg::Area border(zone.getArea().getBorder());
  111. border.unite(otherZone->getArea().getBorder());
  112. auto costFunction = [&border](const int3& s, const int3& d)
  113. {
  114. return 1.f / (1.f + border.distanceSqr(d));
  115. };
  116. auto ourArea = zone.areaPossible() + zone.freePaths();
  117. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  118. theirArea.add(potentialPos);
  119. rmg::Path ourPath(ourArea);
  120. rmg::Path theirPath(theirArea);
  121. ourPath.connect(zone.freePaths());
  122. ourPath = ourPath.search(potentialPos, true, costFunction);
  123. theirPath.connect(otherZone->freePaths());
  124. theirPath = theirPath.search(potentialPos, true, costFunction);
  125. if (ourPath.valid() && theirPath.valid())
  126. {
  127. zone.connectPath(ourPath);
  128. otherZone->connectPath(theirPath);
  129. otherZone->getModificator<ObjectManager>()->updateDistances(potentialPos);
  130. success = true;
  131. break;
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }
  138. if (connection.getConnectionType() == EConnectionType::EConnectionType::FICTIVE ||
  139. connection.getConnectionType() == EConnectionType::EConnectionType::REPULSIVE)
  140. {
  141. //Fictive or repulsive connections are not real, take no action
  142. dCompleted.push_back(connection);
  143. return;
  144. }
  145. float maxDist = -10e6;
  146. if(!success && !directProhibited && directConnectionIterator != dNeighbourZones.end())
  147. {
  148. int3 guardPos(-1, -1, -1);
  149. int3 roadNode;
  150. for (auto borderPos : directConnectionIterator->second)
  151. {
  152. int3 potentialPos = zone.areaPossible().nearest(borderPos);
  153. assert(borderPos != potentialPos);
  154. //Take into account distance to objects from both sides
  155. float dist = std::min(map.getTileInfo(potentialPos).getNearestObjectDistance(),
  156. map.getTileInfo(borderPos).getNearestObjectDistance());
  157. if (dist > 3) //Don't place guards at adjacent tiles
  158. {
  159. auto safetyGap = rmg::Area({ potentialPos });
  160. safetyGap.unite(safetyGap.getBorderOutside());
  161. safetyGap.intersect(zone.areaPossible());
  162. if (!safetyGap.empty())
  163. {
  164. safetyGap.intersect(otherZone->areaPossible());
  165. if (safetyGap.empty())
  166. {
  167. float distanceToCenter = zone.getPos().dist2d(potentialPos) * otherZone->getPos().dist2d(potentialPos);
  168. auto localDist = (dist - distanceToCenter) * //Prefer close to zone center
  169. (std::max(distanceToCenter, dist) / std::min(distanceToCenter, dist));
  170. //Distance to center dominates and is negative, so imbalanced proportions will result in huge penalty
  171. if (localDist > maxDist)
  172. {
  173. maxDist = localDist;
  174. guardPos = potentialPos;
  175. roadNode = borderPos;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. if(guardPos.valid())
  182. {
  183. assert(zone.getModificator<ObjectManager>());
  184. auto & manager = *zone.getModificator<ObjectManager>();
  185. auto * monsterType = manager.chooseGuard(connection.getGuardStrength(), true);
  186. rmg::Area border(zone.getArea().getBorder());
  187. border.unite(otherZone->getArea().getBorder());
  188. auto costFunction = [&border](const int3 & s, const int3 & d)
  189. {
  190. return 1.f / (1.f + border.distanceSqr(d));
  191. };
  192. auto ourArea = zone.areaPossible() + zone.freePaths();
  193. auto theirArea = otherZone->areaPossible() + otherZone->freePaths();
  194. theirArea.add(guardPos);
  195. rmg::Path ourPath(ourArea);
  196. rmg::Path theirPath(theirArea);
  197. ourPath.connect(zone.freePaths());
  198. ourPath = ourPath.search(guardPos, true, costFunction);
  199. theirPath.connect(otherZone->freePaths());
  200. theirPath = theirPath.search(guardPos, true, costFunction);
  201. if(ourPath.valid() && theirPath.valid())
  202. {
  203. zone.connectPath(ourPath);
  204. otherZone->connectPath(theirPath);
  205. if(monsterType)
  206. {
  207. rmg::Object monster(*monsterType);
  208. monster.setPosition(guardPos);
  209. manager.placeObject(monster, false, true);
  210. //Place objects away from the monster in the other zone, too
  211. otherZone->getModificator<ObjectManager>()->updateDistances(monster);
  212. }
  213. else
  214. {
  215. zone.areaPossible().erase(guardPos);
  216. zone.freePaths().add(guardPos);
  217. map.setOccupied(guardPos, ETileType::FREE);
  218. }
  219. assert(zone.getModificator<RoadPlacer>());
  220. zone.getModificator<RoadPlacer>()->addRoadNode(guardPos);
  221. assert(otherZone->getModificator<RoadPlacer>());
  222. otherZone->getModificator<RoadPlacer>()->addRoadNode(roadNode);
  223. assert(otherZone->getModificator<ConnectionsPlacer>());
  224. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  225. success = true;
  226. }
  227. }
  228. }
  229. //2. connect via water
  230. bool waterMode = map.getMapGenOptions().getWaterContent() != EWaterContent::NONE;
  231. if(waterMode && zone.isUnderground() == otherZone->isUnderground())
  232. {
  233. if(generator.getZoneWater() && generator.getZoneWater()->getModificator<WaterProxy>())
  234. {
  235. if(generator.getZoneWater()->getModificator<WaterProxy>()->waterKeepConnection(connection.getZoneA(), connection.getZoneB()))
  236. {
  237. assert(otherZone->getModificator<ConnectionsPlacer>());
  238. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  239. success = true;
  240. }
  241. }
  242. }
  243. if(success)
  244. dCompleted.push_back(connection);
  245. }
  246. void ConnectionsPlacer::selfSideIndirectConnection(const rmg::ZoneConnection & connection)
  247. {
  248. bool success = false;
  249. auto otherZoneId = (connection.getZoneA() == zone.getId() ? connection.getZoneB() : connection.getZoneA());
  250. auto & otherZone = map.getZones().at(otherZoneId);
  251. //3. place subterrain gates
  252. if(zone.isUnderground() != otherZone->isUnderground())
  253. {
  254. int3 zShift(0, 0, zone.getPos().z - otherZone->getPos().z);
  255. auto commonArea = zone.areaPossible() * (otherZone->areaPossible() + zShift);
  256. if(!commonArea.empty())
  257. {
  258. assert(zone.getModificator<ObjectManager>());
  259. auto & manager = *zone.getModificator<ObjectManager>();
  260. assert(otherZone->getModificator<ObjectManager>());
  261. auto & managerOther = *otherZone->getModificator<ObjectManager>();
  262. auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
  263. auto * gate1 = factory->create();
  264. auto * gate2 = factory->create();
  265. rmg::Object rmgGate1(*gate1);
  266. rmg::Object rmgGate2(*gate2);
  267. rmgGate1.setTemplate(zone.getTerrainType());
  268. rmgGate2.setTemplate(otherZone->getTerrainType());
  269. bool guarded1 = manager.addGuard(rmgGate1, connection.getGuardStrength(), true);
  270. bool guarded2 = managerOther.addGuard(rmgGate2, connection.getGuardStrength(), true);
  271. int minDist = 3;
  272. std::scoped_lock doubleLock(zone.areaMutex, otherZone->areaMutex);
  273. rmg::Path path2(otherZone->area());
  274. rmg::Path path1 = manager.placeAndConnectObject(commonArea, rmgGate1, [this, minDist, &path2, &rmgGate1, &zShift, guarded2, &managerOther, &rmgGate2 ](const int3 & tile)
  275. {
  276. auto ti = map.getTileInfo(tile);
  277. auto otherTi = map.getTileInfo(tile - zShift);
  278. float dist = ti.getNearestObjectDistance();
  279. float otherDist = otherTi.getNearestObjectDistance();
  280. if(dist < minDist || otherDist < minDist)
  281. return -1.f;
  282. rmg::Area toPlace(rmgGate1.getArea() + rmgGate1.getAccessibleArea());
  283. toPlace.translate(-zShift);
  284. path2 = managerOther.placeAndConnectObject(toPlace, rmgGate2, minDist, guarded2, true, ObjectManager::OptimizeType::NONE);
  285. return path2.valid() ? (dist * otherDist) : -1.f;
  286. }, guarded1, true, ObjectManager::OptimizeType::DISTANCE);
  287. if(path1.valid() && path2.valid())
  288. {
  289. zone.connectPath(path1);
  290. otherZone->connectPath(path2);
  291. manager.placeObject(rmgGate1, guarded1, true);
  292. managerOther.placeObject(rmgGate2, guarded2, true);
  293. assert(otherZone->getModificator<ConnectionsPlacer>());
  294. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  295. success = true;
  296. }
  297. }
  298. }
  299. //4. place monoliths/portals
  300. if(!success)
  301. {
  302. auto factory = VLC->objtypeh->getHandlerFor(Obj::MONOLITH_TWO_WAY, generator.getNextMonlithIndex());
  303. auto * teleport1 = factory->create();
  304. auto * teleport2 = factory->create();
  305. zone.getModificator<ObjectManager>()->addRequiredObject(teleport1, connection.getGuardStrength());
  306. otherZone->getModificator<ObjectManager>()->addRequiredObject(teleport2, connection.getGuardStrength());
  307. assert(otherZone->getModificator<ConnectionsPlacer>());
  308. otherZone->getModificator<ConnectionsPlacer>()->otherSideConnection(connection);
  309. success = true;
  310. }
  311. if(success)
  312. dCompleted.push_back(connection);
  313. }
  314. void ConnectionsPlacer::collectNeighbourZones()
  315. {
  316. auto border = zone.area().getBorderOutside();
  317. for(const auto & i : border)
  318. {
  319. if(!map.isOnMap(i))
  320. continue;
  321. auto zid = map.getZoneID(i);
  322. assert(zid != zone.getId());
  323. dNeighbourZones[zid].insert(i);
  324. }
  325. }
  326. void ConnectionsPlacer::createBorder()
  327. {
  328. rmg::Area borderArea(zone.getArea().getBorder());
  329. rmg::Area borderOutsideArea(zone.getArea().getBorderOutside());
  330. auto blockBorder = borderArea.getSubarea([this, &borderOutsideArea](const int3 & t)
  331. {
  332. auto tile = borderOutsideArea.nearest(t);
  333. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getType() != ETemplateZoneType::WATER;
  334. });
  335. //No border for wide connections
  336. for (auto& connection : zone.getConnections()) // We actually placed that connection already
  337. {
  338. auto otherZone = connection.getOtherZoneId(zone.getId());
  339. if (connection.getConnectionType() == EConnectionType::EConnectionType::WIDE)
  340. {
  341. auto sharedBorder = borderArea.getSubarea([this, otherZone, &borderOutsideArea](const int3 & t)
  342. {
  343. auto tile = borderOutsideArea.nearest(t);
  344. return map.isOnMap(tile) && map.getZones()[map.getZoneID(tile)]->getId() == otherZone;
  345. });
  346. blockBorder.subtract(sharedBorder);
  347. }
  348. };
  349. Zone::Lock lock(zone.areaMutex); //Protect from erasing same tiles again
  350. for(const auto & tile : blockBorder.getTilesVector())
  351. {
  352. if(map.isPossible(tile))
  353. {
  354. map.setOccupied(tile, ETileType::BLOCKED);
  355. zone.areaPossible().erase(tile);
  356. }
  357. map.foreachDirectNeighbour(tile, [this](int3 &nearbyPos)
  358. {
  359. if(map.isPossible(nearbyPos) && map.getZoneID(nearbyPos) == zone.getId())
  360. {
  361. map.setOccupied(nearbyPos, ETileType::BLOCKED);
  362. zone.areaPossible().erase(nearbyPos);
  363. }
  364. });
  365. }
  366. }
  367. VCMI_LIB_NAMESPACE_END